Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 1364, column 14
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name InlineSpiller.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen/InlineSpiller.cpp

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen/InlineSpiller.cpp

1//===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
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// The inline spiller modifies the machine function directly instead of
10// inserting spills and restores in VirtRegMap.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SplitKit.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/LiveInterval.h"
26#include "llvm/CodeGen/LiveIntervals.h"
27#include "llvm/CodeGen/LiveRangeEdit.h"
28#include "llvm/CodeGen/LiveStacks.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31#include "llvm/CodeGen/MachineDominators.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFunctionPass.h"
34#include "llvm/CodeGen/MachineInstr.h"
35#include "llvm/CodeGen/MachineInstrBuilder.h"
36#include "llvm/CodeGen/MachineInstrBundle.h"
37#include "llvm/CodeGen/MachineLoopInfo.h"
38#include "llvm/CodeGen/MachineOperand.h"
39#include "llvm/CodeGen/MachineRegisterInfo.h"
40#include "llvm/CodeGen/SlotIndexes.h"
41#include "llvm/CodeGen/Spiller.h"
42#include "llvm/CodeGen/StackMaps.h"
43#include "llvm/CodeGen/TargetInstrInfo.h"
44#include "llvm/CodeGen/TargetOpcodes.h"
45#include "llvm/CodeGen/TargetRegisterInfo.h"
46#include "llvm/CodeGen/TargetSubtargetInfo.h"
47#include "llvm/CodeGen/VirtRegMap.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/Support/BlockFrequency.h"
50#include "llvm/Support/BranchProbability.h"
51#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/Debug.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/raw_ostream.h"
56#include <cassert>
57#include <iterator>
58#include <tuple>
59#include <utility>
60#include <vector>
61
62using namespace llvm;
63
64#define DEBUG_TYPE"regalloc" "regalloc"
65
66STATISTIC(NumSpilledRanges, "Number of spilled live ranges")static llvm::Statistic NumSpilledRanges = {"regalloc", "NumSpilledRanges"
, "Number of spilled live ranges"}
;
67STATISTIC(NumSnippets, "Number of spilled snippets")static llvm::Statistic NumSnippets = {"regalloc", "NumSnippets"
, "Number of spilled snippets"}
;
68STATISTIC(NumSpills, "Number of spills inserted")static llvm::Statistic NumSpills = {"regalloc", "NumSpills", "Number of spills inserted"
}
;
69STATISTIC(NumSpillsRemoved, "Number of spills removed")static llvm::Statistic NumSpillsRemoved = {"regalloc", "NumSpillsRemoved"
, "Number of spills removed"}
;
70STATISTIC(NumReloads, "Number of reloads inserted")static llvm::Statistic NumReloads = {"regalloc", "NumReloads"
, "Number of reloads inserted"}
;
71STATISTIC(NumReloadsRemoved, "Number of reloads removed")static llvm::Statistic NumReloadsRemoved = {"regalloc", "NumReloadsRemoved"
, "Number of reloads removed"}
;
72STATISTIC(NumFolded, "Number of folded stack accesses")static llvm::Statistic NumFolded = {"regalloc", "NumFolded", "Number of folded stack accesses"
}
;
73STATISTIC(NumFoldedLoads, "Number of folded loads")static llvm::Statistic NumFoldedLoads = {"regalloc", "NumFoldedLoads"
, "Number of folded loads"}
;
74STATISTIC(NumRemats, "Number of rematerialized defs for spilling")static llvm::Statistic NumRemats = {"regalloc", "NumRemats", "Number of rematerialized defs for spilling"
}
;
75
76static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
77 cl::desc("Disable inline spill hoisting"));
78static cl::opt<bool>
79RestrictStatepointRemat("restrict-statepoint-remat",
80 cl::init(false), cl::Hidden,
81 cl::desc("Restrict remat for statepoint operands"));
82
83namespace {
84
85class HoistSpillHelper : private LiveRangeEdit::Delegate {
86 MachineFunction &MF;
87 LiveIntervals &LIS;
88 LiveStacks &LSS;
89 MachineDominatorTree &MDT;
90 MachineLoopInfo &Loops;
91 VirtRegMap &VRM;
92 MachineRegisterInfo &MRI;
93 const TargetInstrInfo &TII;
94 const TargetRegisterInfo &TRI;
95 const MachineBlockFrequencyInfo &MBFI;
96
97 InsertPointAnalysis IPA;
98
99 // Map from StackSlot to the LiveInterval of the original register.
100 // Note the LiveInterval of the original register may have been deleted
101 // after it is spilled. We keep a copy here to track the range where
102 // spills can be moved.
103 DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
104
105 // Map from pair of (StackSlot and Original VNI) to a set of spills which
106 // have the same stackslot and have equal values defined by Original VNI.
107 // These spills are mergeable and are hoist candidates.
108 using MergeableSpillsMap =
109 MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
110 MergeableSpillsMap MergeableSpills;
111
112 /// This is the map from original register to a set containing all its
113 /// siblings. To hoist a spill to another BB, we need to find out a live
114 /// sibling there and use it as the source of the new spill.
115 DenseMap<Register, SmallSetVector<Register, 16>> Virt2SiblingsMap;
116
117 bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
118 MachineBasicBlock &BB, Register &LiveReg);
119
120 void rmRedundantSpills(
121 SmallPtrSet<MachineInstr *, 16> &Spills,
122 SmallVectorImpl<MachineInstr *> &SpillsToRm,
123 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
124
125 void getVisitOrders(
126 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
127 SmallVectorImpl<MachineDomTreeNode *> &Orders,
128 SmallVectorImpl<MachineInstr *> &SpillsToRm,
129 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
130 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
131
132 void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
133 SmallPtrSet<MachineInstr *, 16> &Spills,
134 SmallVectorImpl<MachineInstr *> &SpillsToRm,
135 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
136
137public:
138 HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
139 VirtRegMap &vrm)
140 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
141 LSS(pass.getAnalysis<LiveStacks>()),
142 MDT(pass.getAnalysis<MachineDominatorTree>()),
143 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
144 MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
145 TRI(*mf.getSubtarget().getRegisterInfo()),
146 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
147 IPA(LIS, mf.getNumBlockIDs()) {}
148
149 void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
150 unsigned Original);
151 bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
152 void hoistAllSpills();
153 void LRE_DidCloneVirtReg(Register, Register) override;
154};
155
156class InlineSpiller : public Spiller {
157 MachineFunction &MF;
158 LiveIntervals &LIS;
159 LiveStacks &LSS;
160 MachineDominatorTree &MDT;
161 MachineLoopInfo &Loops;
162 VirtRegMap &VRM;
163 MachineRegisterInfo &MRI;
164 const TargetInstrInfo &TII;
165 const TargetRegisterInfo &TRI;
166 const MachineBlockFrequencyInfo &MBFI;
167
168 // Variables that are valid during spill(), but used by multiple methods.
169 LiveRangeEdit *Edit;
170 LiveInterval *StackInt;
171 int StackSlot;
172 Register Original;
173
174 // All registers to spill to StackSlot, including the main register.
175 SmallVector<Register, 8> RegsToSpill;
176
177 // All COPY instructions to/from snippets.
178 // They are ignored since both operands refer to the same stack slot.
179 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
180
181 // Values that failed to remat at some point.
182 SmallPtrSet<VNInfo*, 8> UsedValues;
183
184 // Dead defs generated during spilling.
185 SmallVector<MachineInstr*, 8> DeadDefs;
186
187 // Object records spills information and does the hoisting.
188 HoistSpillHelper HSpiller;
189
190 // Live range weight calculator.
191 VirtRegAuxInfo &VRAI;
192
193 ~InlineSpiller() override = default;
194
195public:
196 InlineSpiller(MachineFunctionPass &Pass, MachineFunction &MF, VirtRegMap &VRM,
197 VirtRegAuxInfo &VRAI)
198 : MF(MF), LIS(Pass.getAnalysis<LiveIntervals>()),
199 LSS(Pass.getAnalysis<LiveStacks>()),
200 MDT(Pass.getAnalysis<MachineDominatorTree>()),
201 Loops(Pass.getAnalysis<MachineLoopInfo>()), VRM(VRM),
202 MRI(MF.getRegInfo()), TII(*MF.getSubtarget().getInstrInfo()),
203 TRI(*MF.getSubtarget().getRegisterInfo()),
204 MBFI(Pass.getAnalysis<MachineBlockFrequencyInfo>()),
205 HSpiller(Pass, MF, VRM), VRAI(VRAI) {}
206
207 void spill(LiveRangeEdit &) override;
208 void postOptimization() override;
209
210private:
211 bool isSnippet(const LiveInterval &SnipLI);
212 void collectRegsToSpill();
213
214 bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
215
216 bool isSibling(Register Reg);
217 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
218 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
219
220 void markValueUsed(LiveInterval*, VNInfo*);
221 bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
222 bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
223 void reMaterializeAll();
224
225 bool coalesceStackAccess(MachineInstr *MI, Register Reg);
226 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
227 MachineInstr *LoadMI = nullptr);
228 void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
229 void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI);
230
231 void spillAroundUses(Register Reg);
232 void spillAll();
233};
234
235} // end anonymous namespace
236
237Spiller::~Spiller() = default;
238
239void Spiller::anchor() {}
240
241Spiller *llvm::createInlineSpiller(MachineFunctionPass &Pass,
242 MachineFunction &MF, VirtRegMap &VRM,
243 VirtRegAuxInfo &VRAI) {
244 return new InlineSpiller(Pass, MF, VRM, VRAI);
245}
246
247//===----------------------------------------------------------------------===//
248// Snippets
249//===----------------------------------------------------------------------===//
250
251// When spilling a virtual register, we also spill any snippets it is connected
252// to. The snippets are small live ranges that only have a single real use,
253// leftovers from live range splitting. Spilling them enables memory operand
254// folding or tightens the live range around the single use.
255//
256// This minimizes register pressure and maximizes the store-to-load distance for
257// spill slots which can be important in tight loops.
258
259/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
260/// otherwise return 0.
261static Register isFullCopyOf(const MachineInstr &MI, Register Reg) {
262 if (!MI.isFullCopy())
263 return Register();
264 if (MI.getOperand(0).getReg() == Reg)
265 return MI.getOperand(1).getReg();
266 if (MI.getOperand(1).getReg() == Reg)
267 return MI.getOperand(0).getReg();
268 return Register();
269}
270
271static void getVDefInterval(const MachineInstr &MI, LiveIntervals &LIS) {
272 for (const MachineOperand &MO : MI.operands())
273 if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
274 LIS.getInterval(MO.getReg());
275}
276
277/// isSnippet - Identify if a live interval is a snippet that should be spilled.
278/// It is assumed that SnipLI is a virtual register with the same original as
279/// Edit->getReg().
280bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
281 Register Reg = Edit->getReg();
282
283 // A snippet is a tiny live range with only a single instruction using it
284 // besides copies to/from Reg or spills/fills. We accept:
285 //
286 // %snip = COPY %Reg / FILL fi#
287 // %snip = USE %snip
288 // %Reg = COPY %snip / SPILL %snip, fi#
289 //
290 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
291 return false;
292
293 MachineInstr *UseMI = nullptr;
294
295 // Check that all uses satisfy our criteria.
296 for (MachineRegisterInfo::reg_instr_nodbg_iterator
297 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg()),
298 E = MRI.reg_instr_nodbg_end();
299 RI != E;) {
300 MachineInstr &MI = *RI++;
301
302 // Allow copies to/from Reg.
303 if (isFullCopyOf(MI, Reg))
304 continue;
305
306 // Allow stack slot loads.
307 int FI;
308 if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
309 continue;
310
311 // Allow stack slot stores.
312 if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
313 continue;
314
315 // Allow a single additional instruction.
316 if (UseMI && &MI != UseMI)
317 return false;
318 UseMI = &MI;
319 }
320 return true;
321}
322
323/// collectRegsToSpill - Collect live range snippets that only have a single
324/// real use.
325void InlineSpiller::collectRegsToSpill() {
326 Register Reg = Edit->getReg();
327
328 // Main register always spills.
329 RegsToSpill.assign(1, Reg);
330 SnippetCopies.clear();
331
332 // Snippets all have the same original, so there can't be any for an original
333 // register.
334 if (Original == Reg)
335 return;
336
337 for (MachineInstr &MI :
338 llvm::make_early_inc_range(MRI.reg_instructions(Reg))) {
339 Register SnipReg = isFullCopyOf(MI, Reg);
340 if (!isSibling(SnipReg))
341 continue;
342 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
343 if (!isSnippet(SnipLI))
344 continue;
345 SnippetCopies.insert(&MI);
346 if (isRegToSpill(SnipReg))
347 continue;
348 RegsToSpill.push_back(SnipReg);
349 LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\talso spill snippet " <<
SnipLI << '\n'; } } while (false)
;
350 ++NumSnippets;
351 }
352}
353
354bool InlineSpiller::isSibling(Register Reg) {
355 return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
356}
357
358/// It is beneficial to spill to earlier place in the same BB in case
359/// as follows:
360/// There is an alternative def earlier in the same MBB.
361/// Hoist the spill as far as possible in SpillMBB. This can ease
362/// register pressure:
363///
364/// x = def
365/// y = use x
366/// s = copy x
367///
368/// Hoisting the spill of s to immediately after the def removes the
369/// interference between x and y:
370///
371/// x = def
372/// spill x
373/// y = use killed x
374///
375/// This hoist only helps when the copy kills its source.
376///
377bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
378 MachineInstr &CopyMI) {
379 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
380#ifndef NDEBUG
381 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
382 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy")(static_cast <bool> (VNI && VNI->def == Idx.
getRegSlot() && "Not defined by copy") ? void (0) : __assert_fail
("VNI && VNI->def == Idx.getRegSlot() && \"Not defined by copy\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 382, __extension__ __PRETTY_FUNCTION__
))
;
383#endif
384
385 Register SrcReg = CopyMI.getOperand(1).getReg();
386 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
387 VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
388 LiveQueryResult SrcQ = SrcLI.Query(Idx);
389 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
390 if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
391 return false;
392
393 // Conservatively extend the stack slot range to the range of the original
394 // value. We may be able to do better with stack slot coloring by being more
395 // careful here.
396 assert(StackInt && "No stack slot assigned yet.")(static_cast <bool> (StackInt && "No stack slot assigned yet."
) ? void (0) : __assert_fail ("StackInt && \"No stack slot assigned yet.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 396, __extension__ __PRETTY_FUNCTION__
))
;
397 LiveInterval &OrigLI = LIS.getInterval(Original);
398 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
399 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
400 LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tmerged orig valno " <<
OrigVNI->id << ": " << *StackInt << '\n'
; } } while (false)
401 << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tmerged orig valno " <<
OrigVNI->id << ": " << *StackInt << '\n'
; } } while (false)
;
402
403 // We are going to spill SrcVNI immediately after its def, so clear out
404 // any later spills of the same value.
405 eliminateRedundantSpills(SrcLI, SrcVNI);
406
407 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
408 MachineBasicBlock::iterator MII;
409 if (SrcVNI->isPHIDef())
410 MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
411 else {
412 MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
413 assert(DefMI && "Defining instruction disappeared")(static_cast <bool> (DefMI && "Defining instruction disappeared"
) ? void (0) : __assert_fail ("DefMI && \"Defining instruction disappeared\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 413, __extension__ __PRETTY_FUNCTION__
))
;
414 MII = DefMI;
415 ++MII;
416 }
417 MachineInstrSpan MIS(MII, MBB);
418 // Insert spill without kill flag immediately after def.
419 TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
420 MRI.getRegClass(SrcReg), &TRI);
421 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
422 for (const MachineInstr &MI : make_range(MIS.begin(), MII))
423 getVDefInterval(MI, LIS);
424 --MII; // Point to store instruction.
425 LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\thoisted: " << SrcVNI
->def << '\t' << *MII; } } while (false)
;
426
427 // If there is only 1 store instruction is required for spill, add it
428 // to mergeable list. In X86 AMX, 2 intructions are required to store.
429 // We disable the merge for this case.
430 if (MIS.begin() == MII)
431 HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
432 ++NumSpills;
433 return true;
434}
435
436/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
437/// redundant spills of this value in SLI.reg and sibling copies.
438void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
439 assert(VNI && "Missing value")(static_cast <bool> (VNI && "Missing value") ? void
(0) : __assert_fail ("VNI && \"Missing value\"", "llvm/lib/CodeGen/InlineSpiller.cpp"
, 439, __extension__ __PRETTY_FUNCTION__))
;
440 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
441 WorkList.push_back(std::make_pair(&SLI, VNI));
442 assert(StackInt && "No stack slot assigned yet.")(static_cast <bool> (StackInt && "No stack slot assigned yet."
) ? void (0) : __assert_fail ("StackInt && \"No stack slot assigned yet.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 442, __extension__ __PRETTY_FUNCTION__
))
;
443
444 do {
445 LiveInterval *LI;
446 std::tie(LI, VNI) = WorkList.pop_back_val();
447 Register Reg = LI->reg();
448 LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Checking redundant spills for "
<< VNI->id << '@' << VNI->def <<
" in " << *LI << '\n'; } } while (false)
449 << VNI->def << " in " << *LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Checking redundant spills for "
<< VNI->id << '@' << VNI->def <<
" in " << *LI << '\n'; } } while (false)
;
450
451 // Regs to spill are taken care of.
452 if (isRegToSpill(Reg))
453 continue;
454
455 // Add all of VNI's live range to StackInt.
456 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
457 LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Merged to stack int: " <<
*StackInt << '\n'; } } while (false)
;
458
459 // Find all spills and copies of VNI.
460 for (MachineInstr &MI :
461 llvm::make_early_inc_range(MRI.use_nodbg_instructions(Reg))) {
462 if (!MI.isCopy() && !MI.mayStore())
463 continue;
464 SlotIndex Idx = LIS.getInstructionIndex(MI);
465 if (LI->getVNInfoAt(Idx) != VNI)
466 continue;
467
468 // Follow sibling copies down the dominator tree.
469 if (Register DstReg = isFullCopyOf(MI, Reg)) {
470 if (isSibling(DstReg)) {
471 LiveInterval &DstLI = LIS.getInterval(DstReg);
472 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
473 assert(DstVNI && "Missing defined value")(static_cast <bool> (DstVNI && "Missing defined value"
) ? void (0) : __assert_fail ("DstVNI && \"Missing defined value\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 473, __extension__ __PRETTY_FUNCTION__
))
;
474 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot")(static_cast <bool> (DstVNI->def == Idx.getRegSlot()
&& "Wrong copy def slot") ? void (0) : __assert_fail
("DstVNI->def == Idx.getRegSlot() && \"Wrong copy def slot\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 474, __extension__ __PRETTY_FUNCTION__
))
;
475 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
476 }
477 continue;
478 }
479
480 // Erase spills.
481 int FI;
482 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
483 LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Redundant spill " << Idx
<< '\t' << MI; } } while (false)
;
484 // eliminateDeadDefs won't normally remove stores, so switch opcode.
485 MI.setDesc(TII.get(TargetOpcode::KILL));
486 DeadDefs.push_back(&MI);
487 ++NumSpillsRemoved;
488 if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
489 --NumSpills;
490 }
491 }
492 } while (!WorkList.empty());
493}
494
495//===----------------------------------------------------------------------===//
496// Rematerialization
497//===----------------------------------------------------------------------===//
498
499/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
500/// instruction cannot be eliminated. See through snippet copies
501void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
502 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
503 WorkList.push_back(std::make_pair(LI, VNI));
504 do {
505 std::tie(LI, VNI) = WorkList.pop_back_val();
506 if (!UsedValues.insert(VNI).second)
507 continue;
508
509 if (VNI->isPHIDef()) {
510 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
511 for (MachineBasicBlock *P : MBB->predecessors()) {
512 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
513 if (PVNI)
514 WorkList.push_back(std::make_pair(LI, PVNI));
515 }
516 continue;
517 }
518
519 // Follow snippet copies.
520 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
521 if (!SnippetCopies.count(MI))
522 continue;
523 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
524 assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy")(static_cast <bool> (isRegToSpill(SnipLI.reg()) &&
"Unexpected register in copy") ? void (0) : __assert_fail ("isRegToSpill(SnipLI.reg()) && \"Unexpected register in copy\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 524, __extension__ __PRETTY_FUNCTION__
))
;
525 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
526 assert(SnipVNI && "Snippet undefined before copy")(static_cast <bool> (SnipVNI && "Snippet undefined before copy"
) ? void (0) : __assert_fail ("SnipVNI && \"Snippet undefined before copy\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 526, __extension__ __PRETTY_FUNCTION__
))
;
527 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
528 } while (!WorkList.empty());
529}
530
531bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
532 MachineInstr &MI) {
533 if (!RestrictStatepointRemat)
534 return true;
535 // Here's a quick explanation of the problem we're trying to handle here:
536 // * There are some pseudo instructions with more vreg uses than there are
537 // physical registers on the machine.
538 // * This is normally handled by spilling the vreg, and folding the reload
539 // into the user instruction. (Thus decreasing the number of used vregs
540 // until the remainder can be assigned to physregs.)
541 // * However, since we may try to spill vregs in any order, we can end up
542 // trying to spill each operand to the instruction, and then rematting it
543 // instead. When that happens, the new live intervals (for the remats) are
544 // expected to be trivially assignable (i.e. RS_Done). However, since we
545 // may have more remats than physregs, we're guaranteed to fail to assign
546 // one.
547 // At the moment, we only handle this for STATEPOINTs since they're the only
548 // pseudo op where we've seen this. If we start seeing other instructions
549 // with the same problem, we need to revisit this.
550 if (MI.getOpcode() != TargetOpcode::STATEPOINT)
551 return true;
552 // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
553 // that number of physical registers is enough to cover all fixed arguments.
554 // If it is not true we need to revisit it.
555 for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
556 EndIdx = MI.getNumOperands();
557 Idx < EndIdx; ++Idx) {
558 MachineOperand &MO = MI.getOperand(Idx);
559 if (MO.isReg() && MO.getReg() == VReg)
560 return false;
561 }
562 return true;
563}
564
565/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
566bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
567 // Analyze instruction
568 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
569 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops);
570
571 if (!RI.Reads)
572 return false;
573
574 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
575 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
576
577 if (!ParentVNI) {
578 LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tadding <undef> flags: "
; } } while (false)
;
579 for (MachineOperand &MO : MI.operands())
580 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg())
581 MO.setIsUndef();
582 LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << UseIdx << '\t' <<
MI; } } while (false)
;
583 return true;
584 }
585
586 if (SnippetCopies.count(&MI))
587 return false;
588
589 LiveInterval &OrigLI = LIS.getInterval(Original);
590 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
591 LiveRangeEdit::Remat RM(ParentVNI);
592 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
593
594 if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
595 markValueUsed(&VirtReg, ParentVNI);
596 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat for " <<
UseIdx << '\t' << MI; } } while (false)
;
597 return false;
598 }
599
600 // If the instruction also writes VirtReg.reg, it had better not require the
601 // same register for uses and defs.
602 if (RI.Tied) {
603 markValueUsed(&VirtReg, ParentVNI);
604 LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat tied reg: " <<
UseIdx << '\t' << MI; } } while (false)
;
605 return false;
606 }
607
608 // Before rematerializing into a register for a single instruction, try to
609 // fold a load into the instruction. That avoids allocating a new register.
610 if (RM.OrigMI->canFoldAsLoad() &&
611 foldMemoryOperand(Ops, RM.OrigMI)) {
612 Edit->markRematerialized(RM.ParentVNI);
613 ++NumFoldedLoads;
614 return true;
615 }
616
617 // If we can't guarantee that we'll be able to actually assign the new vreg,
618 // we can't remat.
619 if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) {
620 markValueUsed(&VirtReg, ParentVNI);
621 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat for " <<
UseIdx << '\t' << MI; } } while (false)
;
622 return false;
623 }
624
625 // Allocate a new register for the remat.
626 Register NewVReg = Edit->createFrom(Original);
627
628 // Finally we can rematerialize OrigMI before MI.
629 SlotIndex DefIdx =
630 Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
631
632 // We take the DebugLoc from MI, since OrigMI may be attributed to a
633 // different source location.
634 auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
635 NewMI->setDebugLoc(MI.getDebugLoc());
636
637 (void)DefIdx;
638 LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremat: " << DefIdx <<
'\t' << *LIS.getInstructionFromIndex(DefIdx); } } while
(false)
639 << *LIS.getInstructionFromIndex(DefIdx))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremat: " << DefIdx <<
'\t' << *LIS.getInstructionFromIndex(DefIdx); } } while
(false)
;
640
641 // Replace operands
642 for (const auto &OpPair : Ops) {
643 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
644 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) {
645 MO.setReg(NewVReg);
646 MO.setIsKill();
647 }
648 }
649 LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t " << UseIdx <<
'\t' << MI << '\n'; } } while (false)
;
650
651 ++NumRemats;
652 return true;
653}
654
655/// reMaterializeAll - Try to rematerialize as many uses as possible,
656/// and trim the live ranges after.
657void InlineSpiller::reMaterializeAll() {
658 if (!Edit->anyRematerializable())
659 return;
660
661 UsedValues.clear();
662
663 // Try to remat before all uses of snippets.
664 bool anyRemat = false;
665 for (Register Reg : RegsToSpill) {
666 LiveInterval &LI = LIS.getInterval(Reg);
667 for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
668 // Debug values are not allowed to affect codegen.
669 if (MI.isDebugValue())
670 continue;
671
672 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "(static_cast <bool> (!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? void (0) : __assert_fail
("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 673, __extension__ __PRETTY_FUNCTION__
))
673 "instruction that isn't a DBG_VALUE")(static_cast <bool> (!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? void (0) : __assert_fail
("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 673, __extension__ __PRETTY_FUNCTION__
))
;
674
675 anyRemat |= reMaterializeFor(LI, MI);
676 }
677 }
678 if (!anyRemat)
679 return;
680
681 // Remove any values that were completely rematted.
682 for (Register Reg : RegsToSpill) {
683 LiveInterval &LI = LIS.getInterval(Reg);
684 for (VNInfo *VNI : LI.vnis()) {
685 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
686 continue;
687 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
688 MI->addRegisterDead(Reg, &TRI);
689 if (!MI->allDefsAreDead())
690 continue;
691 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "All defs dead: " << *MI
; } } while (false)
;
692 DeadDefs.push_back(MI);
693 }
694 }
695
696 // Eliminate dead code after remat. Note that some snippet copies may be
697 // deleted here.
698 if (DeadDefs.empty())
699 return;
700 LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Remat created " << DeadDefs
.size() << " dead defs.\n"; } } while (false)
;
701 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
702
703 // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
704 // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
705 // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
706 // removed, PHI VNI are still left in the LiveInterval.
707 // So to get rid of unused reg, we need to check whether it has non-dbg
708 // reference instead of whether it has non-empty interval.
709 unsigned ResultPos = 0;
710 for (Register Reg : RegsToSpill) {
711 if (MRI.reg_nodbg_empty(Reg)) {
712 Edit->eraseVirtReg(Reg);
713 continue;
714 }
715
716 assert(LIS.hasInterval(Reg) &&(static_cast <bool> (LIS.hasInterval(Reg) && (!
LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
"Empty and not used live-range?!") ? void (0) : __assert_fail
("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 718, __extension__ __PRETTY_FUNCTION__
))
717 (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&(static_cast <bool> (LIS.hasInterval(Reg) && (!
LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
"Empty and not used live-range?!") ? void (0) : __assert_fail
("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 718, __extension__ __PRETTY_FUNCTION__
))
718 "Empty and not used live-range?!")(static_cast <bool> (LIS.hasInterval(Reg) && (!
LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
"Empty and not used live-range?!") ? void (0) : __assert_fail
("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 718, __extension__ __PRETTY_FUNCTION__
))
;
719
720 RegsToSpill[ResultPos++] = Reg;
721 }
722 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
723 LLVM_DEBUG(dbgs() << RegsToSpill.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"
; } } while (false)
724 << " registers to spill after remat.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"
; } } while (false)
;
725}
726
727//===----------------------------------------------------------------------===//
728// Spilling
729//===----------------------------------------------------------------------===//
730
731/// If MI is a load or store of StackSlot, it can be removed.
732bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
733 int FI = 0;
734 Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
735 bool IsLoad = InstrReg;
736 if (!IsLoad)
737 InstrReg = TII.isStoreToStackSlot(*MI, FI);
738
739 // We have a stack access. Is it the right register and slot?
740 if (InstrReg != Reg || FI != StackSlot)
741 return false;
742
743 if (!IsLoad)
744 HSpiller.rmFromMergeableSpills(*MI, StackSlot);
745
746 LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Coalescing stack access: " <<
*MI; } } while (false)
;
747 LIS.RemoveMachineInstrFromMaps(*MI);
748 MI->eraseFromParent();
749
750 if (IsLoad) {
751 ++NumReloadsRemoved;
752 --NumReloads;
753 } else {
754 ++NumSpillsRemoved;
755 --NumSpills;
756 }
757
758 return true;
759}
760
761#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
762LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__))
763// Dump the range of instructions from B to E with their slot indexes.
764static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
765 MachineBasicBlock::iterator E,
766 LiveIntervals const &LIS,
767 const char *const header,
768 Register VReg = Register()) {
769 char NextLine = '\n';
770 char SlotIndent = '\t';
771
772 if (std::next(B) == E) {
773 NextLine = ' ';
774 SlotIndent = ' ';
775 }
776
777 dbgs() << '\t' << header << ": " << NextLine;
778
779 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
780 SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
781
782 // If a register was passed in and this instruction has it as a
783 // destination that is marked as an early clobber, print the
784 // early-clobber slot index.
785 if (VReg) {
786 MachineOperand *MO = I->findRegisterDefOperand(VReg);
787 if (MO && MO->isEarlyClobber())
788 Idx = Idx.getRegSlot(true);
789 }
790
791 dbgs() << SlotIndent << Idx << '\t' << *I;
792 }
793}
794#endif
795
796/// foldMemoryOperand - Try folding stack slot references in Ops into their
797/// instructions.
798///
799/// @param Ops Operand indices from AnalyzeVirtRegInBundle().
800/// @param LoadMI Load instruction to use instead of stack slot when non-null.
801/// @return True on success.
802bool InlineSpiller::
803foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
804 MachineInstr *LoadMI) {
805 if (Ops.empty())
806 return false;
807 // Don't attempt folding in bundles.
808 MachineInstr *MI = Ops.front().first;
809 if (Ops.back().first != MI || MI->isBundled())
810 return false;
811
812 bool WasCopy = MI->isCopy();
813 Register ImpReg;
814
815 // TII::foldMemoryOperand will do what we need here for statepoint
816 // (fold load into use and remove corresponding def). We will replace
817 // uses of removed def with loads (spillAroundUses).
818 // For that to work we need to untie def and use to pass it through
819 // foldMemoryOperand and signal foldPatchpoint that it is allowed to
820 // fold them.
821 bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
822
823 // Spill subregs if the target allows it.
824 // We always want to spill subregs for stackmap/patchpoint pseudos.
825 bool SpillSubRegs = TII.isSubregFoldable() ||
826 MI->getOpcode() == TargetOpcode::STATEPOINT ||
827 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
828 MI->getOpcode() == TargetOpcode::STACKMAP;
829
830 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
831 // operands.
832 SmallVector<unsigned, 8> FoldOps;
833 for (const auto &OpPair : Ops) {
834 unsigned Idx = OpPair.second;
835 assert(MI == OpPair.first && "Instruction conflict during operand folding")(static_cast <bool> (MI == OpPair.first && "Instruction conflict during operand folding"
) ? void (0) : __assert_fail ("MI == OpPair.first && \"Instruction conflict during operand folding\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 835, __extension__ __PRETTY_FUNCTION__
))
;
836 MachineOperand &MO = MI->getOperand(Idx);
837
838 // No point restoring an undef read, and we'll produce an invalid live
839 // interval.
840 // TODO: Is this really the correct way to handle undef tied uses?
841 if (MO.isUse() && !MO.readsReg() && !MO.isTied())
842 continue;
843
844 if (MO.isImplicit()) {
845 ImpReg = MO.getReg();
846 continue;
847 }
848
849 if (!SpillSubRegs && MO.getSubReg())
850 return false;
851 // We cannot fold a load instruction into a def.
852 if (LoadMI && MO.isDef())
853 return false;
854 // Tied use operands should not be passed to foldMemoryOperand.
855 if (UntieRegs || !MI->isRegTiedToDefOperand(Idx))
856 FoldOps.push_back(Idx);
857 }
858
859 // If we only have implicit uses, we won't be able to fold that.
860 // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
861 if (FoldOps.empty())
862 return false;
863
864 MachineInstrSpan MIS(MI, MI->getParent());
865
866 SmallVector<std::pair<unsigned, unsigned> > TiedOps;
867 if (UntieRegs)
868 for (unsigned Idx : FoldOps) {
869 MachineOperand &MO = MI->getOperand(Idx);
870 if (!MO.isTied())
871 continue;
872 unsigned Tied = MI->findTiedOperandIdx(Idx);
873 if (MO.isUse())
874 TiedOps.emplace_back(Tied, Idx);
875 else {
876 assert(MO.isDef() && "Tied to not use and def?")(static_cast <bool> (MO.isDef() && "Tied to not use and def?"
) ? void (0) : __assert_fail ("MO.isDef() && \"Tied to not use and def?\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 876, __extension__ __PRETTY_FUNCTION__
))
;
877 TiedOps.emplace_back(Idx, Tied);
878 }
879 MI->untieRegOperand(Idx);
880 }
881
882 MachineInstr *FoldMI =
883 LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
884 : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
885 if (!FoldMI) {
886 // Re-tie operands.
887 for (auto Tied : TiedOps)
888 MI->tieOperands(Tied.first, Tied.second);
889 return false;
890 }
891
892 // Remove LIS for any dead defs in the original MI not in FoldMI.
893 for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
894 if (!MO->isReg())
895 continue;
896 Register Reg = MO->getReg();
897 if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
898 continue;
899 }
900 // Skip non-Defs, including undef uses and internal reads.
901 if (MO->isUse())
902 continue;
903 PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
904 if (RI.FullyDefined)
905 continue;
906 // FoldMI does not define this physreg. Remove the LI segment.
907 assert(MO->isDead() && "Cannot fold physreg def")(static_cast <bool> (MO->isDead() && "Cannot fold physreg def"
) ? void (0) : __assert_fail ("MO->isDead() && \"Cannot fold physreg def\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 907, __extension__ __PRETTY_FUNCTION__
))
;
908 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
909 LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
910 }
911
912 int FI;
913 if (TII.isStoreToStackSlot(*MI, FI) &&
914 HSpiller.rmFromMergeableSpills(*MI, FI))
915 --NumSpills;
916 LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
917 // Update the call site info.
918 if (MI->isCandidateForCallSiteEntry())
919 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
920
921 // If we've folded a store into an instruction labelled with debug-info,
922 // record a substitution from the old operand to the memory operand. Handle
923 // the simple common case where operand 0 is the one being folded, plus when
924 // the destination operand is also a tied def. More values could be
925 // substituted / preserved with more analysis.
926 if (MI->peekDebugInstrNum() && Ops[0].second == 0) {
927 // Helper lambda.
928 auto MakeSubstitution = [this,FoldMI,MI,&Ops]() {
929 // Substitute old operand zero to the new instructions memory operand.
930 unsigned OldOperandNum = Ops[0].second;
931 unsigned NewNum = FoldMI->getDebugInstrNum();
932 unsigned OldNum = MI->getDebugInstrNum();
933 MF.makeDebugValueSubstitution({OldNum, OldOperandNum},
934 {NewNum, MachineFunction::DebugOperandMemNumber});
935 };
936
937 const MachineOperand &Op0 = MI->getOperand(Ops[0].second);
938 if (Ops.size() == 1 && Op0.isDef()) {
939 MakeSubstitution();
940 } else if (Ops.size() == 2 && Op0.isDef() && MI->getOperand(1).isTied() &&
941 Op0.getReg() == MI->getOperand(1).getReg()) {
942 MakeSubstitution();
943 }
944 } else if (MI->peekDebugInstrNum()) {
945 // This is a debug-labelled instruction, but the operand being folded isn't
946 // at operand zero. Most likely this means it's a load being folded in.
947 // Substitute any register defs from operand zero up to the one being
948 // folded -- past that point, we don't know what the new operand indexes
949 // will be.
950 MF.substituteDebugValuesForInst(*MI, *FoldMI, Ops[0].second);
951 }
952
953 MI->eraseFromParent();
954
955 // Insert any new instructions other than FoldMI into the LIS maps.
956 assert(!MIS.empty() && "Unexpected empty span of instructions!")(static_cast <bool> (!MIS.empty() && "Unexpected empty span of instructions!"
) ? void (0) : __assert_fail ("!MIS.empty() && \"Unexpected empty span of instructions!\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 956, __extension__ __PRETTY_FUNCTION__
))
;
957 for (MachineInstr &MI : MIS)
958 if (&MI != FoldMI)
959 LIS.InsertMachineInstrInMaps(MI);
960
961 // TII.foldMemoryOperand may have left some implicit operands on the
962 // instruction. Strip them.
963 if (ImpReg)
964 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
965 MachineOperand &MO = FoldMI->getOperand(i - 1);
966 if (!MO.isReg() || !MO.isImplicit())
967 break;
968 if (MO.getReg() == ImpReg)
969 FoldMI->removeOperand(i - 1);
970 }
971
972 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MIS.end(), LIS, "folded"); } } while (false)
973 "folded"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MIS.end(), LIS, "folded"); } } while (false)
;
974
975 if (!WasCopy)
976 ++NumFolded;
977 else if (Ops.front().second == 0) {
978 ++NumSpills;
979 // If there is only 1 store instruction is required for spill, add it
980 // to mergeable list. In X86 AMX, 2 intructions are required to store.
981 // We disable the merge for this case.
982 if (std::distance(MIS.begin(), MIS.end()) <= 1)
983 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
984 } else
985 ++NumReloads;
986 return true;
987}
988
989void InlineSpiller::insertReload(Register NewVReg,
990 SlotIndex Idx,
991 MachineBasicBlock::iterator MI) {
992 MachineBasicBlock &MBB = *MI->getParent();
993
994 MachineInstrSpan MIS(MI, &MBB);
995 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
996 MRI.getRegClass(NewVReg), &TRI);
997
998 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
999
1000 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MI, LIS, "reload", NewVReg); } } while (false)
1001 NewVReg))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MI, LIS, "reload", NewVReg); } } while (false)
;
1002 ++NumReloads;
1003}
1004
1005/// Check if \p Def fully defines a VReg with an undefined value.
1006/// If that's the case, that means the value of VReg is actually
1007/// not relevant.
1008static bool isRealSpill(const MachineInstr &Def) {
1009 if (!Def.isImplicitDef())
1010 return true;
1011 assert(Def.getNumOperands() == 1 &&(static_cast <bool> (Def.getNumOperands() == 1 &&
"Implicit def with more than one definition") ? void (0) : __assert_fail
("Def.getNumOperands() == 1 && \"Implicit def with more than one definition\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1012, __extension__ __PRETTY_FUNCTION__
))
1012 "Implicit def with more than one definition")(static_cast <bool> (Def.getNumOperands() == 1 &&
"Implicit def with more than one definition") ? void (0) : __assert_fail
("Def.getNumOperands() == 1 && \"Implicit def with more than one definition\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1012, __extension__ __PRETTY_FUNCTION__
))
;
1013 // We can say that the VReg defined by Def is undef, only if it is
1014 // fully defined by Def. Otherwise, some of the lanes may not be
1015 // undef and the value of the VReg matters.
1016 return Def.getOperand(0).getSubReg();
1017}
1018
1019/// insertSpill - Insert a spill of NewVReg after MI.
1020void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
1021 MachineBasicBlock::iterator MI) {
1022 // Spill are not terminators, so inserting spills after terminators will
1023 // violate invariants in MachineVerifier.
1024 assert(!MI->isTerminator() && "Inserting a spill after a terminator")(static_cast <bool> (!MI->isTerminator() && "Inserting a spill after a terminator"
) ? void (0) : __assert_fail ("!MI->isTerminator() && \"Inserting a spill after a terminator\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1024, __extension__ __PRETTY_FUNCTION__
))
;
1025 MachineBasicBlock &MBB = *MI->getParent();
1026
1027 MachineInstrSpan MIS(MI, &MBB);
1028 MachineBasicBlock::iterator SpillBefore = std::next(MI);
1029 bool IsRealSpill = isRealSpill(*MI);
1030
1031 if (IsRealSpill)
1032 TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
1033 MRI.getRegClass(NewVReg), &TRI);
1034 else
1035 // Don't spill undef value.
1036 // Anything works for undef, in particular keeping the memory
1037 // uninitialized is a viable option and it saves code size and
1038 // run time.
1039 BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
1040 .addReg(NewVReg, getKillRegState(isKill));
1041
1042 MachineBasicBlock::iterator Spill = std::next(MI);
1043 LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
1044 for (const MachineInstr &MI : make_range(Spill, MIS.end()))
1045 getVDefInterval(MI, LIS);
1046
1047 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(Spill, MIS
.end(), LIS, "spill"); } } while (false)
1048 dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(Spill, MIS
.end(), LIS, "spill"); } } while (false)
;
1049 ++NumSpills;
1050 // If there is only 1 store instruction is required for spill, add it
1051 // to mergeable list. In X86 AMX, 2 intructions are required to store.
1052 // We disable the merge for this case.
1053 if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
1054 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
1055}
1056
1057/// spillAroundUses - insert spill code around each use of Reg.
1058void InlineSpiller::spillAroundUses(Register Reg) {
1059 LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "spillAroundUses " << printReg
(Reg) << '\n'; } } while (false)
;
1060 LiveInterval &OldLI = LIS.getInterval(Reg);
1061
1062 // Iterate over instructions using Reg.
1063 for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
1064 // Debug values are not allowed to affect codegen.
1065 if (MI.isDebugValue()) {
1066 // Modify DBG_VALUE now that the value is in a spill slot.
1067 MachineBasicBlock *MBB = MI.getParent();
1068 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Modifying debug info due to spill:\t"
<< MI; } } while (false)
;
1069 buildDbgValueForSpill(*MBB, &MI, MI, StackSlot, Reg);
1070 MBB->erase(MI);
1071 continue;
1072 }
1073
1074 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "(static_cast <bool> (!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? void (0) : __assert_fail
("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1075, __extension__ __PRETTY_FUNCTION__
))
1075 "instruction that isn't a DBG_VALUE")(static_cast <bool> (!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? void (0) : __assert_fail
("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1075, __extension__ __PRETTY_FUNCTION__
))
;
1076
1077 // Ignore copies to/from snippets. We'll delete them.
1078 if (SnippetCopies.count(&MI))
1079 continue;
1080
1081 // Stack slot accesses may coalesce away.
1082 if (coalesceStackAccess(&MI, Reg))
1083 continue;
1084
1085 // Analyze instruction.
1086 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1087 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, Reg, &Ops);
1088
1089 // Find the slot index where this instruction reads and writes OldLI.
1090 // This is usually the def slot, except for tied early clobbers.
1091 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1092 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1093 if (SlotIndex::isSameInstr(Idx, VNI->def))
1094 Idx = VNI->def;
1095
1096 // Check for a sibling copy.
1097 Register SibReg = isFullCopyOf(MI, Reg);
1098 if (SibReg && isSibling(SibReg)) {
1099 // This may actually be a copy between snippets.
1100 if (isRegToSpill(SibReg)) {
1101 LLVM_DEBUG(dbgs() << "Found new snippet copy: " << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Found new snippet copy: " <<
MI; } } while (false)
;
1102 SnippetCopies.insert(&MI);
1103 continue;
1104 }
1105 if (RI.Writes) {
1106 if (hoistSpillInsideBB(OldLI, MI)) {
1107 // This COPY is now dead, the value is already in the stack slot.
1108 MI.getOperand(0).setIsDead();
1109 DeadDefs.push_back(&MI);
1110 continue;
1111 }
1112 } else {
1113 // This is a reload for a sib-reg copy. Drop spills downstream.
1114 LiveInterval &SibLI = LIS.getInterval(SibReg);
1115 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1116 // The COPY will fold to a reload below.
1117 }
1118 }
1119
1120 // Attempt to fold memory ops.
1121 if (foldMemoryOperand(Ops))
1122 continue;
1123
1124 // Create a new virtual register for spill/fill.
1125 // FIXME: Infer regclass from instruction alone.
1126 Register NewVReg = Edit->createFrom(Reg);
1127
1128 if (RI.Reads)
1129 insertReload(NewVReg, Idx, &MI);
1130
1131 // Rewrite instruction operands.
1132 bool hasLiveDef = false;
1133 for (const auto &OpPair : Ops) {
1134 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1135 MO.setReg(NewVReg);
1136 if (MO.isUse()) {
1137 if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1138 MO.setIsKill();
1139 } else {
1140 if (!MO.isDead())
1141 hasLiveDef = true;
1142 }
1143 }
1144 LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << MI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\trewrite: " << Idx <<
'\t' << MI << '\n'; } } while (false)
;
1145
1146 // FIXME: Use a second vreg if instruction has no tied ops.
1147 if (RI.Writes)
1148 if (hasLiveDef)
1149 insertSpill(NewVReg, true, &MI);
1150 }
1151}
1152
1153/// spillAll - Spill all registers remaining after rematerialization.
1154void InlineSpiller::spillAll() {
1155 // Update LiveStacks now that we are committed to spilling.
1156 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1157 StackSlot = VRM.assignVirt2StackSlot(Original);
1158 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1159 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1160 } else
1161 StackInt = &LSS.getInterval(StackSlot);
1162
1163 if (Original != Edit->getReg())
1164 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1165
1166 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values")(static_cast <bool> (StackInt->getNumValNums() == 1 &&
"Bad stack interval values") ? void (0) : __assert_fail ("StackInt->getNumValNums() == 1 && \"Bad stack interval values\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1166, __extension__ __PRETTY_FUNCTION__
))
;
1167 for (Register Reg : RegsToSpill)
1168 StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1169 StackInt->getValNumInfo(0));
1170 LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Merged spilled regs: " <<
*StackInt << '\n'; } } while (false)
;
1171
1172 // Spill around uses of all RegsToSpill.
1173 for (Register Reg : RegsToSpill)
1174 spillAroundUses(Reg);
1175
1176 // Hoisted spills may cause dead code.
1177 if (!DeadDefs.empty()) {
1178 LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Eliminating " << DeadDefs
.size() << " dead defs\n"; } } while (false)
;
1179 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1180 }
1181
1182 // Finally delete the SnippetCopies.
1183 for (Register Reg : RegsToSpill) {
1184 for (MachineInstr &MI :
1185 llvm::make_early_inc_range(MRI.reg_instructions(Reg))) {
1186 assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy")(static_cast <bool> (SnippetCopies.count(&MI) &&
"Remaining use wasn't a snippet copy") ? void (0) : __assert_fail
("SnippetCopies.count(&MI) && \"Remaining use wasn't a snippet copy\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1186, __extension__ __PRETTY_FUNCTION__
))
;
1187 // FIXME: Do this with a LiveRangeEdit callback.
1188 LIS.RemoveMachineInstrFromMaps(MI);
1189 MI.eraseFromParent();
1190 }
1191 }
1192
1193 // Delete all spilled registers.
1194 for (Register Reg : RegsToSpill)
1195 Edit->eraseVirtReg(Reg);
1196}
1197
1198void InlineSpiller::spill(LiveRangeEdit &edit) {
1199 ++NumSpilledRanges;
1200 Edit = &edit;
1201 assert(!Register::isStackSlot(edit.getReg()) &&(static_cast <bool> (!Register::isStackSlot(edit.getReg
()) && "Trying to spill a stack slot.") ? void (0) : __assert_fail
("!Register::isStackSlot(edit.getReg()) && \"Trying to spill a stack slot.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1202, __extension__ __PRETTY_FUNCTION__
))
1202 "Trying to spill a stack slot.")(static_cast <bool> (!Register::isStackSlot(edit.getReg
()) && "Trying to spill a stack slot.") ? void (0) : __assert_fail
("!Register::isStackSlot(edit.getReg()) && \"Trying to spill a stack slot.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1202, __extension__ __PRETTY_FUNCTION__
))
;
1203 // Share a stack slot among all descendants of Original.
1204 Original = VRM.getOriginal(edit.getReg());
1205 StackSlot = VRM.getStackSlot(Original);
1206 StackInt = nullptr;
1207
1208 LLVM_DEBUG(dbgs() << "Inline spilling "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1209 << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1210 << ':' << edit.getParent() << "\nFrom original "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1211 << printReg(Original) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
;
1212 assert(edit.getParent().isSpillable() &&(static_cast <bool> (edit.getParent().isSpillable() &&
"Attempting to spill already spilled value.") ? void (0) : __assert_fail
("edit.getParent().isSpillable() && \"Attempting to spill already spilled value.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1213, __extension__ __PRETTY_FUNCTION__
))
1213 "Attempting to spill already spilled value.")(static_cast <bool> (edit.getParent().isSpillable() &&
"Attempting to spill already spilled value.") ? void (0) : __assert_fail
("edit.getParent().isSpillable() && \"Attempting to spill already spilled value.\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1213, __extension__ __PRETTY_FUNCTION__
))
;
1214 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs")(static_cast <bool> (DeadDefs.empty() && "Previous spill didn't remove dead defs"
) ? void (0) : __assert_fail ("DeadDefs.empty() && \"Previous spill didn't remove dead defs\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1214, __extension__ __PRETTY_FUNCTION__
))
;
1215
1216 collectRegsToSpill();
1217 reMaterializeAll();
1218
1219 // Remat may handle everything.
1220 if (!RegsToSpill.empty())
1221 spillAll();
1222
1223 Edit->calculateRegClassAndHint(MF, VRAI);
1224}
1225
1226/// Optimizations after all the reg selections and spills are done.
1227void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1
Calling 'HoistSpillHelper::hoistAllSpills'
1228
1229/// When a spill is inserted, add the spill to MergeableSpills map.
1230void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1231 unsigned Original) {
1232 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1233 LiveInterval &OrigLI = LIS.getInterval(Original);
1234 // save a copy of LiveInterval in StackSlotToOrigLI because the original
1235 // LiveInterval may be cleared after all its references are spilled.
1236 if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
1237 auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1238 LI->assign(OrigLI, Allocator);
1239 StackSlotToOrigLI[StackSlot] = std::move(LI);
1240 }
1241 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1242 VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
1243 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1244 MergeableSpills[MIdx].insert(&Spill);
1245}
1246
1247/// When a spill is removed, remove the spill from MergeableSpills map.
1248/// Return true if the spill is removed successfully.
1249bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1250 int StackSlot) {
1251 auto It = StackSlotToOrigLI.find(StackSlot);
1252 if (It == StackSlotToOrigLI.end())
1253 return false;
1254 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1255 VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1256 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1257 return MergeableSpills[MIdx].erase(&Spill);
1258}
1259
1260/// Check BB to see if it is a possible target BB to place a hoisted spill,
1261/// i.e., there should be a living sibling of OrigReg at the insert point.
1262bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1263 MachineBasicBlock &BB, Register &LiveReg) {
1264 SlotIndex Idx = IPA.getLastInsertPoint(OrigLI, BB);
1265 // The original def could be after the last insert point in the root block,
1266 // we can't hoist to here.
1267 if (Idx < OrigVNI.def) {
1268 // TODO: We could be better here. If LI is not alive in landing pad
1269 // we could hoist spill after LIP.
1270 LLVM_DEBUG(dbgs() << "can't spill in root block - def after LIP\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "can't spill in root block - def after LIP\n"
; } } while (false)
;
1271 return false;
1272 }
1273 Register OrigReg = OrigLI.reg();
1274 SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1275 assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI")(static_cast <bool> (OrigLI.getVNInfoAt(Idx) == &OrigVNI
&& "Unexpected VNI") ? void (0) : __assert_fail ("OrigLI.getVNInfoAt(Idx) == &OrigVNI && \"Unexpected VNI\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1275, __extension__ __PRETTY_FUNCTION__
))
;
1276
1277 for (const Register &SibReg : Siblings) {
1278 LiveInterval &LI = LIS.getInterval(SibReg);
1279 VNInfo *VNI = LI.getVNInfoAt(Idx);
1280 if (VNI) {
1281 LiveReg = SibReg;
1282 return true;
1283 }
1284 }
1285 return false;
1286}
1287
1288/// Remove redundant spills in the same BB. Save those redundant spills in
1289/// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1290void HoistSpillHelper::rmRedundantSpills(
1291 SmallPtrSet<MachineInstr *, 16> &Spills,
1292 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1293 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1294 // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1295 // another spill inside. If a BB contains more than one spill, only keep the
1296 // earlier spill with smaller SlotIndex.
1297 for (auto *const CurrentSpill : Spills) {
1298 MachineBasicBlock *Block = CurrentSpill->getParent();
1299 MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
1300 MachineInstr *PrevSpill = SpillBBToSpill[Node];
1301 if (PrevSpill) {
1302 SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1303 SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1304 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1305 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1306 SpillsToRm.push_back(SpillToRm);
1307 SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
1308 } else {
1309 SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
1310 }
1311 }
1312 for (auto *const SpillToRm : SpillsToRm)
1313 Spills.erase(SpillToRm);
1314}
1315
1316/// Starting from \p Root find a top-down traversal order of the dominator
1317/// tree to visit all basic blocks containing the elements of \p Spills.
1318/// Redundant spills will be found and put into \p SpillsToRm at the same
1319/// time. \p SpillBBToSpill will be populated as part of the process and
1320/// maps a basic block to the first store occurring in the basic block.
1321/// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1322void HoistSpillHelper::getVisitOrders(
1323 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1324 SmallVectorImpl<MachineDomTreeNode *> &Orders,
1325 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1326 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1327 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1328 // The set contains all the possible BB nodes to which we may hoist
1329 // original spills.
1330 SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
1331 // Save the BB nodes on the path from the first BB node containing
1332 // non-redundant spill to the Root node.
1333 SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
1334 // All the spills to be hoisted must originate from a single def instruction
1335 // to the OrigReg. It means the def instruction should dominate all the spills
1336 // to be hoisted. We choose the BB where the def instruction is located as
1337 // the Root.
1338 MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1339 // For every node on the dominator tree with spill, walk up on the dominator
1340 // tree towards the Root node until it is reached. If there is other node
1341 // containing spill in the middle of the path, the previous spill saw will
1342 // be redundant and the node containing it will be removed. All the nodes on
1343 // the path starting from the first node with non-redundant spill to the Root
1344 // node will be added to the WorkSet, which will contain all the possible
1345 // locations where spills may be hoisted to after the loop below is done.
1346 for (auto *const Spill : Spills) {
1347 MachineBasicBlock *Block = Spill->getParent();
1348 MachineDomTreeNode *Node = MDT[Block];
9
Calling 'MachineDominatorTree::operator[]'
15
Returning from 'MachineDominatorTree::operator[]'
16
'Node' initialized here
1349 MachineInstr *SpillToRm = nullptr;
1350 while (Node != RootIDomNode) {
17
Assuming 'Node' is not equal to 'RootIDomNode'
1351 // If Node dominates Block, and it already contains a spill, the spill in
1352 // Block will be redundant.
1353 if (Node != MDT[Block] && SpillBBToSpill[Node]) {
18
Assuming the condition is false
19
Assuming pointer value is null
1354 SpillToRm = SpillBBToSpill[MDT[Block]];
1355 break;
1356 /// If we see the Node already in WorkSet, the path from the Node to
1357 /// the Root node must already be traversed by another spill.
1358 /// Then no need to repeat.
1359 } else if (WorkSet.count(Node)) {
20
Assuming the condition is false
21
Taking false branch
1360 break;
1361 } else {
1362 NodesOnPath.insert(Node);
1363 }
1364 Node = Node->getIDom();
22
Called C++ object pointer is null
1365 }
1366 if (SpillToRm) {
1367 SpillsToRm.push_back(SpillToRm);
1368 } else {
1369 // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1370 // set the initial status before hoisting start. The value of BBs
1371 // containing original spills is set to 0, in order to descriminate
1372 // with BBs containing hoisted spills which will be inserted to
1373 // SpillsToKeep later during hoisting.
1374 SpillsToKeep[MDT[Block]] = 0;
1375 WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
1376 }
1377 NodesOnPath.clear();
1378 }
1379
1380 // Sort the nodes in WorkSet in top-down order and save the nodes
1381 // in Orders. Orders will be used for hoisting in runHoistSpills.
1382 unsigned idx = 0;
1383 Orders.push_back(MDT.getBase().getNode(Root));
1384 do {
1385 MachineDomTreeNode *Node = Orders[idx++];
1386 for (MachineDomTreeNode *Child : Node->children()) {
1387 if (WorkSet.count(Child))
1388 Orders.push_back(Child);
1389 }
1390 } while (idx != Orders.size());
1391 assert(Orders.size() == WorkSet.size() &&(static_cast <bool> (Orders.size() == WorkSet.size() &&
"Orders have different size with WorkSet") ? void (0) : __assert_fail
("Orders.size() == WorkSet.size() && \"Orders have different size with WorkSet\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1392, __extension__ __PRETTY_FUNCTION__
))
1392 "Orders have different size with WorkSet")(static_cast <bool> (Orders.size() == WorkSet.size() &&
"Orders have different size with WorkSet") ? void (0) : __assert_fail
("Orders.size() == WorkSet.size() && \"Orders have different size with WorkSet\""
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1392, __extension__ __PRETTY_FUNCTION__
))
;
1393
1394#ifndef NDEBUG
1395 LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Orders size is " << Orders
.size() << "\n"; } } while (false)
;
1396 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1397 for (; RIt != Orders.rend(); RIt++)
1398 LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "BB" << (*RIt)->getBlock
()->getNumber() << ","; } } while (false)
;
1399 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\n"; } } while (false)
;
1400#endif
1401}
1402
1403/// Try to hoist spills according to BB hotness. The spills to removed will
1404/// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1405/// \p SpillsToIns.
1406void HoistSpillHelper::runHoistSpills(
1407 LiveInterval &OrigLI, VNInfo &OrigVNI,
1408 SmallPtrSet<MachineInstr *, 16> &Spills,
1409 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1410 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
1411 // Visit order of dominator tree nodes.
1412 SmallVector<MachineDomTreeNode *, 32> Orders;
1413 // SpillsToKeep contains all the nodes where spills are to be inserted
1414 // during hoisting. If the spill to be inserted is an original spill
1415 // (not a hoisted one), the value of the map entry is 0. If the spill
1416 // is a hoisted spill, the value of the map entry is the VReg to be used
1417 // as the source of the spill.
1418 DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
1419 // Map from BB to the first spill inside of it.
1420 DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
1421
1422 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1423
1424 MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1425 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
8
Calling 'HoistSpillHelper::getVisitOrders'
1426 SpillBBToSpill);
1427
1428 // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1429 // nodes set and the cost of all the spills inside those nodes.
1430 // The nodes set are the locations where spills are to be inserted
1431 // in the subtree of current node.
1432 using NodesCostPair =
1433 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1434 DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
1435
1436 // Iterate Orders set in reverse order, which will be a bottom-up order
1437 // in the dominator tree. Once we visit a dom tree node, we know its
1438 // children have already been visited and the spill locations in the
1439 // subtrees of all the children have been determined.
1440 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1441 for (; RIt != Orders.rend(); RIt++) {
1442 MachineBasicBlock *Block = (*RIt)->getBlock();
1443
1444 // If Block contains an original spill, simply continue.
1445 if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
1446 SpillsInSubTreeMap[*RIt].first.insert(*RIt);
1447 // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
1448 SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
1449 continue;
1450 }
1451
1452 // Collect spills in subtree of current node (*RIt) to
1453 // SpillsInSubTreeMap[*RIt].first.
1454 for (MachineDomTreeNode *Child : (*RIt)->children()) {
1455 if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
1456 continue;
1457 // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
1458 // should be placed before getting the begin and end iterators of
1459 // SpillsInSubTreeMap[Child].first, or else the iterators may be
1460 // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1461 // and the map grows and then the original buckets in the map are moved.
1462 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1463 SpillsInSubTreeMap[*RIt].first;
1464 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1465 SubTreeCost += SpillsInSubTreeMap[Child].second;
1466 auto BI = SpillsInSubTreeMap[Child].first.begin();
1467 auto EI = SpillsInSubTreeMap[Child].first.end();
1468 SpillsInSubTree.insert(BI, EI);
1469 SpillsInSubTreeMap.erase(Child);
1470 }
1471
1472 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1473 SpillsInSubTreeMap[*RIt].first;
1474 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1475 // No spills in subtree, simply continue.
1476 if (SpillsInSubTree.empty())
1477 continue;
1478
1479 // Check whether Block is a possible candidate to insert spill.
1480 Register LiveReg;
1481 if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1482 continue;
1483
1484 // If there are multiple spills that could be merged, bias a little
1485 // to hoist the spill.
1486 BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1487 ? BranchProbability(9, 10)
1488 : BranchProbability(1, 1);
1489 if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1490 // Hoist: Move spills to current Block.
1491 for (auto *const SpillBB : SpillsInSubTree) {
1492 // When SpillBB is a BB contains original spill, insert the spill
1493 // to SpillsToRm.
1494 if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
1495 !SpillsToKeep[SpillBB]) {
1496 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1497 SpillsToRm.push_back(SpillToRm);
1498 }
1499 // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1500 SpillsToKeep.erase(SpillBB);
1501 }
1502 // Current Block is the BB containing the new hoisted spill. Add it to
1503 // SpillsToKeep. LiveReg is the source of the new spill.
1504 SpillsToKeep[*RIt] = LiveReg;
1505 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1506 dbgs() << "spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1507 for (const auto Rspill : SpillsInSubTree)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1508 dbgs() << Rspill->getBlock()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1509 dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1510 << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1511 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
;
1512 SpillsInSubTree.clear();
1513 SpillsInSubTree.insert(*RIt);
1514 SubTreeCost = MBFI.getBlockFreq(Block);
1515 }
1516 }
1517 // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1518 // save them to SpillsToIns.
1519 for (const auto &Ent : SpillsToKeep) {
1520 if (Ent.second)
1521 SpillsToIns[Ent.first->getBlock()] = Ent.second;
1522 }
1523}
1524
1525/// For spills with equal values, remove redundant spills and hoist those left
1526/// to less hot spots.
1527///
1528/// Spills with equal values will be collected into the same set in
1529/// MergeableSpills when spill is inserted. These equal spills are originated
1530/// from the same defining instruction and are dominated by the instruction.
1531/// Before hoisting all the equal spills, redundant spills inside in the same
1532/// BB are first marked to be deleted. Then starting from the spills left, walk
1533/// up on the dominator tree towards the Root node where the define instruction
1534/// is located, mark the dominated spills to be deleted along the way and
1535/// collect the BB nodes on the path from non-dominated spills to the define
1536/// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1537/// where we are considering to hoist the spills. We iterate the WorkSet in
1538/// bottom-up order, and for each node, we will decide whether to hoist spills
1539/// inside its subtree to that node. In this way, we can get benefit locally
1540/// even if hoisting all the equal spills to one cold place is impossible.
1541void HoistSpillHelper::hoistAllSpills() {
1542 SmallVector<Register, 4> NewVRegs;
1543 LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1544
1545 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
2
Assuming 'i' is equal to 'e'
3
Loop condition is false. Execution continues on line 1553
1546 Register Reg = Register::index2VirtReg(i);
1547 Register Original = VRM.getPreSplitReg(Reg);
1548 if (!MRI.def_empty(Reg))
1549 Virt2SiblingsMap[Original].insert(Reg);
1550 }
1551
1552 // Each entry in MergeableSpills contains a spill set with equal values.
1553 for (auto &Ent : MergeableSpills) {
1554 int Slot = Ent.first.first;
1555 LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1556 VNInfo *OrigVNI = Ent.first.second;
1557 SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1558 if (Ent.second.empty())
1559 continue;
1560
1561 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
4
Taking false branch
5
Assuming 'DebugFlag' is false
6
Loop condition is false. Exiting loop
1562 dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1563 << "Equal spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1564 for (const auto spill : EqValSpills)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1565 dbgs() << spill->getParent()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1566 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1567 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
;
1568
1569 // SpillsToRm is the spill set to be removed from EqValSpills.
1570 SmallVector<MachineInstr *, 16> SpillsToRm;
1571 // SpillsToIns is the spill set to be newly inserted after hoisting.
1572 DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
1573
1574 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
7
Calling 'HoistSpillHelper::runHoistSpills'
1575
1576 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1577 dbgs() << "Finally inserted spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1578 for (const auto &Ispill : SpillsToIns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1579 dbgs() << Ispill.first->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1580 dbgs() << "\nFinally removed spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1581 for (const auto Rspill : SpillsToRm)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1582 dbgs() << Rspill->getParent()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1583 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1584 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
;
1585
1586 // Stack live range update.
1587 LiveInterval &StackIntvl = LSS.getInterval(Slot);
1588 if (!SpillsToIns.empty() || !SpillsToRm.empty())
1589 StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1590 StackIntvl.getValNumInfo(0));
1591
1592 // Insert hoisted spills.
1593 for (auto const &Insert : SpillsToIns) {
1594 MachineBasicBlock *BB = Insert.first;
1595 Register LiveReg = Insert.second;
1596 MachineBasicBlock::iterator MII = IPA.getLastInsertPointIter(OrigLI, *BB);
1597 MachineInstrSpan MIS(MII, BB);
1598 TII.storeRegToStackSlot(*BB, MII, LiveReg, false, Slot,
1599 MRI.getRegClass(LiveReg), &TRI);
1600 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
1601 for (const MachineInstr &MI : make_range(MIS.begin(), MII))
1602 getVDefInterval(MI, LIS);
1603 ++NumSpills;
1604 }
1605
1606 // Remove redundant spills or change them to dead instructions.
1607 NumSpills -= SpillsToRm.size();
1608 for (auto *const RMEnt : SpillsToRm) {
1609 RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1610 for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1611 MachineOperand &MO = RMEnt->getOperand(i - 1);
1612 if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1613 RMEnt->removeOperand(i - 1);
1614 }
1615 }
1616 Edit.eliminateDeadDefs(SpillsToRm, None);
1617 }
1618}
1619
1620/// For VirtReg clone, the \p New register should have the same physreg or
1621/// stackslot as the \p old register.
1622void HoistSpillHelper::LRE_DidCloneVirtReg(Register New, Register Old) {
1623 if (VRM.hasPhys(Old))
1624 VRM.assignVirt2Phys(New, VRM.getPhys(Old));
1625 else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
1626 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1627 else
1628 llvm_unreachable("VReg should be assigned either physreg or stackslot")::llvm::llvm_unreachable_internal("VReg should be assigned either physreg or stackslot"
, "llvm/lib/CodeGen/InlineSpiller.cpp", 1628)
;
1629 if (VRM.hasShape(Old))
1630 VRM.assignVirt2Shape(New, VRM.getShape(Old));
1631}

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/CodeGen/MachineDominators.h

