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 unsigned NumBlocks = MF->getNumBlockIDs();
34 Seen.resize(NumBlocks);
35 Map.resize(NumBlocks);
39 static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
40 LiveRange &LR, const MachineOperand &MO) {
41 const MachineInstr *MI = MO.getParent();
44 DefIdx = Indexes.getMBBStartIdx(MI->getParent());
46 DefIdx = Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
48 // Create the def in LR. This may find an existing def.
49 LR.createDeadDef(DefIdx, Alloc);
52 void LiveRangeCalc::calculate(LiveInterval &LI) {
53 assert(MRI && Indexes && "call reset() first");
55 // Step 1: Create minimal live segments for every definition of Reg.
56 // Visit all def operands. If the same instruction has multiple defs of Reg,
57 // LR.createDeadDef() will deduplicate.
58 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
59 unsigned Reg = LI.reg;
60 for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
61 unsigned SubReg = MO.getSubReg();
62 if (LI.hasSubRanges() || (SubReg != 0 && MRI->tracksSubRegLiveness())) {
63 unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
64 : MRI->getMaxLaneMaskForVReg(Reg);
66 // If this is the first time we see a subregister def, initialize
67 // subranges by creating a copy of the main range.
68 if (!LI.hasSubRanges() && !LI.empty()) {
69 unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
70 LI.createSubRangeFrom(*Alloc, ClassMask, LI);
73 for (LiveInterval::SubRange &S : LI.subranges()) {
74 // A Mask for subregs common to the existing subrange and current def.
75 unsigned Common = S.LaneMask & Mask;
78 // A Mask for subregs covered by the subrange but not the current def.
79 unsigned LRest = S.LaneMask & ~Mask;
80 LiveInterval::SubRange *CommonRange;
82 // Split current subrange into Common and LRest ranges.
84 CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
86 assert(Common == S.LaneMask);
90 createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
93 // Create a new SubRange for subregs we did not cover yet.
95 LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
97 createDeadDef(*Indexes, *Alloc, *NewRange, MO);
101 // Create the def in the main liverange.
103 createDeadDef(*Indexes, *Alloc, LI, MO);
106 // Step 2: Extend live segments to all uses, constructing SSA form as
108 for (LiveInterval::SubRange &S : LI.subranges()) {
109 extendToUses(S, Reg, S.LaneMask);
111 extendToUses(LI, Reg, ~0u);
115 void LiveRangeCalc::calculate(LiveRange &LR, unsigned Reg, bool IgnoreUses) {
116 assert(MRI && Indexes && "call reset() first");
118 // Step 1: Create minimal live segments for every definition of Reg.
119 // Visit all def operands. If the same instruction has multiple defs of Reg,
120 // LR.createDeadDef() will deduplicate.
121 for (MachineOperand &MO : MRI->def_operands(Reg)) {
122 createDeadDef(*Indexes, *Alloc, LR, MO);
125 // Step 2: Extend live segments to all uses, constructing SSA form as
128 extendToUses(LR, Reg, ~0u);
132 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, unsigned Mask) {
133 unsigned NumBlocks = MF->getNumBlockIDs();
135 Seen.resize(NumBlocks);
136 Map.resize(NumBlocks);
138 // Visit all operands that read Reg. This may include partial defs.
139 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
140 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
141 // Clear all kill flags. They will be reinserted after register allocation
142 // by LiveIntervalAnalysis::addKillFlags().
145 // We are only interested in uses. For the main range this also includes
146 // the reads happening on partial register defs.
147 if (!MO.isUse() && (!MO.readsReg() || Mask != ~0u))
149 unsigned SubReg = MO.getSubReg();
151 unsigned SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
152 // Ignore uses not covering the current subrange.
153 if ((SubRegMask & Mask) == 0)
155 // The create dead-defs logic in calculate() splits subranges as fine as
156 // necessary for all uses, so SubRegMask shouldn't be smaller than Mask.
157 assert((SubRegMask & ~Mask) == 0);
160 // Determine the actual place of the use.
161 const MachineInstr *MI = MO.getParent();
162 unsigned OpNo = (&MO - &MI->getOperand(0));
165 assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
166 // The actual place where a phi operand is used is the end of the pred
167 // MBB. PHI operands are paired: (Reg, PredMBB).
168 UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
170 // Check for early-clobber redefs.
171 bool isEarlyClobber = false;
174 isEarlyClobber = MO.isEarlyClobber();
175 } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
176 // FIXME: This would be a lot easier if tied early-clobber uses also
177 // had an early-clobber flag.
178 isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
180 UseIdx = Indexes->getInstructionIndex(MI).getRegSlot(isEarlyClobber);
183 // MI is reading Reg. We may have visited MI before if it happens to be
184 // reading Reg multiple times. That is OK, extend() is idempotent.
185 extend(LR, UseIdx, Reg);
190 void LiveRangeCalc::updateFromLiveIns() {
191 LiveRangeUpdater Updater;
192 for (const LiveInBlock &I : LiveIn) {
195 MachineBasicBlock *MBB = I.DomNode->getBlock();
196 assert(I.Value && "No live-in value found");
197 SlotIndex Start, End;
198 std::tie(Start, End) = Indexes->getMBBRange(MBB);
200 if (I.Kill.isValid())
201 // Value is killed inside this block.
204 // The value is live-through, update LiveOut as well.
205 // Defer the Domtree lookup until it is needed.
206 assert(Seen.test(MBB->getNumber()));
207 Map[MBB] = LiveOutPair(I.Value, nullptr);
209 Updater.setDest(&I.LR);
210 Updater.add(Start, End, I.Value);
216 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg) {
217 assert(Kill.isValid() && "Invalid SlotIndex");
218 assert(Indexes && "Missing SlotIndexes");
219 assert(DomTree && "Missing dominator tree");
221 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
222 assert(KillMBB && "No MBB at Kill");
224 // Is there a def in the same MBB we can extend?
225 if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
228 // Find the single reaching def, or determine if Kill is jointly dominated by
229 // multiple values, and we may need to create even more phi-defs to preserve
230 // VNInfo SSA form. Perform a search for all predecessor blocks where we
231 // know the dominating VNInfo.
232 if (findReachingDefs(LR, *KillMBB, Kill, PhysReg))
235 // When there were multiple different values, we may need new PHIs.
240 // This function is called by a client after using the low-level API to add
241 // live-out and live-in blocks. The unique value optimization is not
242 // available, SplitEditor::transferValues handles that case directly anyway.
243 void LiveRangeCalc::calculateValues() {
244 assert(Indexes && "Missing SlotIndexes");
245 assert(DomTree && "Missing dominator tree");
251 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
252 SlotIndex Kill, unsigned PhysReg) {
253 unsigned KillMBBNum = KillMBB.getNumber();
255 // Block numbers where LR should be live-in.
256 SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
258 // Remember if we have seen more than one value.
259 bool UniqueVNI = true;
260 VNInfo *TheVNI = nullptr;
262 // Using Seen as a visited set, perform a BFS for all reaching defs.
263 for (unsigned i = 0; i != WorkList.size(); ++i) {
264 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
267 if (MBB->pred_empty()) {
268 MBB->getParent()->verify();
269 llvm_unreachable("Use not jointly dominated by defs.");
272 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
273 !MBB->isLiveIn(PhysReg)) {
274 MBB->getParent()->verify();
275 errs() << "The register needs to be live in to BB#" << MBB->getNumber()
276 << ", but is missing from the live-in list.\n";
277 llvm_unreachable("Invalid global physical register");
281 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
282 PE = MBB->pred_end(); PI != PE; ++PI) {
283 MachineBasicBlock *Pred = *PI;
285 // Is this a known live-out block?
286 if (Seen.test(Pred->getNumber())) {
287 if (VNInfo *VNI = Map[Pred].first) {
288 if (TheVNI && TheVNI != VNI)
295 SlotIndex Start, End;
296 std::tie(Start, End) = Indexes->getMBBRange(Pred);
298 // First time we see Pred. Try to determine the live-out value, but set
299 // it as null if Pred is live-through with an unknown value.
300 VNInfo *VNI = LR.extendInBlock(Start, End);
301 setLiveOutValue(Pred, VNI);
303 if (TheVNI && TheVNI != VNI)
309 // No, we need a live-in value for Pred as well
310 if (Pred != &KillMBB)
311 WorkList.push_back(Pred->getNumber());
313 // Loopback to KillMBB, so value is really live through.
320 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
321 // neither require it. Skip the sorting overhead for small updates.
322 if (WorkList.size() > 4)
323 array_pod_sort(WorkList.begin(), WorkList.end());
325 // If a unique reaching def was found, blit in the live ranges immediately.
327 LiveRangeUpdater Updater(&LR);
328 for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
329 E = WorkList.end(); I != E; ++I) {
330 SlotIndex Start, End;
331 std::tie(Start, End) = Indexes->getMBBRange(*I);
332 // Trim the live range in KillMBB.
333 if (*I == KillMBBNum && Kill.isValid())
336 Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
337 Updater.add(Start, End, TheVNI);
342 // Multiple values were found, so transfer the work list to the LiveIn array
343 // where UpdateSSA will use it as a work list.
344 LiveIn.reserve(WorkList.size());
345 for (SmallVectorImpl<unsigned>::const_iterator
346 I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
347 MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
348 addLiveInBlock(LR, DomTree->getNode(MBB));
350 LiveIn.back().Kill = Kill;
357 // This is essentially the same iterative algorithm that SSAUpdater uses,
358 // except we already have a dominator tree, so we don't have to recompute it.
359 void LiveRangeCalc::updateSSA() {
360 assert(Indexes && "Missing SlotIndexes");
361 assert(DomTree && "Missing dominator tree");
363 // Interate until convergence.
367 // Propagate live-out values down the dominator tree, inserting phi-defs
369 for (LiveInBlock &I : LiveIn) {
370 MachineDomTreeNode *Node = I.DomNode;
371 // Skip block if the live-in value has already been determined.
374 MachineBasicBlock *MBB = Node->getBlock();
375 MachineDomTreeNode *IDom = Node->getIDom();
376 LiveOutPair IDomValue;
378 // We need a live-in value to a block with no immediate dominator?
379 // This is probably an unreachable block that has survived somehow.
380 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
382 // IDom dominates all of our predecessors, but it may not be their
383 // immediate dominator. Check if any of them have live-out values that are
384 // properly dominated by IDom. If so, we need a phi-def here.
386 IDomValue = Map[IDom->getBlock()];
388 // Cache the DomTree node that defined the value.
389 if (IDomValue.first && !IDomValue.second)
390 Map[IDom->getBlock()].second = IDomValue.second =
391 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
393 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
394 PE = MBB->pred_end(); PI != PE; ++PI) {
395 LiveOutPair &Value = Map[*PI];
396 if (!Value.first || Value.first == IDomValue.first)
399 // Cache the DomTree node that defined the value.
402 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
404 // This predecessor is carrying something other than IDomValue.
405 // It could be because IDomValue hasn't propagated yet, or it could be
406 // because MBB is in the dominance frontier of that value.
407 if (DomTree->dominates(IDom, Value.second)) {
414 // The value may be live-through even if Kill is set, as can happen when
415 // we are called from extendRange. In that case LiveOutSeen is true, and
416 // LiveOut indicates a foreign or missing value.
417 LiveOutPair &LOP = Map[MBB];
419 // Create a phi-def if required.
422 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
423 SlotIndex Start, End;
424 std::tie(Start, End) = Indexes->getMBBRange(MBB);
425 LiveRange &LR = I.LR;
426 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
428 // This block is done, we know the final value.
431 // Add liveness since updateFromLiveIns now skips this node.
432 if (I.Kill.isValid())
433 LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
435 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
436 LOP = LiveOutPair(VNI, Node);
438 } else if (IDomValue.first) {
439 // No phi-def here. Remember incoming value.
440 I.Value = IDomValue.first;
442 // If the IDomValue is killed in the block, don't propagate through.
443 if (I.Kill.isValid())
446 // Propagate IDomValue if it isn't killed:
447 // MBB is live-out and doesn't define its own value.
448 if (LOP.first == IDomValue.first)