RegAllocEvictionAdvisor.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //===- RegAllocEvictionAdvisor.cpp - eviction advisor ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implementation of the default eviction advisor and of the Analysis pass.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "RegAllocEvictionAdvisor.h"
  13. #include "RegAllocGreedy.h"
  14. #include "llvm/CodeGen/MachineFunction.h"
  15. #include "llvm/CodeGen/RegisterClassInfo.h"
  16. #include "llvm/CodeGen/VirtRegMap.h"
  17. #include "llvm/InitializePasses.h"
  18. #include "llvm/Pass.h"
  19. #include "llvm/PassRegistry.h"
  20. #include "llvm/Support/CommandLine.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Target/TargetMachine.h"
  23. using namespace llvm;
  24. static cl::opt<RegAllocEvictionAdvisorAnalysis::AdvisorMode> Mode(
  25. "regalloc-enable-advisor", cl::Hidden, cl::ZeroOrMore,
  26. cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default),
  27. cl::desc("Enable regalloc advisor mode"),
  28. cl::values(
  29. clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default,
  30. "default", "Default"),
  31. clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release,
  32. "release", "precompiled"),
  33. clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development,
  34. "development", "for training")));
  35. static cl::opt<bool> EnableLocalReassignment(
  36. "enable-local-reassign", cl::Hidden,
  37. cl::desc("Local reassignment can yield better allocation decisions, but "
  38. "may be compile time intensive"),
  39. cl::init(false));
  40. #define DEBUG_TYPE "regalloc"
  41. #ifdef LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL
  42. #define LLVM_HAVE_TF_AOT
  43. #endif
  44. char RegAllocEvictionAdvisorAnalysis::ID = 0;
  45. INITIALIZE_PASS(RegAllocEvictionAdvisorAnalysis, "regalloc-evict",
  46. "Regalloc eviction policy", false, true)
  47. namespace {
  48. class DefaultEvictionAdvisorAnalysis final
  49. : public RegAllocEvictionAdvisorAnalysis {
  50. public:
  51. DefaultEvictionAdvisorAnalysis(bool NotAsRequested)
  52. : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Default),
  53. NotAsRequested(NotAsRequested) {}
  54. // support for isa<> and dyn_cast.
  55. static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
  56. return R->getAdvisorMode() == AdvisorMode::Default;
  57. }
  58. private:
  59. std::unique_ptr<RegAllocEvictionAdvisor>
  60. getAdvisor(MachineFunction &MF, const RAGreedy &RA) override {
  61. return std::make_unique<DefaultEvictionAdvisor>(MF, RA);
  62. }
  63. bool doInitialization(Module &M) override {
  64. if (NotAsRequested)
  65. M.getContext().emitError("Requested regalloc eviction advisor analysis "
  66. "could be created. Using default");
  67. return RegAllocEvictionAdvisorAnalysis::doInitialization(M);
  68. }
  69. const bool NotAsRequested;
  70. };
  71. } // namespace
  72. template <> Pass *llvm::callDefaultCtor<RegAllocEvictionAdvisorAnalysis>() {
  73. Pass *Ret = nullptr;
  74. switch (Mode) {
  75. case RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default:
  76. Ret = new DefaultEvictionAdvisorAnalysis(/*NotAsRequested*/ false);
  77. break;
  78. case RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development:
  79. #if defined(LLVM_HAVE_TF_API)
  80. Ret = createDevelopmentModeAdvisor();
  81. #endif
  82. break;
  83. case RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release:
  84. #if defined(LLVM_HAVE_TF_AOT)
  85. Ret = createReleaseModeAdvisor();
  86. #endif
  87. break;
  88. }
  89. if (Ret)
  90. return Ret;
  91. return new DefaultEvictionAdvisorAnalysis(/*NotAsRequested*/ true);
  92. }
  93. StringRef RegAllocEvictionAdvisorAnalysis::getPassName() const {
  94. switch (getAdvisorMode()) {
  95. case AdvisorMode::Default:
  96. return "Default Regalloc Eviction Advisor";
  97. case AdvisorMode::Release:
  98. return "Release mode Regalloc Eviction Advisor";
  99. case AdvisorMode::Development:
  100. return "Development mode Regalloc Eviction Advisor";
  101. }
  102. llvm_unreachable("Unknown advisor kind");
  103. }
  104. RegAllocEvictionAdvisor::RegAllocEvictionAdvisor(MachineFunction &MF,
  105. const RAGreedy &RA)
  106. : MF(MF), RA(RA), Matrix(RA.getInterferenceMatrix()),
  107. LIS(RA.getLiveIntervals()), VRM(RA.getVirtRegMap()),
  108. MRI(&VRM->getRegInfo()), TRI(MF.getSubtarget().getRegisterInfo()),
  109. RegClassInfo(RA.getRegClassInfo()), RegCosts(TRI->getRegisterCosts(MF)),
  110. EnableLocalReassign(EnableLocalReassignment ||
  111. MF.getSubtarget().enableRALocalReassignment(
  112. MF.getTarget().getOptLevel())) {}
  113. /// shouldEvict - determine if A should evict the assigned live range B. The
  114. /// eviction policy defined by this function together with the allocation order
  115. /// defined by enqueue() decides which registers ultimately end up being split
  116. /// and spilled.
  117. ///
  118. /// Cascade numbers are used to prevent infinite loops if this function is a
  119. /// cyclic relation.
  120. ///
  121. /// @param A The live range to be assigned.
  122. /// @param IsHint True when A is about to be assigned to its preferred
  123. /// register.
  124. /// @param B The live range to be evicted.
  125. /// @param BreaksHint True when B is already assigned to its preferred register.
  126. bool DefaultEvictionAdvisor::shouldEvict(LiveInterval &A, bool IsHint,
  127. LiveInterval &B,
  128. bool BreaksHint) const {
  129. bool CanSplit = RA.getExtraInfo().getStage(B) < RS_Spill;
  130. // Be fairly aggressive about following hints as long as the evictee can be
  131. // split.
  132. if (CanSplit && IsHint && !BreaksHint)
  133. return true;
  134. if (A.weight() > B.weight()) {
  135. LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight() << '\n');
  136. return true;
  137. }
  138. return false;
  139. }
  140. /// canEvictHintInterference - return true if the interference for VirtReg
  141. /// on the PhysReg, which is VirtReg's hint, can be evicted in favor of VirtReg.
  142. bool DefaultEvictionAdvisor::canEvictHintInterference(
  143. LiveInterval &VirtReg, MCRegister PhysReg,
  144. const SmallVirtRegSet &FixedRegisters) const {
  145. EvictionCost MaxCost;
  146. MaxCost.setBrokenHints(1);
  147. return canEvictInterferenceBasedOnCost(VirtReg, PhysReg, true, MaxCost,
  148. FixedRegisters);
  149. }
  150. /// canEvictInterferenceBasedOnCost - Return true if all interferences between
  151. /// VirtReg and PhysReg can be evicted.
  152. ///
  153. /// @param VirtReg Live range that is about to be assigned.
  154. /// @param PhysReg Desired register for assignment.
  155. /// @param IsHint True when PhysReg is VirtReg's preferred register.
  156. /// @param MaxCost Only look for cheaper candidates and update with new cost
  157. /// when returning true.
  158. /// @returns True when interference can be evicted cheaper than MaxCost.
  159. bool DefaultEvictionAdvisor::canEvictInterferenceBasedOnCost(
  160. LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
  161. EvictionCost &MaxCost, const SmallVirtRegSet &FixedRegisters) const {
  162. // It is only possible to evict virtual register interference.
  163. if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
  164. return false;
  165. bool IsLocal = VirtReg.empty() || LIS->intervalIsInOneMBB(VirtReg);
  166. // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
  167. // involved in an eviction before. If a cascade number was assigned, deny
  168. // evicting anything with the same or a newer cascade number. This prevents
  169. // infinite eviction loops.
  170. //
  171. // This works out so a register without a cascade number is allowed to evict
  172. // anything, and it can be evicted by anything.
  173. unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
  174. EvictionCost Cost;
  175. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  176. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  177. // If there is 10 or more interferences, chances are one is heavier.
  178. const auto &Interferences = Q.interferingVRegs(10);
  179. if (Interferences.size() >= 10)
  180. return false;
  181. // Check if any interfering live range is heavier than MaxWeight.
  182. for (LiveInterval *Intf : reverse(Interferences)) {
  183. assert(Register::isVirtualRegister(Intf->reg()) &&
  184. "Only expecting virtual register interference from query");
  185. // Do not allow eviction of a virtual register if we are in the middle
  186. // of last-chance recoloring and this virtual register is one that we
  187. // have scavenged a physical register for.
  188. if (FixedRegisters.count(Intf->reg()))
  189. return false;
  190. // Never evict spill products. They cannot split or spill.
  191. if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
  192. return false;
  193. // Once a live range becomes small enough, it is urgent that we find a
  194. // register for it. This is indicated by an infinite spill weight. These
  195. // urgent live ranges get to evict almost anything.
  196. //
  197. // Also allow urgent evictions of unspillable ranges from a strictly
  198. // larger allocation order.
  199. bool Urgent =
  200. !VirtReg.isSpillable() &&
  201. (Intf->isSpillable() ||
  202. RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
  203. RegClassInfo.getNumAllocatableRegs(
  204. MRI->getRegClass(Intf->reg())));
  205. // Only evict older cascades or live ranges without a cascade.
  206. unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
  207. if (Cascade <= IntfCascade) {
  208. if (!Urgent)
  209. return false;
  210. // We permit breaking cascades for urgent evictions. It should be the
  211. // last resort, though, so make it really expensive.
  212. Cost.BrokenHints += 10;
  213. }
  214. // Would this break a satisfied hint?
  215. bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
  216. // Update eviction cost.
  217. Cost.BrokenHints += BreaksHint;
  218. Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
  219. // Abort if this would be too expensive.
  220. if (!(Cost < MaxCost))
  221. return false;
  222. if (Urgent)
  223. continue;
  224. // Apply the eviction policy for non-urgent evictions.
  225. if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
  226. return false;
  227. // If !MaxCost.isMax(), then we're just looking for a cheap register.
  228. // Evicting another local live range in this case could lead to suboptimal
  229. // coloring.
  230. if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
  231. (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
  232. return false;
  233. }
  234. }
  235. }
  236. MaxCost = Cost;
  237. return true;
  238. }
  239. MCRegister DefaultEvictionAdvisor::tryFindEvictionCandidate(
  240. LiveInterval &VirtReg, const AllocationOrder &Order,
  241. uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
  242. // Keep track of the cheapest interference seen so far.
  243. EvictionCost BestCost;
  244. BestCost.setMax();
  245. MCRegister BestPhys;
  246. auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
  247. if (!MaybeOrderLimit)
  248. return MCRegister::NoRegister;
  249. unsigned OrderLimit = *MaybeOrderLimit;
  250. // When we are just looking for a reduced cost per use, don't break any
  251. // hints, and only evict smaller spill weights.
  252. if (CostPerUseLimit < uint8_t(~0u)) {
  253. BestCost.BrokenHints = 0;
  254. BestCost.MaxWeight = VirtReg.weight();
  255. }
  256. for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
  257. ++I) {
  258. MCRegister PhysReg = *I;
  259. assert(PhysReg);
  260. if (!canAllocatePhysReg(CostPerUseLimit, PhysReg) ||
  261. !canEvictInterferenceBasedOnCost(VirtReg, PhysReg, false, BestCost,
  262. FixedRegisters))
  263. continue;
  264. // Best so far.
  265. BestPhys = PhysReg;
  266. // Stop if the hint can be used.
  267. if (I.isHint())
  268. break;
  269. }
  270. return BestPhys;
  271. }