SplitKit.cpp 54 KB

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