2
0

RegAllocGreedy.cpp 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577
  1. //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the RAGreedy function pass for register allocation in
  11. // optimized builds.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "AllocationOrder.h"
  16. #include "InterferenceCache.h"
  17. #include "LiveDebugVariables.h"
  18. #include "RegAllocBase.h"
  19. #include "SpillPlacement.h"
  20. #include "Spiller.h"
  21. #include "SplitKit.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/CalcSpillWeights.h"
  25. #include "llvm/CodeGen/EdgeBundles.h"
  26. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  27. #include "llvm/CodeGen/LiveRangeEdit.h"
  28. #include "llvm/CodeGen/LiveRegMatrix.h"
  29. #include "llvm/CodeGen/LiveStackAnalysis.h"
  30. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  31. #include "llvm/CodeGen/MachineDominators.h"
  32. #include "llvm/CodeGen/MachineFunctionPass.h"
  33. #include "llvm/CodeGen/MachineLoopInfo.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/RegAllocRegistry.h"
  36. #include "llvm/CodeGen/RegisterClassInfo.h"
  37. #include "llvm/CodeGen/VirtRegMap.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/PassAnalysisSupport.h"
  40. #include "llvm/Support/BranchProbability.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/Timer.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Target/TargetSubtargetInfo.h"
  47. #include <queue>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "regalloc"
  50. STATISTIC(NumGlobalSplits, "Number of split global live ranges");
  51. STATISTIC(NumLocalSplits, "Number of split local live ranges");
  52. STATISTIC(NumEvicted, "Number of interferences evicted");
  53. static cl::opt<SplitEditor::ComplementSpillMode>
  54. SplitSpillMode("split-spill-mode", cl::Hidden,
  55. cl::desc("Spill mode for splitting live ranges"),
  56. cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
  57. clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
  58. clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
  59. clEnumValEnd),
  60. cl::init(SplitEditor::SM_Partition));
  61. static cl::opt<unsigned>
  62. LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
  63. cl::desc("Last chance recoloring max depth"),
  64. cl::init(5));
  65. static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
  66. "lcr-max-interf", cl::Hidden,
  67. cl::desc("Last chance recoloring maximum number of considered"
  68. " interference at a time"),
  69. cl::init(8));
  70. static cl::opt<bool>
  71. ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
  72. cl::desc("Exhaustive Search for registers bypassing the depth "
  73. "and interference cutoffs of last chance recoloring"));
  74. static cl::opt<bool> EnableLocalReassignment(
  75. "enable-local-reassign", cl::Hidden,
  76. cl::desc("Local reassignment can yield better allocation decisions, but "
  77. "may be compile time intensive"),
  78. cl::init(false));
  79. // FIXME: Find a good default for this flag and remove the flag.
  80. static cl::opt<unsigned>
  81. CSRFirstTimeCost("regalloc-csr-first-time-cost",
  82. cl::desc("Cost for first time use of callee-saved register."),
  83. cl::init(0), cl::Hidden);
  84. static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
  85. createGreedyRegisterAllocator);
  86. namespace {
  87. class RAGreedy : public MachineFunctionPass,
  88. public RegAllocBase,
  89. private LiveRangeEdit::Delegate {
  90. // Convenient shortcuts.
  91. typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
  92. typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
  93. typedef SmallSet<unsigned, 16> SmallVirtRegSet;
  94. // context
  95. MachineFunction *MF;
  96. // Shortcuts to some useful interface.
  97. const TargetInstrInfo *TII;
  98. const TargetRegisterInfo *TRI;
  99. RegisterClassInfo RCI;
  100. // analyses
  101. SlotIndexes *Indexes;
  102. MachineBlockFrequencyInfo *MBFI;
  103. MachineDominatorTree *DomTree;
  104. MachineLoopInfo *Loops;
  105. EdgeBundles *Bundles;
  106. SpillPlacement *SpillPlacer;
  107. LiveDebugVariables *DebugVars;
  108. // state
  109. std::unique_ptr<Spiller> SpillerInstance;
  110. PQueue Queue;
  111. unsigned NextCascade;
  112. // Live ranges pass through a number of stages as we try to allocate them.
  113. // Some of the stages may also create new live ranges:
  114. //
  115. // - Region splitting.
  116. // - Per-block splitting.
  117. // - Local splitting.
  118. // - Spilling.
  119. //
  120. // Ranges produced by one of the stages skip the previous stages when they are
  121. // dequeued. This improves performance because we can skip interference checks
  122. // that are unlikely to give any results. It also guarantees that the live
  123. // range splitting algorithm terminates, something that is otherwise hard to
  124. // ensure.
  125. enum LiveRangeStage {
  126. /// Newly created live range that has never been queued.
  127. RS_New,
  128. /// Only attempt assignment and eviction. Then requeue as RS_Split.
  129. RS_Assign,
  130. /// Attempt live range splitting if assignment is impossible.
  131. RS_Split,
  132. /// Attempt more aggressive live range splitting that is guaranteed to make
  133. /// progress. This is used for split products that may not be making
  134. /// progress.
  135. RS_Split2,
  136. /// Live range will be spilled. No more splitting will be attempted.
  137. RS_Spill,
  138. /// There is nothing more we can do to this live range. Abort compilation
  139. /// if it can't be assigned.
  140. RS_Done
  141. };
  142. // Enum CutOffStage to keep a track whether the register allocation failed
  143. // because of the cutoffs encountered in last chance recoloring.
  144. // Note: This is used as bitmask. New value should be next power of 2.
  145. enum CutOffStage {
  146. // No cutoffs encountered
  147. CO_None = 0,
  148. // lcr-max-depth cutoff encountered
  149. CO_Depth = 1,
  150. // lcr-max-interf cutoff encountered
  151. CO_Interf = 2
  152. };
  153. uint8_t CutOffInfo;
  154. #ifndef NDEBUG
  155. static const char *const StageName[];
  156. #endif
  157. // RegInfo - Keep additional information about each live range.
  158. struct RegInfo {
  159. LiveRangeStage Stage;
  160. // Cascade - Eviction loop prevention. See canEvictInterference().
  161. unsigned Cascade;
  162. RegInfo() : Stage(RS_New), Cascade(0) {}
  163. };
  164. IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
  165. LiveRangeStage getStage(const LiveInterval &VirtReg) const {
  166. return ExtraRegInfo[VirtReg.reg].Stage;
  167. }
  168. void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
  169. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  170. ExtraRegInfo[VirtReg.reg].Stage = Stage;
  171. }
  172. template<typename Iterator>
  173. void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
  174. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  175. for (;Begin != End; ++Begin) {
  176. unsigned Reg = *Begin;
  177. if (ExtraRegInfo[Reg].Stage == RS_New)
  178. ExtraRegInfo[Reg].Stage = NewStage;
  179. }
  180. }
  181. /// Cost of evicting interference.
  182. struct EvictionCost {
  183. unsigned BrokenHints; ///< Total number of broken hints.
  184. float MaxWeight; ///< Maximum spill weight evicted.
  185. EvictionCost(): BrokenHints(0), MaxWeight(0) {}
  186. bool isMax() const { return BrokenHints == ~0u; }
  187. void setMax() { BrokenHints = ~0u; }
  188. void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
  189. bool operator<(const EvictionCost &O) const {
  190. return std::tie(BrokenHints, MaxWeight) <
  191. std::tie(O.BrokenHints, O.MaxWeight);
  192. }
  193. };
  194. // splitting state.
  195. std::unique_ptr<SplitAnalysis> SA;
  196. std::unique_ptr<SplitEditor> SE;
  197. /// Cached per-block interference maps
  198. InterferenceCache IntfCache;
  199. /// All basic blocks where the current register has uses.
  200. SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
  201. /// Global live range splitting candidate info.
  202. struct GlobalSplitCandidate {
  203. // Register intended for assignment, or 0.
  204. unsigned PhysReg;
  205. // SplitKit interval index for this candidate.
  206. unsigned IntvIdx;
  207. // Interference for PhysReg.
  208. InterferenceCache::Cursor Intf;
  209. // Bundles where this candidate should be live.
  210. BitVector LiveBundles;
  211. SmallVector<unsigned, 8> ActiveBlocks;
  212. void reset(InterferenceCache &Cache, unsigned Reg) {
  213. PhysReg = Reg;
  214. IntvIdx = 0;
  215. Intf.setPhysReg(Cache, Reg);
  216. LiveBundles.clear();
  217. ActiveBlocks.clear();
  218. }
  219. // Set B[i] = C for every live bundle where B[i] was NoCand.
  220. unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
  221. unsigned Count = 0;
  222. for (int i = LiveBundles.find_first(); i >= 0;
  223. i = LiveBundles.find_next(i))
  224. if (B[i] == NoCand) {
  225. B[i] = C;
  226. Count++;
  227. }
  228. return Count;
  229. }
  230. };
  231. /// Candidate info for each PhysReg in AllocationOrder.
  232. /// This vector never shrinks, but grows to the size of the largest register
  233. /// class.
  234. SmallVector<GlobalSplitCandidate, 32> GlobalCand;
  235. enum : unsigned { NoCand = ~0u };
  236. /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
  237. /// NoCand which indicates the stack interval.
  238. SmallVector<unsigned, 32> BundleCand;
  239. /// Callee-save register cost, calculated once per machine function.
  240. BlockFrequency CSRCost;
  241. /// Run or not the local reassignment heuristic. This information is
  242. /// obtained from the TargetSubtargetInfo.
  243. bool EnableLocalReassign;
  244. /// Set of broken hints that may be reconciled later because of eviction.
  245. SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
  246. public:
  247. RAGreedy();
  248. /// Return the pass name.
  249. const char* getPassName() const override {
  250. return "Greedy Register Allocator";
  251. }
  252. /// RAGreedy analysis usage.
  253. void getAnalysisUsage(AnalysisUsage &AU) const override;
  254. void releaseMemory() override;
  255. Spiller &spiller() override { return *SpillerInstance; }
  256. void enqueue(LiveInterval *LI) override;
  257. LiveInterval *dequeue() override;
  258. unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
  259. void aboutToRemoveInterval(LiveInterval &) override;
  260. /// Perform register allocation.
  261. bool runOnMachineFunction(MachineFunction &mf) override;
  262. static char ID;
  263. private:
  264. unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
  265. SmallVirtRegSet &, unsigned = 0);
  266. bool LRE_CanEraseVirtReg(unsigned) override;
  267. void LRE_WillShrinkVirtReg(unsigned) override;
  268. void LRE_DidCloneVirtReg(unsigned, unsigned) override;
  269. void enqueue(PQueue &CurQueue, LiveInterval *LI);
  270. LiveInterval *dequeue(PQueue &CurQueue);
  271. BlockFrequency calcSpillCost();
  272. bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
  273. void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
  274. void growRegion(GlobalSplitCandidate &Cand);
  275. BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
  276. bool calcCompactRegion(GlobalSplitCandidate&);
  277. void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
  278. void calcGapWeights(unsigned, SmallVectorImpl<float>&);
  279. unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
  280. bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
  281. bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
  282. void evictInterference(LiveInterval&, unsigned,
  283. SmallVectorImpl<unsigned>&);
  284. bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
  285. SmallLISet &RecoloringCandidates,
  286. const SmallVirtRegSet &FixedRegisters);
  287. unsigned tryAssign(LiveInterval&, AllocationOrder&,
  288. SmallVectorImpl<unsigned>&);
  289. unsigned tryEvict(LiveInterval&, AllocationOrder&,
  290. SmallVectorImpl<unsigned>&, unsigned = ~0u);
  291. unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
  292. SmallVectorImpl<unsigned>&);
  293. /// Calculate cost of region splitting.
  294. unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
  295. AllocationOrder &Order,
  296. BlockFrequency &BestCost,
  297. unsigned &NumCands, bool IgnoreCSR);
  298. /// Perform region splitting.
  299. unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
  300. bool HasCompact,
  301. SmallVectorImpl<unsigned> &NewVRegs);
  302. /// Check other options before using a callee-saved register for the first
  303. /// time.
  304. unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
  305. unsigned PhysReg, unsigned &CostPerUseLimit,
  306. SmallVectorImpl<unsigned> &NewVRegs);
  307. void initializeCSRCost();
  308. unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
  309. SmallVectorImpl<unsigned>&);
  310. unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
  311. SmallVectorImpl<unsigned>&);
  312. unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
  313. SmallVectorImpl<unsigned>&);
  314. unsigned trySplit(LiveInterval&, AllocationOrder&,
  315. SmallVectorImpl<unsigned>&);
  316. unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
  317. SmallVectorImpl<unsigned> &,
  318. SmallVirtRegSet &, unsigned);
  319. bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
  320. SmallVirtRegSet &, unsigned);
  321. void tryHintRecoloring(LiveInterval &);
  322. void tryHintsRecoloring();
  323. /// Model the information carried by one end of a copy.
  324. struct HintInfo {
  325. /// The frequency of the copy.
  326. BlockFrequency Freq;
  327. /// The virtual register or physical register.
  328. unsigned Reg;
  329. /// Its currently assigned register.
  330. /// In case of a physical register Reg == PhysReg.
  331. unsigned PhysReg;
  332. HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
  333. : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
  334. };
  335. typedef SmallVector<HintInfo, 4> HintsInfo;
  336. BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
  337. void collectHintInfo(unsigned, HintsInfo &);
  338. bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
  339. };
  340. } // end anonymous namespace
  341. char RAGreedy::ID = 0;
  342. #ifndef NDEBUG
  343. const char *const RAGreedy::StageName[] = {
  344. "RS_New",
  345. "RS_Assign",
  346. "RS_Split",
  347. "RS_Split2",
  348. "RS_Spill",
  349. "RS_Done"
  350. };
  351. #endif
  352. // Hysteresis to use when comparing floats.
  353. // This helps stabilize decisions based on float comparisons.
  354. const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
  355. FunctionPass* llvm::createGreedyRegisterAllocator() {
  356. return new RAGreedy();
  357. }
  358. RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
  359. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  360. initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
  361. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  362. initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
  363. initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
  364. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  365. initializeLiveStacksPass(*PassRegistry::getPassRegistry());
  366. initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
  367. initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
  368. initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
  369. initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
  370. initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
  371. initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
  372. }
  373. void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
  374. AU.setPreservesCFG();
  375. AU.addRequired<MachineBlockFrequencyInfo>();
  376. AU.addPreserved<MachineBlockFrequencyInfo>();
  377. AU.addRequired<AliasAnalysis>();
  378. AU.addPreserved<AliasAnalysis>();
  379. AU.addRequired<LiveIntervals>();
  380. AU.addPreserved<LiveIntervals>();
  381. AU.addRequired<SlotIndexes>();
  382. AU.addPreserved<SlotIndexes>();
  383. AU.addRequired<LiveDebugVariables>();
  384. AU.addPreserved<LiveDebugVariables>();
  385. AU.addRequired<LiveStacks>();
  386. AU.addPreserved<LiveStacks>();
  387. AU.addRequired<MachineDominatorTree>();
  388. AU.addPreserved<MachineDominatorTree>();
  389. AU.addRequired<MachineLoopInfo>();
  390. AU.addPreserved<MachineLoopInfo>();
  391. AU.addRequired<VirtRegMap>();
  392. AU.addPreserved<VirtRegMap>();
  393. AU.addRequired<LiveRegMatrix>();
  394. AU.addPreserved<LiveRegMatrix>();
  395. AU.addRequired<EdgeBundles>();
  396. AU.addRequired<SpillPlacement>();
  397. MachineFunctionPass::getAnalysisUsage(AU);
  398. }
  399. //===----------------------------------------------------------------------===//
  400. // LiveRangeEdit delegate methods
  401. //===----------------------------------------------------------------------===//
  402. bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
  403. if (VRM->hasPhys(VirtReg)) {
  404. LiveInterval &LI = LIS->getInterval(VirtReg);
  405. Matrix->unassign(LI);
  406. aboutToRemoveInterval(LI);
  407. return true;
  408. }
  409. // Unassigned virtreg is probably in the priority queue.
  410. // RegAllocBase will erase it after dequeueing.
  411. return false;
  412. }
  413. void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
  414. if (!VRM->hasPhys(VirtReg))
  415. return;
  416. // Register is assigned, put it back on the queue for reassignment.
  417. LiveInterval &LI = LIS->getInterval(VirtReg);
  418. Matrix->unassign(LI);
  419. enqueue(&LI);
  420. }
  421. void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
  422. // Cloning a register we haven't even heard about yet? Just ignore it.
  423. if (!ExtraRegInfo.inBounds(Old))
  424. return;
  425. // LRE may clone a virtual register because dead code elimination causes it to
  426. // be split into connected components. The new components are much smaller
  427. // than the original, so they should get a new chance at being assigned.
  428. // same stage as the parent.
  429. ExtraRegInfo[Old].Stage = RS_Assign;
  430. ExtraRegInfo.grow(New);
  431. ExtraRegInfo[New] = ExtraRegInfo[Old];
  432. }
  433. void RAGreedy::releaseMemory() {
  434. SpillerInstance.reset();
  435. ExtraRegInfo.clear();
  436. GlobalCand.clear();
  437. }
  438. void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
  439. void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
  440. // Prioritize live ranges by size, assigning larger ranges first.
  441. // The queue holds (size, reg) pairs.
  442. const unsigned Size = LI->getSize();
  443. const unsigned Reg = LI->reg;
  444. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  445. "Can only enqueue virtual registers");
  446. unsigned Prio;
  447. ExtraRegInfo.grow(Reg);
  448. if (ExtraRegInfo[Reg].Stage == RS_New)
  449. ExtraRegInfo[Reg].Stage = RS_Assign;
  450. if (ExtraRegInfo[Reg].Stage == RS_Split) {
  451. // Unsplit ranges that couldn't be allocated immediately are deferred until
  452. // everything else has been allocated.
  453. Prio = Size;
  454. } else {
  455. // Giant live ranges fall back to the global assignment heuristic, which
  456. // prevents excessive spilling in pathological cases.
  457. bool ReverseLocal = TRI->reverseLocalAssignment();
  458. const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
  459. bool ForceGlobal = !ReverseLocal &&
  460. (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
  461. if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
  462. LIS->intervalIsInOneMBB(*LI)) {
  463. // Allocate original local ranges in linear instruction order. Since they
  464. // are singly defined, this produces optimal coloring in the absence of
  465. // global interference and other constraints.
  466. if (!ReverseLocal)
  467. Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
  468. else {
  469. // Allocating bottom up may allow many short LRGs to be assigned first
  470. // to one of the cheap registers. This could be much faster for very
  471. // large blocks on targets with many physical registers.
  472. Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
  473. }
  474. Prio |= RC.AllocationPriority << 24;
  475. } else {
  476. // Allocate global and split ranges in long->short order. Long ranges that
  477. // don't fit should be spilled (or split) ASAP so they don't create
  478. // interference. Mark a bit to prioritize global above local ranges.
  479. Prio = (1u << 29) + Size;
  480. }
  481. // Mark a higher bit to prioritize global and local above RS_Split.
  482. Prio |= (1u << 31);
  483. // Boost ranges that have a physical register hint.
  484. if (VRM->hasKnownPreference(Reg))
  485. Prio |= (1u << 30);
  486. }
  487. // The virtual register number is a tie breaker for same-sized ranges.
  488. // Give lower vreg numbers higher priority to assign them first.
  489. CurQueue.push(std::make_pair(Prio, ~Reg));
  490. }
  491. LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
  492. LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
  493. if (CurQueue.empty())
  494. return nullptr;
  495. LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
  496. CurQueue.pop();
  497. return LI;
  498. }
  499. //===----------------------------------------------------------------------===//
  500. // Direct Assignment
  501. //===----------------------------------------------------------------------===//
  502. /// tryAssign - Try to assign VirtReg to an available register.
  503. unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
  504. AllocationOrder &Order,
  505. SmallVectorImpl<unsigned> &NewVRegs) {
  506. Order.rewind();
  507. unsigned PhysReg;
  508. while ((PhysReg = Order.next()))
  509. if (!Matrix->checkInterference(VirtReg, PhysReg))
  510. break;
  511. if (!PhysReg || Order.isHint())
  512. return PhysReg;
  513. // PhysReg is available, but there may be a better choice.
  514. // If we missed a simple hint, try to cheaply evict interference from the
  515. // preferred register.
  516. if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
  517. if (Order.isHint(Hint)) {
  518. DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
  519. EvictionCost MaxCost;
  520. MaxCost.setBrokenHints(1);
  521. if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
  522. evictInterference(VirtReg, Hint, NewVRegs);
  523. return Hint;
  524. }
  525. }
  526. // Try to evict interference from a cheaper alternative.
  527. unsigned Cost = TRI->getCostPerUse(PhysReg);
  528. // Most registers have 0 additional cost.
  529. if (!Cost)
  530. return PhysReg;
  531. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
  532. << '\n');
  533. unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
  534. return CheapReg ? CheapReg : PhysReg;
  535. }
  536. //===----------------------------------------------------------------------===//
  537. // Interference eviction
  538. //===----------------------------------------------------------------------===//
  539. unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
  540. AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
  541. unsigned PhysReg;
  542. while ((PhysReg = Order.next())) {
  543. if (PhysReg == PrevReg)
  544. continue;
  545. MCRegUnitIterator Units(PhysReg, TRI);
  546. for (; Units.isValid(); ++Units) {
  547. // Instantiate a "subquery", not to be confused with the Queries array.
  548. LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
  549. if (subQ.checkInterference())
  550. break;
  551. }
  552. // If no units have interference, break out with the current PhysReg.
  553. if (!Units.isValid())
  554. break;
  555. }
  556. if (PhysReg)
  557. DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
  558. << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
  559. << '\n');
  560. return PhysReg;
  561. }
  562. /// shouldEvict - determine if A should evict the assigned live range B. The
  563. /// eviction policy defined by this function together with the allocation order
  564. /// defined by enqueue() decides which registers ultimately end up being split
  565. /// and spilled.
  566. ///
  567. /// Cascade numbers are used to prevent infinite loops if this function is a
  568. /// cyclic relation.
  569. ///
  570. /// @param A The live range to be assigned.
  571. /// @param IsHint True when A is about to be assigned to its preferred
  572. /// register.
  573. /// @param B The live range to be evicted.
  574. /// @param BreaksHint True when B is already assigned to its preferred register.
  575. bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
  576. LiveInterval &B, bool BreaksHint) {
  577. bool CanSplit = getStage(B) < RS_Spill;
  578. // Be fairly aggressive about following hints as long as the evictee can be
  579. // split.
  580. if (CanSplit && IsHint && !BreaksHint)
  581. return true;
  582. if (A.weight > B.weight) {
  583. DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
  584. return true;
  585. }
  586. return false;
  587. }
  588. /// canEvictInterference - Return true if all interferences between VirtReg and
  589. /// PhysReg can be evicted.
  590. ///
  591. /// @param VirtReg Live range that is about to be assigned.
  592. /// @param PhysReg Desired register for assignment.
  593. /// @param IsHint True when PhysReg is VirtReg's preferred register.
  594. /// @param MaxCost Only look for cheaper candidates and update with new cost
  595. /// when returning true.
  596. /// @returns True when interference can be evicted cheaper than MaxCost.
  597. bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
  598. bool IsHint, EvictionCost &MaxCost) {
  599. // It is only possible to evict virtual register interference.
  600. if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
  601. return false;
  602. bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
  603. // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
  604. // involved in an eviction before. If a cascade number was assigned, deny
  605. // evicting anything with the same or a newer cascade number. This prevents
  606. // infinite eviction loops.
  607. //
  608. // This works out so a register without a cascade number is allowed to evict
  609. // anything, and it can be evicted by anything.
  610. unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
  611. if (!Cascade)
  612. Cascade = NextCascade;
  613. EvictionCost Cost;
  614. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  615. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  616. // If there is 10 or more interferences, chances are one is heavier.
  617. if (Q.collectInterferingVRegs(10) >= 10)
  618. return false;
  619. // Check if any interfering live range is heavier than MaxWeight.
  620. for (unsigned i = Q.interferingVRegs().size(); i; --i) {
  621. LiveInterval *Intf = Q.interferingVRegs()[i - 1];
  622. assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
  623. "Only expecting virtual register interference from query");
  624. // Never evict spill products. They cannot split or spill.
  625. if (getStage(*Intf) == RS_Done)
  626. return false;
  627. // Once a live range becomes small enough, it is urgent that we find a
  628. // register for it. This is indicated by an infinite spill weight. These
  629. // urgent live ranges get to evict almost anything.
  630. //
  631. // Also allow urgent evictions of unspillable ranges from a strictly
  632. // larger allocation order.
  633. bool Urgent = !VirtReg.isSpillable() &&
  634. (Intf->isSpillable() ||
  635. RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
  636. RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
  637. // Only evict older cascades or live ranges without a cascade.
  638. unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
  639. if (Cascade <= IntfCascade) {
  640. if (!Urgent)
  641. return false;
  642. // We permit breaking cascades for urgent evictions. It should be the
  643. // last resort, though, so make it really expensive.
  644. Cost.BrokenHints += 10;
  645. }
  646. // Would this break a satisfied hint?
  647. bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
  648. // Update eviction cost.
  649. Cost.BrokenHints += BreaksHint;
  650. Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
  651. // Abort if this would be too expensive.
  652. if (!(Cost < MaxCost))
  653. return false;
  654. if (Urgent)
  655. continue;
  656. // Apply the eviction policy for non-urgent evictions.
  657. if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
  658. return false;
  659. // If !MaxCost.isMax(), then we're just looking for a cheap register.
  660. // Evicting another local live range in this case could lead to suboptimal
  661. // coloring.
  662. if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
  663. (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
  664. return false;
  665. }
  666. }
  667. }
  668. MaxCost = Cost;
  669. return true;
  670. }
  671. /// evictInterference - Evict any interferring registers that prevent VirtReg
  672. /// from being assigned to Physreg. This assumes that canEvictInterference
  673. /// returned true.
  674. void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
  675. SmallVectorImpl<unsigned> &NewVRegs) {
  676. // Make sure that VirtReg has a cascade number, and assign that cascade
  677. // number to every evicted register. These live ranges than then only be
  678. // evicted by a newer cascade, preventing infinite loops.
  679. unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
  680. if (!Cascade)
  681. Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
  682. DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
  683. << " interference: Cascade " << Cascade << '\n');
  684. // Collect all interfering virtregs first.
  685. SmallVector<LiveInterval*, 8> Intfs;
  686. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  687. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  688. assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
  689. ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
  690. Intfs.append(IVR.begin(), IVR.end());
  691. }
  692. // Evict them second. This will invalidate the queries.
  693. for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
  694. LiveInterval *Intf = Intfs[i];
  695. // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
  696. if (!VRM->hasPhys(Intf->reg))
  697. continue;
  698. Matrix->unassign(*Intf);
  699. assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
  700. VirtReg.isSpillable() < Intf->isSpillable()) &&
  701. "Cannot decrease cascade number, illegal eviction");
  702. ExtraRegInfo[Intf->reg].Cascade = Cascade;
  703. ++NumEvicted;
  704. NewVRegs.push_back(Intf->reg);
  705. }
  706. }
  707. /// Returns true if the given \p PhysReg is a callee saved register and has not
  708. /// been used for allocation yet.
  709. bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
  710. unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
  711. if (CSR == 0)
  712. return false;
  713. return !Matrix->isPhysRegUsed(PhysReg);
  714. }
  715. /// tryEvict - Try to evict all interferences for a physreg.
  716. /// @param VirtReg Currently unassigned virtual register.
  717. /// @param Order Physregs to try.
  718. /// @return Physreg to assign VirtReg, or 0.
  719. unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
  720. AllocationOrder &Order,
  721. SmallVectorImpl<unsigned> &NewVRegs,
  722. unsigned CostPerUseLimit) {
  723. NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
  724. // Keep track of the cheapest interference seen so far.
  725. EvictionCost BestCost;
  726. BestCost.setMax();
  727. unsigned BestPhys = 0;
  728. unsigned OrderLimit = Order.getOrder().size();
  729. // When we are just looking for a reduced cost per use, don't break any
  730. // hints, and only evict smaller spill weights.
  731. if (CostPerUseLimit < ~0u) {
  732. BestCost.BrokenHints = 0;
  733. BestCost.MaxWeight = VirtReg.weight;
  734. // Check of any registers in RC are below CostPerUseLimit.
  735. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
  736. unsigned MinCost = RegClassInfo.getMinCost(RC);
  737. if (MinCost >= CostPerUseLimit) {
  738. DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
  739. << ", no cheaper registers to be found.\n");
  740. return 0;
  741. }
  742. // It is normal for register classes to have a long tail of registers with
  743. // the same cost. We don't need to look at them if they're too expensive.
  744. if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
  745. OrderLimit = RegClassInfo.getLastCostChange(RC);
  746. DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
  747. }
  748. }
  749. Order.rewind();
  750. while (unsigned PhysReg = Order.next(OrderLimit)) {
  751. if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
  752. continue;
  753. // The first use of a callee-saved register in a function has cost 1.
  754. // Don't start using a CSR when the CostPerUseLimit is low.
  755. if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
  756. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
  757. << PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
  758. << '\n');
  759. continue;
  760. }
  761. if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
  762. continue;
  763. // Best so far.
  764. BestPhys = PhysReg;
  765. // Stop if the hint can be used.
  766. if (Order.isHint())
  767. break;
  768. }
  769. if (!BestPhys)
  770. return 0;
  771. evictInterference(VirtReg, BestPhys, NewVRegs);
  772. return BestPhys;
  773. }
  774. //===----------------------------------------------------------------------===//
  775. // Region Splitting
  776. //===----------------------------------------------------------------------===//
  777. /// addSplitConstraints - Fill out the SplitConstraints vector based on the
  778. /// interference pattern in Physreg and its aliases. Add the constraints to
  779. /// SpillPlacement and return the static cost of this split in Cost, assuming
  780. /// that all preferences in SplitConstraints are met.
  781. /// Return false if there are no bundles with positive bias.
  782. bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
  783. BlockFrequency &Cost) {
  784. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  785. // Reset interference dependent info.
  786. SplitConstraints.resize(UseBlocks.size());
  787. BlockFrequency StaticCost = 0;
  788. for (unsigned i = 0; i != UseBlocks.size(); ++i) {
  789. const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
  790. SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
  791. BC.Number = BI.MBB->getNumber();
  792. Intf.moveToBlock(BC.Number);
  793. BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
  794. BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
  795. BC.ChangesValue = BI.FirstDef.isValid();
  796. if (!Intf.hasInterference())
  797. continue;
  798. // Number of spill code instructions to insert.
  799. unsigned Ins = 0;
  800. // Interference for the live-in value.
  801. if (BI.LiveIn) {
  802. if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
  803. BC.Entry = SpillPlacement::MustSpill, ++Ins;
  804. else if (Intf.first() < BI.FirstInstr)
  805. BC.Entry = SpillPlacement::PrefSpill, ++Ins;
  806. else if (Intf.first() < BI.LastInstr)
  807. ++Ins;
  808. }
  809. // Interference for the live-out value.
  810. if (BI.LiveOut) {
  811. if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
  812. BC.Exit = SpillPlacement::MustSpill, ++Ins;
  813. else if (Intf.last() > BI.LastInstr)
  814. BC.Exit = SpillPlacement::PrefSpill, ++Ins;
  815. else if (Intf.last() > BI.FirstInstr)
  816. ++Ins;
  817. }
  818. // Accumulate the total frequency of inserted spill code.
  819. while (Ins--)
  820. StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
  821. }
  822. Cost = StaticCost;
  823. // Add constraints for use-blocks. Note that these are the only constraints
  824. // that may add a positive bias, it is downhill from here.
  825. SpillPlacer->addConstraints(SplitConstraints);
  826. return SpillPlacer->scanActiveBundles();
  827. }
  828. /// addThroughConstraints - Add constraints and links to SpillPlacer from the
  829. /// live-through blocks in Blocks.
  830. void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
  831. ArrayRef<unsigned> Blocks) {
  832. const unsigned GroupSize = 8;
  833. SpillPlacement::BlockConstraint BCS[GroupSize];
  834. unsigned TBS[GroupSize];
  835. unsigned B = 0, T = 0;
  836. for (unsigned i = 0; i != Blocks.size(); ++i) {
  837. unsigned Number = Blocks[i];
  838. Intf.moveToBlock(Number);
  839. if (!Intf.hasInterference()) {
  840. assert(T < GroupSize && "Array overflow");
  841. _Analysis_assume_(T < GroupSize); // This is reset to zero when it reaches GroupSize
  842. TBS[T] = Number;
  843. if (++T == GroupSize) {
  844. SpillPlacer->addLinks(makeArrayRef(TBS, T));
  845. T = 0;
  846. }
  847. continue;
  848. }
  849. assert(B < GroupSize && "Array overflow");
  850. _Analysis_assume_(B < GroupSize); // This is reset to zero when it reaches GroupSize
  851. BCS[B].Number = Number;
  852. // Interference for the live-in value.
  853. if (Intf.first() <= Indexes->getMBBStartIdx(Number))
  854. BCS[B].Entry = SpillPlacement::MustSpill;
  855. else
  856. BCS[B].Entry = SpillPlacement::PrefSpill;
  857. // Interference for the live-out value.
  858. if (Intf.last() >= SA->getLastSplitPoint(Number))
  859. BCS[B].Exit = SpillPlacement::MustSpill;
  860. else
  861. BCS[B].Exit = SpillPlacement::PrefSpill;
  862. if (++B == GroupSize) {
  863. SpillPlacer->addConstraints(makeArrayRef(BCS, B));
  864. B = 0;
  865. }
  866. }
  867. SpillPlacer->addConstraints(makeArrayRef(BCS, B));
  868. SpillPlacer->addLinks(makeArrayRef(TBS, T));
  869. }
  870. void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
  871. // Keep track of through blocks that have not been added to SpillPlacer.
  872. BitVector Todo = SA->getThroughBlocks();
  873. SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
  874. unsigned AddedTo = 0;
  875. #ifndef NDEBUG
  876. unsigned Visited = 0;
  877. #endif
  878. for (;;) {
  879. ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
  880. // Find new through blocks in the periphery of PrefRegBundles.
  881. for (int i = 0, e = NewBundles.size(); i != e; ++i) {
  882. unsigned Bundle = NewBundles[i];
  883. // Look at all blocks connected to Bundle in the full graph.
  884. ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
  885. for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
  886. I != E; ++I) {
  887. unsigned Block = *I;
  888. if (!Todo.test(Block))
  889. continue;
  890. Todo.reset(Block);
  891. // This is a new through block. Add it to SpillPlacer later.
  892. ActiveBlocks.push_back(Block);
  893. #ifndef NDEBUG
  894. ++Visited;
  895. #endif
  896. }
  897. }
  898. // Any new blocks to add?
  899. if (ActiveBlocks.size() == AddedTo)
  900. break;
  901. // Compute through constraints from the interference, or assume that all
  902. // through blocks prefer spilling when forming compact regions.
  903. auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
  904. if (Cand.PhysReg)
  905. addThroughConstraints(Cand.Intf, NewBlocks);
  906. else
  907. // Provide a strong negative bias on through blocks to prevent unwanted
  908. // liveness on loop backedges.
  909. SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
  910. AddedTo = ActiveBlocks.size();
  911. // Perhaps iterating can enable more bundles?
  912. SpillPlacer->iterate();
  913. }
  914. DEBUG(dbgs() << ", v=" << Visited);
  915. }
  916. /// calcCompactRegion - Compute the set of edge bundles that should be live
  917. /// when splitting the current live range into compact regions. Compact
  918. /// regions can be computed without looking at interference. They are the
  919. /// regions formed by removing all the live-through blocks from the live range.
  920. ///
  921. /// Returns false if the current live range is already compact, or if the
  922. /// compact regions would form single block regions anyway.
  923. bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
  924. // Without any through blocks, the live range is already compact.
  925. if (!SA->getNumThroughBlocks())
  926. return false;
  927. // Compact regions don't correspond to any physreg.
  928. Cand.reset(IntfCache, 0);
  929. DEBUG(dbgs() << "Compact region bundles");
  930. // Use the spill placer to determine the live bundles. GrowRegion pretends
  931. // that all the through blocks have interference when PhysReg is unset.
  932. SpillPlacer->prepare(Cand.LiveBundles);
  933. // The static split cost will be zero since Cand.Intf reports no interference.
  934. BlockFrequency Cost;
  935. if (!addSplitConstraints(Cand.Intf, Cost)) {
  936. DEBUG(dbgs() << ", none.\n");
  937. return false;
  938. }
  939. growRegion(Cand);
  940. SpillPlacer->finish();
  941. if (!Cand.LiveBundles.any()) {
  942. DEBUG(dbgs() << ", none.\n");
  943. return false;
  944. }
  945. DEBUG({
  946. for (int i = Cand.LiveBundles.find_first(); i>=0;
  947. i = Cand.LiveBundles.find_next(i))
  948. dbgs() << " EB#" << i;
  949. dbgs() << ".\n";
  950. });
  951. return true;
  952. }
  953. /// calcSpillCost - Compute how expensive it would be to split the live range in
  954. /// SA around all use blocks instead of forming bundle regions.
  955. BlockFrequency RAGreedy::calcSpillCost() {
  956. BlockFrequency Cost = 0;
  957. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  958. for (unsigned i = 0; i != UseBlocks.size(); ++i) {
  959. const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
  960. unsigned Number = BI.MBB->getNumber();
  961. // We normally only need one spill instruction - a load or a store.
  962. Cost += SpillPlacer->getBlockFrequency(Number);
  963. // Unless the value is redefined in the block.
  964. if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
  965. Cost += SpillPlacer->getBlockFrequency(Number);
  966. }
  967. return Cost;
  968. }
  969. /// calcGlobalSplitCost - Return the global split cost of following the split
  970. /// pattern in LiveBundles. This cost should be added to the local cost of the
  971. /// interference pattern in SplitConstraints.
  972. ///
  973. BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
  974. BlockFrequency GlobalCost = 0;
  975. const BitVector &LiveBundles = Cand.LiveBundles;
  976. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  977. for (unsigned i = 0; i != UseBlocks.size(); ++i) {
  978. const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
  979. SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
  980. bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
  981. bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
  982. unsigned Ins = 0;
  983. if (BI.LiveIn)
  984. Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
  985. if (BI.LiveOut)
  986. Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
  987. while (Ins--)
  988. GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
  989. }
  990. for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
  991. unsigned Number = Cand.ActiveBlocks[i];
  992. bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
  993. bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
  994. if (!RegIn && !RegOut)
  995. continue;
  996. if (RegIn && RegOut) {
  997. // We need double spill code if this block has interference.
  998. Cand.Intf.moveToBlock(Number);
  999. if (Cand.Intf.hasInterference()) {
  1000. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  1001. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  1002. }
  1003. continue;
  1004. }
  1005. // live-in / stack-out or stack-in live-out.
  1006. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  1007. }
  1008. return GlobalCost;
  1009. }
  1010. /// splitAroundRegion - Split the current live range around the regions
  1011. /// determined by BundleCand and GlobalCand.
  1012. ///
  1013. /// Before calling this function, GlobalCand and BundleCand must be initialized
  1014. /// so each bundle is assigned to a valid candidate, or NoCand for the
  1015. /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
  1016. /// objects must be initialized for the current live range, and intervals
  1017. /// created for the used candidates.
  1018. ///
  1019. /// @param LREdit The LiveRangeEdit object handling the current split.
  1020. /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
  1021. /// must appear in this list.
  1022. void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
  1023. ArrayRef<unsigned> UsedCands) {
  1024. // These are the intervals created for new global ranges. We may create more
  1025. // intervals for local ranges.
  1026. const unsigned NumGlobalIntvs = LREdit.size();
  1027. DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
  1028. assert(NumGlobalIntvs && "No global intervals configured");
  1029. // Isolate even single instructions when dealing with a proper sub-class.
  1030. // That guarantees register class inflation for the stack interval because it
  1031. // is all copies.
  1032. unsigned Reg = SA->getParent().reg;
  1033. bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
  1034. // First handle all the blocks with uses.
  1035. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  1036. for (unsigned i = 0; i != UseBlocks.size(); ++i) {
  1037. const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
  1038. unsigned Number = BI.MBB->getNumber();
  1039. unsigned IntvIn = 0, IntvOut = 0;
  1040. SlotIndex IntfIn, IntfOut;
  1041. if (BI.LiveIn) {
  1042. unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
  1043. if (CandIn != NoCand) {
  1044. GlobalSplitCandidate &Cand = GlobalCand[CandIn];
  1045. IntvIn = Cand.IntvIdx;
  1046. Cand.Intf.moveToBlock(Number);
  1047. IntfIn = Cand.Intf.first();
  1048. }
  1049. }
  1050. if (BI.LiveOut) {
  1051. unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
  1052. if (CandOut != NoCand) {
  1053. GlobalSplitCandidate &Cand = GlobalCand[CandOut];
  1054. IntvOut = Cand.IntvIdx;
  1055. Cand.Intf.moveToBlock(Number);
  1056. IntfOut = Cand.Intf.last();
  1057. }
  1058. }
  1059. // Create separate intervals for isolated blocks with multiple uses.
  1060. if (!IntvIn && !IntvOut) {
  1061. DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
  1062. if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
  1063. SE->splitSingleBlock(BI);
  1064. continue;
  1065. }
  1066. if (IntvIn && IntvOut)
  1067. SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
  1068. else if (IntvIn)
  1069. SE->splitRegInBlock(BI, IntvIn, IntfIn);
  1070. else
  1071. SE->splitRegOutBlock(BI, IntvOut, IntfOut);
  1072. }
  1073. // Handle live-through blocks. The relevant live-through blocks are stored in
  1074. // the ActiveBlocks list with each candidate. We need to filter out
  1075. // duplicates.
  1076. BitVector Todo = SA->getThroughBlocks();
  1077. for (unsigned c = 0; c != UsedCands.size(); ++c) {
  1078. ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
  1079. for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
  1080. unsigned Number = Blocks[i];
  1081. if (!Todo.test(Number))
  1082. continue;
  1083. Todo.reset(Number);
  1084. unsigned IntvIn = 0, IntvOut = 0;
  1085. SlotIndex IntfIn, IntfOut;
  1086. unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
  1087. if (CandIn != NoCand) {
  1088. GlobalSplitCandidate &Cand = GlobalCand[CandIn];
  1089. IntvIn = Cand.IntvIdx;
  1090. Cand.Intf.moveToBlock(Number);
  1091. IntfIn = Cand.Intf.first();
  1092. }
  1093. unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
  1094. if (CandOut != NoCand) {
  1095. GlobalSplitCandidate &Cand = GlobalCand[CandOut];
  1096. IntvOut = Cand.IntvIdx;
  1097. Cand.Intf.moveToBlock(Number);
  1098. IntfOut = Cand.Intf.last();
  1099. }
  1100. if (!IntvIn && !IntvOut)
  1101. continue;
  1102. SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
  1103. }
  1104. }
  1105. ++NumGlobalSplits;
  1106. SmallVector<unsigned, 8> IntvMap;
  1107. SE->finish(&IntvMap);
  1108. DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
  1109. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  1110. unsigned OrigBlocks = SA->getNumLiveBlocks();
  1111. // Sort out the new intervals created by splitting. We get four kinds:
  1112. // - Remainder intervals should not be split again.
  1113. // - Candidate intervals can be assigned to Cand.PhysReg.
  1114. // - Block-local splits are candidates for local splitting.
  1115. // - DCE leftovers should go back on the queue.
  1116. for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
  1117. LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
  1118. // Ignore old intervals from DCE.
  1119. if (getStage(Reg) != RS_New)
  1120. continue;
  1121. // Remainder interval. Don't try splitting again, spill if it doesn't
  1122. // allocate.
  1123. if (IntvMap[i] == 0) {
  1124. setStage(Reg, RS_Spill);
  1125. continue;
  1126. }
  1127. // Global intervals. Allow repeated splitting as long as the number of live
  1128. // blocks is strictly decreasing.
  1129. if (IntvMap[i] < NumGlobalIntvs) {
  1130. if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
  1131. DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
  1132. << " blocks as original.\n");
  1133. // Don't allow repeated splitting as a safe guard against looping.
  1134. setStage(Reg, RS_Split2);
  1135. }
  1136. continue;
  1137. }
  1138. // Other intervals are treated as new. This includes local intervals created
  1139. // for blocks with multiple uses, and anything created by DCE.
  1140. }
  1141. if (VerifyEnabled)
  1142. MF->verify(this, "After splitting live range around region");
  1143. }
  1144. unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
  1145. SmallVectorImpl<unsigned> &NewVRegs) {
  1146. unsigned NumCands = 0;
  1147. BlockFrequency BestCost;
  1148. // Check if we can split this live range around a compact region.
  1149. bool HasCompact = calcCompactRegion(GlobalCand.front());
  1150. if (HasCompact) {
  1151. // Yes, keep GlobalCand[0] as the compact region candidate.
  1152. NumCands = 1;
  1153. BestCost = BlockFrequency::getMaxFrequency();
  1154. } else {
  1155. // No benefit from the compact region, our fallback will be per-block
  1156. // splitting. Make sure we find a solution that is cheaper than spilling.
  1157. BestCost = calcSpillCost();
  1158. DEBUG(dbgs() << "Cost of isolating all blocks = ";
  1159. MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
  1160. }
  1161. unsigned BestCand =
  1162. calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
  1163. false/*IgnoreCSR*/);
  1164. // No solutions found, fall back to single block splitting.
  1165. if (!HasCompact && BestCand == NoCand)
  1166. return 0;
  1167. return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
  1168. }
  1169. unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
  1170. AllocationOrder &Order,
  1171. BlockFrequency &BestCost,
  1172. unsigned &NumCands,
  1173. bool IgnoreCSR) {
  1174. unsigned BestCand = NoCand;
  1175. Order.rewind();
  1176. while (unsigned PhysReg = Order.next()) {
  1177. if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
  1178. continue;
  1179. // Discard bad candidates before we run out of interference cache cursors.
  1180. // This will only affect register classes with a lot of registers (>32).
  1181. if (NumCands == IntfCache.getMaxCursors()) {
  1182. unsigned WorstCount = ~0u;
  1183. unsigned Worst = 0;
  1184. for (unsigned i = 0; i != NumCands; ++i) {
  1185. if (i == BestCand || !GlobalCand[i].PhysReg)
  1186. continue;
  1187. unsigned Count = GlobalCand[i].LiveBundles.count();
  1188. if (Count < WorstCount)
  1189. Worst = i, WorstCount = Count;
  1190. }
  1191. --NumCands;
  1192. GlobalCand[Worst] = GlobalCand[NumCands];
  1193. if (BestCand == NumCands)
  1194. BestCand = Worst;
  1195. }
  1196. if (GlobalCand.size() <= NumCands)
  1197. GlobalCand.resize(NumCands+1);
  1198. GlobalSplitCandidate &Cand = GlobalCand[NumCands];
  1199. Cand.reset(IntfCache, PhysReg);
  1200. SpillPlacer->prepare(Cand.LiveBundles);
  1201. BlockFrequency Cost;
  1202. if (!addSplitConstraints(Cand.Intf, Cost)) {
  1203. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
  1204. continue;
  1205. }
  1206. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
  1207. MBFI->printBlockFreq(dbgs(), Cost));
  1208. if (Cost >= BestCost) {
  1209. DEBUG({
  1210. if (BestCand == NoCand)
  1211. dbgs() << " worse than no bundles\n";
  1212. else
  1213. dbgs() << " worse than "
  1214. << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
  1215. });
  1216. continue;
  1217. }
  1218. growRegion(Cand);
  1219. SpillPlacer->finish();
  1220. // No live bundles, defer to splitSingleBlocks().
  1221. if (!Cand.LiveBundles.any()) {
  1222. DEBUG(dbgs() << " no bundles.\n");
  1223. continue;
  1224. }
  1225. Cost += calcGlobalSplitCost(Cand);
  1226. DEBUG({
  1227. dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
  1228. << " with bundles";
  1229. for (int i = Cand.LiveBundles.find_first(); i>=0;
  1230. i = Cand.LiveBundles.find_next(i))
  1231. dbgs() << " EB#" << i;
  1232. dbgs() << ".\n";
  1233. });
  1234. if (Cost < BestCost) {
  1235. BestCand = NumCands;
  1236. BestCost = Cost;
  1237. }
  1238. ++NumCands;
  1239. }
  1240. return BestCand;
  1241. }
  1242. unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
  1243. bool HasCompact,
  1244. SmallVectorImpl<unsigned> &NewVRegs) {
  1245. SmallVector<unsigned, 8> UsedCands;
  1246. // Prepare split editor.
  1247. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
  1248. SE->reset(LREdit, SplitSpillMode);
  1249. // Assign all edge bundles to the preferred candidate, or NoCand.
  1250. BundleCand.assign(Bundles->getNumBundles(), NoCand);
  1251. // Assign bundles for the best candidate region.
  1252. if (BestCand != NoCand) {
  1253. GlobalSplitCandidate &Cand = GlobalCand[BestCand];
  1254. if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
  1255. UsedCands.push_back(BestCand);
  1256. Cand.IntvIdx = SE->openIntv();
  1257. DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
  1258. << B << " bundles, intv " << Cand.IntvIdx << ".\n");
  1259. (void)B;
  1260. }
  1261. }
  1262. // Assign bundles for the compact region.
  1263. if (HasCompact) {
  1264. GlobalSplitCandidate &Cand = GlobalCand.front();
  1265. assert(!Cand.PhysReg && "Compact region has no physreg");
  1266. if (unsigned B = Cand.getBundles(BundleCand, 0)) {
  1267. UsedCands.push_back(0);
  1268. Cand.IntvIdx = SE->openIntv();
  1269. DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
  1270. << Cand.IntvIdx << ".\n");
  1271. (void)B;
  1272. }
  1273. }
  1274. splitAroundRegion(LREdit, UsedCands);
  1275. return 0;
  1276. }
  1277. //===----------------------------------------------------------------------===//
  1278. // Per-Block Splitting
  1279. //===----------------------------------------------------------------------===//
  1280. /// tryBlockSplit - Split a global live range around every block with uses. This
  1281. /// creates a lot of local live ranges, that will be split by tryLocalSplit if
  1282. /// they don't allocate.
  1283. unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
  1284. SmallVectorImpl<unsigned> &NewVRegs) {
  1285. assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
  1286. unsigned Reg = VirtReg.reg;
  1287. bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
  1288. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
  1289. SE->reset(LREdit, SplitSpillMode);
  1290. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  1291. for (unsigned i = 0; i != UseBlocks.size(); ++i) {
  1292. const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
  1293. if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
  1294. SE->splitSingleBlock(BI);
  1295. }
  1296. // No blocks were split.
  1297. if (LREdit.empty())
  1298. return 0;
  1299. // We did split for some blocks.
  1300. SmallVector<unsigned, 8> IntvMap;
  1301. SE->finish(&IntvMap);
  1302. // Tell LiveDebugVariables about the new ranges.
  1303. DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
  1304. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  1305. // Sort out the new intervals created by splitting. The remainder interval
  1306. // goes straight to spilling, the new local ranges get to stay RS_New.
  1307. for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
  1308. LiveInterval &LI = LIS->getInterval(LREdit.get(i));
  1309. if (getStage(LI) == RS_New && IntvMap[i] == 0)
  1310. setStage(LI, RS_Spill);
  1311. }
  1312. if (VerifyEnabled)
  1313. MF->verify(this, "After splitting live range around basic blocks");
  1314. return 0;
  1315. }
  1316. //===----------------------------------------------------------------------===//
  1317. // Per-Instruction Splitting
  1318. //===----------------------------------------------------------------------===//
  1319. /// Get the number of allocatable registers that match the constraints of \p Reg
  1320. /// on \p MI and that are also in \p SuperRC.
  1321. static unsigned getNumAllocatableRegsForConstraints(
  1322. const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
  1323. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
  1324. const RegisterClassInfo &RCI) {
  1325. assert(SuperRC && "Invalid register class");
  1326. const TargetRegisterClass *ConstrainedRC =
  1327. MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
  1328. /* ExploreBundle */ true);
  1329. if (!ConstrainedRC)
  1330. return 0;
  1331. return RCI.getNumAllocatableRegs(ConstrainedRC);
  1332. }
  1333. /// tryInstructionSplit - Split a live range around individual instructions.
  1334. /// This is normally not worthwhile since the spiller is doing essentially the
  1335. /// same thing. However, when the live range is in a constrained register
  1336. /// class, it may help to insert copies such that parts of the live range can
  1337. /// be moved to a larger register class.
  1338. ///
  1339. /// This is similar to spilling to a larger register class.
  1340. unsigned
  1341. RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
  1342. SmallVectorImpl<unsigned> &NewVRegs) {
  1343. const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
  1344. // There is no point to this if there are no larger sub-classes.
  1345. if (!RegClassInfo.isProperSubClass(CurRC))
  1346. return 0;
  1347. // Always enable split spill mode, since we're effectively spilling to a
  1348. // register.
  1349. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
  1350. SE->reset(LREdit, SplitEditor::SM_Size);
  1351. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1352. if (Uses.size() <= 1)
  1353. return 0;
  1354. DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
  1355. const TargetRegisterClass *SuperRC =
  1356. TRI->getLargestLegalSuperClass(CurRC, *MF);
  1357. unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
  1358. // Split around every non-copy instruction if this split will relax
  1359. // the constraints on the virtual register.
  1360. // Otherwise, splitting just inserts uncoalescable copies that do not help
  1361. // the allocation.
  1362. for (unsigned i = 0; i != Uses.size(); ++i) {
  1363. if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
  1364. if (MI->isFullCopy() ||
  1365. SuperRCNumAllocatableRegs ==
  1366. getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
  1367. TRI, RCI)) {
  1368. DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
  1369. continue;
  1370. }
  1371. SE->openIntv();
  1372. SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
  1373. SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
  1374. SE->useIntv(SegStart, SegStop);
  1375. }
  1376. if (LREdit.empty()) {
  1377. DEBUG(dbgs() << "All uses were copies.\n");
  1378. return 0;
  1379. }
  1380. SmallVector<unsigned, 8> IntvMap;
  1381. SE->finish(&IntvMap);
  1382. DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
  1383. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  1384. // Assign all new registers to RS_Spill. This was the last chance.
  1385. setStage(LREdit.begin(), LREdit.end(), RS_Spill);
  1386. return 0;
  1387. }
  1388. //===----------------------------------------------------------------------===//
  1389. // Local Splitting
  1390. //===----------------------------------------------------------------------===//
  1391. /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
  1392. /// in order to use PhysReg between two entries in SA->UseSlots.
  1393. ///
  1394. /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
  1395. ///
  1396. void RAGreedy::calcGapWeights(unsigned PhysReg,
  1397. SmallVectorImpl<float> &GapWeight) {
  1398. assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
  1399. const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
  1400. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1401. const unsigned NumGaps = Uses.size()-1;
  1402. // Start and end points for the interference check.
  1403. SlotIndex StartIdx =
  1404. BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
  1405. SlotIndex StopIdx =
  1406. BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
  1407. GapWeight.assign(NumGaps, 0.0f);
  1408. // Add interference from each overlapping register.
  1409. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1410. if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
  1411. .checkInterference())
  1412. continue;
  1413. // We know that VirtReg is a continuous interval from FirstInstr to
  1414. // LastInstr, so we don't need InterferenceQuery.
  1415. //
  1416. // Interference that overlaps an instruction is counted in both gaps
  1417. // surrounding the instruction. The exception is interference before
  1418. // StartIdx and after StopIdx.
  1419. //
  1420. LiveIntervalUnion::SegmentIter IntI =
  1421. Matrix->getLiveUnions()[*Units] .find(StartIdx);
  1422. for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
  1423. // Skip the gaps before IntI.
  1424. while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
  1425. if (++Gap == NumGaps)
  1426. break;
  1427. if (Gap == NumGaps)
  1428. break;
  1429. // Update the gaps covered by IntI.
  1430. const float weight = IntI.value()->weight;
  1431. for (; Gap != NumGaps; ++Gap) {
  1432. GapWeight[Gap] = std::max(GapWeight[Gap], weight);
  1433. if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
  1434. break;
  1435. }
  1436. if (Gap == NumGaps)
  1437. break;
  1438. }
  1439. }
  1440. // Add fixed interference.
  1441. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1442. const LiveRange &LR = LIS->getRegUnit(*Units);
  1443. LiveRange::const_iterator I = LR.find(StartIdx);
  1444. LiveRange::const_iterator E = LR.end();
  1445. // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
  1446. for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
  1447. while (Uses[Gap+1].getBoundaryIndex() < I->start)
  1448. if (++Gap == NumGaps)
  1449. break;
  1450. if (Gap == NumGaps)
  1451. break;
  1452. for (; Gap != NumGaps; ++Gap) {
  1453. GapWeight[Gap] = llvm::huge_valf;
  1454. if (Uses[Gap+1].getBaseIndex() >= I->end)
  1455. break;
  1456. }
  1457. if (Gap == NumGaps)
  1458. break;
  1459. }
  1460. }
  1461. }
  1462. /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
  1463. /// basic block.
  1464. ///
  1465. unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
  1466. SmallVectorImpl<unsigned> &NewVRegs) {
  1467. assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
  1468. const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
  1469. // Note that it is possible to have an interval that is live-in or live-out
  1470. // while only covering a single block - A phi-def can use undef values from
  1471. // predecessors, and the block could be a single-block loop.
  1472. // We don't bother doing anything clever about such a case, we simply assume
  1473. // that the interval is continuous from FirstInstr to LastInstr. We should
  1474. // make sure that we don't do anything illegal to such an interval, though.
  1475. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1476. if (Uses.size() <= 2)
  1477. return 0;
  1478. const unsigned NumGaps = Uses.size()-1;
  1479. DEBUG({
  1480. dbgs() << "tryLocalSplit: ";
  1481. for (unsigned i = 0, e = Uses.size(); i != e; ++i)
  1482. dbgs() << ' ' << Uses[i];
  1483. dbgs() << '\n';
  1484. });
  1485. // If VirtReg is live across any register mask operands, compute a list of
  1486. // gaps with register masks.
  1487. SmallVector<unsigned, 8> RegMaskGaps;
  1488. if (Matrix->checkRegMaskInterference(VirtReg)) {
  1489. // Get regmask slots for the whole block.
  1490. ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
  1491. DEBUG(dbgs() << RMS.size() << " regmasks in block:");
  1492. // Constrain to VirtReg's live range.
  1493. unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
  1494. Uses.front().getRegSlot()) - RMS.begin();
  1495. unsigned re = RMS.size();
  1496. for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
  1497. // Look for Uses[i] <= RMS <= Uses[i+1].
  1498. assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
  1499. if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
  1500. continue;
  1501. // Skip a regmask on the same instruction as the last use. It doesn't
  1502. // overlap the live range.
  1503. if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
  1504. break;
  1505. DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
  1506. RegMaskGaps.push_back(i);
  1507. // Advance ri to the next gap. A regmask on one of the uses counts in
  1508. // both gaps.
  1509. while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
  1510. ++ri;
  1511. }
  1512. DEBUG(dbgs() << '\n');
  1513. }
  1514. // Since we allow local split results to be split again, there is a risk of
  1515. // creating infinite loops. It is tempting to require that the new live
  1516. // ranges have less instructions than the original. That would guarantee
  1517. // convergence, but it is too strict. A live range with 3 instructions can be
  1518. // split 2+3 (including the COPY), and we want to allow that.
  1519. //
  1520. // Instead we use these rules:
  1521. //
  1522. // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
  1523. // noop split, of course).
  1524. // 2. Require progress be made for ranges with getStage() == RS_Split2. All
  1525. // the new ranges must have fewer instructions than before the split.
  1526. // 3. New ranges with the same number of instructions are marked RS_Split2,
  1527. // smaller ranges are marked RS_New.
  1528. //
  1529. // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
  1530. // excessive splitting and infinite loops.
  1531. //
  1532. bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
  1533. // Best split candidate.
  1534. unsigned BestBefore = NumGaps;
  1535. unsigned BestAfter = 0;
  1536. float BestDiff = 0;
  1537. const float blockFreq =
  1538. SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
  1539. (1.0f / MBFI->getEntryFreq());
  1540. SmallVector<float, 8> GapWeight;
  1541. Order.rewind();
  1542. while (unsigned PhysReg = Order.next()) {
  1543. // Keep track of the largest spill weight that would need to be evicted in
  1544. // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
  1545. calcGapWeights(PhysReg, GapWeight);
  1546. // Remove any gaps with regmask clobbers.
  1547. if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
  1548. for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
  1549. GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
  1550. // Try to find the best sequence of gaps to close.
  1551. // The new spill weight must be larger than any gap interference.
  1552. // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
  1553. unsigned SplitBefore = 0, SplitAfter = 1;
  1554. // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
  1555. // It is the spill weight that needs to be evicted.
  1556. float MaxGap = GapWeight[0];
  1557. for (;;) {
  1558. // Live before/after split?
  1559. const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
  1560. const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
  1561. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
  1562. << Uses[SplitBefore] << '-' << Uses[SplitAfter]
  1563. << " i=" << MaxGap);
  1564. // Stop before the interval gets so big we wouldn't be making progress.
  1565. if (!LiveBefore && !LiveAfter) {
  1566. DEBUG(dbgs() << " all\n");
  1567. break;
  1568. }
  1569. // Should the interval be extended or shrunk?
  1570. bool Shrink = true;
  1571. // How many gaps would the new range have?
  1572. unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
  1573. // Legally, without causing looping?
  1574. bool Legal = !ProgressRequired || NewGaps < NumGaps;
  1575. if (Legal && MaxGap < llvm::huge_valf) {
  1576. // Estimate the new spill weight. Each instruction reads or writes the
  1577. // register. Conservatively assume there are no read-modify-write
  1578. // instructions.
  1579. //
  1580. // Try to guess the size of the new interval.
  1581. const float EstWeight = normalizeSpillWeight(
  1582. blockFreq * (NewGaps + 1),
  1583. Uses[SplitBefore].distance(Uses[SplitAfter]) +
  1584. (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
  1585. 1);
  1586. // Would this split be possible to allocate?
  1587. // Never allocate all gaps, we wouldn't be making progress.
  1588. DEBUG(dbgs() << " w=" << EstWeight);
  1589. if (EstWeight * Hysteresis >= MaxGap) {
  1590. Shrink = false;
  1591. float Diff = EstWeight - MaxGap;
  1592. if (Diff > BestDiff) {
  1593. DEBUG(dbgs() << " (best)");
  1594. BestDiff = Hysteresis * Diff;
  1595. BestBefore = SplitBefore;
  1596. BestAfter = SplitAfter;
  1597. }
  1598. }
  1599. }
  1600. // Try to shrink.
  1601. if (Shrink) {
  1602. if (++SplitBefore < SplitAfter) {
  1603. DEBUG(dbgs() << " shrink\n");
  1604. // Recompute the max when necessary.
  1605. if (GapWeight[SplitBefore - 1] >= MaxGap) {
  1606. MaxGap = GapWeight[SplitBefore];
  1607. for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
  1608. MaxGap = std::max(MaxGap, GapWeight[i]);
  1609. }
  1610. continue;
  1611. }
  1612. MaxGap = 0;
  1613. }
  1614. // Try to extend the interval.
  1615. if (SplitAfter >= NumGaps) {
  1616. DEBUG(dbgs() << " end\n");
  1617. break;
  1618. }
  1619. DEBUG(dbgs() << " extend\n");
  1620. MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
  1621. }
  1622. }
  1623. // Didn't find any candidates?
  1624. if (BestBefore == NumGaps)
  1625. return 0;
  1626. DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
  1627. << '-' << Uses[BestAfter] << ", " << BestDiff
  1628. << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
  1629. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
  1630. SE->reset(LREdit);
  1631. SE->openIntv();
  1632. SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
  1633. SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
  1634. SE->useIntv(SegStart, SegStop);
  1635. SmallVector<unsigned, 8> IntvMap;
  1636. SE->finish(&IntvMap);
  1637. DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
  1638. // If the new range has the same number of instructions as before, mark it as
  1639. // RS_Split2 so the next split will be forced to make progress. Otherwise,
  1640. // leave the new intervals as RS_New so they can compete.
  1641. bool LiveBefore = BestBefore != 0 || BI.LiveIn;
  1642. bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
  1643. unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
  1644. if (NewGaps >= NumGaps) {
  1645. DEBUG(dbgs() << "Tagging non-progress ranges: ");
  1646. assert(!ProgressRequired && "Didn't make progress when it was required.");
  1647. for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
  1648. if (IntvMap[i] == 1) {
  1649. setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
  1650. DEBUG(dbgs() << PrintReg(LREdit.get(i)));
  1651. }
  1652. DEBUG(dbgs() << '\n');
  1653. }
  1654. ++NumLocalSplits;
  1655. return 0;
  1656. }
  1657. //===----------------------------------------------------------------------===//
  1658. // Live Range Splitting
  1659. //===----------------------------------------------------------------------===//
  1660. /// trySplit - Try to split VirtReg or one of its interferences, making it
  1661. /// assignable.
  1662. /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
  1663. unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
  1664. SmallVectorImpl<unsigned>&NewVRegs) {
  1665. // Ranges must be Split2 or less.
  1666. if (getStage(VirtReg) >= RS_Spill)
  1667. return 0;
  1668. // Local intervals are handled separately.
  1669. if (LIS->intervalIsInOneMBB(VirtReg)) {
  1670. NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
  1671. SA->analyze(&VirtReg);
  1672. unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
  1673. if (PhysReg || !NewVRegs.empty())
  1674. return PhysReg;
  1675. return tryInstructionSplit(VirtReg, Order, NewVRegs);
  1676. }
  1677. NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
  1678. SA->analyze(&VirtReg);
  1679. // FIXME: SplitAnalysis may repair broken live ranges coming from the
  1680. // coalescer. That may cause the range to become allocatable which means that
  1681. // tryRegionSplit won't be making progress. This check should be replaced with
  1682. // an assertion when the coalescer is fixed.
  1683. if (SA->didRepairRange()) {
  1684. // VirtReg has changed, so all cached queries are invalid.
  1685. Matrix->invalidateVirtRegs();
  1686. if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
  1687. return PhysReg;
  1688. }
  1689. // First try to split around a region spanning multiple blocks. RS_Split2
  1690. // ranges already made dubious progress with region splitting, so they go
  1691. // straight to single block splitting.
  1692. if (getStage(VirtReg) < RS_Split2) {
  1693. unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
  1694. if (PhysReg || !NewVRegs.empty())
  1695. return PhysReg;
  1696. }
  1697. // Then isolate blocks.
  1698. return tryBlockSplit(VirtReg, Order, NewVRegs);
  1699. }
  1700. //===----------------------------------------------------------------------===//
  1701. // Last Chance Recoloring
  1702. //===----------------------------------------------------------------------===//
  1703. /// mayRecolorAllInterferences - Check if the virtual registers that
  1704. /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
  1705. /// recolored to free \p PhysReg.
  1706. /// When true is returned, \p RecoloringCandidates has been augmented with all
  1707. /// the live intervals that need to be recolored in order to free \p PhysReg
  1708. /// for \p VirtReg.
  1709. /// \p FixedRegisters contains all the virtual registers that cannot be
  1710. /// recolored.
  1711. bool
  1712. RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
  1713. SmallLISet &RecoloringCandidates,
  1714. const SmallVirtRegSet &FixedRegisters) {
  1715. const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
  1716. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1717. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  1718. // If there is LastChanceRecoloringMaxInterference or more interferences,
  1719. // chances are one would not be recolorable.
  1720. if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
  1721. LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
  1722. DEBUG(dbgs() << "Early abort: too many interferences.\n");
  1723. CutOffInfo |= CO_Interf;
  1724. return false;
  1725. }
  1726. for (unsigned i = Q.interferingVRegs().size(); i; --i) {
  1727. LiveInterval *Intf = Q.interferingVRegs()[i - 1];
  1728. // If Intf is done and sit on the same register class as VirtReg,
  1729. // it would not be recolorable as it is in the same state as VirtReg.
  1730. if ((getStage(*Intf) == RS_Done &&
  1731. MRI->getRegClass(Intf->reg) == CurRC) ||
  1732. FixedRegisters.count(Intf->reg)) {
  1733. DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
  1734. return false;
  1735. }
  1736. RecoloringCandidates.insert(Intf);
  1737. }
  1738. }
  1739. return true;
  1740. }
  1741. /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
  1742. /// its interferences.
  1743. /// Last chance recoloring chooses a color for \p VirtReg and recolors every
  1744. /// virtual register that was using it. The recoloring process may recursively
  1745. /// use the last chance recoloring. Therefore, when a virtual register has been
  1746. /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
  1747. /// be last-chance-recolored again during this recoloring "session".
  1748. /// E.g.,
  1749. /// Let
  1750. /// vA can use {R1, R2 }
  1751. /// vB can use { R2, R3}
  1752. /// vC can use {R1 }
  1753. /// Where vA, vB, and vC cannot be split anymore (they are reloads for
  1754. /// instance) and they all interfere.
  1755. ///
  1756. /// vA is assigned R1
  1757. /// vB is assigned R2
  1758. /// vC tries to evict vA but vA is already done.
  1759. /// Regular register allocation fails.
  1760. ///
  1761. /// Last chance recoloring kicks in:
  1762. /// vC does as if vA was evicted => vC uses R1.
  1763. /// vC is marked as fixed.
  1764. /// vA needs to find a color.
  1765. /// None are available.
  1766. /// vA cannot evict vC: vC is a fixed virtual register now.
  1767. /// vA does as if vB was evicted => vA uses R2.
  1768. /// vB needs to find a color.
  1769. /// R3 is available.
  1770. /// Recoloring => vC = R1, vA = R2, vB = R3
  1771. ///
  1772. /// \p Order defines the preferred allocation order for \p VirtReg.
  1773. /// \p NewRegs will contain any new virtual register that have been created
  1774. /// (split, spill) during the process and that must be assigned.
  1775. /// \p FixedRegisters contains all the virtual registers that cannot be
  1776. /// recolored.
  1777. /// \p Depth gives the current depth of the last chance recoloring.
  1778. /// \return a physical register that can be used for VirtReg or ~0u if none
  1779. /// exists.
  1780. unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
  1781. AllocationOrder &Order,
  1782. SmallVectorImpl<unsigned> &NewVRegs,
  1783. SmallVirtRegSet &FixedRegisters,
  1784. unsigned Depth) {
  1785. DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
  1786. // Ranges must be Done.
  1787. assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
  1788. "Last chance recoloring should really be last chance");
  1789. // Set the max depth to LastChanceRecoloringMaxDepth.
  1790. // We may want to reconsider that if we end up with a too large search space
  1791. // for target with hundreds of registers.
  1792. // Indeed, in that case we may want to cut the search space earlier.
  1793. if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
  1794. DEBUG(dbgs() << "Abort because max depth has been reached.\n");
  1795. CutOffInfo |= CO_Depth;
  1796. return ~0u;
  1797. }
  1798. // Set of Live intervals that will need to be recolored.
  1799. SmallLISet RecoloringCandidates;
  1800. // Record the original mapping virtual register to physical register in case
  1801. // the recoloring fails.
  1802. DenseMap<unsigned, unsigned> VirtRegToPhysReg;
  1803. // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
  1804. // this recoloring "session".
  1805. FixedRegisters.insert(VirtReg.reg);
  1806. Order.rewind();
  1807. while (unsigned PhysReg = Order.next()) {
  1808. DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
  1809. << PrintReg(PhysReg, TRI) << '\n');
  1810. RecoloringCandidates.clear();
  1811. VirtRegToPhysReg.clear();
  1812. // It is only possible to recolor virtual register interference.
  1813. if (Matrix->checkInterference(VirtReg, PhysReg) >
  1814. LiveRegMatrix::IK_VirtReg) {
  1815. DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
  1816. continue;
  1817. }
  1818. // Early give up on this PhysReg if it is obvious we cannot recolor all
  1819. // the interferences.
  1820. if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
  1821. FixedRegisters)) {
  1822. DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
  1823. continue;
  1824. }
  1825. // RecoloringCandidates contains all the virtual registers that interfer
  1826. // with VirtReg on PhysReg (or one of its aliases).
  1827. // Enqueue them for recoloring and perform the actual recoloring.
  1828. PQueue RecoloringQueue;
  1829. for (SmallLISet::iterator It = RecoloringCandidates.begin(),
  1830. EndIt = RecoloringCandidates.end();
  1831. It != EndIt; ++It) {
  1832. unsigned ItVirtReg = (*It)->reg;
  1833. enqueue(RecoloringQueue, *It);
  1834. assert(VRM->hasPhys(ItVirtReg) &&
  1835. "Interferences are supposed to be with allocated vairables");
  1836. // Record the current allocation.
  1837. VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
  1838. // unset the related struct.
  1839. Matrix->unassign(**It);
  1840. }
  1841. // Do as if VirtReg was assigned to PhysReg so that the underlying
  1842. // recoloring has the right information about the interferes and
  1843. // available colors.
  1844. Matrix->assign(VirtReg, PhysReg);
  1845. // Save the current recoloring state.
  1846. // If we cannot recolor all the interferences, we will have to start again
  1847. // at this point for the next physical register.
  1848. SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
  1849. if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
  1850. Depth)) {
  1851. // Do not mess up with the global assignment process.
  1852. // I.e., VirtReg must be unassigned.
  1853. Matrix->unassign(VirtReg);
  1854. return PhysReg;
  1855. }
  1856. DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
  1857. << PrintReg(PhysReg, TRI) << '\n');
  1858. // The recoloring attempt failed, undo the changes.
  1859. FixedRegisters = SaveFixedRegisters;
  1860. Matrix->unassign(VirtReg);
  1861. for (SmallLISet::iterator It = RecoloringCandidates.begin(),
  1862. EndIt = RecoloringCandidates.end();
  1863. It != EndIt; ++It) {
  1864. unsigned ItVirtReg = (*It)->reg;
  1865. if (VRM->hasPhys(ItVirtReg))
  1866. Matrix->unassign(**It);
  1867. unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
  1868. Matrix->assign(**It, ItPhysReg);
  1869. }
  1870. }
  1871. // Last chance recoloring did not worked either, give up.
  1872. return ~0u;
  1873. }
  1874. /// tryRecoloringCandidates - Try to assign a new color to every register
  1875. /// in \RecoloringQueue.
  1876. /// \p NewRegs will contain any new virtual register created during the
  1877. /// recoloring process.
  1878. /// \p FixedRegisters[in/out] contains all the registers that have been
  1879. /// recolored.
  1880. /// \return true if all virtual registers in RecoloringQueue were successfully
  1881. /// recolored, false otherwise.
  1882. bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
  1883. SmallVectorImpl<unsigned> &NewVRegs,
  1884. SmallVirtRegSet &FixedRegisters,
  1885. unsigned Depth) {
  1886. while (!RecoloringQueue.empty()) {
  1887. LiveInterval *LI = dequeue(RecoloringQueue);
  1888. DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
  1889. unsigned PhysReg;
  1890. PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
  1891. if (PhysReg == ~0u || !PhysReg)
  1892. return false;
  1893. DEBUG(dbgs() << "Recoloring of " << *LI
  1894. << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
  1895. Matrix->assign(*LI, PhysReg);
  1896. FixedRegisters.insert(LI->reg);
  1897. }
  1898. return true;
  1899. }
  1900. //===----------------------------------------------------------------------===//
  1901. // Main Entry Point
  1902. //===----------------------------------------------------------------------===//
  1903. unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
  1904. SmallVectorImpl<unsigned> &NewVRegs) {
  1905. CutOffInfo = CO_None;
  1906. LLVMContext &Ctx = MF->getFunction()->getContext();
  1907. SmallVirtRegSet FixedRegisters;
  1908. unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
  1909. if (Reg == ~0U && (CutOffInfo != CO_None)) {
  1910. uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
  1911. if (CutOffEncountered == CO_Depth)
  1912. Ctx.emitError("register allocation failed: maximum depth for recoloring "
  1913. "reached. Use -fexhaustive-register-search to skip "
  1914. "cutoffs");
  1915. else if (CutOffEncountered == CO_Interf)
  1916. Ctx.emitError("register allocation failed: maximum interference for "
  1917. "recoloring reached. Use -fexhaustive-register-search "
  1918. "to skip cutoffs");
  1919. else if (CutOffEncountered == (CO_Depth | CO_Interf))
  1920. Ctx.emitError("register allocation failed: maximum interference and "
  1921. "depth for recoloring reached. Use "
  1922. "-fexhaustive-register-search to skip cutoffs");
  1923. }
  1924. return Reg;
  1925. }
  1926. /// Using a CSR for the first time has a cost because it causes push|pop
  1927. /// to be added to prologue|epilogue. Splitting a cold section of the live
  1928. /// range can have lower cost than using the CSR for the first time;
  1929. /// Spilling a live range in the cold path can have lower cost than using
  1930. /// the CSR for the first time. Returns the physical register if we decide
  1931. /// to use the CSR; otherwise return 0.
  1932. unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
  1933. AllocationOrder &Order,
  1934. unsigned PhysReg,
  1935. unsigned &CostPerUseLimit,
  1936. SmallVectorImpl<unsigned> &NewVRegs) {
  1937. if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
  1938. // We choose spill over using the CSR for the first time if the spill cost
  1939. // is lower than CSRCost.
  1940. SA->analyze(&VirtReg);
  1941. if (calcSpillCost() >= CSRCost)
  1942. return PhysReg;
  1943. // We are going to spill, set CostPerUseLimit to 1 to make sure that
  1944. // we will not use a callee-saved register in tryEvict.
  1945. CostPerUseLimit = 1;
  1946. return 0;
  1947. }
  1948. if (getStage(VirtReg) < RS_Split) {
  1949. // We choose pre-splitting over using the CSR for the first time if
  1950. // the cost of splitting is lower than CSRCost.
  1951. SA->analyze(&VirtReg);
  1952. unsigned NumCands = 0;
  1953. BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
  1954. unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
  1955. NumCands, true /*IgnoreCSR*/);
  1956. if (BestCand == NoCand)
  1957. // Use the CSR if we can't find a region split below CSRCost.
  1958. return PhysReg;
  1959. // Perform the actual pre-splitting.
  1960. doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
  1961. return 0;
  1962. }
  1963. return PhysReg;
  1964. }
  1965. void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
  1966. // Do not keep invalid information around.
  1967. SetOfBrokenHints.remove(&LI);
  1968. }
  1969. void RAGreedy::initializeCSRCost() {
  1970. // We use the larger one out of the command-line option and the value report
  1971. // by TRI.
  1972. CSRCost = BlockFrequency(
  1973. std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
  1974. if (!CSRCost.getFrequency())
  1975. return;
  1976. // Raw cost is relative to Entry == 2^14; scale it appropriately.
  1977. uint64_t ActualEntry = MBFI->getEntryFreq();
  1978. if (!ActualEntry) {
  1979. CSRCost = 0;
  1980. return;
  1981. }
  1982. uint64_t FixedEntry = 1 << 14;
  1983. if (ActualEntry < FixedEntry)
  1984. CSRCost *= BranchProbability(ActualEntry, FixedEntry);
  1985. else if (ActualEntry <= UINT32_MAX)
  1986. // Invert the fraction and divide.
  1987. CSRCost /= BranchProbability(FixedEntry, ActualEntry);
  1988. else
  1989. // Can't use BranchProbability in general, since it takes 32-bit numbers.
  1990. CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
  1991. }
  1992. /// \brief Collect the hint info for \p Reg.
  1993. /// The results are stored into \p Out.
  1994. /// \p Out is not cleared before being populated.
  1995. void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
  1996. for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
  1997. if (!Instr.isFullCopy())
  1998. continue;
  1999. // Look for the other end of the copy.
  2000. unsigned OtherReg = Instr.getOperand(0).getReg();
  2001. if (OtherReg == Reg) {
  2002. OtherReg = Instr.getOperand(1).getReg();
  2003. if (OtherReg == Reg)
  2004. continue;
  2005. }
  2006. // Get the current assignment.
  2007. unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
  2008. ? OtherReg
  2009. : VRM->getPhys(OtherReg);
  2010. // Push the collected information.
  2011. Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
  2012. OtherPhysReg));
  2013. }
  2014. }
  2015. /// \brief Using the given \p List, compute the cost of the broken hints if
  2016. /// \p PhysReg was used.
  2017. /// \return The cost of \p List for \p PhysReg.
  2018. BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
  2019. unsigned PhysReg) {
  2020. BlockFrequency Cost = 0;
  2021. for (const HintInfo &Info : List) {
  2022. if (Info.PhysReg != PhysReg)
  2023. Cost += Info.Freq;
  2024. }
  2025. return Cost;
  2026. }
  2027. /// \brief Using the register assigned to \p VirtReg, try to recolor
  2028. /// all the live ranges that are copy-related with \p VirtReg.
  2029. /// The recoloring is then propagated to all the live-ranges that have
  2030. /// been recolored and so on, until no more copies can be coalesced or
  2031. /// it is not profitable.
  2032. /// For a given live range, profitability is determined by the sum of the
  2033. /// frequencies of the non-identity copies it would introduce with the old
  2034. /// and new register.
  2035. void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
  2036. // We have a broken hint, check if it is possible to fix it by
  2037. // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
  2038. // some register and PhysReg may be available for the other live-ranges.
  2039. SmallSet<unsigned, 4> Visited;
  2040. SmallVector<unsigned, 2> RecoloringCandidates;
  2041. HintsInfo Info;
  2042. unsigned Reg = VirtReg.reg;
  2043. unsigned PhysReg = VRM->getPhys(Reg);
  2044. // Start the recoloring algorithm from the input live-interval, then
  2045. // it will propagate to the ones that are copy-related with it.
  2046. Visited.insert(Reg);
  2047. RecoloringCandidates.push_back(Reg);
  2048. DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
  2049. << PrintReg(PhysReg, TRI) << ")\n");
  2050. do {
  2051. Reg = RecoloringCandidates.pop_back_val();
  2052. // We cannot recolor physcal register.
  2053. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  2054. continue;
  2055. assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
  2056. // Get the live interval mapped with this virtual register to be able
  2057. // to check for the interference with the new color.
  2058. LiveInterval &LI = LIS->getInterval(Reg);
  2059. unsigned CurrPhys = VRM->getPhys(Reg);
  2060. // Check that the new color matches the register class constraints and
  2061. // that it is free for this live range.
  2062. if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
  2063. Matrix->checkInterference(LI, PhysReg)))
  2064. continue;
  2065. DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
  2066. << ") is recolorable.\n");
  2067. // Gather the hint info.
  2068. Info.clear();
  2069. collectHintInfo(Reg, Info);
  2070. // Check if recoloring the live-range will increase the cost of the
  2071. // non-identity copies.
  2072. if (CurrPhys != PhysReg) {
  2073. DEBUG(dbgs() << "Checking profitability:\n");
  2074. BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
  2075. BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
  2076. DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
  2077. << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
  2078. if (OldCopiesCost < NewCopiesCost) {
  2079. DEBUG(dbgs() << "=> Not profitable.\n");
  2080. continue;
  2081. }
  2082. // At this point, the cost is either cheaper or equal. If it is
  2083. // equal, we consider this is profitable because it may expose
  2084. // more recoloring opportunities.
  2085. DEBUG(dbgs() << "=> Profitable.\n");
  2086. // Recolor the live-range.
  2087. Matrix->unassign(LI);
  2088. Matrix->assign(LI, PhysReg);
  2089. }
  2090. // Push all copy-related live-ranges to keep reconciling the broken
  2091. // hints.
  2092. for (const HintInfo &HI : Info) {
  2093. if (Visited.insert(HI.Reg).second)
  2094. RecoloringCandidates.push_back(HI.Reg);
  2095. }
  2096. } while (!RecoloringCandidates.empty());
  2097. }
  2098. /// \brief Try to recolor broken hints.
  2099. /// Broken hints may be repaired by recoloring when an evicted variable
  2100. /// freed up a register for a larger live-range.
  2101. /// Consider the following example:
  2102. /// BB1:
  2103. /// a =
  2104. /// b =
  2105. /// BB2:
  2106. /// ...
  2107. /// = b
  2108. /// = a
  2109. /// Let us assume b gets split:
  2110. /// BB1:
  2111. /// a =
  2112. /// b =
  2113. /// BB2:
  2114. /// c = b
  2115. /// ...
  2116. /// d = c
  2117. /// = d
  2118. /// = a
  2119. /// Because of how the allocation work, b, c, and d may be assigned different
  2120. /// colors. Now, if a gets evicted later:
  2121. /// BB1:
  2122. /// a =
  2123. /// st a, SpillSlot
  2124. /// b =
  2125. /// BB2:
  2126. /// c = b
  2127. /// ...
  2128. /// d = c
  2129. /// = d
  2130. /// e = ld SpillSlot
  2131. /// = e
  2132. /// This is likely that we can assign the same register for b, c, and d,
  2133. /// getting rid of 2 copies.
  2134. void RAGreedy::tryHintsRecoloring() {
  2135. for (LiveInterval *LI : SetOfBrokenHints) {
  2136. assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
  2137. "Recoloring is possible only for virtual registers");
  2138. // Some dead defs may be around (e.g., because of debug uses).
  2139. // Ignore those.
  2140. if (!VRM->hasPhys(LI->reg))
  2141. continue;
  2142. tryHintRecoloring(*LI);
  2143. }
  2144. }
  2145. unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
  2146. SmallVectorImpl<unsigned> &NewVRegs,
  2147. SmallVirtRegSet &FixedRegisters,
  2148. unsigned Depth) {
  2149. unsigned CostPerUseLimit = ~0u;
  2150. // First try assigning a free register.
  2151. AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
  2152. if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
  2153. // When NewVRegs is not empty, we may have made decisions such as evicting
  2154. // a virtual register, go with the earlier decisions and use the physical
  2155. // register.
  2156. if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
  2157. NewVRegs.empty()) {
  2158. unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
  2159. CostPerUseLimit, NewVRegs);
  2160. if (CSRReg || !NewVRegs.empty())
  2161. // Return now if we decide to use a CSR or create new vregs due to
  2162. // pre-splitting.
  2163. return CSRReg;
  2164. } else
  2165. return PhysReg;
  2166. }
  2167. LiveRangeStage Stage = getStage(VirtReg);
  2168. DEBUG(dbgs() << StageName[Stage]
  2169. << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
  2170. // Try to evict a less worthy live range, but only for ranges from the primary
  2171. // queue. The RS_Split ranges already failed to do this, and they should not
  2172. // get a second chance until they have been split.
  2173. if (Stage != RS_Split)
  2174. if (unsigned PhysReg =
  2175. tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
  2176. unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
  2177. // If VirtReg has a hint and that hint is broken record this
  2178. // virtual register as a recoloring candidate for broken hint.
  2179. // Indeed, since we evicted a variable in its neighborhood it is
  2180. // likely we can at least partially recolor some of the
  2181. // copy-related live-ranges.
  2182. if (Hint && Hint != PhysReg)
  2183. SetOfBrokenHints.insert(&VirtReg);
  2184. return PhysReg;
  2185. }
  2186. assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
  2187. // The first time we see a live range, don't try to split or spill.
  2188. // Wait until the second time, when all smaller ranges have been allocated.
  2189. // This gives a better picture of the interference to split around.
  2190. if (Stage < RS_Split) {
  2191. setStage(VirtReg, RS_Split);
  2192. DEBUG(dbgs() << "wait for second round\n");
  2193. NewVRegs.push_back(VirtReg.reg);
  2194. return 0;
  2195. }
  2196. // If we couldn't allocate a register from spilling, there is probably some
  2197. // invalid inline assembly. The base class wil report it.
  2198. if (Stage >= RS_Done || !VirtReg.isSpillable())
  2199. return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
  2200. Depth);
  2201. // Try splitting VirtReg or interferences.
  2202. unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
  2203. if (PhysReg || !NewVRegs.empty())
  2204. return PhysReg;
  2205. // Finally spill VirtReg itself.
  2206. NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
  2207. LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
  2208. spiller().spill(LRE);
  2209. setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
  2210. if (VerifyEnabled)
  2211. MF->verify(this, "After spilling");
  2212. // The live virtual register requesting allocation was spilled, so tell
  2213. // the caller not to allocate anything during this round.
  2214. return 0;
  2215. }
  2216. bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
  2217. DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
  2218. << "********** Function: " << mf.getName() << '\n');
  2219. MF = &mf;
  2220. TRI = MF->getSubtarget().getRegisterInfo();
  2221. TII = MF->getSubtarget().getInstrInfo();
  2222. RCI.runOnMachineFunction(mf);
  2223. EnableLocalReassign = EnableLocalReassignment ||
  2224. MF->getSubtarget().enableRALocalReassignment(
  2225. MF->getTarget().getOptLevel());
  2226. if (VerifyEnabled)
  2227. MF->verify(this, "Before greedy register allocator");
  2228. RegAllocBase::init(getAnalysis<VirtRegMap>(),
  2229. getAnalysis<LiveIntervals>(),
  2230. getAnalysis<LiveRegMatrix>());
  2231. Indexes = &getAnalysis<SlotIndexes>();
  2232. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  2233. DomTree = &getAnalysis<MachineDominatorTree>();
  2234. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
  2235. Loops = &getAnalysis<MachineLoopInfo>();
  2236. Bundles = &getAnalysis<EdgeBundles>();
  2237. SpillPlacer = &getAnalysis<SpillPlacement>();
  2238. DebugVars = &getAnalysis<LiveDebugVariables>();
  2239. initializeCSRCost();
  2240. calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
  2241. DEBUG(LIS->dump());
  2242. SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
  2243. SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
  2244. ExtraRegInfo.clear();
  2245. ExtraRegInfo.resize(MRI->getNumVirtRegs());
  2246. NextCascade = 1;
  2247. IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
  2248. GlobalCand.resize(32); // This will grow as needed.
  2249. SetOfBrokenHints.clear();
  2250. allocatePhysRegs();
  2251. tryHintsRecoloring();
  2252. releaseMemory();
  2253. return true;
  2254. }