1//==- llvm/CodeGen/MachineDominators.h - Machine Dom Calculation -*- C++ -*-==//
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// This file defines classes mirroring those in llvm/Analysis/Dominators.h,
10// but for target-specific code rather than target-independent IR.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_MACHINEDOMINATORS_H
15#define LLVM_CODEGEN_MACHINEDOMINATORS_H
16
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineInstr.h"
22#include "llvm/CodeGen/MachineInstrBundleIterator.h"
23#include "llvm/Support/GenericDomTree.h"
24#include "llvm/Support/GenericDomTreeConstruction.h"
25#include <cassert>
26#include <memory>
27
28namespace llvm {
29class AnalysisUsage;
30class MachineFunction;
31class Module;
32class raw_ostream;
33
34template <>
35inline void DominatorTreeBase<MachineBasicBlock, false>::addRoot(
36 MachineBasicBlock *MBB) {
37 this->Roots.push_back(MBB);
38}
39
40extern template class DomTreeNodeBase<MachineBasicBlock>;
41extern template class DominatorTreeBase<MachineBasicBlock, false>; // DomTree
42extern template class DominatorTreeBase<MachineBasicBlock, true>; // PostDomTree
43
44using MachineDomTree = DomTreeBase<MachineBasicBlock>;
45using MachineDomTreeNode = DomTreeNodeBase<MachineBasicBlock>;
46
47//===-------------------------------------
48/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
49/// compute a normal dominator tree.
50///
51class MachineDominatorTree : public MachineFunctionPass {
52 /// Helper structure used to hold all the basic blocks
53 /// involved in the split of a critical edge.
54 struct CriticalEdge {
55 MachineBasicBlock *FromBB;
56 MachineBasicBlock *ToBB;
57 MachineBasicBlock *NewBB;
58 };
59
60 /// Pile up all the critical edges to be split.
61 /// The splitting of a critical edge is local and thus, it is possible
62 /// to apply several of those changes at the same time.
63 mutable SmallVector<CriticalEdge, 32> CriticalEdgesToSplit;
64
65 /// Remember all the basic blocks that are inserted during
66 /// edge splitting.
67 /// Invariant: NewBBs == all the basic blocks contained in the NewBB
68 /// field of all the elements of CriticalEdgesToSplit.
69 /// I.e., forall elt in CriticalEdgesToSplit, it exists BB in NewBBs
70 /// such as BB == elt.NewBB.
71 mutable SmallSet<MachineBasicBlock *, 32> NewBBs;
72
73 /// The DominatorTreeBase that is used to compute a normal dominator tree.
74 std::unique_ptr<MachineDomTree> DT;
75
76 /// Apply all the recorded critical edges to the DT.
77 /// This updates the underlying DT information in a way that uses
78 /// the fast query path of DT as much as possible.
79 ///
80 /// \post CriticalEdgesToSplit.empty().
81 void applySplitCriticalEdges() const;
82
83public:
84 static char ID; // Pass ID, replacement for typeid
85
86 MachineDominatorTree();
87 explicit MachineDominatorTree(MachineFunction &MF) : MachineFunctionPass(ID) {
88 calculate(MF);
89 }
90
91 MachineDomTree &getBase() {
92 if (!DT)
93 DT.reset(new MachineDomTree());
94 applySplitCriticalEdges();
95 return *DT;
96 }
97
98 void getAnalysisUsage(AnalysisUsage &AU) const override;
99
100 MachineBasicBlock *getRoot() const {
101 applySplitCriticalEdges();
102 return DT->getRoot();
103 }
104
105 MachineDomTreeNode *getRootNode() const {
106 applySplitCriticalEdges();
107 return DT->getRootNode();
108 }
109
110 bool runOnMachineFunction(MachineFunction &F) override;
111
112 void calculate(MachineFunction &F);
113
114 bool dominates(const MachineDomTreeNode *A,
115 const MachineDomTreeNode *B) const {
116 applySplitCriticalEdges();
117 return DT->dominates(A, B);
118 }
119
120 void getDescendants(MachineBasicBlock *A,
121 SmallVectorImpl<MachineBasicBlock *> &Result) {
122 applySplitCriticalEdges();
123 DT->getDescendants(A, Result);
124 }
125
126 bool dominates(const MachineBasicBlock *A, const MachineBasicBlock *B) const {
127 applySplitCriticalEdges();
128 return DT->dominates(A, B);
129 }
130
131 // dominates - Return true if A dominates B. This performs the
132 // special checks necessary if A and B are in the same basic block.
133 bool dominates(const MachineInstr *A, const MachineInstr *B) const {
134 applySplitCriticalEdges();
135 const MachineBasicBlock *BBA = A->getParent(), *BBB = B->getParent();
136 if (BBA != BBB) return DT->dominates(BBA, BBB);
137
138 // Loop through the basic block until we find A or B.
139 MachineBasicBlock::const_iterator I = BBA->begin();
140 for (; &*I != A && &*I != B; ++I)
141 /*empty*/ ;
142
143 return &*I == A;
144 }
145
146 bool properlyDominates(const MachineDomTreeNode *A,
147 const MachineDomTreeNode *B) const {
148 applySplitCriticalEdges();
149 return DT->properlyDominates(A, B);
150 }
151
152 bool properlyDominates(const MachineBasicBlock *A,
153 const MachineBasicBlock *B) const {
154 applySplitCriticalEdges();
155 return DT->properlyDominates(A, B);
156 }
157
158 /// findNearestCommonDominator - Find nearest common dominator basic block
159 /// for basic block A and B. If there is no such block then return NULL.
160 MachineBasicBlock *findNearestCommonDominator(MachineBasicBlock *A,
161 MachineBasicBlock *B) {
162 applySplitCriticalEdges();
163 return DT->findNearestCommonDominator(A, B);
164 }
165
166 MachineDomTreeNode *operator[](MachineBasicBlock *BB) const {
167 applySplitCriticalEdges();
168 return DT->getNode(BB);
10
Calling 'DominatorTreeBase::getNode'
13
Returning from 'DominatorTreeBase::getNode'
14
Returning pointer
169 }
170
171 /// getNode - return the (Post)DominatorTree node for the specified basic
172 /// block. This is the same as using operator[] on this class.
173 ///
174 MachineDomTreeNode *getNode(MachineBasicBlock *BB) const {
175 applySplitCriticalEdges();
176 return DT->getNode(BB);
177 }
178
179 /// addNewBlock - Add a new node to the dominator tree information. This
180 /// creates a new node as a child of DomBB dominator node,linking it into
181 /// the children list of the immediate dominator.
182 MachineDomTreeNode *addNewBlock(MachineBasicBlock *BB,
183 MachineBasicBlock *DomBB) {
184 applySplitCriticalEdges();
185 return DT->addNewBlock(BB, DomBB);
186 }
187
188 /// changeImmediateDominator - This method is used to update the dominator
189 /// tree information when a node's immediate dominator changes.
190 ///
191 void changeImmediateDominator(MachineBasicBlock *N,
192 MachineBasicBlock *NewIDom) {
193 applySplitCriticalEdges();
194 DT->changeImmediateDominator(N, NewIDom);
195 }
196
197 void changeImmediateDominator(MachineDomTreeNode *N,
198 MachineDomTreeNode *NewIDom) {
199 applySplitCriticalEdges();
200 DT->changeImmediateDominator(N, NewIDom);
201 }
202
203 /// eraseNode - Removes a node from the dominator tree. Block must not
204 /// dominate any other blocks. Removes node from its immediate dominator's
205 /// children list. Deletes dominator node associated with basic block BB.
206 void eraseNode(MachineBasicBlock *BB) {
207 applySplitCriticalEdges();
208 DT->eraseNode(BB);
209 }
210
211 /// splitBlock - BB is split and now it has one successor. Update dominator
212 /// tree to reflect this change.
213 void splitBlock(MachineBasicBlock* NewBB) {
214 applySplitCriticalEdges();
215 DT->splitBlock(NewBB);
216 }
217
218 /// isReachableFromEntry - Return true if A is dominated by the entry
219 /// block of the function containing it.
220 bool isReachableFromEntry(const MachineBasicBlock *A) {
221 applySplitCriticalEdges();
222 return DT->isReachableFromEntry(A);
223 }
224
225 void releaseMemory() override;
226
227 void verifyAnalysis() const override;
228
229 void print(raw_ostream &OS, const Module*) const override;
230
231 /// Record that the critical edge (FromBB, ToBB) has been
232 /// split with NewBB.
233 /// This is best to use this method instead of directly update the
234 /// underlying information, because this helps mitigating the
235 /// number of time the DT information is invalidated.
236 ///
237 /// \note Do not use this method with regular edges.
238 ///
239 /// \note To benefit from the compile time improvement incurred by this
240 /// method, the users of this method have to limit the queries to the DT
241 /// interface between two edges splitting. In other words, they have to
242 /// pack the splitting of critical edges as much as possible.
243 void recordSplitCriticalEdge(MachineBasicBlock *FromBB,
244 MachineBasicBlock *ToBB,
245 MachineBasicBlock *NewBB) {
246 bool Inserted = NewBBs.insert(NewBB).second;
247 (void)Inserted;
248 assert(Inserted &&(static_cast <bool> (Inserted && "A basic block inserted via edge splitting cannot appear twice"
) ? void (0) : __assert_fail ("Inserted && \"A basic block inserted via edge splitting cannot appear twice\""
, "llvm/include/llvm/CodeGen/MachineDominators.h", 249, __extension__
__PRETTY_FUNCTION__))
249 "A basic block inserted via edge splitting cannot appear twice")(static_cast <bool> (Inserted && "A basic block inserted via edge splitting cannot appear twice"
) ? void (0) : __assert_fail ("Inserted && \"A basic block inserted via edge splitting cannot appear twice\""
, "llvm/include/llvm/CodeGen/MachineDominators.h", 249, __extension__
__PRETTY_FUNCTION__))
;
250 CriticalEdgesToSplit.push_back({FromBB, ToBB, NewBB});
251 }
252};
253
254//===-------------------------------------
255/// DominatorTree GraphTraits specialization so the DominatorTree can be
256/// iterable by generic graph iterators.
257///
258
259template <class Node, class ChildIterator>
260struct MachineDomTreeGraphTraitsBase {
261 using NodeRef = Node *;
262 using ChildIteratorType = ChildIterator;
263
264 static NodeRef getEntryNode(NodeRef N) { return N; }
265 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
266 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
267};
268
269template <class T> struct GraphTraits;
270
271template <>
272struct GraphTraits<MachineDomTreeNode *>
273 : public MachineDomTreeGraphTraitsBase<MachineDomTreeNode,
274 MachineDomTreeNode::const_iterator> {
275};
276
277template <>
278struct GraphTraits<const MachineDomTreeNode *>
279 : public MachineDomTreeGraphTraitsBase<const MachineDomTreeNode,
280 MachineDomTreeNode::const_iterator> {
281};
282
283template <> struct GraphTraits<MachineDominatorTree*>
284 : public GraphTraits<MachineDomTreeNode *> {
285 static NodeRef getEntryNode(MachineDominatorTree *DT) {
286 return DT->getRootNode();
287 }
288};
289
290} // end namespace llvm
291
292#endif // LLVM_CODEGEN_MACHINEDOMINATORS_H

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/Support/GenericDomTree.h

