1 //===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the LiveRangeCalc class.
12 //===----------------------------------------------------------------------===//
14 #include "LiveRangeCalc.h"
15 #include "llvm/CodeGen/MachineDominators.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #define DEBUG_TYPE "regalloc"
22 void LiveRangeCalc::reset(const MachineFunction *mf,
24 MachineDominatorTree *MDT,
25 VNInfo::Allocator *VNIA) {
27 MRI = &MF->getRegInfo();
32 MainLiveOutData.reset(MF->getNumBlockIDs());
37 static SlotIndex getDefIndex(const SlotIndexes &Indexes, const MachineInstr &MI,
39 // PHI defs begin at the basic block start index.
41 return Indexes.getMBBStartIdx(MI.getParent());
43 // Instructions are either normal 'r', or early clobber 'e'.
44 return Indexes.getInstructionIndex(&MI).getRegSlot(EarlyClobber);
47 void LiveRangeCalc::createDeadDefs(LiveInterval &LI) {
48 assert(MRI && Indexes && "call reset() first");
50 // Visit all def operands. If the same instruction has multiple defs of Reg,
51 // LR.createDeadDef() will deduplicate.
52 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
53 unsigned Reg = LI.reg;
54 for (const MachineOperand &MO : MRI->def_operands(Reg)) {
55 const MachineInstr *MI = MO.getParent();
56 SlotIndex Idx = getDefIndex(*Indexes, *MI, MO.isEarlyClobber());
57 unsigned SubReg = MO.getSubReg();
58 if (LI.hasSubRanges() || (SubReg != 0 && MRI->tracksSubRegLiveness())) {
59 unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
60 : MRI->getMaxLaneMaskForVReg(Reg);
62 // If this is the first time we see a subregister def, initialize
63 // subranges by creating a copy of the main range.
64 if (!LI.hasSubRanges() && !LI.empty()) {
65 unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
66 LI.createSubRangeFrom(*Alloc, ClassMask, LI);
69 for (LiveInterval::SubRange &S : LI.subranges()) {
70 // A Mask for subregs common to the existing subrange and current def.
71 unsigned Common = S.LaneMask & Mask;
74 // A Mask for subregs covered by the subrange but not the current def.
75 unsigned LRest = S.LaneMask & ~Mask;
76 LiveInterval::SubRange *CommonRange;
78 // Split current subrange into Common and LRest ranges.
80 CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
82 assert(Common == S.LaneMask);
85 CommonRange->createDeadDef(Idx, *Alloc);
89 LiveInterval::SubRange *SubRange = LI.createSubRange(*Alloc, Mask);
90 SubRange->createDeadDef(Idx, *Alloc);
94 // Create the def in LR. This may find an existing def.
95 LI.createDeadDef(Idx, *Alloc);
100 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
101 assert(MRI && Indexes && "call reset() first");
103 // Visit all def operands. If the same instruction has multiple defs of Reg,
104 // LR.createDeadDef() will deduplicate.
105 for (MachineOperand &MO : MRI->def_operands(Reg)) {
106 const MachineInstr *MI = MO.getParent();
107 SlotIndex Idx = getDefIndex(*Indexes, *MI, MO.isEarlyClobber());
108 // Create the def in LR. This may find an existing def.
109 LR.createDeadDef(Idx, *Alloc);
114 static SlotIndex getUseIndex(const SlotIndexes &Indexes,
115 const MachineOperand &MO) {
116 const MachineInstr *MI = MO.getParent();
117 unsigned OpNo = (&MO - &MI->getOperand(0));
119 assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
120 // The actual place where a phi operand is used is the end of the pred MBB.
121 // PHI operands are paired: (Reg, PredMBB).
122 return Indexes.getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
125 // Check for early-clobber redefs.
126 bool isEarlyClobber = false;
129 isEarlyClobber = MO.isEarlyClobber();
130 } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
131 // FIXME: This would be a lot easier if tied early-clobber uses also
132 // had an early-clobber flag.
133 isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
135 return Indexes.getInstructionIndex(MI).getRegSlot(isEarlyClobber);
139 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg) {
140 assert(MRI && Indexes && "call reset() first");
142 // Visit all operands that read Reg. This may include partial defs.
143 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
144 // Clear all kill flags. They will be reinserted after register allocation
145 // by LiveIntervalAnalysis::addKillFlags().
150 // MI is reading Reg. We may have visited MI before if it happens to be
151 // reading Reg multiple times. That is OK, extend() is idempotent.
152 SlotIndex Idx = getUseIndex(*Indexes, MO);
153 extend(LR, Idx, Reg, MainLiveOutData);
158 void LiveRangeCalc::extendToUses(LiveInterval &LI) {
159 assert(MRI && Indexes && "call reset() first");
161 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
162 SmallVector<LiveOutData,2> LiveOuts;
163 unsigned NumSubRanges = 0;
164 for (const auto &S : LI.subranges()) {
167 LiveOuts.push_back(LiveOutData());
168 LiveOuts.back().reset(MF->getNumBlockIDs());
171 // Visit all operands that read Reg. This may include partial defs.
172 unsigned Reg = LI.reg;
173 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
174 // Clear all kill flags. They will be reinserted after register allocation
175 // by LiveIntervalAnalysis::addKillFlags().
180 SlotIndex Idx = getUseIndex(*Indexes, MO);
181 unsigned SubReg = MO.getSubReg();
182 if (MO.isUse() && (LI.hasSubRanges() ||
183 (MRI->tracksSubRegLiveness() && SubReg != 0))) {
184 unsigned Mask = SubReg != 0
185 ? TRI.getSubRegIndexLaneMask(SubReg)
186 : MRI->getMaxLaneMaskForVReg(Reg);
188 // If this is the first time we see a subregister def/use. Initialize
189 // subranges by creating a copy of the main range.
190 if (!LI.hasSubRanges()) {
191 unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
192 LI.createSubRangeFrom(*Alloc, ClassMask, LI);
193 LiveOuts.insert(LiveOuts.begin(), LiveOutData());
194 LiveOuts.front().reset(MF->getNumBlockIDs());
197 unsigned SubRangeIdx = 0;
198 for (LiveInterval::subrange_iterator S = LI.subrange_begin(),
199 SE = LI.subrange_end(); S != SE; ++S, ++SubRangeIdx) {
200 // A Mask for subregs common to the existing subrange and current def.
201 unsigned Common = S->LaneMask & Mask;
204 // A Mask for subregs covered by the subrange but not the current def.
205 unsigned LRest = S->LaneMask & ~Mask;
206 LiveInterval::SubRange *CommonRange;
207 unsigned CommonRangeIdx;
209 // Split current subrange into Common and LRest ranges.
211 CommonRange = LI.createSubRangeFrom(*Alloc, Common, *S);
213 LiveOuts.insert(LiveOuts.begin(), LiveOutData());
214 LiveOuts.front().reset(MF->getNumBlockIDs());
218 // The subrange and current def lanemasks match completely.
219 assert(Common == S->LaneMask);
221 CommonRangeIdx = SubRangeIdx;
223 extend(*CommonRange, Idx, Reg, LiveOuts[CommonRangeIdx]);
226 assert(SubRangeIdx == NumSubRanges);
228 extend(LI, Idx, Reg, MainLiveOutData);
233 void LiveRangeCalc::updateFromLiveIns(LiveOutData &LiveOuts) {
234 LiveRangeUpdater Updater;
235 for (const LiveInBlock &I : LiveIn) {
238 MachineBasicBlock *MBB = I.DomNode->getBlock();
239 assert(I.Value && "No live-in value found");
240 SlotIndex Start, End;
241 std::tie(Start, End) = Indexes->getMBBRange(MBB);
243 if (I.Kill.isValid())
244 // Value is killed inside this block.
247 // The value is live-through, update LiveOut as well.
248 // Defer the Domtree lookup until it is needed.
249 assert(LiveOuts.Seen.test(MBB->getNumber()));
250 LiveOuts.Map[MBB] = LiveOutPair(I.Value, nullptr);
252 Updater.setDest(&I.LR);
253 Updater.add(Start, End, I.Value);
259 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg,
260 LiveOutData &LiveOuts) {
261 assert(Kill.isValid() && "Invalid SlotIndex");
262 assert(Indexes && "Missing SlotIndexes");
263 assert(DomTree && "Missing dominator tree");
265 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
266 assert(KillMBB && "No MBB at Kill");
268 // Is there a def in the same MBB we can extend?
269 if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
272 // Find the single reaching def, or determine if Kill is jointly dominated by
273 // multiple values, and we may need to create even more phi-defs to preserve
274 // VNInfo SSA form. Perform a search for all predecessor blocks where we
275 // know the dominating VNInfo.
276 if (findReachingDefs(LR, *KillMBB, Kill, PhysReg, LiveOuts))
279 // When there were multiple different values, we may need new PHIs.
280 calculateValues(LiveOuts);
284 // This function is called by a client after using the low-level API to add
285 // live-out and live-in blocks. The unique value optimization is not
286 // available, SplitEditor::transferValues handles that case directly anyway.
287 void LiveRangeCalc::calculateValues(LiveOutData &LiveOuts) {
288 assert(Indexes && "Missing SlotIndexes");
289 assert(DomTree && "Missing dominator tree");
291 updateFromLiveIns(LiveOuts);
295 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
296 SlotIndex Kill, unsigned PhysReg,
297 LiveOutData &LiveOuts) {
298 unsigned KillMBBNum = KillMBB.getNumber();
300 // Block numbers where LR should be live-in.
301 SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
303 // Remember if we have seen more than one value.
304 bool UniqueVNI = true;
305 VNInfo *TheVNI = nullptr;
307 // Using Seen as a visited set, perform a BFS for all reaching defs.
308 for (unsigned i = 0; i != WorkList.size(); ++i) {
309 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
312 if (MBB->pred_empty()) {
313 MBB->getParent()->verify();
314 llvm_unreachable("Use not jointly dominated by defs.");
317 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
318 !MBB->isLiveIn(PhysReg)) {
319 MBB->getParent()->verify();
320 errs() << "The register needs to be live in to BB#" << MBB->getNumber()
321 << ", but is missing from the live-in list.\n";
322 llvm_unreachable("Invalid global physical register");
326 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
327 PE = MBB->pred_end(); PI != PE; ++PI) {
328 MachineBasicBlock *Pred = *PI;
330 // Is this a known live-out block?
331 if (LiveOuts.Seen.test(Pred->getNumber())) {
332 if (VNInfo *VNI = LiveOuts.Map[Pred].first) {
333 if (TheVNI && TheVNI != VNI)
340 SlotIndex Start, End;
341 std::tie(Start, End) = Indexes->getMBBRange(Pred);
343 // First time we see Pred. Try to determine the live-out value, but set
344 // it as null if Pred is live-through with an unknown value.
345 VNInfo *VNI = LR.extendInBlock(Start, End);
346 LiveOuts.setLiveOutValue(Pred, VNI);
348 if (TheVNI && TheVNI != VNI)
354 // No, we need a live-in value for Pred as well
355 if (Pred != &KillMBB)
356 WorkList.push_back(Pred->getNumber());
358 // Loopback to KillMBB, so value is really live through.
365 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
366 // neither require it. Skip the sorting overhead for small updates.
367 if (WorkList.size() > 4)
368 array_pod_sort(WorkList.begin(), WorkList.end());
370 // If a unique reaching def was found, blit in the live ranges immediately.
372 LiveRangeUpdater Updater(&LR);
373 for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
374 E = WorkList.end(); I != E; ++I) {
375 SlotIndex Start, End;
376 std::tie(Start, End) = Indexes->getMBBRange(*I);
377 // Trim the live range in KillMBB.
378 if (*I == KillMBBNum && Kill.isValid())
381 LiveOuts.Map[MF->getBlockNumbered(*I)] =
382 LiveOutPair(TheVNI, nullptr);
383 Updater.add(Start, End, TheVNI);
388 // Multiple values were found, so transfer the work list to the LiveIn array
389 // where UpdateSSA will use it as a work list.
390 LiveIn.reserve(WorkList.size());
391 for (SmallVectorImpl<unsigned>::const_iterator
392 I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
393 MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
394 addLiveInBlock(LR, DomTree->getNode(MBB));
396 LiveIn.back().Kill = Kill;
403 // This is essentially the same iterative algorithm that SSAUpdater uses,
404 // except we already have a dominator tree, so we don't have to recompute it.
405 void LiveRangeCalc::updateSSA(LiveOutData &LiveOuts) {
406 assert(Indexes && "Missing SlotIndexes");
407 assert(DomTree && "Missing dominator tree");
409 // Interate until convergence.
413 // Propagate live-out values down the dominator tree, inserting phi-defs
415 for (LiveInBlock &I : LiveIn) {
416 MachineDomTreeNode *Node = I.DomNode;
417 // Skip block if the live-in value has already been determined.
420 MachineBasicBlock *MBB = Node->getBlock();
421 MachineDomTreeNode *IDom = Node->getIDom();
422 LiveOutPair IDomValue;
424 // We need a live-in value to a block with no immediate dominator?
425 // This is probably an unreachable block that has survived somehow.
427 || !LiveOuts.Seen.test(IDom->getBlock()->getNumber());
429 // IDom dominates all of our predecessors, but it may not be their
430 // immediate dominator. Check if any of them have live-out values that are
431 // properly dominated by IDom. If so, we need a phi-def here.
433 IDomValue = LiveOuts.Map[IDom->getBlock()];
435 // Cache the DomTree node that defined the value.
436 if (IDomValue.first && !IDomValue.second)
437 LiveOuts.Map[IDom->getBlock()].second = IDomValue.second =
438 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
440 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
441 PE = MBB->pred_end(); PI != PE; ++PI) {
442 LiveOutPair &Value = LiveOuts.Map[*PI];
443 if (!Value.first || Value.first == IDomValue.first)
446 // Cache the DomTree node that defined the value.
449 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
451 // This predecessor is carrying something other than IDomValue.
452 // It could be because IDomValue hasn't propagated yet, or it could be
453 // because MBB is in the dominance frontier of that value.
454 if (DomTree->dominates(IDom, Value.second)) {
461 // The value may be live-through even if Kill is set, as can happen when
462 // we are called from extendRange. In that case LiveOutSeen is true, and
463 // LiveOut indicates a foreign or missing value.
464 LiveOutPair &LOP = LiveOuts.Map[MBB];
466 // Create a phi-def if required.
469 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
470 SlotIndex Start, End;
471 std::tie(Start, End) = Indexes->getMBBRange(MBB);
472 LiveRange &LR = I.LR;
473 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
475 // This block is done, we know the final value.
478 // Add liveness since updateFromLiveIns now skips this node.
479 if (I.Kill.isValid())
480 LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
482 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
483 LOP = LiveOutPair(VNI, Node);
485 } else if (IDomValue.first) {
486 // No phi-def here. Remember incoming value.
487 I.Value = IDomValue.first;
489 // If the IDomValue is killed in the block, don't propagate through.
490 if (I.Kill.isValid())
493 // Propagate IDomValue if it isn't killed:
494 // MBB is live-out and doesn't define its own value.
495 if (LOP.first == IDomValue.first)