LiveIntervalAnalysis: Compute subregister ranges.
[oota-llvm.git] / lib / CodeGen / LiveRangeCalc.cpp
1 //===---- LiveRangeCalc.cpp - Calculate 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 // Implementation of the LiveRangeCalc class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LiveRangeCalc.h"
15 #include "llvm/CodeGen/MachineDominators.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17
18 using namespace llvm;
19
20 #define DEBUG_TYPE "regalloc"
21
22 void LiveRangeCalc::reset(const MachineFunction *mf,
23                           SlotIndexes *SI,
24                           MachineDominatorTree *MDT,
25                           VNInfo::Allocator *VNIA) {
26   MF = mf;
27   MRI = &MF->getRegInfo();
28   Indexes = SI;
29   DomTree = MDT;
30   Alloc = VNIA;
31
32   MainLiveOutData.reset(MF->getNumBlockIDs());
33   LiveIn.clear();
34 }
35
36
37 static SlotIndex getDefIndex(const SlotIndexes &Indexes, const MachineInstr &MI,
38                              bool EarlyClobber) {
39   // PHI defs begin at the basic block start index.
40   if (MI.isPHI())
41     return Indexes.getMBBStartIdx(MI.getParent());
42
43   // Instructions are either normal 'r', or early clobber 'e'.
44   return Indexes.getInstructionIndex(&MI).getRegSlot(EarlyClobber);
45 }
46
47 void LiveRangeCalc::createDeadDefs(LiveInterval &LI) {
48   assert(MRI && Indexes && "call reset() first");
49
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 (SubReg != 0 || LI.hasSubRanges()) {
59       unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
60                                   : MRI->getMaxLaneMaskForVReg(Reg);
61
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);
67       }
68
69       for (LiveInterval::subrange_iterator S = LI.subrange_begin(),
70            SE = LI.subrange_end(); S != SE; ++S) {
71         // A Mask for subregs common to the existing subrange and current def.
72         unsigned Common = S->LaneMask & Mask;
73         if (Common == 0)
74           continue;
75         // A Mask for subregs covered by the subrange but not the current def.
76         unsigned LRest = S->LaneMask & ~Mask;
77         LiveInterval::SubRange *CommonRange;
78         if (LRest != 0) {
79           // Split current subrange into Common and LRest ranges.
80           S->LaneMask = LRest;
81           CommonRange = LI.createSubRangeFrom(*Alloc, Common, *S);
82         } else {
83           assert(Common == S->LaneMask);
84           CommonRange = &*S;
85         }
86         CommonRange->createDeadDef(Idx, *Alloc);
87         Mask &= ~Common;
88       }
89       if (Mask != 0) {
90         LiveInterval::SubRange *SubRange = LI.createSubRange(*Alloc, Mask);
91         SubRange->createDeadDef(Idx, *Alloc);
92       }
93     }
94
95     // Create the def in LR. This may find an existing def.
96     LI.createDeadDef(Idx, *Alloc);
97   }
98 }
99
100
101 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
102   assert(MRI && Indexes && "call reset() first");
103
104   // Visit all def operands. If the same instruction has multiple defs of Reg,
105   // LR.createDeadDef() will deduplicate.
106   for (MachineOperand &MO : MRI->def_operands(Reg)) {
107     const MachineInstr *MI = MO.getParent();
108     SlotIndex Idx = getDefIndex(*Indexes, *MI, MO.isEarlyClobber());
109     // Create the def in LR. This may find an existing def.
110     LR.createDeadDef(Idx, *Alloc);
111   }
112 }
113
114
115 static SlotIndex getUseIndex(const SlotIndexes &Indexes,
116                              const MachineOperand &MO) {
117   const MachineInstr *MI = MO.getParent();
118   unsigned OpNo = (&MO - &MI->getOperand(0));
119   if (MI->isPHI()) {
120     assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
121     // The actual place where a phi operand is used is the end of the pred MBB.
122     // PHI operands are paired: (Reg, PredMBB).
123     return Indexes.getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
124   }
125
126   // Check for early-clobber redefs.
127   bool isEarlyClobber = false;
128   unsigned DefIdx;
129   if (MO.isDef()) {
130     isEarlyClobber = MO.isEarlyClobber();
131   } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
132     // FIXME: This would be a lot easier if tied early-clobber uses also
133     // had an early-clobber flag.
134     isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
135   }
136   return Indexes.getInstructionIndex(MI).getRegSlot(isEarlyClobber);
137 }
138
139
140 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg) {
141   assert(MRI && Indexes && "call reset() first");
142
143   // Visit all operands that read Reg. This may include partial defs.
144   for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
145     // Clear all kill flags. They will be reinserted after register allocation
146     // by LiveIntervalAnalysis::addKillFlags().
147     if (MO.isUse())
148       MO.setIsKill(false);
149     if (!MO.readsReg())
150       continue;
151     // MI is reading Reg. We may have visited MI before if it happens to be
152     // reading Reg multiple times. That is OK, extend() is idempotent.
153     SlotIndex Idx = getUseIndex(*Indexes, MO);
154     extend(LR, Idx, Reg, MainLiveOutData);
155   }
156 }
157
158
159 void LiveRangeCalc::extendToUses(LiveInterval &LI) {
160   assert(MRI && Indexes && "call reset() first");
161
162   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
163   SmallVector<LiveOutData,2> LiveOuts;
164   unsigned NumSubRanges = 0;
165   for (LiveInterval::subrange_iterator S = LI.subrange_begin(),
166        SE = LI.subrange_end(); S != SE; ++S, ++NumSubRanges) {
167     LiveOuts.push_back(LiveOutData());
168     LiveOuts.back().reset(MF->getNumBlockIDs());
169   }
170
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().
176     if (MO.isUse())
177       MO.setIsKill(false);
178     if (!MO.readsReg())
179       continue;
180     SlotIndex Idx = getUseIndex(*Indexes, MO);
181     unsigned SubReg = MO.getSubReg();
182     if (MO.isUse() && (LI.hasSubRanges() || SubReg != 0)) {
183       unsigned Mask = SubReg != 0
184         ? TRI.getSubRegIndexLaneMask(SubReg)
185         : Mask = MRI->getMaxLaneMaskForVReg(Reg);
186
187       // If this is the first time we see a subregister def/use. Initialize
188       // subranges by creating a copy of the main range.
189       if (!LI.hasSubRanges()) {
190         unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
191         LI.createSubRangeFrom(*Alloc, ClassMask, LI);
192         LiveOuts.insert(LiveOuts.begin(), LiveOutData());
193         LiveOuts.front().reset(MF->getNumBlockIDs());
194         ++NumSubRanges;
195       }
196       unsigned SubRangeIdx = 0;
197       for (LiveInterval::subrange_iterator S = LI.subrange_begin(),
198            SE = LI.subrange_end(); S != SE; ++S, ++SubRangeIdx) {
199         // A Mask for subregs common to the existing subrange and current def.
200         unsigned Common = S->LaneMask & Mask;
201         if (Common == 0)
202           continue;
203         // A Mask for subregs covered by the subrange but not the current def.
204         unsigned LRest = S->LaneMask & ~Mask;
205         LiveInterval::SubRange *CommonRange;
206         unsigned CommonRangeIdx;
207         if (LRest != 0) {
208           // Split current subrange into Common and LRest ranges.
209           S->LaneMask = LRest;
210           CommonRange = LI.createSubRangeFrom(*Alloc, Common, *S);
211           CommonRangeIdx = 0;
212           LiveOuts.insert(LiveOuts.begin(), LiveOutData());
213           LiveOuts.front().reset(MF->getNumBlockIDs());
214           ++NumSubRanges;
215           ++SubRangeIdx;
216         } else {
217           // The subrange and current def lanemasks match completely.
218           assert(Common == S->LaneMask);
219           CommonRange = &*S;
220           CommonRangeIdx = SubRangeIdx;
221         }
222         extend(*CommonRange, Idx, Reg, LiveOuts[CommonRangeIdx]);
223         Mask &= ~Common;
224       }
225       assert(SubRangeIdx == NumSubRanges);
226     }
227     extend(LI, Idx, Reg, MainLiveOutData);
228   }
229 }
230
231
232 void LiveRangeCalc::updateFromLiveIns(LiveOutData &LiveOuts) {
233   LiveRangeUpdater Updater;
234   for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
235          E = LiveIn.end(); I != E; ++I) {
236     if (!I->DomNode)
237       continue;
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);
242
243     if (I->Kill.isValid())
244       // Value is killed inside this block.
245       End = I->Kill;
246     else {
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);
251     }
252     Updater.setDest(&I->LR);
253     Updater.add(Start, End, I->Value);
254   }
255   LiveIn.clear();
256 }
257
258
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");
264
265   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
266   assert(KillMBB && "No MBB at Kill");
267
268   // Is there a def in the same MBB we can extend?
269   if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
270     return;
271
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))
277     return;
278
279   // When there were multiple different values, we may need new PHIs.
280   calculateValues(LiveOuts);
281 }
282
283
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");
290   updateSSA(LiveOuts);
291   updateFromLiveIns(LiveOuts);
292 }
293
294
295 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
296                                      SlotIndex Kill, unsigned PhysReg,
297                                      LiveOutData &LiveOuts) {
298   unsigned KillMBBNum = KillMBB.getNumber();
299
300   // Block numbers where LR should be live-in.
301   SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
302
303   // Remember if we have seen more than one value.
304   bool UniqueVNI = true;
305   VNInfo *TheVNI = nullptr;
306
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]);
310
311 #ifndef NDEBUG
312     if (MBB->pred_empty()) {
313       MBB->getParent()->verify();
314       llvm_unreachable("Use not jointly dominated by defs.");
315     }
316
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");
323     }
324 #endif
325
326     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
327          PE = MBB->pred_end(); PI != PE; ++PI) {
328        MachineBasicBlock *Pred = *PI;
329
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)
334              UniqueVNI = false;
335            TheVNI = VNI;
336          }
337          continue;
338        }
339
340        SlotIndex Start, End;
341        std::tie(Start, End) = Indexes->getMBBRange(Pred);
342
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);
347        if (VNI) {
348          if (TheVNI && TheVNI != VNI)
349            UniqueVNI = false;
350          TheVNI = VNI;
351          continue;
352        }
353
354        // No, we need a live-in value for Pred as well
355        if (Pred != &KillMBB)
356           WorkList.push_back(Pred->getNumber());
357        else
358           // Loopback to KillMBB, so value is really live through.
359          Kill = SlotIndex();
360     }
361   }
362
363   LiveIn.clear();
364
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());
369
370   // If a unique reaching def was found, blit in the live ranges immediately.
371   if (UniqueVNI) {
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())
379          End = Kill;
380        else
381          LiveOuts.Map[MF->getBlockNumbered(*I)] =
382            LiveOutPair(TheVNI, nullptr);
383        Updater.add(Start, End, TheVNI);
384     }
385     return true;
386   }
387
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));
395     if (MBB == &KillMBB)
396       LiveIn.back().Kill = Kill;
397   }
398
399   return false;
400 }
401
402
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");
408
409   // Interate until convergence.
410   unsigned Changes;
411   do {
412     Changes = 0;
413     // Propagate live-out values down the dominator tree, inserting phi-defs
414     // when necessary.
415     for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
416            E = LiveIn.end(); I != E; ++I) {
417       MachineDomTreeNode *Node = I->DomNode;
418       // Skip block if the live-in value has already been determined.
419       if (!Node)
420         continue;
421       MachineBasicBlock *MBB = Node->getBlock();
422       MachineDomTreeNode *IDom = Node->getIDom();
423       LiveOutPair IDomValue;
424
425       // We need a live-in value to a block with no immediate dominator?
426       // This is probably an unreachable block that has survived somehow.
427       bool needPHI = !IDom
428                   || !LiveOuts.Seen.test(IDom->getBlock()->getNumber());
429
430       // IDom dominates all of our predecessors, but it may not be their
431       // immediate dominator. Check if any of them have live-out values that are
432       // properly dominated by IDom. If so, we need a phi-def here.
433       if (!needPHI) {
434         IDomValue = LiveOuts.Map[IDom->getBlock()];
435
436         // Cache the DomTree node that defined the value.
437         if (IDomValue.first && !IDomValue.second)
438           LiveOuts.Map[IDom->getBlock()].second = IDomValue.second =
439             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
440
441         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
442                PE = MBB->pred_end(); PI != PE; ++PI) {
443           LiveOutPair &Value = LiveOuts.Map[*PI];
444           if (!Value.first || Value.first == IDomValue.first)
445             continue;
446
447           // Cache the DomTree node that defined the value.
448           if (!Value.second)
449             Value.second =
450               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
451
452           // This predecessor is carrying something other than IDomValue.
453           // It could be because IDomValue hasn't propagated yet, or it could be
454           // because MBB is in the dominance frontier of that value.
455           if (DomTree->dominates(IDom, Value.second)) {
456             needPHI = true;
457             break;
458           }
459         }
460       }
461
462       // The value may be live-through even if Kill is set, as can happen when
463       // we are called from extendRange. In that case LiveOutSeen is true, and
464       // LiveOut indicates a foreign or missing value.
465       LiveOutPair &LOP = LiveOuts.Map[MBB];
466
467       // Create a phi-def if required.
468       if (needPHI) {
469         ++Changes;
470         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
471         SlotIndex Start, End;
472         std::tie(Start, End) = Indexes->getMBBRange(MBB);
473         LiveRange &LR = I->LR;
474         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
475         I->Value = VNI;
476         // This block is done, we know the final value.
477         I->DomNode = nullptr;
478
479         // Add liveness since updateFromLiveIns now skips this node.
480         if (I->Kill.isValid())
481           LR.addSegment(LiveInterval::Segment(Start, I->Kill, VNI));
482         else {
483           LR.addSegment(LiveInterval::Segment(Start, End, VNI));
484           LOP = LiveOutPair(VNI, Node);
485         }
486       } else if (IDomValue.first) {
487         // No phi-def here. Remember incoming value.
488         I->Value = IDomValue.first;
489
490         // If the IDomValue is killed in the block, don't propagate through.
491         if (I->Kill.isValid())
492           continue;
493
494         // Propagate IDomValue if it isn't killed:
495         // MBB is live-out and doesn't define its own value.
496         if (LOP.first == IDomValue.first)
497           continue;
498         ++Changes;
499         LOP = IDomValue;
500       }
501     }
502   } while (Changes);
503 }