LLVM 24.0.0git
LiveRangeCalc.cpp
Go to the documentation of this file.
1//===- LiveRangeCalc.cpp - Calculate live ranges -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the LiveRangeCalc class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/BitVector.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
28#include <cassert>
29#include <iterator>
30#include <tuple>
31
32using namespace llvm;
33
34#define DEBUG_TYPE "regalloc"
35
36// Reserve an address that indicates a value that is known to be "undef".
37static VNInfo UndefVNI(0xbad, SlotIndex());
38
40 unsigned NumBlocks = MF->getNumBlockIDs();
41 Seen.clear();
42 Seen.resize(NumBlocks);
43 EntryInfos.clear();
44 Map.resize(NumBlocks);
45}
46
50 VNInfo::Allocator *VNIA) {
51 MF = mf;
52 MRI = &MF->getRegInfo();
53 Indexes = SI;
54 DomTree = MDT;
55 Alloc = VNIA;
57 LiveIn.clear();
58}
59
60void LiveRangeCalc::updateFromLiveIns() {
61 LiveRangeUpdater Updater;
62 for (const LiveInBlock &I : LiveIn) {
63 if (!I.DomNode)
64 continue;
65 MachineBasicBlock *MBB = I.DomNode->getBlock();
66 assert(I.Value && "No live-in value found");
67 SlotIndex Start, End;
68 std::tie(Start, End) = Indexes->getMBBRange(MBB);
69
70 if (I.Kill.isValid())
71 // Value is killed inside this block.
72 End = I.Kill;
73 else {
74 // The value is live-through, update LiveOut as well.
75 // Defer the Domtree lookup until it is needed.
76 assert(Seen.test(MBB->getNumber()));
77 Map[MBB] = LiveOutPair(I.Value, nullptr);
78 }
79 Updater.setDest(&I.LR);
80 Updater.add(Start, End, I.Value);
81 }
82 LiveIn.clear();
83}
84
86 ArrayRef<SlotIndex> Undefs) {
87 assert(Use.isValid() && "Invalid SlotIndex");
88 assert(Indexes && "Missing SlotIndexes");
89 assert(DomTree && "Missing dominator tree");
90
91 MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
92 assert(UseMBB && "No MBB at Use");
93
94 // Is there a def in the same MBB we can extend?
95 auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
96 if (EP.first != nullptr || EP.second)
97 return;
98
99 // Find the single reaching def, or determine if Use is jointly dominated by
100 // multiple values, and we may need to create even more phi-defs to preserve
101 // VNInfo SSA form. Perform a search for all predecessor blocks where we
102 // know the dominating VNInfo.
103 if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
104 return;
105
106 // When there were multiple different values, we may need new PHIs.
108}
109
110// This function is called by a client after using the low-level API to add
111// live-out and live-in blocks. The unique value optimization is not
112// available, SplitEditor::transferValues handles that case directly anyway.
114 assert(Indexes && "Missing SlotIndexes");
115 assert(DomTree && "Missing dominator tree");
116 updateSSA();
117 updateFromLiveIns();
118}
119
120bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
121 MachineBasicBlock &MBB, BitVector &DefOnEntry,
122 BitVector &UndefOnEntry) {
123 unsigned BN = MBB.getNumber();
124 if (DefOnEntry[BN])
125 return true;
126 if (UndefOnEntry[BN])
127 return false;
128
129 auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
130 for (MachineBasicBlock *S : B.successors())
131 DefOnEntry[S->getNumber()] = true;
132 DefOnEntry[BN] = true;
133 return true;
134 };
135
136 SetVector<unsigned> WorkList;
137 // Checking if the entry of MBB is reached by some def: add all predecessors
138 // that are potentially defined-on-exit to the work list.
139 for (MachineBasicBlock *P : MBB.predecessors())
140 WorkList.insert(P->getNumber());
141
142 for (unsigned i = 0; i != WorkList.size(); ++i) {
143 // Determine if the exit from the block is reached by some def.
144 unsigned N = WorkList[i];
146 if (Seen[N]) {
147 const LiveOutPair &LOB = Map[&B];
148 if (LOB.first != nullptr && LOB.first != &UndefVNI)
149 return MarkDefined(B);
150 }
151 SlotIndex Begin, End;
152 std::tie(Begin, End) = Indexes->getMBBRange(&B);
153 // Treat End as not belonging to B.
154 // If LR has a segment S that starts at the next block, i.e. [End, ...),
155 // std::upper_bound will return the segment following S. Instead,
156 // S should be treated as the first segment that does not overlap B.
157 LiveRange::iterator UB = upper_bound(LR, End.getPrevSlot());
158 if (UB != LR.begin()) {
159 LiveRange::Segment &Seg = *std::prev(UB);
160 if (Seg.end > Begin) {
161 // There is a segment that overlaps B. If the range is not explicitly
162 // undefined between the end of the segment and the end of the block,
163 // treat the block as defined on exit. If it is, go to the next block
164 // on the work list.
165 if (LR.isUndefIn(Undefs, Seg.end, End))
166 continue;
167 return MarkDefined(B);
168 }
169 }
170
171 // No segment overlaps with this block. If this block is not defined on
172 // entry, or it undefines the range, do not process its predecessors.
173 if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
174 UndefOnEntry[N] = true;
175 continue;
176 }
177 if (DefOnEntry[N])
178 return MarkDefined(B);
179
180 // Still don't know: add all predecessors to the work list.
181 for (MachineBasicBlock *P : B.predecessors())
182 WorkList.insert(P->getNumber());
183 }
184
185 UndefOnEntry[BN] = true;
186 return false;
187}
188
189bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
190 SlotIndex Use, Register PhysReg,
191 ArrayRef<SlotIndex> Undefs) {
192 unsigned UseMBBNum = UseMBB.getNumber();
193
194 // Block numbers where LR should be live-in.
195 SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
196
197 // Remember if we have seen more than one value.
198 bool UniqueVNI = true;
199 VNInfo *TheVNI = nullptr;
200
201 bool FoundUndef = false;
202 bool FoundUnreachable = false;
203
204 // Using Seen as a visited set, perform a BFS for all reaching defs.
205 for (unsigned i = 0; i != WorkList.size(); ++i) {
206 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
207
208 bool Unreachable = !DomTree->isReachableFromEntry(MBB);
209 FoundUnreachable |= Unreachable;
210
211#ifndef NDEBUG
212 if (!Unreachable && MBB->pred_empty()) {
213 MBB->getParent()->verify(nullptr, nullptr, &errs());
214 errs() << "Use of " << printReg(PhysReg, MRI->getTargetRegisterInfo())
215 << " does not have a corresponding definition on every path:\n";
216 const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
217 if (MI != nullptr)
218 errs() << Use << " " << *MI;
219 report_fatal_error("Use not jointly dominated by defs.");
220 }
221
222 if (PhysReg.isPhysical()) {
223 const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
224 bool IsLiveIn = MBB->isLiveIn(PhysReg);
225 for (MCRegAliasIterator Alias(PhysReg, TRI, false); !IsLiveIn && Alias.isValid(); ++Alias)
226 IsLiveIn = MBB->isLiveIn(*Alias);
227 if (!IsLiveIn) {
228 MBB->getParent()->verify(nullptr, nullptr, &errs());
229 errs() << "The register " << printReg(PhysReg, TRI)
230 << " needs to be live in to " << printMBBReference(*MBB)
231 << ", but is missing from the live-in list.\n";
232 report_fatal_error("Invalid global physical register");
233 }
234 }
235#endif
236 FoundUndef |= MBB->pred_empty();
237
238 for (MachineBasicBlock *Pred : MBB->predecessors()) {
239 // Is this a known live-out block?
240 if (Seen.test(Pred->getNumber())) {
241 if (VNInfo *VNI = Map[Pred].first) {
242 if (TheVNI && TheVNI != VNI)
243 UniqueVNI = false;
244 TheVNI = VNI;
245 }
246 continue;
247 }
248
249 SlotIndex Start, End;
250 std::tie(Start, End) = Indexes->getMBBRange(Pred);
251
252 // First time we see Pred. Try to determine the live-out value, but set
253 // it as null if Pred is live-through with an unknown value.
254 auto EP = LR.extendInBlock(Undefs, Start, End);
255 VNInfo *VNI = EP.first;
256 FoundUndef |= EP.second;
257 setLiveOutValue(Pred, EP.second ? &UndefVNI : VNI);
258 if (VNI) {
259 if (TheVNI && TheVNI != VNI)
260 UniqueVNI = false;
261 TheVNI = VNI;
262 }
263 if (VNI || EP.second)
264 continue;
265
266 // No, we need a live-in value for Pred as well
267 if (Pred != &UseMBB)
268 WorkList.push_back(Pred->getNumber());
269 else
270 // Loopback to UseMBB, so value is really live through.
271 Use = SlotIndex();
272 }
273 }
274
275 LiveIn.clear();
276 FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
277 if ((!Undefs.empty() && FoundUndef) || FoundUnreachable)
278 UniqueVNI = false;
279
280 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
281 // neither require it. Skip the sorting overhead for small updates.
282 if (WorkList.size() > 4)
283 llvm::sort(WorkList, std::less<>());
284
285 // If a unique reaching def was found, blit in the live ranges immediately.
286 if (UniqueVNI) {
287 assert(TheVNI != nullptr && TheVNI != &UndefVNI);
288 LiveRangeUpdater Updater(&LR);
289 for (unsigned BN : WorkList) {
290 MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
291 SlotIndex Start, End;
292 std::tie(Start, End) = Indexes->getMBBRange(MBB);
293 // Trim the live range in UseMBB.
294 if (BN == UseMBBNum && Use.isValid())
295 End = Use;
296 else
297 Map[MBB] = LiveOutPair(TheVNI, nullptr);
298 Updater.add(Start, End, TheVNI);
299 }
300 return true;
301 }
302
303 // Prepare the defined/undefined bit vectors.
304 EntryInfoMap::iterator Entry;
305 bool DidInsert;
306 std::tie(Entry, DidInsert) = EntryInfos.insert(
307 std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
308 if (DidInsert) {
309 // Initialize newly inserted entries.
310 unsigned N = MF->getNumBlockIDs();
311 Entry->second.first.resize(N);
312 Entry->second.second.resize(N);
313 }
314 BitVector &DefOnEntry = Entry->second.first;
315 BitVector &UndefOnEntry = Entry->second.second;
316
317 // Multiple values were found, so transfer the work list to the LiveIn array
318 // where UpdateSSA will use it as a work list.
319 LiveIn.reserve(WorkList.size());
320 for (unsigned BN : WorkList) {
321 MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
322 MachineDomTreeNode *Node = DomTree->getNode(MBB);
323 if (!Node) {
324 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
325 SlotIndex Start, End;
326 std::tie(Start, End) = Indexes->getMBBRange(MBB);
327 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
328 if (MBB == &UseMBB && Use.isValid())
329 End = Use;
330 else
331 Map[MBB] = LiveOutPair(VNI, nullptr);
332 LR.addSegment(LiveRange::Segment(Start, End, VNI));
333 continue;
334 }
335
336 if (!Undefs.empty() &&
337 !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
338 continue;
339
340 addLiveInBlock(LR, Node);
341 if (MBB == &UseMBB)
342 LiveIn.back().Kill = Use;
343 }
344
345 return false;
346}
347
348// This is essentially the same iterative algorithm that SSAUpdater uses,
349// except we already have a dominator tree, so we don't have to recompute it.
350void LiveRangeCalc::updateSSA() {
351 assert(Indexes && "Missing SlotIndexes");
352 assert(DomTree && "Missing dominator tree");
353
354 // Interate until convergence.
355 bool Changed;
356 do {
357 Changed = false;
358 // Propagate live-out values down the dominator tree, inserting phi-defs
359 // when necessary.
360 for (LiveInBlock &I : LiveIn) {
361 MachineDomTreeNode *Node = I.DomNode;
362 // Skip block if the live-in value has already been determined.
363 if (!Node)
364 continue;
365 MachineBasicBlock *MBB = Node->getBlock();
366 MachineDomTreeNode *IDom = Node->getIDom();
367 LiveOutPair IDomValue;
368
369 // Unreachable blocks already received phi-defs in findReachingDefs, so
370 // only the entry block has no immediate dominator.
371 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
372
373 // IDom dominates all of our predecessors, but it may not be their
374 // immediate dominator. Check if any of them have live-out values that are
375 // properly dominated by IDom. If so, we need a phi-def here.
376 if (!needPHI) {
377 IDomValue = Map[IDom->getBlock()];
378
379 // Cache the DomTree node that defined the value.
380 if (IDomValue.first && IDomValue.first != &UndefVNI &&
381 !IDomValue.second) {
382 Map[IDom->getBlock()].second = IDomValue.second =
383 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
384 }
385
386 for (MachineBasicBlock *Pred : MBB->predecessors()) {
387 LiveOutPair &Value = Map[Pred];
388 if (!Value.first || Value.first == IDomValue.first)
389 continue;
390 if (Value.first == &UndefVNI) {
391 needPHI = true;
392 break;
393 }
394
395 // Cache the DomTree node that defined the value.
396 if (!Value.second)
397 Value.second =
398 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
399
400 // This predecessor is carrying something other than IDomValue.
401 // It could be because IDomValue hasn't propagated yet, or it could be
402 // because MBB is in the dominance frontier of that value.
403 if (DomTree->dominates(IDom, Value.second)) {
404 needPHI = true;
405 break;
406 }
407 }
408 }
409
410 // The value may be live-through even if Kill is set, as can happen when
411 // we are called from extendRange. In that case LiveOutSeen is true, and
412 // LiveOut indicates a foreign or missing value.
413 LiveOutPair &LOP = Map[MBB];
414
415 // Create a phi-def if required.
416 if (needPHI) {
417 Changed = true;
418 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
419 SlotIndex Start, End;
420 std::tie(Start, End) = Indexes->getMBBRange(MBB);
421 LiveRange &LR = I.LR;
422 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
423 I.Value = VNI;
424 // This block is done, we know the final value.
425 I.DomNode = nullptr;
426
427 // Add liveness since updateFromLiveIns now skips this node.
428 if (I.Kill.isValid()) {
429 if (VNI)
430 LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
431 } else {
432 if (VNI)
433 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
434 LOP = LiveOutPair(VNI, Node);
435 }
436 } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
437 // No phi-def here. Remember incoming value.
438 I.Value = IDomValue.first;
439
440 // If the IDomValue is killed in the block, don't propagate through.
441 if (I.Kill.isValid())
442 continue;
443
444 // Propagate IDomValue if it isn't killed:
445 // MBB is live-out and doesn't define its own value.
446 if (LOP.first == IDomValue.first)
447 continue;
448 Changed = true;
449 LOP = IDomValue;
450 }
451 }
452 } while (Changed);
453}
454
457 const SlotIndexes &Indexes) {
458 const MachineFunction &MF = *MBB->getParent();
459 BitVector DefBlocks(MF.getNumBlockIDs());
460 for (SlotIndex I : Defs)
461 DefBlocks.set(Indexes.getMBBFromIndex(I)->getNumber());
462
463 unsigned EntryNum = MF.front().getNumber();
464 SetVector<unsigned> PredQueue;
465 PredQueue.insert(MBB->getNumber());
466 for (unsigned i = 0; i != PredQueue.size(); ++i) {
467 unsigned BN = PredQueue[i];
468 if (DefBlocks[BN])
469 continue;
470 if (BN == EntryNum) {
471 // We found a path from MBB back to the entry block without hitting any of
472 // the def blocks.
473 return false;
474 }
475 const MachineBasicBlock *B = MF.getBlockNumbered(BN);
476 for (const MachineBasicBlock *P : B->predecessors())
477 PredQueue.insert(P->getNumber());
478 }
479 return true;
480}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
IRTranslator LLVM IR MI
static VNInfo UndefVNI(0xbad, SlotIndex())
static VNInfo UndefVNI(0xbad, SlotIndex())
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#define P(N)
SI Optimize VGPR LiveRange
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
NodeT * getBlock() const
static LLVM_ABI bool isJointlyDominated(const MachineBasicBlock *MBB, ArrayRef< SlotIndex > Defs, const SlotIndexes &Indexes)
A diagnostic function to check if the end of the block MBB is jointly dominated by the blocks corresp...
void addLiveInBlock(LiveRange &LR, MachineDomTreeNode *DomNode, SlotIndex Kill=SlotIndex())
addLiveInBlock - Add a block with an unknown live-in value.
LLVM_ABI void resetLiveOutMap()
Reset Map and Seen fields.
LLVM_ABI void reset(const MachineFunction *mf, SlotIndexes *SI, MachineDominatorTree *MDT, VNInfo::Allocator *VNIA)
reset - Prepare caches for a new set of non-overlapping live ranges.
LLVM_ABI void extend(LiveRange &LR, SlotIndex Use, Register PhysReg, ArrayRef< SlotIndex > Undefs)
Extend the live range of LR to reach Use.
LLVM_ABI void calculateValues()
calculateValues - Calculate the value that will be live-in to each block added with addLiveInBlock.
void setLiveOutValue(MachineBasicBlock *MBB, VNInfo *VNI)
setLiveOutValue - Indicate that VNI is live out from MBB.
Helper class for performant LiveRange bulk updates.
void setDest(LiveRange *lr)
Select a different destination live range.
LLVM_ABI void add(LiveRange::Segment)
Add a segment to LR and coalesce when possible, just like LR.addSegment().
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
Segments::iterator iterator
LLVM_ABI std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
iterator begin()
bool isUndefIn(ArrayRef< SlotIndex > Undefs, SlotIndex Begin, SlotIndex End) const
Returns true if there is an explicit "undef" between Begin End.
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
SlotIndexes pass.
const std::pair< SlotIndex, SlotIndex > & getMBBRange(const MachineBasicBlock *MBB) const
Return the (start,end) range of the given basic block.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
VNInfo - Value Number Information.
BumpPtrAllocator Allocator
@ Entry
Definition COFF.h:862
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
#define N