1//===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
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/// \file
9///
10/// This file defines a set of templates that efficiently compute a dominator
11/// tree over a generic graph. This is used typically in LLVM for fast
12/// dominance queries on the CFG, but is fully generic w.r.t. the underlying
13/// graph types.
14///
15/// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
16/// on the graph's NodeRef. The NodeRef should be a pointer and,
17/// NodeRef->getParent() must return the parent node that is also a pointer.
18///
19/// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_SUPPORT_GENERICDOMTREE_H
24#define LLVM_SUPPORT_GENERICDOMTREE_H
25
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/GraphTraits.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/Support/CFGDiff.h"
32#include "llvm/Support/CFGUpdate.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <iterator>
38#include <memory>
39#include <type_traits>
40#include <utility>
41
42namespace llvm {
43
44template <typename NodeT, bool IsPostDom>
45class DominatorTreeBase;
46
47namespace DomTreeBuilder {
48template <typename DomTreeT>
49struct SemiNCAInfo;
50} // namespace DomTreeBuilder
51
52/// Base class for the actual dominator tree node.
53template <class NodeT> class DomTreeNodeBase {
54 friend class PostDominatorTree;
55 friend class DominatorTreeBase<NodeT, false>;
56 friend class DominatorTreeBase<NodeT, true>;
57 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, false>>;
58 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, true>>;
59
60 NodeT *TheBB;
61 DomTreeNodeBase *IDom;
62 unsigned Level;
63 SmallVector<DomTreeNodeBase *, 4> Children;
64 mutable unsigned DFSNumIn = ~0;
65 mutable unsigned DFSNumOut = ~0;
66
67 public:
68 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom)
69 : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {}
70
71 using iterator = typename SmallVector<DomTreeNodeBase *, 4>::iterator;
72 using const_iterator =
73 typename SmallVector<DomTreeNodeBase *, 4>::const_iterator;
74
75 iterator begin() { return Children.begin(); }
76 iterator end() { return Children.end(); }
77 const_iterator begin() const { return Children.begin(); }
78 const_iterator end() const { return Children.end(); }
79
80 DomTreeNodeBase *const &back() const { return Children.back(); }
81 DomTreeNodeBase *&back() { return Children.back(); }
82
83 iterator_range<iterator> children() { return make_range(begin(), end()); }
84 iterator_range<const_iterator> children() const {
85 return make_range(begin(), end());
86 }
87
88 NodeT *getBlock() const { return TheBB; }
89 DomTreeNodeBase *getIDom() const { return IDom; }
90 unsigned getLevel() const { return Level; }
91
92 std::unique_ptr<DomTreeNodeBase> addChild(
93 std::unique_ptr<DomTreeNodeBase> C) {
94 Children.push_back(C.get());
95 return C;
96 }
97
98 bool isLeaf() const { return Children.empty(); }
99 size_t getNumChildren() const { return Children.size(); }
100
101 void clearAllChildren() { Children.clear(); }
102
103 bool compare(const DomTreeNodeBase *Other) const {
104 if (getNumChildren() != Other->getNumChildren())
105 return true;
106
107 if (Level != Other->Level) return true;
108
109 SmallPtrSet<const NodeT *, 4> OtherChildren;
110 for (const DomTreeNodeBase *I : *Other) {
111 const NodeT *Nd = I->getBlock();
112 OtherChildren.insert(Nd);
113 }
114
115 for (const DomTreeNodeBase *I : *this) {
116 const NodeT *N = I->getBlock();
117 if (OtherChildren.count(N) == 0)
118 return true;
119 }
120 return false;
121 }
122
123 void setIDom(DomTreeNodeBase *NewIDom) {
124 assert(IDom && "No immediate dominator?")(static_cast <bool> (IDom && "No immediate dominator?"
) ? void (0) : __assert_fail ("IDom && \"No immediate dominator?\""
, "llvm/include/llvm/Support/GenericDomTree.h", 124, __extension__
__PRETTY_FUNCTION__))
;
125 if (IDom == NewIDom) return;
126
127 auto I = find(IDom->Children, this);
128 assert(I != IDom->Children.end() &&(static_cast <bool> (I != IDom->Children.end() &&
"Not in immediate dominator children set!") ? void (0) : __assert_fail
("I != IDom->Children.end() && \"Not in immediate dominator children set!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 129, __extension__
__PRETTY_FUNCTION__))
129 "Not in immediate dominator children set!")(static_cast <bool> (I != IDom->Children.end() &&
"Not in immediate dominator children set!") ? void (0) : __assert_fail
("I != IDom->Children.end() && \"Not in immediate dominator children set!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 129, __extension__
__PRETTY_FUNCTION__))
;
130 // I am no longer your child...
131 IDom->Children.erase(I);
132
133 // Switch to new dominator
134 IDom = NewIDom;
135 IDom->Children.push_back(this);
136
137 UpdateLevel();
138 }
139
140 /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
141 /// in the dominator tree. They are only guaranteed valid if
142 /// updateDFSNumbers() has been called.
143 unsigned getDFSNumIn() const { return DFSNumIn; }
144 unsigned getDFSNumOut() const { return DFSNumOut; }
145
146private:
147 // Return true if this node is dominated by other. Use this only if DFS info
148 // is valid.
149 bool DominatedBy(const DomTreeNodeBase *other) const {
150 return this->DFSNumIn >= other->DFSNumIn &&
151 this->DFSNumOut <= other->DFSNumOut;
152 }
153
154 void UpdateLevel() {
155 assert(IDom)(static_cast <bool> (IDom) ? void (0) : __assert_fail (
"IDom", "llvm/include/llvm/Support/GenericDomTree.h", 155, __extension__
__PRETTY_FUNCTION__))
;
156 if (Level == IDom->Level + 1) return;
157
158 SmallVector<DomTreeNodeBase *, 64> WorkStack = {this};
159
160 while (!WorkStack.empty()) {
161 DomTreeNodeBase *Current = WorkStack.pop_back_val();
162 Current->Level = Current->IDom->Level + 1;
163
164 for (DomTreeNodeBase *C : *Current) {
165 assert(C->IDom)(static_cast <bool> (C->IDom) ? void (0) : __assert_fail
("C->IDom", "llvm/include/llvm/Support/GenericDomTree.h",
165, __extension__ __PRETTY_FUNCTION__))
;
166 if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C);
167 }
168 }
169 }
170};
171
172template <class NodeT>
173raw_ostream &operator<<(raw_ostream &O, const DomTreeNodeBase<NodeT> *Node) {
174 if (Node->getBlock())
175 Node->getBlock()->printAsOperand(O, false);
176 else
177 O << " <<exit node>>";
178
179 O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} ["
180 << Node->getLevel() << "]\n";
181
182 return O;
183}
184
185template <class NodeT>
186void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &O,
187 unsigned Lev) {
188 O.indent(2 * Lev) << "[" << Lev << "] " << N;
189 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
190 E = N->end();
191 I != E; ++I)
192 PrintDomTree<NodeT>(*I, O, Lev + 1);
193}
194
195namespace DomTreeBuilder {
196// The routines below are provided in a separate header but referenced here.
197template <typename DomTreeT>
198void Calculate(DomTreeT &DT);
199
200template <typename DomTreeT>
201void CalculateWithUpdates(DomTreeT &DT,
202 ArrayRef<typename DomTreeT::UpdateType> Updates);
203
204template <typename DomTreeT>
205void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
206 typename DomTreeT::NodePtr To);
207
208template <typename DomTreeT>
209void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
210 typename DomTreeT::NodePtr To);
211
212template <typename DomTreeT>
213void ApplyUpdates(DomTreeT &DT,
214 GraphDiff<typename DomTreeT::NodePtr,
215 DomTreeT::IsPostDominator> &PreViewCFG,
216 GraphDiff<typename DomTreeT::NodePtr,
217 DomTreeT::IsPostDominator> *PostViewCFG);
218
219template <typename DomTreeT>
220bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL);
221} // namespace DomTreeBuilder
222
223/// Core dominator tree base class.
224///
225/// This class is a generic template over graph nodes. It is instantiated for
226/// various graphs in the LLVM IR or in the code generator.
227template <typename NodeT, bool IsPostDom>
228class DominatorTreeBase {
229 public:
230 static_assert(std::is_pointer<typename GraphTraits<NodeT *>::NodeRef>::value,
231 "Currently DominatorTreeBase supports only pointer nodes");
232 using NodeType = NodeT;
233 using NodePtr = NodeT *;
234 using ParentPtr = decltype(std::declval<NodeT *>()->getParent());
235 static_assert(std::is_pointer<ParentPtr>::value,
236 "Currently NodeT's parent must be a pointer type");
237 using ParentType = std::remove_pointer_t<ParentPtr>;
238 static constexpr bool IsPostDominator = IsPostDom;
239
240 using UpdateType = cfg::Update<NodePtr>;
241 using UpdateKind = cfg::UpdateKind;
242 static constexpr UpdateKind Insert = UpdateKind::Insert;
243 static constexpr UpdateKind Delete = UpdateKind::Delete;
244
245 enum class VerificationLevel { Fast, Basic, Full };
246
247protected:
248 // Dominators always have a single root, postdominators can have more.
249 SmallVector<NodeT *, IsPostDom ? 4 : 1> Roots;
250
251 using DomTreeNodeMapType =
252 DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>;
253 DomTreeNodeMapType DomTreeNodes;
254 DomTreeNodeBase<NodeT> *RootNode = nullptr;
255 ParentPtr Parent = nullptr;
256
257 mutable bool DFSInfoValid = false;
258 mutable unsigned int SlowQueries = 0;
259
260 friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase>;
261
262 public:
263 DominatorTreeBase() = default;
264
265 DominatorTreeBase(DominatorTreeBase &&Arg)
266 : Roots(std::move(Arg.Roots)),
267 DomTreeNodes(std::move(Arg.DomTreeNodes)),
268 RootNode(Arg.RootNode),
269 Parent(Arg.Parent),
270 DFSInfoValid(Arg.DFSInfoValid),
271 SlowQueries(Arg.SlowQueries) {
272 Arg.wipe();
273 }
274
275 DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
276 Roots = std::move(RHS.Roots);
277 DomTreeNodes = std::move(RHS.DomTreeNodes);
278 RootNode = RHS.RootNode;
279 Parent = RHS.Parent;
280 DFSInfoValid = RHS.DFSInfoValid;
281 SlowQueries = RHS.SlowQueries;
282 RHS.wipe();
283 return *this;
284 }
285
286 DominatorTreeBase(const DominatorTreeBase &) = delete;
287 DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
288
289 /// Iteration over roots.
290 ///
291 /// This may include multiple blocks if we are computing post dominators.
292 /// For forward dominators, this will always be a single block (the entry
293 /// block).
294 using root_iterator = typename SmallVectorImpl<NodeT *>::iterator;
295 using const_root_iterator = typename SmallVectorImpl<NodeT *>::const_iterator;
296
297 root_iterator root_begin() { return Roots.begin(); }
298 const_root_iterator root_begin() const { return Roots.begin(); }
299 root_iterator root_end() { return Roots.end(); }
300 const_root_iterator root_end() const { return Roots.end(); }
301
302 size_t root_size() const { return Roots.size(); }
303
304 iterator_range<root_iterator> roots() {
305 return make_range(root_begin(), root_end());
306 }
307 iterator_range<const_root_iterator> roots() const {
308 return make_range(root_begin(), root_end());
309 }
310
311 /// isPostDominator - Returns true if analysis based of postdoms
312 ///
313 bool isPostDominator() const { return IsPostDominator; }
314
315 /// compare - Return false if the other dominator tree base matches this
316 /// dominator tree base. Otherwise return true.
317 bool compare(const DominatorTreeBase &Other) const {
318 if (Parent != Other.Parent) return true;
319
320 if (Roots.size() != Other.Roots.size())
321 return true;
322
323 if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin()))
324 return true;
325
326 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
327 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
328 return true;
329
330 for (const auto &DomTreeNode : DomTreeNodes) {
331 NodeT *BB = DomTreeNode.first;
332 typename DomTreeNodeMapType::const_iterator OI =
333 OtherDomTreeNodes.find(BB);
334 if (OI == OtherDomTreeNodes.end())
335 return true;
336
337 DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second;
338 DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
339
340 if (MyNd.compare(&OtherNd))
341 return true;
342 }
343
344 return false;
345 }
346
347 /// getNode - return the (Post)DominatorTree node for the specified basic
348 /// block. This is the same as using operator[] on this class. The result
349 /// may (but is not required to) be null for a forward (backwards)
350 /// statically unreachable block.
351 DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const {
352 auto I = DomTreeNodes.find(BB);
353 if (I != DomTreeNodes.end())
11
Taking true branch
354 return I->second.get();
12
Returning pointer
355 return nullptr;
356 }
357
358 /// See getNode.
359 DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const {
360 return getNode(BB);
361 }
362
363 /// getRootNode - This returns the entry node for the CFG of the function. If
364 /// this tree represents the post-dominance relations for a function, however,
365 /// this root may be a node with the block == NULL. This is the case when
366 /// there are multiple exit nodes from a particular function. Consumers of
367 /// post-dominance information must be capable of dealing with this
368 /// possibility.
369 ///
370 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
371 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
372
373 /// Get all nodes dominated by R, including R itself.
374 void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
375 Result.clear();
376 const DomTreeNodeBase<NodeT> *RN = getNode(R);
377 if (!RN)
378 return; // If R is unreachable, it will not be present in the DOM tree.
379 SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
380 WL.push_back(RN);
381
382 while (!WL.empty()) {
383 const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
384 Result.push_back(N->getBlock());
385 WL.append(N->begin(), N->end());
386 }
387 }
388
389 /// properlyDominates - Returns true iff A dominates B and A != B.
390 /// Note that this is not a constant time operation!
391 ///
392 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
393 const DomTreeNodeBase<NodeT> *B) const {
394 if (!A || !B)
395 return false;
396 if (A == B)
397 return false;
398 return dominates(A, B);
399 }
400
401 bool properlyDominates(const NodeT *A, const NodeT *B) const;
402
403 /// isReachableFromEntry - Return true if A is dominated by the entry
404 /// block of the function containing it.
405 bool isReachableFromEntry(const NodeT *A) const {
406 assert(!this->isPostDominator() &&(static_cast <bool> (!this->isPostDominator() &&
"This is not implemented for post dominators") ? void (0) : __assert_fail
("!this->isPostDominator() && \"This is not implemented for post dominators\""
, "llvm/include/llvm/Support/GenericDomTree.h", 407, __extension__
__PRETTY_FUNCTION__))
407 "This is not implemented for post dominators")(static_cast <bool> (!this->isPostDominator() &&
"This is not implemented for post dominators") ? void (0) : __assert_fail
("!this->isPostDominator() && \"This is not implemented for post dominators\""
, "llvm/include/llvm/Support/GenericDomTree.h", 407, __extension__
__PRETTY_FUNCTION__))
;
408 return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
409 }
410
411 bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
412
413 /// dominates - Returns true iff A dominates B. Note that this is not a
414 /// constant time operation!
415 ///
416 bool dominates(const DomTreeNodeBase<NodeT> *A,
417 const DomTreeNodeBase<NodeT> *B) const {
418 // A node trivially dominates itself.
419 if (B == A)
420 return true;
421
422 // An unreachable node is dominated by anything.
423 if (!isReachableFromEntry(B))
424 return true;
425
426 // And dominates nothing.
427 if (!isReachableFromEntry(A))
428 return false;
429
430 if (B->getIDom() == A) return true;
431
432 if (A->getIDom() == B) return false;
433
434 // A can only dominate B if it is higher in the tree.
435 if (A->getLevel() >= B->getLevel()) return false;
436
437 // Compare the result of the tree walk and the dfs numbers, if expensive
438 // checks are enabled.
439#ifdef EXPENSIVE_CHECKS
440 assert((!DFSInfoValid ||(static_cast <bool> ((!DFSInfoValid || (dominatedBySlowTreeWalk
(A, B) == B->DominatedBy(A))) && "Tree walk disagrees with dfs numbers!"
) ? void (0) : __assert_fail ("(!DFSInfoValid || (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) && \"Tree walk disagrees with dfs numbers!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 442, __extension__
__PRETTY_FUNCTION__))
441 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&(static_cast <bool> ((!DFSInfoValid || (dominatedBySlowTreeWalk
(A, B) == B->DominatedBy(A))) && "Tree walk disagrees with dfs numbers!"
) ? void (0) : __assert_fail ("(!DFSInfoValid || (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) && \"Tree walk disagrees with dfs numbers!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 442, __extension__
__PRETTY_FUNCTION__))
442 "Tree walk disagrees with dfs numbers!")(static_cast <bool> ((!DFSInfoValid || (dominatedBySlowTreeWalk
(A, B) == B->DominatedBy(A))) && "Tree walk disagrees with dfs numbers!"
) ? void (0) : __assert_fail ("(!DFSInfoValid || (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) && \"Tree walk disagrees with dfs numbers!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 442, __extension__
__PRETTY_FUNCTION__))
;
443#endif
444
445 if (DFSInfoValid)
446 return B->DominatedBy(A);
447
448 // If we end up with too many slow queries, just update the
449 // DFS numbers on the theory that we are going to keep querying.
450 SlowQueries++;
451 if (SlowQueries > 32) {
452 updateDFSNumbers();
453 return B->DominatedBy(A);
454 }
455
456 return dominatedBySlowTreeWalk(A, B);
457 }
458
459 bool dominates(const NodeT *A, const NodeT *B) const;
460
461 NodeT *getRoot() const {
462 assert(this->Roots.size() == 1 && "Should always have entry node!")(static_cast <bool> (this->Roots.size() == 1 &&
"Should always have entry node!") ? void (0) : __assert_fail
("this->Roots.size() == 1 && \"Should always have entry node!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 462, __extension__
__PRETTY_FUNCTION__))
;
463 return this->Roots[0];
464 }
465
466 /// Find nearest common dominator basic block for basic block A and B. A and B
467 /// must have tree nodes.
468 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const {
469 assert(A && B && "Pointers are not valid")(static_cast <bool> (A && B && "Pointers are not valid"
) ? void (0) : __assert_fail ("A && B && \"Pointers are not valid\""
, "llvm/include/llvm/Support/GenericDomTree.h", 469, __extension__
__PRETTY_FUNCTION__))
;
470 assert(A->getParent() == B->getParent() &&(static_cast <bool> (A->getParent() == B->getParent
() && "Two blocks are not in same function") ? void (
0) : __assert_fail ("A->getParent() == B->getParent() && \"Two blocks are not in same function\""
, "llvm/include/llvm/Support/GenericDomTree.h", 471, __extension__
__PRETTY_FUNCTION__))
471 "Two blocks are not in same function")(static_cast <bool> (A->getParent() == B->getParent
() && "Two blocks are not in same function") ? void (
0) : __assert_fail ("A->getParent() == B->getParent() && \"Two blocks are not in same function\""
, "llvm/include/llvm/Support/GenericDomTree.h", 471, __extension__
__PRETTY_FUNCTION__))
;
472
473 // If either A or B is a entry block then it is nearest common dominator
474 // (for forward-dominators).
475 if (!isPostDominator()) {
476 NodeT &Entry = A->getParent()->front();
477 if (A == &Entry || B == &Entry)
478 return &Entry;
479 }
480
481 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
482 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
483 assert(NodeA && "A must be in the tree")(static_cast <bool> (NodeA && "A must be in the tree"
) ? void (0) : __assert_fail ("NodeA && \"A must be in the tree\""
, "llvm/include/llvm/Support/GenericDomTree.h", 483, __extension__
__PRETTY_FUNCTION__))
;
484 assert(NodeB && "B must be in the tree")(static_cast <bool> (NodeB && "B must be in the tree"
) ? void (0) : __assert_fail ("NodeB && \"B must be in the tree\""
, "llvm/include/llvm/Support/GenericDomTree.h", 484, __extension__
__PRETTY_FUNCTION__))
;
485
486 // Use level information to go up the tree until the levels match. Then
487 // continue going up til we arrive at the same node.
488 while (NodeA != NodeB) {
489 if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB);
490
491 NodeA = NodeA->IDom;
492 }
493
494 return NodeA->getBlock();
495 }
496
497 const NodeT *findNearestCommonDominator(const NodeT *A,
498 const NodeT *B) const {
499 // Cast away the const qualifiers here. This is ok since
500 // const is re-introduced on the return type.
501 return findNearestCommonDominator(const_cast<NodeT *>(A),
502 const_cast<NodeT *>(B));
503 }
504
505 bool isVirtualRoot(const DomTreeNodeBase<NodeT> *A) const {
506 return isPostDominator() && !A->getBlock();
507 }
508
509 //===--------------------------------------------------------------------===//
510 // API to update (Post)DominatorTree information based on modifications to
511 // the CFG...
512
513 /// Inform the dominator tree about a sequence of CFG edge insertions and
514 /// deletions and perform a batch update on the tree.
515 ///
516 /// This function should be used when there were multiple CFG updates after
517 /// the last dominator tree update. It takes care of performing the updates
518 /// in sync with the CFG and optimizes away the redundant operations that
519 /// cancel each other.
520 /// The functions expects the sequence of updates to be balanced. Eg.:
521 /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because
522 /// logically it results in a single insertions.
523 /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make
524 /// sense to insert the same edge twice.
525 ///
526 /// What's more, the functions assumes that it's safe to ask every node in the
527 /// CFG about its children and inverse children. This implies that deletions
528 /// of CFG edges must not delete the CFG nodes before calling this function.
529 ///
530 /// The applyUpdates function can reorder the updates and remove redundant
531 /// ones internally (as long as it is done in a deterministic fashion). The
532 /// batch updater is also able to detect sequences of zero and exactly one
533 /// update -- it's optimized to do less work in these cases.
534 ///
535 /// Note that for postdominators it automatically takes care of applying
536 /// updates on reverse edges internally (so there's no need to swap the
537 /// From and To pointers when constructing DominatorTree::UpdateType).
538 /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T>
539 /// with the same template parameter T.
540 ///
541 /// \param Updates An ordered sequence of updates to perform. The current CFG
542 /// and the reverse of these updates provides the pre-view of the CFG.
543 ///
544 void applyUpdates(ArrayRef<UpdateType> Updates) {
545 GraphDiff<NodePtr, IsPostDominator> PreViewCFG(
546 Updates, /*ReverseApplyUpdates=*/true);
547 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr);
548 }
549
550 /// \param Updates An ordered sequence of updates to perform. The current CFG
551 /// and the reverse of these updates provides the pre-view of the CFG.
552 /// \param PostViewUpdates An ordered sequence of update to perform in order
553 /// to obtain a post-view of the CFG. The DT will be updated assuming the
554 /// obtained PostViewCFG is the desired end state.
555 void applyUpdates(ArrayRef<UpdateType> Updates,
556 ArrayRef<UpdateType> PostViewUpdates) {
557 if (Updates.empty()) {
558 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
559 DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG);
560 } else {
561 // PreViewCFG needs to merge Updates and PostViewCFG. The updates in
562 // Updates need to be reversed, and match the direction in PostViewCFG.
563 // The PostViewCFG is created with updates reversed (equivalent to changes
564 // made to the CFG), so the PreViewCFG needs all the updates reverse
565 // applied.
566 SmallVector<UpdateType> AllUpdates(Updates.begin(), Updates.end());
567 append_range(AllUpdates, PostViewUpdates);
568 GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates,
569 /*ReverseApplyUpdates=*/true);
570 GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates);
571 DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG);
572 }
573 }
574
575 /// Inform the dominator tree about a CFG edge insertion and update the tree.
576 ///
577 /// This function has to be called just before or just after making the update
578 /// on the actual CFG. There cannot be any other updates that the dominator
579 /// tree doesn't know about.
580 ///
581 /// Note that for postdominators it automatically takes care of inserting
582 /// a reverse edge internally (so there's no need to swap the parameters).
583 ///
584 void insertEdge(NodeT *From, NodeT *To) {
585 assert(From)(static_cast <bool> (From) ? void (0) : __assert_fail (
"From", "llvm/include/llvm/Support/GenericDomTree.h", 585, __extension__
__PRETTY_FUNCTION__))
;
586 assert(To)(static_cast <bool> (To) ? void (0) : __assert_fail ("To"
, "llvm/include/llvm/Support/GenericDomTree.h", 586, __extension__
__PRETTY_FUNCTION__))
;
587 assert(From->getParent() == Parent)(static_cast <bool> (From->getParent() == Parent) ? void
(0) : __assert_fail ("From->getParent() == Parent", "llvm/include/llvm/Support/GenericDomTree.h"
, 587, __extension__ __PRETTY_FUNCTION__))
;
588 assert(To->getParent() == Parent)(static_cast <bool> (To->getParent() == Parent) ? void
(0) : __assert_fail ("To->getParent() == Parent", "llvm/include/llvm/Support/GenericDomTree.h"
, 588, __extension__ __PRETTY_FUNCTION__))
;
589 DomTreeBuilder::InsertEdge(*this, From, To);
590 }
591
592 /// Inform the dominator tree about a CFG edge deletion and update the tree.
593 ///
594 /// This function has to be called just after making the update on the actual
595 /// CFG. An internal functions checks if the edge doesn't exist in the CFG in
596 /// DEBUG mode. There cannot be any other updates that the
597 /// dominator tree doesn't know about.
598 ///
599 /// Note that for postdominators it automatically takes care of deleting
600 /// a reverse edge internally (so there's no need to swap the parameters).
601 ///
602 void deleteEdge(NodeT *From, NodeT *To) {
603 assert(From)(static_cast <bool> (From) ? void (0) : __assert_fail (
"From", "llvm/include/llvm/Support/GenericDomTree.h", 603, __extension__
__PRETTY_FUNCTION__))
;
604 assert(To)(static_cast <bool> (To) ? void (0) : __assert_fail ("To"
, "llvm/include/llvm/Support/GenericDomTree.h", 604, __extension__
__PRETTY_FUNCTION__))
;
605 assert(From->getParent() == Parent)(static_cast <bool> (From->getParent() == Parent) ? void
(0) : __assert_fail ("From->getParent() == Parent", "llvm/include/llvm/Support/GenericDomTree.h"
, 605, __extension__ __PRETTY_FUNCTION__))
;
606 assert(To->getParent() == Parent)(static_cast <bool> (To->getParent() == Parent) ? void
(0) : __assert_fail ("To->getParent() == Parent", "llvm/include/llvm/Support/GenericDomTree.h"
, 606, __extension__ __PRETTY_FUNCTION__))
;
607 DomTreeBuilder::DeleteEdge(*this, From, To);
608 }
609
610 /// Add a new node to the dominator tree information.
611 ///
612 /// This creates a new node as a child of DomBB dominator node, linking it
613 /// into the children list of the immediate dominator.
614 ///
615 /// \param BB New node in CFG.
616 /// \param DomBB CFG node that is dominator for BB.
617 /// \returns New dominator tree node that represents new CFG node.
618 ///
619 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
620 assert(getNode(BB) == nullptr && "Block already in dominator tree!")(static_cast <bool> (getNode(BB) == nullptr && "Block already in dominator tree!"
) ? void (0) : __assert_fail ("getNode(BB) == nullptr && \"Block already in dominator tree!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 620, __extension__
__PRETTY_FUNCTION__))
;
621 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
622 assert(IDomNode && "Not immediate dominator specified for block!")(static_cast <bool> (IDomNode && "Not immediate dominator specified for block!"
) ? void (0) : __assert_fail ("IDomNode && \"Not immediate dominator specified for block!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 622, __extension__
__PRETTY_FUNCTION__))
;
623 DFSInfoValid = false;
624 return createChild(BB, IDomNode);
625 }
626
627 /// Add a new node to the forward dominator tree and make it a new root.
628 ///
629 /// \param BB New node in CFG.
630 /// \returns New dominator tree node that represents new CFG node.
631 ///
632 DomTreeNodeBase<NodeT> *setNewRoot(NodeT *BB) {
633 assert(getNode(BB) == nullptr && "Block already in dominator tree!")(static_cast <bool> (getNode(BB) == nullptr && "Block already in dominator tree!"
) ? void (0) : __assert_fail ("getNode(BB) == nullptr && \"Block already in dominator tree!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 633, __extension__
__PRETTY_FUNCTION__))
;
634 assert(!this->isPostDominator() &&(static_cast <bool> (!this->isPostDominator() &&
"Cannot change root of post-dominator tree") ? void (0) : __assert_fail
("!this->isPostDominator() && \"Cannot change root of post-dominator tree\""
, "llvm/include/llvm/Support/GenericDomTree.h", 635, __extension__
__PRETTY_FUNCTION__))
635 "Cannot change root of post-dominator tree")(static_cast <bool> (!this->isPostDominator() &&
"Cannot change root of post-dominator tree") ? void (0) : __assert_fail
("!this->isPostDominator() && \"Cannot change root of post-dominator tree\""
, "llvm/include/llvm/Support/GenericDomTree.h", 635, __extension__
__PRETTY_FUNCTION__))
;
636 DFSInfoValid = false;
637 DomTreeNodeBase<NodeT> *NewNode = createNode(BB);
638 if (Roots.empty()) {
639 addRoot(BB);
640 } else {
641 assert(Roots.size() == 1)(static_cast <bool> (Roots.size() == 1) ? void (0) : __assert_fail
("Roots.size() == 1", "llvm/include/llvm/Support/GenericDomTree.h"
, 641, __extension__ __PRETTY_FUNCTION__))
;
642 NodeT *OldRoot = Roots.front();
643 auto &OldNode = DomTreeNodes[OldRoot];
644 OldNode = NewNode->addChild(std::move(DomTreeNodes[OldRoot]));
645 OldNode->IDom = NewNode;
646 OldNode->UpdateLevel();
647 Roots[0] = BB;
648 }
649 return RootNode = NewNode;
650 }
651
652 /// changeImmediateDominator - This method is used to update the dominator
653 /// tree information when a node's immediate dominator changes.
654 ///
655 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
656 DomTreeNodeBase<NodeT> *NewIDom) {
657 assert(N && NewIDom && "Cannot change null node pointers!")(static_cast <bool> (N && NewIDom && "Cannot change null node pointers!"
) ? void (0) : __assert_fail ("N && NewIDom && \"Cannot change null node pointers!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 657, __extension__
__PRETTY_FUNCTION__))
;
658 DFSInfoValid = false;
659 N->setIDom(NewIDom);
660 }
661
662 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
663 changeImmediateDominator(getNode(BB), getNode(NewBB));
664 }
665
666 /// eraseNode - Removes a node from the dominator tree. Block must not
667 /// dominate any other blocks. Removes node from its immediate dominator's
668 /// children list. Deletes dominator node associated with basic block BB.
669 void eraseNode(NodeT *BB) {
670 DomTreeNodeBase<NodeT> *Node = getNode(BB);
671 assert(Node && "Removing node that isn't in dominator tree.")(static_cast <bool> (Node && "Removing node that isn't in dominator tree."
) ? void (0) : __assert_fail ("Node && \"Removing node that isn't in dominator tree.\""
, "llvm/include/llvm/Support/GenericDomTree.h", 671, __extension__
__PRETTY_FUNCTION__))
;
672 assert(Node->isLeaf() && "Node is not a leaf node.")(static_cast <bool> (Node->isLeaf() && "Node is not a leaf node."
) ? void (0) : __assert_fail ("Node->isLeaf() && \"Node is not a leaf node.\""
, "llvm/include/llvm/Support/GenericDomTree.h", 672, __extension__
__PRETTY_FUNCTION__))
;
673
674 DFSInfoValid = false;
675
676 // Remove node from immediate dominator's children list.
677 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
678 if (IDom) {
679 const auto I = find(IDom->Children, Node);
680 assert(I != IDom->Children.end() &&(static_cast <bool> (I != IDom->Children.end() &&
"Not in immediate dominator children set!") ? void (0) : __assert_fail
("I != IDom->Children.end() && \"Not in immediate dominator children set!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 681, __extension__
__PRETTY_FUNCTION__))
681 "Not in immediate dominator children set!")(static_cast <bool> (I != IDom->Children.end() &&
"Not in immediate dominator children set!") ? void (0) : __assert_fail
("I != IDom->Children.end() && \"Not in immediate dominator children set!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 681, __extension__
__PRETTY_FUNCTION__))
;
682 // I am no longer your child...
683 IDom->Children.erase(I);
684 }
685
686 DomTreeNodes.erase(BB);
687
688 if (!IsPostDom) return;
689
690 // Remember to update PostDominatorTree roots.
691 auto RIt = llvm::find(Roots, BB);
692 if (RIt != Roots.end()) {
693 std::swap(*RIt, Roots.back());
694 Roots.pop_back();
695 }
696 }
697
698 /// splitBlock - BB is split and now it has one successor. Update dominator
699 /// tree to reflect this change.
700 void splitBlock(NodeT *NewBB) {
701 if (IsPostDominator)
702 Split<Inverse<NodeT *>>(NewBB);
703 else
704 Split<NodeT *>(NewBB);
705 }
706
707 /// print - Convert to human readable form
708 ///
709 void print(raw_ostream &O) const {
710 O << "=============================--------------------------------\n";
711 if (IsPostDominator)
712 O << "Inorder PostDominator Tree: ";
713 else
714 O << "Inorder Dominator Tree: ";
715 if (!DFSInfoValid)
716 O << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
717 O << "\n";
718
719 // The postdom tree can have a null root if there are no returns.
720 if (getRootNode()) PrintDomTree<NodeT>(getRootNode(), O, 1);
721 O << "Roots: ";
722 for (const NodePtr Block : Roots) {
723 Block->printAsOperand(O, false);
724 O << " ";
725 }
726 O << "\n";
727 }
728
729public:
730 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
731 /// dominator tree in dfs order.
732 void updateDFSNumbers() const {
733 if (DFSInfoValid) {
734 SlowQueries = 0;
735 return;
736 }
737
738 SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
739 typename DomTreeNodeBase<NodeT>::const_iterator>,
740 32> WorkStack;
741
742 const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
743 assert((!Parent || ThisRoot) && "Empty constructed DomTree")(static_cast <bool> ((!Parent || ThisRoot) && "Empty constructed DomTree"
) ? void (0) : __assert_fail ("(!Parent || ThisRoot) && \"Empty constructed DomTree\""
, "llvm/include/llvm/Support/GenericDomTree.h", 743, __extension__
__PRETTY_FUNCTION__))
;
744 if (!ThisRoot)
745 return;
746
747 // Both dominators and postdominators have a single root node. In the case
748 // case of PostDominatorTree, this node is a virtual root.
749 WorkStack.push_back({ThisRoot, ThisRoot->begin()});
750
751 unsigned DFSNum = 0;
752 ThisRoot->DFSNumIn = DFSNum++;
753
754 while (!WorkStack.empty()) {
755 const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
756 const auto ChildIt = WorkStack.back().second;
757
758 // If we visited all of the children of this node, "recurse" back up the
759 // stack setting the DFOutNum.
760 if (ChildIt == Node->end()) {
761 Node->DFSNumOut = DFSNum++;
762 WorkStack.pop_back();
763 } else {
764 // Otherwise, recursively visit this child.
765 const DomTreeNodeBase<NodeT> *Child = *ChildIt;
766 ++WorkStack.back().second;
767
768 WorkStack.push_back({Child, Child->begin()});
769 Child->DFSNumIn = DFSNum++;
770 }
771 }
772
773 SlowQueries = 0;
774 DFSInfoValid = true;
775 }
776
777 /// recalculate - compute a dominator tree for the given function
778 void recalculate(ParentType &Func) {
779 Parent = &Func;
780 DomTreeBuilder::Calculate(*this);
781 }
782
783 void recalculate(ParentType &Func, ArrayRef<UpdateType> Updates) {
784 Parent = &Func;
785 DomTreeBuilder::CalculateWithUpdates(*this, Updates);
786 }
787
788 /// verify - checks if the tree is correct. There are 3 level of verification:
789 /// - Full -- verifies if the tree is correct by making sure all the
790 /// properties (including the parent and the sibling property)
791 /// hold.
792 /// Takes O(N^3) time.
793 ///
794 /// - Basic -- checks if the tree is correct, but compares it to a freshly
795 /// constructed tree instead of checking the sibling property.
796 /// Takes O(N^2) time.
797 ///
798 /// - Fast -- checks basic tree structure and compares it with a freshly
799 /// constructed tree.
800 /// Takes O(N^2) time worst case, but is faster in practise (same
801 /// as tree construction).
802 bool verify(VerificationLevel VL = VerificationLevel::Full) const {
803 return DomTreeBuilder::Verify(*this, VL);
804 }
805
806 void reset() {
807 DomTreeNodes.clear();
808 Roots.clear();
809 RootNode = nullptr;
810 Parent = nullptr;
811 DFSInfoValid = false;
812 SlowQueries = 0;
813 }
814
815protected:
816 void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
817
818 DomTreeNodeBase<NodeT> *createChild(NodeT *BB, DomTreeNodeBase<NodeT> *IDom) {
819 return (DomTreeNodes[BB] = IDom->addChild(
820 std::make_unique<DomTreeNodeBase<NodeT>>(BB, IDom)))
821 .get();
822 }
823
824 DomTreeNodeBase<NodeT> *createNode(NodeT *BB) {
825 return (DomTreeNodes[BB] =
826 std::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr))
827 .get();
828 }
829
830 // NewBB is split and now it has one successor. Update dominator tree to
831 // reflect this change.
832 template <class N>
833 void Split(typename GraphTraits<N>::NodeRef NewBB) {
834 using GraphT = GraphTraits<N>;
835 using NodeRef = typename GraphT::NodeRef;
836 assert(std::distance(GraphT::child_begin(NewBB),(static_cast <bool> (std::distance(GraphT::child_begin(
NewBB), GraphT::child_end(NewBB)) == 1 && "NewBB should have a single successor!"
) ? void (0) : __assert_fail ("std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1 && \"NewBB should have a single successor!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 838, __extension__
__PRETTY_FUNCTION__))
837 GraphT::child_end(NewBB)) == 1 &&(static_cast <bool> (std::distance(GraphT::child_begin(
NewBB), GraphT::child_end(NewBB)) == 1 && "NewBB should have a single successor!"
) ? void (0) : __assert_fail ("std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1 && \"NewBB should have a single successor!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 838, __extension__
__PRETTY_FUNCTION__))
838 "NewBB should have a single successor!")(static_cast <bool> (std::distance(GraphT::child_begin(
NewBB), GraphT::child_end(NewBB)) == 1 && "NewBB should have a single successor!"
) ? void (0) : __assert_fail ("std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1 && \"NewBB should have a single successor!\""
, "llvm/include/llvm/Support/GenericDomTree.h", 838, __extension__
__PRETTY_FUNCTION__))
;
839 NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
840
841 SmallVector<NodeRef, 4> PredBlocks(children<Inverse<N>>(NewBB));
842
843 assert(!PredBlocks.empty() && "No predblocks?")(static_cast <bool> (!PredBlocks.empty() && "No predblocks?"
) ? void (0) : __assert_fail ("!PredBlocks.empty() && \"No predblocks?\""
, "llvm/include/llvm/Support/GenericDomTree.h", 843, __extension__
__PRETTY_FUNCTION__))
;
844
845 bool NewBBDominatesNewBBSucc = true;
846 for (auto *Pred : children<Inverse<N>>(NewBBSucc)) {
847 if (Pred != NewBB && !dominates(NewBBSucc, Pred) &&
848 isReachableFromEntry(Pred)) {
849 NewBBDominatesNewBBSucc = false;
850 break;
851 }
852 }
853
854 // Find NewBB's immediate dominator and create new dominator tree node for
855 // NewBB.
856 NodeT *NewBBIDom = nullptr;
857 unsigned i = 0;
858 for (i = 0; i < PredBlocks.size(); ++i)
859 if (isReachableFromEntry(PredBlocks[i])) {
860 NewBBIDom = PredBlocks[i];
861 break;
862 }
863
864 // It's possible that none of the predecessors of NewBB are reachable;
865 // in that case, NewBB itself is unreachable, so nothing needs to be
866 // changed.
867 if (!NewBBIDom) return;
868
869 for (i = i + 1; i < PredBlocks.size(); ++i) {
870 if (isReachableFromEntry(PredBlocks[i]))
871 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
872 }
873
874 // Create the new dominator tree node... and set the idom of NewBB.
875 DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom);
876
877 // If NewBB strictly dominates other blocks, then it is now the immediate
878 // dominator of NewBBSucc. Update the dominator tree as appropriate.
879 if (NewBBDominatesNewBBSucc) {
880 DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc);
881 changeImmediateDominator(NewBBSuccNode, NewBBNode);
882 }
883 }
884
885 private:
886 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
887 const DomTreeNodeBase<NodeT> *B) const {
888 assert(A != B)(static_cast <bool> (A != B) ? void (0) : __assert_fail
("A != B", "llvm/include/llvm/Support/GenericDomTree.h", 888
, __extension__ __PRETTY_FUNCTION__))
;
889 assert(isReachableFromEntry(B))(static_cast <bool> (isReachableFromEntry(B)) ? void (0
) : __assert_fail ("isReachableFromEntry(B)", "llvm/include/llvm/Support/GenericDomTree.h"
, 889, __extension__ __PRETTY_FUNCTION__))
;
890 assert(isReachableFromEntry(A))(static_cast <bool> (isReachableFromEntry(A)) ? void (0
) : __assert_fail ("isReachableFromEntry(A)", "llvm/include/llvm/Support/GenericDomTree.h"
, 890, __extension__ __PRETTY_FUNCTION__))
;
891
892 const unsigned ALevel = A->getLevel();
893 const DomTreeNodeBase<NodeT> *IDom;
894
895 // Don't walk nodes above A's subtree. When we reach A's level, we must
896 // either find A or be in some other subtree not dominated by A.
897 while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel)
898 B = IDom; // Walk up the tree
899
900 return B == A;
901 }
902
903 /// Wipe this tree's state without releasing any resources.
904 ///
905 /// This is essentially a post-move helper only. It leaves the object in an
906 /// assignable and destroyable state, but otherwise invalid.
907 void wipe() {
908 DomTreeNodes.clear();
909 RootNode = nullptr;
910 Parent = nullptr;
911 }
912};
913
914template <typename T>
915using DomTreeBase = DominatorTreeBase<T, false>;
916
917template <typename T>
918using PostDomTreeBase = DominatorTreeBase<T, true>;
919
920// These two functions are declared out of line as a workaround for building
921// with old (< r147295) versions of clang because of pr11642.
922template <typename NodeT, bool IsPostDom>
923bool DominatorTreeBase<NodeT, IsPostDom>::dominates(const NodeT *A,
924 const NodeT *B) const {
925 if (A == B)
926 return true;
927
928 // Cast away the const qualifiers here. This is ok since
929 // this function doesn't actually return the values returned
930 // from getNode.
931 return dominates(getNode(const_cast<NodeT *>(A)),
932 getNode(const_cast<NodeT *>(B)));
933}
934template <typename NodeT, bool IsPostDom>
935bool DominatorTreeBase<NodeT, IsPostDom>::properlyDominates(
936 const NodeT *A, const NodeT *B) const {
937 if (A == B)
938 return false;
939
940 // Cast away the const qualifiers here. This is ok since
941 // this function doesn't actually return the values returned
942 // from getNode.
943 return dominates(getNode(const_cast<NodeT *>(A)),
944 getNode(const_cast<NodeT *>(B)));
945}
946
947} // end namespace llvm
948
949#endif // LLVM_SUPPORT_GENERICDOMTREE_H