SplitKit.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
  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 contains the SplitAnalysis class as well as mutator functions for
  11. // live range splitting.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "regalloc"
  15. #include "SplitKit.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  18. #include "llvm/CodeGen/LiveRangeEdit.h"
  19. #include "llvm/CodeGen/MachineDominators.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineLoopInfo.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/VirtRegMap.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/Target/TargetInstrInfo.h"
  27. #include "llvm/Target/TargetMachine.h"
  28. using namespace llvm;
  29. STATISTIC(NumFinished, "Number of splits finished");
  30. STATISTIC(NumSimple, "Number of splits that were simple");
  31. STATISTIC(NumCopies, "Number of copies inserted for splitting");
  32. STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
  33. STATISTIC(NumRepairs, "Number of invalid live ranges repaired");
  34. //===----------------------------------------------------------------------===//
  35. // Split Analysis
  36. //===----------------------------------------------------------------------===//
  37. SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm,
  38. const LiveIntervals &lis,
  39. const MachineLoopInfo &mli)
  40. : MF(vrm.getMachineFunction()),
  41. VRM(vrm),
  42. LIS(lis),
  43. Loops(mli),
  44. TII(*MF.getTarget().getInstrInfo()),
  45. CurLI(0),
  46. LastSplitPoint(MF.getNumBlockIDs()) {}
  47. void SplitAnalysis::clear() {
  48. UseSlots.clear();
  49. UseBlocks.clear();
  50. ThroughBlocks.clear();
  51. CurLI = 0;
  52. DidRepairRange = false;
  53. }
  54. SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
  55. const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
  56. const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
  57. std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
  58. SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
  59. // Compute split points on the first call. The pair is independent of the
  60. // current live interval.
  61. if (!LSP.first.isValid()) {
  62. MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
  63. if (FirstTerm == MBB->end())
  64. LSP.first = MBBEnd;
  65. else
  66. LSP.first = LIS.getInstructionIndex(FirstTerm);
  67. // If there is a landing pad successor, also find the call instruction.
  68. if (!LPad)
  69. return LSP.first;
  70. // There may not be a call instruction (?) in which case we ignore LPad.
  71. LSP.second = LSP.first;
  72. for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
  73. I != E;) {
  74. --I;
  75. if (I->isCall()) {
  76. LSP.second = LIS.getInstructionIndex(I);
  77. break;
  78. }
  79. }
  80. }
  81. // If CurLI is live into a landing pad successor, move the last split point
  82. // back to the call that may throw.
  83. if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
  84. return LSP.first;
  85. // Find the value leaving MBB.
  86. const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
  87. if (!VNI)
  88. return LSP.first;
  89. // If the value leaving MBB was defined after the call in MBB, it can't
  90. // really be live-in to the landing pad. This can happen if the landing pad
  91. // has a PHI, and this register is undef on the exceptional edge.
  92. // <rdar://problem/10664933>
  93. if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
  94. return LSP.first;
  95. // Value is properly live-in to the landing pad.
  96. // Only allow splits before the call.
  97. return LSP.second;
  98. }
  99. MachineBasicBlock::iterator
  100. SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
  101. SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
  102. if (LSP == LIS.getMBBEndIdx(MBB))
  103. return MBB->end();
  104. return LIS.getInstructionFromIndex(LSP);
  105. }
  106. /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
  107. void SplitAnalysis::analyzeUses() {
  108. assert(UseSlots.empty() && "Call clear first");
  109. // First get all the defs from the interval values. This provides the correct
  110. // slots for early clobbers.
  111. for (LiveInterval::const_vni_iterator I = CurLI->vni_begin(),
  112. E = CurLI->vni_end(); I != E; ++I)
  113. if (!(*I)->isPHIDef() && !(*I)->isUnused())
  114. UseSlots.push_back((*I)->def);
  115. // Get use slots form the use-def chain.
  116. const MachineRegisterInfo &MRI = MF.getRegInfo();
  117. for (MachineRegisterInfo::use_nodbg_iterator
  118. I = MRI.use_nodbg_begin(CurLI->reg), E = MRI.use_nodbg_end(); I != E;
  119. ++I)
  120. if (!I.getOperand().isUndef())
  121. UseSlots.push_back(LIS.getInstructionIndex(&*I).getRegSlot());
  122. array_pod_sort(UseSlots.begin(), UseSlots.end());
  123. // Remove duplicates, keeping the smaller slot for each instruction.
  124. // That is what we want for early clobbers.
  125. UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
  126. SlotIndex::isSameInstr),
  127. UseSlots.end());
  128. // Compute per-live block info.
  129. if (!calcLiveBlockInfo()) {
  130. // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
  131. // I am looking at you, RegisterCoalescer!
  132. DidRepairRange = true;
  133. ++NumRepairs;
  134. DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
  135. const_cast<LiveIntervals&>(LIS)
  136. .shrinkToUses(const_cast<LiveInterval*>(CurLI));
  137. UseBlocks.clear();
  138. ThroughBlocks.clear();
  139. bool fixed = calcLiveBlockInfo();
  140. (void)fixed;
  141. assert(fixed && "Couldn't fix broken live interval");
  142. }
  143. DEBUG(dbgs() << "Analyze counted "
  144. << UseSlots.size() << " instrs in "
  145. << UseBlocks.size() << " blocks, through "
  146. << NumThroughBlocks << " blocks.\n");
  147. }
  148. /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
  149. /// where CurLI is live.
  150. bool SplitAnalysis::calcLiveBlockInfo() {
  151. ThroughBlocks.resize(MF.getNumBlockIDs());
  152. NumThroughBlocks = NumGapBlocks = 0;
  153. if (CurLI->empty())
  154. return true;
  155. LiveInterval::const_iterator LVI = CurLI->begin();
  156. LiveInterval::const_iterator LVE = CurLI->end();
  157. SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
  158. UseI = UseSlots.begin();
  159. UseE = UseSlots.end();
  160. // Loop over basic blocks where CurLI is live.
  161. MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
  162. for (;;) {
  163. BlockInfo BI;
  164. BI.MBB = MFI;
  165. SlotIndex Start, Stop;
  166. tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  167. // If the block contains no uses, the range must be live through. At one
  168. // point, RegisterCoalescer could create dangling ranges that ended
  169. // mid-block.
  170. if (UseI == UseE || *UseI >= Stop) {
  171. ++NumThroughBlocks;
  172. ThroughBlocks.set(BI.MBB->getNumber());
  173. // The range shouldn't end mid-block if there are no uses. This shouldn't
  174. // happen.
  175. if (LVI->end < Stop)
  176. return false;
  177. } else {
  178. // This block has uses. Find the first and last uses in the block.
  179. BI.FirstInstr = *UseI;
  180. assert(BI.FirstInstr >= Start);
  181. do ++UseI;
  182. while (UseI != UseE && *UseI < Stop);
  183. BI.LastInstr = UseI[-1];
  184. assert(BI.LastInstr < Stop);
  185. // LVI is the first live segment overlapping MBB.
  186. BI.LiveIn = LVI->start <= Start;
  187. // When not live in, the first use should be a def.
  188. if (!BI.LiveIn) {
  189. assert(LVI->start == LVI->valno->def && "Dangling Segment start");
  190. assert(LVI->start == BI.FirstInstr && "First instr should be a def");
  191. BI.FirstDef = BI.FirstInstr;
  192. }
  193. // Look for gaps in the live range.
  194. BI.LiveOut = true;
  195. while (LVI->end < Stop) {
  196. SlotIndex LastStop = LVI->end;
  197. if (++LVI == LVE || LVI->start >= Stop) {
  198. BI.LiveOut = false;
  199. BI.LastInstr = LastStop;
  200. break;
  201. }
  202. if (LastStop < LVI->start) {
  203. // There is a gap in the live range. Create duplicate entries for the
  204. // live-in snippet and the live-out snippet.
  205. ++NumGapBlocks;
  206. // Push the Live-in part.
  207. BI.LiveOut = false;
  208. UseBlocks.push_back(BI);
  209. UseBlocks.back().LastInstr = LastStop;
  210. // Set up BI for the live-out part.
  211. BI.LiveIn = false;
  212. BI.LiveOut = true;
  213. BI.FirstInstr = BI.FirstDef = LVI->start;
  214. }
  215. // A Segment that starts in the middle of the block must be a def.
  216. assert(LVI->start == LVI->valno->def && "Dangling Segment start");
  217. if (!BI.FirstDef)
  218. BI.FirstDef = LVI->start;
  219. }
  220. UseBlocks.push_back(BI);
  221. // LVI is now at LVE or LVI->end >= Stop.
  222. if (LVI == LVE)
  223. break;
  224. }
  225. // Live segment ends exactly at Stop. Move to the next segment.
  226. if (LVI->end == Stop && ++LVI == LVE)
  227. break;
  228. // Pick the next basic block.
  229. if (LVI->start < Stop)
  230. ++MFI;
  231. else
  232. MFI = LIS.getMBBFromIndex(LVI->start);
  233. }
  234. assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
  235. return true;
  236. }
  237. unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
  238. if (cli->empty())
  239. return 0;
  240. LiveInterval *li = const_cast<LiveInterval*>(cli);
  241. LiveInterval::iterator LVI = li->begin();
  242. LiveInterval::iterator LVE = li->end();
  243. unsigned Count = 0;
  244. // Loop over basic blocks where li is live.
  245. MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
  246. SlotIndex Stop = LIS.getMBBEndIdx(MFI);
  247. for (;;) {
  248. ++Count;
  249. LVI = li->advanceTo(LVI, Stop);
  250. if (LVI == LVE)
  251. return Count;
  252. do {
  253. ++MFI;
  254. Stop = LIS.getMBBEndIdx(MFI);
  255. } while (Stop <= LVI->start);
  256. }
  257. }
  258. bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
  259. unsigned OrigReg = VRM.getOriginal(CurLI->reg);
  260. const LiveInterval &Orig = LIS.getInterval(OrigReg);
  261. assert(!Orig.empty() && "Splitting empty interval?");
  262. LiveInterval::const_iterator I = Orig.find(Idx);
  263. // Range containing Idx should begin at Idx.
  264. if (I != Orig.end() && I->start <= Idx)
  265. return I->start == Idx;
  266. // Range does not contain Idx, previous must end at Idx.
  267. return I != Orig.begin() && (--I)->end == Idx;
  268. }
  269. void SplitAnalysis::analyze(const LiveInterval *li) {
  270. clear();
  271. CurLI = li;
  272. analyzeUses();
  273. }
  274. //===----------------------------------------------------------------------===//
  275. // Split Editor
  276. //===----------------------------------------------------------------------===//
  277. /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
  278. SplitEditor::SplitEditor(SplitAnalysis &sa,
  279. LiveIntervals &lis,
  280. VirtRegMap &vrm,
  281. MachineDominatorTree &mdt,
  282. MachineBlockFrequencyInfo &mbfi)
  283. : SA(sa), LIS(lis), VRM(vrm),
  284. MRI(vrm.getMachineFunction().getRegInfo()),
  285. MDT(mdt),
  286. TII(*vrm.getMachineFunction().getTarget().getInstrInfo()),
  287. TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
  288. MBFI(mbfi),
  289. Edit(0),
  290. OpenIdx(0),
  291. SpillMode(SM_Partition),
  292. RegAssign(Allocator)
  293. {}
  294. void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
  295. Edit = &LRE;
  296. SpillMode = SM;
  297. OpenIdx = 0;
  298. RegAssign.clear();
  299. Values.clear();
  300. // Reset the LiveRangeCalc instances needed for this spill mode.
  301. LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
  302. &LIS.getVNInfoAllocator());
  303. if (SpillMode)
  304. LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
  305. &LIS.getVNInfoAllocator());
  306. // We don't need an AliasAnalysis since we will only be performing
  307. // cheap-as-a-copy remats anyway.
  308. Edit->anyRematerializable(0);
  309. }
  310. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  311. void SplitEditor::dump() const {
  312. if (RegAssign.empty()) {
  313. dbgs() << " empty\n";
  314. return;
  315. }
  316. for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
  317. dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
  318. dbgs() << '\n';
  319. }
  320. #endif
  321. VNInfo *SplitEditor::defValue(unsigned RegIdx,
  322. const VNInfo *ParentVNI,
  323. SlotIndex Idx) {
  324. assert(ParentVNI && "Mapping NULL value");
  325. assert(Idx.isValid() && "Invalid SlotIndex");
  326. assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
  327. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  328. // Create a new value.
  329. VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
  330. // Use insert for lookup, so we can add missing values with a second lookup.
  331. std::pair<ValueMap::iterator, bool> InsP =
  332. Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
  333. ValueForcePair(VNI, false)));
  334. // This was the first time (RegIdx, ParentVNI) was mapped.
  335. // Keep it as a simple def without any liveness.
  336. if (InsP.second)
  337. return VNI;
  338. // If the previous value was a simple mapping, add liveness for it now.
  339. if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
  340. SlotIndex Def = OldVNI->def;
  341. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI));
  342. // No longer a simple mapping. Switch to a complex, non-forced mapping.
  343. InsP.first->second = ValueForcePair();
  344. }
  345. // This is a complex mapping, add liveness for VNI
  346. SlotIndex Def = VNI->def;
  347. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
  348. return VNI;
  349. }
  350. void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
  351. assert(ParentVNI && "Mapping NULL value");
  352. ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
  353. VNInfo *VNI = VFP.getPointer();
  354. // ParentVNI was either unmapped or already complex mapped. Either way, just
  355. // set the force bit.
  356. if (!VNI) {
  357. VFP.setInt(true);
  358. return;
  359. }
  360. // This was previously a single mapping. Make sure the old def is represented
  361. // by a trivial live range.
  362. SlotIndex Def = VNI->def;
  363. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  364. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
  365. // Mark as complex mapped, forced.
  366. VFP = ValueForcePair(0, true);
  367. }
  368. VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
  369. VNInfo *ParentVNI,
  370. SlotIndex UseIdx,
  371. MachineBasicBlock &MBB,
  372. MachineBasicBlock::iterator I) {
  373. MachineInstr *CopyMI = 0;
  374. SlotIndex Def;
  375. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  376. // We may be trying to avoid interference that ends at a deleted instruction,
  377. // so always begin RegIdx 0 early and all others late.
  378. bool Late = RegIdx != 0;
  379. // Attempt cheap-as-a-copy rematerialization.
  380. LiveRangeEdit::Remat RM(ParentVNI);
  381. if (Edit->canRematerializeAt(RM, UseIdx, true)) {
  382. Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
  383. ++NumRemats;
  384. } else {
  385. // Can't remat, just insert a copy from parent.
  386. CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
  387. .addReg(Edit->getReg());
  388. Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
  389. .getRegSlot();
  390. ++NumCopies;
  391. }
  392. // Define the value in Reg.
  393. return defValue(RegIdx, ParentVNI, Def);
  394. }
  395. /// Create a new virtual register and live interval.
  396. unsigned SplitEditor::openIntv() {
  397. // Create the complement as index 0.
  398. if (Edit->empty())
  399. Edit->createEmptyInterval();
  400. // Create the open interval.
  401. OpenIdx = Edit->size();
  402. Edit->createEmptyInterval();
  403. return OpenIdx;
  404. }
  405. void SplitEditor::selectIntv(unsigned Idx) {
  406. assert(Idx != 0 && "Cannot select the complement interval");
  407. assert(Idx < Edit->size() && "Can only select previously opened interval");
  408. DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
  409. OpenIdx = Idx;
  410. }
  411. SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
  412. assert(OpenIdx && "openIntv not called before enterIntvBefore");
  413. DEBUG(dbgs() << " enterIntvBefore " << Idx);
  414. Idx = Idx.getBaseIndex();
  415. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  416. if (!ParentVNI) {
  417. DEBUG(dbgs() << ": not live\n");
  418. return Idx;
  419. }
  420. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  421. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  422. assert(MI && "enterIntvBefore called with invalid index");
  423. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
  424. return VNI->def;
  425. }
  426. SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
  427. assert(OpenIdx && "openIntv not called before enterIntvAfter");
  428. DEBUG(dbgs() << " enterIntvAfter " << Idx);
  429. Idx = Idx.getBoundaryIndex();
  430. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  431. if (!ParentVNI) {
  432. DEBUG(dbgs() << ": not live\n");
  433. return Idx;
  434. }
  435. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  436. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  437. assert(MI && "enterIntvAfter called with invalid index");
  438. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
  439. std::next(MachineBasicBlock::iterator(MI)));
  440. return VNI->def;
  441. }
  442. SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
  443. assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
  444. SlotIndex End = LIS.getMBBEndIdx(&MBB);
  445. SlotIndex Last = End.getPrevSlot();
  446. DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
  447. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
  448. if (!ParentVNI) {
  449. DEBUG(dbgs() << ": not live\n");
  450. return End;
  451. }
  452. DEBUG(dbgs() << ": valno " << ParentVNI->id);
  453. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
  454. SA.getLastSplitPointIter(&MBB));
  455. RegAssign.insert(VNI->def, End, OpenIdx);
  456. DEBUG(dump());
  457. return VNI->def;
  458. }
  459. /// useIntv - indicate that all instructions in MBB should use OpenLI.
  460. void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
  461. useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
  462. }
  463. void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
  464. assert(OpenIdx && "openIntv not called before useIntv");
  465. DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
  466. RegAssign.insert(Start, End, OpenIdx);
  467. DEBUG(dump());
  468. }
  469. SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
  470. assert(OpenIdx && "openIntv not called before leaveIntvAfter");
  471. DEBUG(dbgs() << " leaveIntvAfter " << Idx);
  472. // The interval must be live beyond the instruction at Idx.
  473. SlotIndex Boundary = Idx.getBoundaryIndex();
  474. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
  475. if (!ParentVNI) {
  476. DEBUG(dbgs() << ": not live\n");
  477. return Boundary.getNextSlot();
  478. }
  479. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  480. MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
  481. assert(MI && "No instruction at index");
  482. // In spill mode, make live ranges as short as possible by inserting the copy
  483. // before MI. This is only possible if that instruction doesn't redefine the
  484. // value. The inserted COPY is not a kill, and we don't need to recompute
  485. // the source live range. The spiller also won't try to hoist this copy.
  486. if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
  487. MI->readsVirtualRegister(Edit->getReg())) {
  488. forceRecompute(0, ParentVNI);
  489. defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
  490. return Idx;
  491. }
  492. VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
  493. std::next(MachineBasicBlock::iterator(MI)));
  494. return VNI->def;
  495. }
  496. SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
  497. assert(OpenIdx && "openIntv not called before leaveIntvBefore");
  498. DEBUG(dbgs() << " leaveIntvBefore " << Idx);
  499. // The interval must be live into the instruction at Idx.
  500. Idx = Idx.getBaseIndex();
  501. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  502. if (!ParentVNI) {
  503. DEBUG(dbgs() << ": not live\n");
  504. return Idx.getNextSlot();
  505. }
  506. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  507. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  508. assert(MI && "No instruction at index");
  509. VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
  510. return VNI->def;
  511. }
  512. SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
  513. assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
  514. SlotIndex Start = LIS.getMBBStartIdx(&MBB);
  515. DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
  516. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
  517. if (!ParentVNI) {
  518. DEBUG(dbgs() << ": not live\n");
  519. return Start;
  520. }
  521. VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
  522. MBB.SkipPHIsAndLabels(MBB.begin()));
  523. RegAssign.insert(Start, VNI->def, OpenIdx);
  524. DEBUG(dump());
  525. return VNI->def;
  526. }
  527. void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
  528. assert(OpenIdx && "openIntv not called before overlapIntv");
  529. const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
  530. assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
  531. "Parent changes value in extended range");
  532. assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
  533. "Range cannot span basic blocks");
  534. // The complement interval will be extended as needed by LRCalc.extend().
  535. if (ParentVNI)
  536. forceRecompute(0, ParentVNI);
  537. DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
  538. RegAssign.insert(Start, End, OpenIdx);
  539. DEBUG(dump());
  540. }
  541. //===----------------------------------------------------------------------===//
  542. // Spill modes
  543. //===----------------------------------------------------------------------===//
  544. void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
  545. LiveInterval *LI = &LIS.getInterval(Edit->get(0));
  546. DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
  547. RegAssignMap::iterator AssignI;
  548. AssignI.setMap(RegAssign);
  549. for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
  550. VNInfo *VNI = Copies[i];
  551. SlotIndex Def = VNI->def;
  552. MachineInstr *MI = LIS.getInstructionFromIndex(Def);
  553. assert(MI && "No instruction for back-copy");
  554. MachineBasicBlock *MBB = MI->getParent();
  555. MachineBasicBlock::iterator MBBI(MI);
  556. bool AtBegin;
  557. do AtBegin = MBBI == MBB->begin();
  558. while (!AtBegin && (--MBBI)->isDebugValue());
  559. DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
  560. LI->removeValNo(VNI);
  561. LIS.RemoveMachineInstrFromMaps(MI);
  562. MI->eraseFromParent();
  563. // Adjust RegAssign if a register assignment is killed at VNI->def. We
  564. // want to avoid calculating the live range of the source register if
  565. // possible.
  566. AssignI.find(Def.getPrevSlot());
  567. if (!AssignI.valid() || AssignI.start() >= Def)
  568. continue;
  569. // If MI doesn't kill the assigned register, just leave it.
  570. if (AssignI.stop() != Def)
  571. continue;
  572. unsigned RegIdx = AssignI.value();
  573. if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
  574. DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n');
  575. forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
  576. } else {
  577. SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
  578. DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
  579. AssignI.setStop(Kill);
  580. }
  581. }
  582. }
  583. MachineBasicBlock*
  584. SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
  585. MachineBasicBlock *DefMBB) {
  586. if (MBB == DefMBB)
  587. return MBB;
  588. assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
  589. const MachineLoopInfo &Loops = SA.Loops;
  590. const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
  591. MachineDomTreeNode *DefDomNode = MDT[DefMBB];
  592. // Best candidate so far.
  593. MachineBasicBlock *BestMBB = MBB;
  594. unsigned BestDepth = UINT_MAX;
  595. for (;;) {
  596. const MachineLoop *Loop = Loops.getLoopFor(MBB);
  597. // MBB isn't in a loop, it doesn't get any better. All dominators have a
  598. // higher frequency by definition.
  599. if (!Loop) {
  600. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  601. << MBB->getNumber() << " at depth 0\n");
  602. return MBB;
  603. }
  604. // We'll never be able to exit the DefLoop.
  605. if (Loop == DefLoop) {
  606. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  607. << MBB->getNumber() << " in the same loop\n");
  608. return MBB;
  609. }
  610. // Least busy dominator seen so far.
  611. unsigned Depth = Loop->getLoopDepth();
  612. if (Depth < BestDepth) {
  613. BestMBB = MBB;
  614. BestDepth = Depth;
  615. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  616. << MBB->getNumber() << " at depth " << Depth << '\n');
  617. }
  618. // Leave loop by going to the immediate dominator of the loop header.
  619. // This is a bigger stride than simply walking up the dominator tree.
  620. MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
  621. // Too far up the dominator tree?
  622. if (!IDom || !MDT.dominates(DefDomNode, IDom))
  623. return BestMBB;
  624. MBB = IDom->getBlock();
  625. }
  626. }
  627. void SplitEditor::hoistCopiesForSize() {
  628. // Get the complement interval, always RegIdx 0.
  629. LiveInterval *LI = &LIS.getInterval(Edit->get(0));
  630. LiveInterval *Parent = &Edit->getParent();
  631. // Track the nearest common dominator for all back-copies for each ParentVNI,
  632. // indexed by ParentVNI->id.
  633. typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
  634. SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
  635. // Find the nearest common dominator for parent values with multiple
  636. // back-copies. If a single back-copy dominates, put it in DomPair.second.
  637. for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
  638. VI != VE; ++VI) {
  639. VNInfo *VNI = *VI;
  640. if (VNI->isUnused())
  641. continue;
  642. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
  643. assert(ParentVNI && "Parent not live at complement def");
  644. // Don't hoist remats. The complement is probably going to disappear
  645. // completely anyway.
  646. if (Edit->didRematerialize(ParentVNI))
  647. continue;
  648. MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
  649. DomPair &Dom = NearestDom[ParentVNI->id];
  650. // Keep directly defined parent values. This is either a PHI or an
  651. // instruction in the complement range. All other copies of ParentVNI
  652. // should be eliminated.
  653. if (VNI->def == ParentVNI->def) {
  654. DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
  655. Dom = DomPair(ValMBB, VNI->def);
  656. continue;
  657. }
  658. // Skip the singly mapped values. There is nothing to gain from hoisting a
  659. // single back-copy.
  660. if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
  661. DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
  662. continue;
  663. }
  664. if (!Dom.first) {
  665. // First time we see ParentVNI. VNI dominates itself.
  666. Dom = DomPair(ValMBB, VNI->def);
  667. } else if (Dom.first == ValMBB) {
  668. // Two defs in the same block. Pick the earlier def.
  669. if (!Dom.second.isValid() || VNI->def < Dom.second)
  670. Dom.second = VNI->def;
  671. } else {
  672. // Different basic blocks. Check if one dominates.
  673. MachineBasicBlock *Near =
  674. MDT.findNearestCommonDominator(Dom.first, ValMBB);
  675. if (Near == ValMBB)
  676. // Def ValMBB dominates.
  677. Dom = DomPair(ValMBB, VNI->def);
  678. else if (Near != Dom.first)
  679. // None dominate. Hoist to common dominator, need new def.
  680. Dom = DomPair(Near, SlotIndex());
  681. }
  682. DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
  683. << " for parent " << ParentVNI->id << '@' << ParentVNI->def
  684. << " hoist to BB#" << Dom.first->getNumber() << ' '
  685. << Dom.second << '\n');
  686. }
  687. // Insert the hoisted copies.
  688. for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
  689. DomPair &Dom = NearestDom[i];
  690. if (!Dom.first || Dom.second.isValid())
  691. continue;
  692. // This value needs a hoisted copy inserted at the end of Dom.first.
  693. VNInfo *ParentVNI = Parent->getValNumInfo(i);
  694. MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
  695. // Get a less loopy dominator than Dom.first.
  696. Dom.first = findShallowDominator(Dom.first, DefMBB);
  697. SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
  698. Dom.second =
  699. defFromParent(0, ParentVNI, Last, *Dom.first,
  700. SA.getLastSplitPointIter(Dom.first))->def;
  701. }
  702. // Remove redundant back-copies that are now known to be dominated by another
  703. // def with the same value.
  704. SmallVector<VNInfo*, 8> BackCopies;
  705. for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
  706. VI != VE; ++VI) {
  707. VNInfo *VNI = *VI;
  708. if (VNI->isUnused())
  709. continue;
  710. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
  711. const DomPair &Dom = NearestDom[ParentVNI->id];
  712. if (!Dom.first || Dom.second == VNI->def)
  713. continue;
  714. BackCopies.push_back(VNI);
  715. forceRecompute(0, ParentVNI);
  716. }
  717. removeBackCopies(BackCopies);
  718. }
  719. /// transferValues - Transfer all possible values to the new live ranges.
  720. /// Values that were rematerialized are left alone, they need LRCalc.extend().
  721. bool SplitEditor::transferValues() {
  722. bool Skipped = false;
  723. RegAssignMap::const_iterator AssignI = RegAssign.begin();
  724. for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(),
  725. ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) {
  726. DEBUG(dbgs() << " blit " << *ParentI << ':');
  727. VNInfo *ParentVNI = ParentI->valno;
  728. // RegAssign has holes where RegIdx 0 should be used.
  729. SlotIndex Start = ParentI->start;
  730. AssignI.advanceTo(Start);
  731. do {
  732. unsigned RegIdx;
  733. SlotIndex End = ParentI->end;
  734. if (!AssignI.valid()) {
  735. RegIdx = 0;
  736. } else if (AssignI.start() <= Start) {
  737. RegIdx = AssignI.value();
  738. if (AssignI.stop() < End) {
  739. End = AssignI.stop();
  740. ++AssignI;
  741. }
  742. } else {
  743. RegIdx = 0;
  744. End = std::min(End, AssignI.start());
  745. }
  746. // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
  747. DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
  748. LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
  749. // Check for a simply defined value that can be blitted directly.
  750. ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
  751. if (VNInfo *VNI = VFP.getPointer()) {
  752. DEBUG(dbgs() << ':' << VNI->id);
  753. LR.addSegment(LiveInterval::Segment(Start, End, VNI));
  754. Start = End;
  755. continue;
  756. }
  757. // Skip values with forced recomputation.
  758. if (VFP.getInt()) {
  759. DEBUG(dbgs() << "(recalc)");
  760. Skipped = true;
  761. Start = End;
  762. continue;
  763. }
  764. LiveRangeCalc &LRC = getLRCalc(RegIdx);
  765. // This value has multiple defs in RegIdx, but it wasn't rematerialized,
  766. // so the live range is accurate. Add live-in blocks in [Start;End) to the
  767. // LiveInBlocks.
  768. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
  769. SlotIndex BlockStart, BlockEnd;
  770. tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
  771. // The first block may be live-in, or it may have its own def.
  772. if (Start != BlockStart) {
  773. VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
  774. assert(VNI && "Missing def for complex mapped value");
  775. DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
  776. // MBB has its own def. Is it also live-out?
  777. if (BlockEnd <= End)
  778. LRC.setLiveOutValue(MBB, VNI);
  779. // Skip to the next block for live-in.
  780. ++MBB;
  781. BlockStart = BlockEnd;
  782. }
  783. // Handle the live-in blocks covered by [Start;End).
  784. assert(Start <= BlockStart && "Expected live-in block");
  785. while (BlockStart < End) {
  786. DEBUG(dbgs() << ">BB#" << MBB->getNumber());
  787. BlockEnd = LIS.getMBBEndIdx(MBB);
  788. if (BlockStart == ParentVNI->def) {
  789. // This block has the def of a parent PHI, so it isn't live-in.
  790. assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
  791. VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
  792. assert(VNI && "Missing def for complex mapped parent PHI");
  793. if (End >= BlockEnd)
  794. LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
  795. } else {
  796. // This block needs a live-in value. The last block covered may not
  797. // be live-out.
  798. if (End < BlockEnd)
  799. LRC.addLiveInBlock(LR, MDT[MBB], End);
  800. else {
  801. // Live-through, and we don't know the value.
  802. LRC.addLiveInBlock(LR, MDT[MBB]);
  803. LRC.setLiveOutValue(MBB, 0);
  804. }
  805. }
  806. BlockStart = BlockEnd;
  807. ++MBB;
  808. }
  809. Start = End;
  810. } while (Start != ParentI->end);
  811. DEBUG(dbgs() << '\n');
  812. }
  813. LRCalc[0].calculateValues();
  814. if (SpillMode)
  815. LRCalc[1].calculateValues();
  816. return Skipped;
  817. }
  818. void SplitEditor::extendPHIKillRanges() {
  819. // Extend live ranges to be live-out for successor PHI values.
  820. for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
  821. E = Edit->getParent().vni_end(); I != E; ++I) {
  822. const VNInfo *PHIVNI = *I;
  823. if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
  824. continue;
  825. unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
  826. LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
  827. LiveRangeCalc &LRC = getLRCalc(RegIdx);
  828. MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
  829. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  830. PE = MBB->pred_end(); PI != PE; ++PI) {
  831. SlotIndex End = LIS.getMBBEndIdx(*PI);
  832. SlotIndex LastUse = End.getPrevSlot();
  833. // The predecessor may not have a live-out value. That is OK, like an
  834. // undef PHI operand.
  835. if (Edit->getParent().liveAt(LastUse)) {
  836. assert(RegAssign.lookup(LastUse) == RegIdx &&
  837. "Different register assignment in phi predecessor");
  838. LRC.extend(LR, End);
  839. }
  840. }
  841. }
  842. }
  843. /// rewriteAssigned - Rewrite all uses of Edit->getReg().
  844. void SplitEditor::rewriteAssigned(bool ExtendRanges) {
  845. for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
  846. RE = MRI.reg_end(); RI != RE;) {
  847. MachineOperand &MO = RI.getOperand();
  848. MachineInstr *MI = MO.getParent();
  849. ++RI;
  850. // LiveDebugVariables should have handled all DBG_VALUE instructions.
  851. if (MI->isDebugValue()) {
  852. DEBUG(dbgs() << "Zapping " << *MI);
  853. MO.setReg(0);
  854. continue;
  855. }
  856. // <undef> operands don't really read the register, so it doesn't matter
  857. // which register we choose. When the use operand is tied to a def, we must
  858. // use the same register as the def, so just do that always.
  859. SlotIndex Idx = LIS.getInstructionIndex(MI);
  860. if (MO.isDef() || MO.isUndef())
  861. Idx = Idx.getRegSlot(MO.isEarlyClobber());
  862. // Rewrite to the mapped register at Idx.
  863. unsigned RegIdx = RegAssign.lookup(Idx);
  864. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  865. MO.setReg(LI->reg);
  866. DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
  867. << Idx << ':' << RegIdx << '\t' << *MI);
  868. // Extend liveness to Idx if the instruction reads reg.
  869. if (!ExtendRanges || MO.isUndef())
  870. continue;
  871. // Skip instructions that don't read Reg.
  872. if (MO.isDef()) {
  873. if (!MO.getSubReg() && !MO.isEarlyClobber())
  874. continue;
  875. // We may wan't to extend a live range for a partial redef, or for a use
  876. // tied to an early clobber.
  877. Idx = Idx.getPrevSlot();
  878. if (!Edit->getParent().liveAt(Idx))
  879. continue;
  880. } else
  881. Idx = Idx.getRegSlot(true);
  882. getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot());
  883. }
  884. }
  885. void SplitEditor::deleteRematVictims() {
  886. SmallVector<MachineInstr*, 8> Dead;
  887. for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
  888. LiveInterval *LI = &LIS.getInterval(*I);
  889. for (LiveInterval::const_iterator LII = LI->begin(), LIE = LI->end();
  890. LII != LIE; ++LII) {
  891. // Dead defs end at the dead slot.
  892. if (LII->end != LII->valno->def.getDeadSlot())
  893. continue;
  894. MachineInstr *MI = LIS.getInstructionFromIndex(LII->valno->def);
  895. assert(MI && "Missing instruction for dead def");
  896. MI->addRegisterDead(LI->reg, &TRI);
  897. if (!MI->allDefsAreDead())
  898. continue;
  899. DEBUG(dbgs() << "All defs dead: " << *MI);
  900. Dead.push_back(MI);
  901. }
  902. }
  903. if (Dead.empty())
  904. return;
  905. Edit->eliminateDeadDefs(Dead);
  906. }
  907. void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
  908. ++NumFinished;
  909. // At this point, the live intervals in Edit contain VNInfos corresponding to
  910. // the inserted copies.
  911. // Add the original defs from the parent interval.
  912. for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
  913. E = Edit->getParent().vni_end(); I != E; ++I) {
  914. const VNInfo *ParentVNI = *I;
  915. if (ParentVNI->isUnused())
  916. continue;
  917. unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
  918. defValue(RegIdx, ParentVNI, ParentVNI->def);
  919. // Force rematted values to be recomputed everywhere.
  920. // The new live ranges may be truncated.
  921. if (Edit->didRematerialize(ParentVNI))
  922. for (unsigned i = 0, e = Edit->size(); i != e; ++i)
  923. forceRecompute(i, ParentVNI);
  924. }
  925. // Hoist back-copies to the complement interval when in spill mode.
  926. switch (SpillMode) {
  927. case SM_Partition:
  928. // Leave all back-copies as is.
  929. break;
  930. case SM_Size:
  931. hoistCopiesForSize();
  932. break;
  933. case SM_Speed:
  934. llvm_unreachable("Spill mode 'speed' not implemented yet");
  935. }
  936. // Transfer the simply mapped values, check if any are skipped.
  937. bool Skipped = transferValues();
  938. if (Skipped)
  939. extendPHIKillRanges();
  940. else
  941. ++NumSimple;
  942. // Rewrite virtual registers, possibly extending ranges.
  943. rewriteAssigned(Skipped);
  944. // Delete defs that were rematted everywhere.
  945. if (Skipped)
  946. deleteRematVictims();
  947. // Get rid of unused values and set phi-kill flags.
  948. for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) {
  949. LiveInterval &LI = LIS.getInterval(*I);
  950. LI.RenumberValues();
  951. }
  952. // Provide a reverse mapping from original indices to Edit ranges.
  953. if (LRMap) {
  954. LRMap->clear();
  955. for (unsigned i = 0, e = Edit->size(); i != e; ++i)
  956. LRMap->push_back(i);
  957. }
  958. // Now check if any registers were separated into multiple components.
  959. ConnectedVNInfoEqClasses ConEQ(LIS);
  960. for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
  961. // Don't use iterators, they are invalidated by create() below.
  962. LiveInterval *li = &LIS.getInterval(Edit->get(i));
  963. unsigned NumComp = ConEQ.Classify(li);
  964. if (NumComp <= 1)
  965. continue;
  966. DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
  967. SmallVector<LiveInterval*, 8> dups;
  968. dups.push_back(li);
  969. for (unsigned j = 1; j != NumComp; ++j)
  970. dups.push_back(&Edit->createEmptyInterval());
  971. ConEQ.Distribute(&dups[0], MRI);
  972. // The new intervals all map back to i.
  973. if (LRMap)
  974. LRMap->resize(Edit->size(), i);
  975. }
  976. // Calculate spill weight and allocation hints for new intervals.
  977. Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
  978. assert(!LRMap || LRMap->size() == Edit->size());
  979. }
  980. //===----------------------------------------------------------------------===//
  981. // Single Block Splitting
  982. //===----------------------------------------------------------------------===//
  983. bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
  984. bool SingleInstrs) const {
  985. // Always split for multiple instructions.
  986. if (!BI.isOneInstr())
  987. return true;
  988. // Don't split for single instructions unless explicitly requested.
  989. if (!SingleInstrs)
  990. return false;
  991. // Splitting a live-through range always makes progress.
  992. if (BI.LiveIn && BI.LiveOut)
  993. return true;
  994. // No point in isolating a copy. It has no register class constraints.
  995. if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
  996. return false;
  997. // Finally, don't isolate an end point that was created by earlier splits.
  998. return isOriginalEndpoint(BI.FirstInstr);
  999. }
  1000. void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
  1001. openIntv();
  1002. SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
  1003. SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
  1004. LastSplitPoint));
  1005. if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
  1006. useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
  1007. } else {
  1008. // The last use is after the last valid split point.
  1009. SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
  1010. useIntv(SegStart, SegStop);
  1011. overlapIntv(SegStop, BI.LastInstr);
  1012. }
  1013. }
  1014. //===----------------------------------------------------------------------===//
  1015. // Global Live Range Splitting Support
  1016. //===----------------------------------------------------------------------===//
  1017. // These methods support a method of global live range splitting that uses a
  1018. // global algorithm to decide intervals for CFG edges. They will insert split
  1019. // points and color intervals in basic blocks while avoiding interference.
  1020. //
  1021. // Note that splitSingleBlock is also useful for blocks where both CFG edges
  1022. // are on the stack.
  1023. void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
  1024. unsigned IntvIn, SlotIndex LeaveBefore,
  1025. unsigned IntvOut, SlotIndex EnterAfter){
  1026. SlotIndex Start, Stop;
  1027. tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
  1028. DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
  1029. << ") intf " << LeaveBefore << '-' << EnterAfter
  1030. << ", live-through " << IntvIn << " -> " << IntvOut);
  1031. assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
  1032. assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
  1033. assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
  1034. assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
  1035. MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
  1036. if (!IntvOut) {
  1037. DEBUG(dbgs() << ", spill on entry.\n");
  1038. //
  1039. // <<<<<<<<< Possible LeaveBefore interference.
  1040. // |-----------| Live through.
  1041. // -____________ Spill on entry.
  1042. //
  1043. selectIntv(IntvIn);
  1044. SlotIndex Idx = leaveIntvAtTop(*MBB);
  1045. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1046. (void)Idx;
  1047. return;
  1048. }
  1049. if (!IntvIn) {
  1050. DEBUG(dbgs() << ", reload on exit.\n");
  1051. //
  1052. // >>>>>>> Possible EnterAfter interference.
  1053. // |-----------| Live through.
  1054. // ___________-- Reload on exit.
  1055. //
  1056. selectIntv(IntvOut);
  1057. SlotIndex Idx = enterIntvAtEnd(*MBB);
  1058. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1059. (void)Idx;
  1060. return;
  1061. }
  1062. if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
  1063. DEBUG(dbgs() << ", straight through.\n");
  1064. //
  1065. // |-----------| Live through.
  1066. // ------------- Straight through, same intv, no interference.
  1067. //
  1068. selectIntv(IntvOut);
  1069. useIntv(Start, Stop);
  1070. return;
  1071. }
  1072. // We cannot legally insert splits after LSP.
  1073. SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
  1074. assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
  1075. if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
  1076. LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
  1077. DEBUG(dbgs() << ", switch avoiding interference.\n");
  1078. //
  1079. // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
  1080. // |-----------| Live through.
  1081. // ------======= Switch intervals between interference.
  1082. //
  1083. selectIntv(IntvOut);
  1084. SlotIndex Idx;
  1085. if (LeaveBefore && LeaveBefore < LSP) {
  1086. Idx = enterIntvBefore(LeaveBefore);
  1087. useIntv(Idx, Stop);
  1088. } else {
  1089. Idx = enterIntvAtEnd(*MBB);
  1090. }
  1091. selectIntv(IntvIn);
  1092. useIntv(Start, Idx);
  1093. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1094. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1095. return;
  1096. }
  1097. DEBUG(dbgs() << ", create local intv for interference.\n");
  1098. //
  1099. // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
  1100. // |-----------| Live through.
  1101. // ==---------== Switch intervals before/after interference.
  1102. //
  1103. assert(LeaveBefore <= EnterAfter && "Missed case");
  1104. selectIntv(IntvOut);
  1105. SlotIndex Idx = enterIntvAfter(EnterAfter);
  1106. useIntv(Idx, Stop);
  1107. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1108. selectIntv(IntvIn);
  1109. Idx = leaveIntvBefore(LeaveBefore);
  1110. useIntv(Start, Idx);
  1111. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1112. }
  1113. void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
  1114. unsigned IntvIn, SlotIndex LeaveBefore) {
  1115. SlotIndex Start, Stop;
  1116. tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  1117. DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
  1118. << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
  1119. << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
  1120. << (BI.LiveOut ? ", stack-out" : ", killed in block"));
  1121. assert(IntvIn && "Must have register in");
  1122. assert(BI.LiveIn && "Must be live-in");
  1123. assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
  1124. if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
  1125. DEBUG(dbgs() << " before interference.\n");
  1126. //
  1127. // <<< Interference after kill.
  1128. // |---o---x | Killed in block.
  1129. // ========= Use IntvIn everywhere.
  1130. //
  1131. selectIntv(IntvIn);
  1132. useIntv(Start, BI.LastInstr);
  1133. return;
  1134. }
  1135. SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
  1136. if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
  1137. //
  1138. // <<< Possible interference after last use.
  1139. // |---o---o---| Live-out on stack.
  1140. // =========____ Leave IntvIn after last use.
  1141. //
  1142. // < Interference after last use.
  1143. // |---o---o--o| Live-out on stack, late last use.
  1144. // ============ Copy to stack after LSP, overlap IntvIn.
  1145. // \_____ Stack interval is live-out.
  1146. //
  1147. if (BI.LastInstr < LSP) {
  1148. DEBUG(dbgs() << ", spill after last use before interference.\n");
  1149. selectIntv(IntvIn);
  1150. SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
  1151. useIntv(Start, Idx);
  1152. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1153. } else {
  1154. DEBUG(dbgs() << ", spill before last split point.\n");
  1155. selectIntv(IntvIn);
  1156. SlotIndex Idx = leaveIntvBefore(LSP);
  1157. overlapIntv(Idx, BI.LastInstr);
  1158. useIntv(Start, Idx);
  1159. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1160. }
  1161. return;
  1162. }
  1163. // The interference is overlapping somewhere we wanted to use IntvIn. That
  1164. // means we need to create a local interval that can be allocated a
  1165. // different register.
  1166. unsigned LocalIntv = openIntv();
  1167. (void)LocalIntv;
  1168. DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
  1169. if (!BI.LiveOut || BI.LastInstr < LSP) {
  1170. //
  1171. // <<<<<<< Interference overlapping uses.
  1172. // |---o---o---| Live-out on stack.
  1173. // =====----____ Leave IntvIn before interference, then spill.
  1174. //
  1175. SlotIndex To = leaveIntvAfter(BI.LastInstr);
  1176. SlotIndex From = enterIntvBefore(LeaveBefore);
  1177. useIntv(From, To);
  1178. selectIntv(IntvIn);
  1179. useIntv(Start, From);
  1180. assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
  1181. return;
  1182. }
  1183. // <<<<<<< Interference overlapping uses.
  1184. // |---o---o--o| Live-out on stack, late last use.
  1185. // =====------- Copy to stack before LSP, overlap LocalIntv.
  1186. // \_____ Stack interval is live-out.
  1187. //
  1188. SlotIndex To = leaveIntvBefore(LSP);
  1189. overlapIntv(To, BI.LastInstr);
  1190. SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
  1191. useIntv(From, To);
  1192. selectIntv(IntvIn);
  1193. useIntv(Start, From);
  1194. assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
  1195. }
  1196. void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
  1197. unsigned IntvOut, SlotIndex EnterAfter) {
  1198. SlotIndex Start, Stop;
  1199. tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  1200. DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
  1201. << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
  1202. << ", reg-out " << IntvOut << ", enter after " << EnterAfter
  1203. << (BI.LiveIn ? ", stack-in" : ", defined in block"));
  1204. SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
  1205. assert(IntvOut && "Must have register out");
  1206. assert(BI.LiveOut && "Must be live-out");
  1207. assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
  1208. if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
  1209. DEBUG(dbgs() << " after interference.\n");
  1210. //
  1211. // >>>> Interference before def.
  1212. // | o---o---| Defined in block.
  1213. // ========= Use IntvOut everywhere.
  1214. //
  1215. selectIntv(IntvOut);
  1216. useIntv(BI.FirstInstr, Stop);
  1217. return;
  1218. }
  1219. if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
  1220. DEBUG(dbgs() << ", reload after interference.\n");
  1221. //
  1222. // >>>> Interference before def.
  1223. // |---o---o---| Live-through, stack-in.
  1224. // ____========= Enter IntvOut before first use.
  1225. //
  1226. selectIntv(IntvOut);
  1227. SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
  1228. useIntv(Idx, Stop);
  1229. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1230. return;
  1231. }
  1232. // The interference is overlapping somewhere we wanted to use IntvOut. That
  1233. // means we need to create a local interval that can be allocated a
  1234. // different register.
  1235. DEBUG(dbgs() << ", interference overlaps uses.\n");
  1236. //
  1237. // >>>>>>> Interference overlapping uses.
  1238. // |---o---o---| Live-through, stack-in.
  1239. // ____---====== Create local interval for interference range.
  1240. //
  1241. selectIntv(IntvOut);
  1242. SlotIndex Idx = enterIntvAfter(EnterAfter);
  1243. useIntv(Idx, Stop);
  1244. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1245. openIntv();
  1246. SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
  1247. useIntv(From, Idx);
  1248. }