Bug Summary

File:llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 471, column 55
The left operand of '==' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InlineSpiller.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/CodeGen/InlineSpiller.cpp

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- 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 contains some templates that are useful if you are working with the
10// STL at all.
11//
12// No library is required when using these functions.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_STLEXTRAS_H
17#define LLVM_ADT_STLEXTRAS_H
18
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/iterator.h"
21#include "llvm/ADT/iterator_range.h"
22#include "llvm/Config/abi-breaking.h"
23#include "llvm/Support/ErrorHandling.h"
24#include <algorithm>
25#include <cassert>
26#include <cstddef>
27#include <cstdint>
28#include <cstdlib>
29#include <functional>
30#include <initializer_list>
31#include <iterator>
32#include <limits>
33#include <memory>
34#include <tuple>
35#include <type_traits>
36#include <utility>
37
38#ifdef EXPENSIVE_CHECKS
39#include <random> // for std::mt19937
40#endif
41
42namespace llvm {
43
44// Only used by compiler if both template types are the same. Useful when
45// using SFINAE to test for the existence of member functions.
46template <typename T, T> struct SameType;
47
48namespace detail {
49
50template <typename RangeT>
51using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
52
53} // end namespace detail
54
55//===----------------------------------------------------------------------===//
56// Extra additions to <type_traits>
57//===----------------------------------------------------------------------===//
58
59template <typename T>
60struct negation : std::integral_constant<bool, !bool(T::value)> {};
61
62template <typename...> struct conjunction : std::true_type {};
63template <typename B1> struct conjunction<B1> : B1 {};
64template <typename B1, typename... Bn>
65struct conjunction<B1, Bn...>
66 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
67
68template <typename T> struct make_const_ptr {
69 using type =
70 typename std::add_pointer<typename std::add_const<T>::type>::type;
71};
72
73template <typename T> struct make_const_ref {
74 using type = typename std::add_lvalue_reference<
75 typename std::add_const<T>::type>::type;
76};
77
78//===----------------------------------------------------------------------===//
79// Extra additions to <functional>
80//===----------------------------------------------------------------------===//
81
82template <class Ty> struct identity {
83 using argument_type = Ty;
84
85 Ty &operator()(Ty &self) const {
86 return self;
87 }
88 const Ty &operator()(const Ty &self) const {
89 return self;
90 }
91};
92
93/// An efficient, type-erasing, non-owning reference to a callable. This is
94/// intended for use as the type of a function parameter that is not used
95/// after the function in question returns.
96///
97/// This class does not own the callable, so it is not in general safe to store
98/// a function_ref.
99template<typename Fn> class function_ref;
100
101template<typename Ret, typename ...Params>
102class function_ref<Ret(Params...)> {
103 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
104 intptr_t callable;
105
106 template<typename Callable>
107 static Ret callback_fn(intptr_t callable, Params ...params) {
108 return (*reinterpret_cast<Callable*>(callable))(
109 std::forward<Params>(params)...);
110 }
111
112public:
113 function_ref() = default;
114 function_ref(std::nullptr_t) {}
115
116 template <typename Callable>
117 function_ref(Callable &&callable,
118 typename std::enable_if<
119 !std::is_same<typename std::remove_reference<Callable>::type,
120 function_ref>::value>::type * = nullptr)
121 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
122 callable(reinterpret_cast<intptr_t>(&callable)) {}
123
124 Ret operator()(Params ...params) const {
125 return callback(callable, std::forward<Params>(params)...);
126 }
127
128 operator bool() const { return callback; }
129};
130
131// deleter - Very very very simple method that is used to invoke operator
132// delete on something. It is used like this:
133//
134// for_each(V.begin(), B.end(), deleter<Interval>);
135template <class T>
136inline void deleter(T *Ptr) {
137 delete Ptr;
138}
139
140//===----------------------------------------------------------------------===//
141// Extra additions to <iterator>
142//===----------------------------------------------------------------------===//
143
144namespace adl_detail {
145
146using std::begin;
147
148template <typename ContainerTy>
149auto adl_begin(ContainerTy &&container)
150 -> decltype(begin(std::forward<ContainerTy>(container))) {
151 return begin(std::forward<ContainerTy>(container));
152}
153
154using std::end;
155
156template <typename ContainerTy>
157auto adl_end(ContainerTy &&container)
158 -> decltype(end(std::forward<ContainerTy>(container))) {
159 return end(std::forward<ContainerTy>(container));
160}
161
162using std::swap;
163
164template <typename T>
165void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
166 std::declval<T>()))) {
167 swap(std::forward<T>(lhs), std::forward<T>(rhs));
168}
169
170} // end namespace adl_detail
171
172template <typename ContainerTy>
173auto adl_begin(ContainerTy &&container)
174 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
175 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
176}
177
178template <typename ContainerTy>
179auto adl_end(ContainerTy &&container)
180 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
181 return adl_detail::adl_end(std::forward<ContainerTy>(container));
182}
183
184template <typename T>
185void adl_swap(T &&lhs, T &&rhs) noexcept(
186 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
187 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
188}
189
190/// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
191template <typename T>
192constexpr bool empty(const T &RangeOrContainer) {
193 return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
194}
195
196/// Return a range covering \p RangeOrContainer with the first N elements
197/// excluded.
198template <typename T>
199auto drop_begin(T &&RangeOrContainer, size_t N) ->
200 iterator_range<decltype(adl_begin(RangeOrContainer))> {
201 return make_range(std::next(adl_begin(RangeOrContainer), N),
202 adl_end(RangeOrContainer));
203}
204
205// mapped_iterator - This is a simple iterator adapter that causes a function to
206// be applied whenever operator* is invoked on the iterator.
207
208template <typename ItTy, typename FuncTy,
209 typename FuncReturnTy =
210 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
211class mapped_iterator
212 : public iterator_adaptor_base<
213 mapped_iterator<ItTy, FuncTy>, ItTy,
214 typename std::iterator_traits<ItTy>::iterator_category,
215 typename std::remove_reference<FuncReturnTy>::type> {
216public:
217 mapped_iterator(ItTy U, FuncTy F)
218 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
219
220 ItTy getCurrent() { return this->I; }
221
222 FuncReturnTy operator*() { return F(*this->I); }
223
224private:
225 FuncTy F;
226};
227
228// map_iterator - Provide a convenient way to create mapped_iterators, just like
229// make_pair is useful for creating pairs...
230template <class ItTy, class FuncTy>
231inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
232 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
233}
234
235template <class ContainerTy, class FuncTy>
236auto map_range(ContainerTy &&C, FuncTy F)
237 -> decltype(make_range(map_iterator(C.begin(), F),
238 map_iterator(C.end(), F))) {
239 return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F));
240}
241
242/// Helper to determine if type T has a member called rbegin().
243template <typename Ty> class has_rbegin_impl {
244 using yes = char[1];
245 using no = char[2];
246
247 template <typename Inner>
248 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
249
250 template <typename>
251 static no& test(...);
252
253public:
254 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
255};
256
257/// Metafunction to determine if T& or T has a member called rbegin().
258template <typename Ty>
259struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
260};
261
262// Returns an iterator_range over the given container which iterates in reverse.
263// Note that the container must have rbegin()/rend() methods for this to work.
264template <typename ContainerTy>
265auto reverse(ContainerTy &&C,
266 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
267 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
268 return make_range(C.rbegin(), C.rend());
269}
270
271// Returns a std::reverse_iterator wrapped around the given iterator.
272template <typename IteratorTy>
273std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
274 return std::reverse_iterator<IteratorTy>(It);
275}
276
277// Returns an iterator_range over the given container which iterates in reverse.
278// Note that the container must have begin()/end() methods which return
279// bidirectional iterators for this to work.
280template <typename ContainerTy>
281auto reverse(
282 ContainerTy &&C,
283 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
284 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
285 llvm::make_reverse_iterator(std::begin(C)))) {
286 return make_range(llvm::make_reverse_iterator(std::end(C)),
287 llvm::make_reverse_iterator(std::begin(C)));
288}
289
290/// An iterator adaptor that filters the elements of given inner iterators.
291///
292/// The predicate parameter should be a callable object that accepts the wrapped
293/// iterator's reference type and returns a bool. When incrementing or
294/// decrementing the iterator, it will call the predicate on each element and
295/// skip any where it returns false.
296///
297/// \code
298/// int A[] = { 1, 2, 3, 4 };
299/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
300/// // R contains { 1, 3 }.
301/// \endcode
302///
303/// Note: filter_iterator_base implements support for forward iteration.
304/// filter_iterator_impl exists to provide support for bidirectional iteration,
305/// conditional on whether the wrapped iterator supports it.
306template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
307class filter_iterator_base
308 : public iterator_adaptor_base<
309 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
310 WrappedIteratorT,
311 typename std::common_type<
312 IterTag, typename std::iterator_traits<
313 WrappedIteratorT>::iterator_category>::type> {
314 using BaseT = iterator_adaptor_base<
315 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
316 WrappedIteratorT,
317 typename std::common_type<
318 IterTag, typename std::iterator_traits<
319 WrappedIteratorT>::iterator_category>::type>;
320
321protected:
322 WrappedIteratorT End;
323 PredicateT Pred;
324
325 void findNextValid() {
326 while (this->I != End && !Pred(*this->I))
327 BaseT::operator++();
328 }
329
330 // Construct the iterator. The begin iterator needs to know where the end
331 // is, so that it can properly stop when it gets there. The end iterator only
332 // needs the predicate to support bidirectional iteration.
333 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
334 PredicateT Pred)
335 : BaseT(Begin), End(End), Pred(Pred) {
336 findNextValid();
337 }
338
339public:
340 using BaseT::operator++;
341
342 filter_iterator_base &operator++() {
343 BaseT::operator++();
344 findNextValid();
345 return *this;
346 }
347};
348
349/// Specialization of filter_iterator_base for forward iteration only.
350template <typename WrappedIteratorT, typename PredicateT,
351 typename IterTag = std::forward_iterator_tag>
352class filter_iterator_impl
353 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
354 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
355
356public:
357 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
358 PredicateT Pred)
359 : BaseT(Begin, End, Pred) {}
360};
361
362/// Specialization of filter_iterator_base for bidirectional iteration.
363template <typename WrappedIteratorT, typename PredicateT>
364class filter_iterator_impl<WrappedIteratorT, PredicateT,
365 std::bidirectional_iterator_tag>
366 : public filter_iterator_base<WrappedIteratorT, PredicateT,
367 std::bidirectional_iterator_tag> {
368 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
369 std::bidirectional_iterator_tag>;
370 void findPrevValid() {
371 while (!this->Pred(*this->I))
372 BaseT::operator--();
373 }
374
375public:
376 using BaseT::operator--;
377
378 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
379 PredicateT Pred)
380 : BaseT(Begin, End, Pred) {}
381
382 filter_iterator_impl &operator--() {
383 BaseT::operator--();
384 findPrevValid();
385 return *this;
386 }
387};
388
389namespace detail {
390
391template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
392 using type = std::forward_iterator_tag;
393};
394
395template <> struct fwd_or_bidi_tag_impl<true> {
396 using type = std::bidirectional_iterator_tag;
397};
398
399/// Helper which sets its type member to forward_iterator_tag if the category
400/// of \p IterT does not derive from bidirectional_iterator_tag, and to
401/// bidirectional_iterator_tag otherwise.
402template <typename IterT> struct fwd_or_bidi_tag {
403 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
404 std::bidirectional_iterator_tag,
405 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
406};
407
408} // namespace detail
409
410/// Defines filter_iterator to a suitable specialization of
411/// filter_iterator_impl, based on the underlying iterator's category.
412template <typename WrappedIteratorT, typename PredicateT>
413using filter_iterator = filter_iterator_impl<
414 WrappedIteratorT, PredicateT,
415 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
416
417/// Convenience function that takes a range of elements and a predicate,
418/// and return a new filter_iterator range.
419///
420/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
421/// lifetime of that temporary is not kept by the returned range object, and the
422/// temporary is going to be dropped on the floor after the make_iterator_range
423/// full expression that contains this function call.
424template <typename RangeT, typename PredicateT>
425iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
426make_filter_range(RangeT &&Range, PredicateT Pred) {
427 using FilterIteratorT =
428 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
429 return make_range(
430 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
431 std::end(std::forward<RangeT>(Range)), Pred),
432 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
433 std::end(std::forward<RangeT>(Range)), Pred));
434}
435
436/// A pseudo-iterator adaptor that is designed to implement "early increment"
437/// style loops.
438///
439/// This is *not a normal iterator* and should almost never be used directly. It
440/// is intended primarily to be used with range based for loops and some range
441/// algorithms.
442///
443/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
444/// somewhere between them. The constraints of these iterators are:
445///
446/// - On construction or after being incremented, it is comparable and
447/// dereferencable. It is *not* incrementable.
448/// - After being dereferenced, it is neither comparable nor dereferencable, it
449/// is only incrementable.
450///
451/// This means you can only dereference the iterator once, and you can only
452/// increment it once between dereferences.
453template <typename WrappedIteratorT>
454class early_inc_iterator_impl
455 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
456 WrappedIteratorT, std::input_iterator_tag> {
457 using BaseT =
458 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
459 WrappedIteratorT, std::input_iterator_tag>;
460
461 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
462
463protected:
464#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
465 bool IsEarlyIncremented = false;
466#endif
467
468public:
469 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
470
471 using BaseT::operator*;
472 typename BaseT::reference operator*() {
473#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
474 assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!")
? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 474, __PRETTY_FUNCTION__))
;
475 IsEarlyIncremented = true;
476#endif
477 return *(this->I)++;
478 }
479
480 using BaseT::operator++;
481 early_inc_iterator_impl &operator++() {
482#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
483 assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 483, __PRETTY_FUNCTION__))
;
484 IsEarlyIncremented = false;
485#endif
486 return *this;
487 }
488
489 using BaseT::operator==;
490 bool operator==(const early_inc_iterator_impl &RHS) const {
491#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
492 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 492, __PRETTY_FUNCTION__))
;
493#endif
494 return BaseT::operator==(RHS);
495 }
496};
497
498/// Make a range that does early increment to allow mutation of the underlying
499/// range without disrupting iteration.
500///
501/// The underlying iterator will be incremented immediately after it is
502/// dereferenced, allowing deletion of the current node or insertion of nodes to
503/// not disrupt iteration provided they do not invalidate the *next* iterator --
504/// the current iterator can be invalidated.
505///
506/// This requires a very exact pattern of use that is only really suitable to
507/// range based for loops and other range algorithms that explicitly guarantee
508/// to dereference exactly once each element, and to increment exactly once each
509/// element.
510template <typename RangeT>
511iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
512make_early_inc_range(RangeT &&Range) {
513 using EarlyIncIteratorT =
514 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
515 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
516 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
517}
518
519// forward declarations required by zip_shortest/zip_first/zip_longest
520template <typename R, typename UnaryPredicate>
521bool all_of(R &&range, UnaryPredicate P);
522template <typename R, typename UnaryPredicate>
523bool any_of(R &&range, UnaryPredicate P);
524
525namespace detail {
526
527using std::declval;
528
529// We have to alias this since inlining the actual type at the usage site
530// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
531template<typename... Iters> struct ZipTupleType {
532 using type = std::tuple<decltype(*declval<Iters>())...>;
533};
534
535template <typename ZipType, typename... Iters>
536using zip_traits = iterator_facade_base<
537 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
538 typename std::iterator_traits<
539 Iters>::iterator_category...>::type,
540 // ^ TODO: Implement random access methods.
541 typename ZipTupleType<Iters...>::type,
542 typename std::iterator_traits<typename std::tuple_element<
543 0, std::tuple<Iters...>>::type>::difference_type,
544 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
545 // inner iterators have the same difference_type. It would fail if, for
546 // instance, the second field's difference_type were non-numeric while the
547 // first is.
548 typename ZipTupleType<Iters...>::type *,
549 typename ZipTupleType<Iters...>::type>;
550
551template <typename ZipType, typename... Iters>
552struct zip_common : public zip_traits<ZipType, Iters...> {
553 using Base = zip_traits<ZipType, Iters...>;
554 using value_type = typename Base::value_type;
555
556 std::tuple<Iters...> iterators;
557
558protected:
559 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
560 return value_type(*std::get<Ns>(iterators)...);
561 }
562
563 template <size_t... Ns>
564 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
565 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
566 }
567
568 template <size_t... Ns>
569 decltype(iterators) tup_dec(std::index_sequence<Ns...>) const {
570 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
571 }
572
573public:
574 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
575
576 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
577
578 const value_type operator*() const {
579 return deref(std::index_sequence_for<Iters...>{});
580 }
581
582 ZipType &operator++() {
583 iterators = tup_inc(std::index_sequence_for<Iters...>{});
584 return *reinterpret_cast<ZipType *>(this);
585 }
586
587 ZipType &operator--() {
588 static_assert(Base::IsBidirectional,
589 "All inner iterators must be at least bidirectional.");
590 iterators = tup_dec(std::index_sequence_for<Iters...>{});
591 return *reinterpret_cast<ZipType *>(this);
592 }
593};
594
595template <typename... Iters>
596struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
597 using Base = zip_common<zip_first<Iters...>, Iters...>;
598
599 bool operator==(const zip_first<Iters...> &other) const {
600 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
601 }
602
603 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
604};
605
606template <typename... Iters>
607class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
608 template <size_t... Ns>
609 bool test(const zip_shortest<Iters...> &other,
610 std::index_sequence<Ns...>) const {
611 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
612 std::get<Ns>(other.iterators)...},
613 identity<bool>{});
614 }
615
616public:
617 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
618
619 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
620
621 bool operator==(const zip_shortest<Iters...> &other) const {
622 return !test(other, std::index_sequence_for<Iters...>{});
623 }
624};
625
626template <template <typename...> class ItType, typename... Args> class zippy {
627public:
628 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
629 using iterator_category = typename iterator::iterator_category;
630 using value_type = typename iterator::value_type;
631 using difference_type = typename iterator::difference_type;
632 using pointer = typename iterator::pointer;
633 using reference = typename iterator::reference;
634
635private:
636 std::tuple<Args...> ts;
637
638 template <size_t... Ns>
639 iterator begin_impl(std::index_sequence<Ns...>) const {
640 return iterator(std::begin(std::get<Ns>(ts))...);
641 }
642 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
643 return iterator(std::end(std::get<Ns>(ts))...);
644 }
645
646public:
647 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
648
649 iterator begin() const {
650 return begin_impl(std::index_sequence_for<Args...>{});
651 }
652 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
653};
654
655} // end namespace detail
656
657/// zip iterator for two or more iteratable types.
658template <typename T, typename U, typename... Args>
659detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
660 Args &&... args) {
661 return detail::zippy<detail::zip_shortest, T, U, Args...>(
662 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
663}
664
665/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
666/// be the shortest.
667template <typename T, typename U, typename... Args>
668detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
669 Args &&... args) {
670 return detail::zippy<detail::zip_first, T, U, Args...>(
671 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
672}
673
674namespace detail {
675template <typename Iter>
676static Iter next_or_end(const Iter &I, const Iter &End) {
677 if (I == End)
678 return End;
679 return std::next(I);
680}
681
682template <typename Iter>
683static auto deref_or_none(const Iter &I, const Iter &End)
684 -> llvm::Optional<typename std::remove_const<
685 typename std::remove_reference<decltype(*I)>::type>::type> {
686 if (I == End)
687 return None;
688 return *I;
689}
690
691template <typename Iter> struct ZipLongestItemType {
692 using type =
693 llvm::Optional<typename std::remove_const<typename std::remove_reference<
694 decltype(*std::declval<Iter>())>::type>::type>;
695};
696
697template <typename... Iters> struct ZipLongestTupleType {
698 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
699};
700
701template <typename... Iters>
702class zip_longest_iterator
703 : public iterator_facade_base<
704 zip_longest_iterator<Iters...>,
705 typename std::common_type<
706 std::forward_iterator_tag,
707 typename std::iterator_traits<Iters>::iterator_category...>::type,
708 typename ZipLongestTupleType<Iters...>::type,
709 typename std::iterator_traits<typename std::tuple_element<
710 0, std::tuple<Iters...>>::type>::difference_type,
711 typename ZipLongestTupleType<Iters...>::type *,
712 typename ZipLongestTupleType<Iters...>::type> {
713public:
714 using value_type = typename ZipLongestTupleType<Iters...>::type;
715
716private:
717 std::tuple<Iters...> iterators;
718 std::tuple<Iters...> end_iterators;
719
720 template <size_t... Ns>
721 bool test(const zip_longest_iterator<Iters...> &other,
722 std::index_sequence<Ns...>) const {
723 return llvm::any_of(
724 std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
725 std::get<Ns>(other.iterators)...},
726 identity<bool>{});
727 }
728
729 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
730 return value_type(
731 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
732 }
733
734 template <size_t... Ns>
735 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
736 return std::tuple<Iters...>(
737 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
738 }
739
740public:
741 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
742 : iterators(std::forward<Iters>(ts.first)...),
743 end_iterators(std::forward<Iters>(ts.second)...) {}
744
745 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
746
747 value_type operator*() const {
748 return deref(std::index_sequence_for<Iters...>{});
749 }
750
751 zip_longest_iterator<Iters...> &operator++() {
752 iterators = tup_inc(std::index_sequence_for<Iters...>{});
753 return *this;
754 }
755
756 bool operator==(const zip_longest_iterator<Iters...> &other) const {
757 return !test(other, std::index_sequence_for<Iters...>{});
758 }
759};
760
761template <typename... Args> class zip_longest_range {
762public:
763 using iterator =
764 zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
765 using iterator_category = typename iterator::iterator_category;
766 using value_type = typename iterator::value_type;
767 using difference_type = typename iterator::difference_type;
768 using pointer = typename iterator::pointer;
769 using reference = typename iterator::reference;
770
771private:
772 std::tuple<Args...> ts;
773
774 template <size_t... Ns>
775 iterator begin_impl(std::index_sequence<Ns...>) const {
776 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
777 adl_end(std::get<Ns>(ts)))...);
778 }
779
780 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
781 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
782 adl_end(std::get<Ns>(ts)))...);
783 }
784
785public:
786 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
787
788 iterator begin() const {
789 return begin_impl(std::index_sequence_for<Args...>{});
790 }
791 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
792};
793} // namespace detail
794
795/// Iterate over two or more iterators at the same time. Iteration continues
796/// until all iterators reach the end. The llvm::Optional only contains a value
797/// if the iterator has not reached the end.
798template <typename T, typename U, typename... Args>
799detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
800 Args &&... args) {
801 return detail::zip_longest_range<T, U, Args...>(
802 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
803}
804
805/// Iterator wrapper that concatenates sequences together.
806///
807/// This can concatenate different iterators, even with different types, into
808/// a single iterator provided the value types of all the concatenated
809/// iterators expose `reference` and `pointer` types that can be converted to
810/// `ValueT &` and `ValueT *` respectively. It doesn't support more
811/// interesting/customized pointer or reference types.
812///
813/// Currently this only supports forward or higher iterator categories as
814/// inputs and always exposes a forward iterator interface.
815template <typename ValueT, typename... IterTs>
816class concat_iterator
817 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
818 std::forward_iterator_tag, ValueT> {
819 using BaseT = typename concat_iterator::iterator_facade_base;
820
821 /// We store both the current and end iterators for each concatenated
822 /// sequence in a tuple of pairs.
823 ///
824 /// Note that something like iterator_range seems nice at first here, but the
825 /// range properties are of little benefit and end up getting in the way
826 /// because we need to do mutation on the current iterators.
827 std::tuple<IterTs...> Begins;
828 std::tuple<IterTs...> Ends;
829
830 /// Attempts to increment a specific iterator.
831 ///
832 /// Returns true if it was able to increment the iterator. Returns false if
833 /// the iterator is already at the end iterator.
834 template <size_t Index> bool incrementHelper() {
835 auto &Begin = std::get<Index>(Begins);
836 auto &End = std::get<Index>(Ends);
837 if (Begin == End)
838 return false;
839
840 ++Begin;
841 return true;
842 }
843
844 /// Increments the first non-end iterator.
845 ///
846 /// It is an error to call this with all iterators at the end.
847 template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
848 // Build a sequence of functions to increment each iterator if possible.
849 bool (concat_iterator::*IncrementHelperFns[])() = {
850 &concat_iterator::incrementHelper<Ns>...};
851
852 // Loop over them, and stop as soon as we succeed at incrementing one.
853 for (auto &IncrementHelperFn : IncrementHelperFns)
854 if ((this->*IncrementHelperFn)())
855 return;
856
857 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 857)
;
858 }
859
860 /// Returns null if the specified iterator is at the end. Otherwise,
861 /// dereferences the iterator and returns the address of the resulting
862 /// reference.
863 template <size_t Index> ValueT *getHelper() const {
864 auto &Begin = std::get<Index>(Begins);
865 auto &End = std::get<Index>(Ends);
866 if (Begin == End)
867 return nullptr;
868
869 return &*Begin;
870 }
871
872 /// Finds the first non-end iterator, dereferences, and returns the resulting
873 /// reference.
874 ///
875 /// It is an error to call this with all iterators at the end.
876 template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const {
877 // Build a sequence of functions to get from iterator if possible.
878 ValueT *(concat_iterator::*GetHelperFns[])() const = {
879 &concat_iterator::getHelper<Ns>...};
880
881 // Loop over them, and return the first result we find.
882 for (auto &GetHelperFn : GetHelperFns)
883 if (ValueT *P = (this->*GetHelperFn)())
884 return *P;
885
886 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 886)
;
887 }
888
889public:
890 /// Constructs an iterator from a squence of ranges.
891 ///
892 /// We need the full range to know how to switch between each of the
893 /// iterators.
894 template <typename... RangeTs>
895 explicit concat_iterator(RangeTs &&... Ranges)
896 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
897
898 using BaseT::operator++;
899
900 concat_iterator &operator++() {
901 increment(std::index_sequence_for<IterTs...>());
902 return *this;
903 }
904
905 ValueT &operator*() const {
906 return get(std::index_sequence_for<IterTs...>());
907 }
908
909 bool operator==(const concat_iterator &RHS) const {
910 return Begins == RHS.Begins && Ends == RHS.Ends;
911 }
912};
913
914namespace detail {
915
916/// Helper to store a sequence of ranges being concatenated and access them.
917///
918/// This is designed to facilitate providing actual storage when temporaries
919/// are passed into the constructor such that we can use it as part of range
920/// based for loops.
921template <typename ValueT, typename... RangeTs> class concat_range {
922public:
923 using iterator =
924 concat_iterator<ValueT,
925 decltype(std::begin(std::declval<RangeTs &>()))...>;
926
927private:
928 std::tuple<RangeTs...> Ranges;
929
930 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
931 return iterator(std::get<Ns>(Ranges)...);
932 }
933 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
934 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
935 std::end(std::get<Ns>(Ranges)))...);
936 }
937
938public:
939 concat_range(RangeTs &&... Ranges)
940 : Ranges(std::forward<RangeTs>(Ranges)...) {}
941
942 iterator begin() { return begin_impl(std::index_sequence_for<RangeTs...>{}); }
943 iterator end() { return end_impl(std::index_sequence_for<RangeTs...>{}); }
944};
945
946} // end namespace detail
947
948/// Concatenated range across two or more ranges.
949///
950/// The desired value type must be explicitly specified.
951template <typename ValueT, typename... RangeTs>
952detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
953 static_assert(sizeof...(RangeTs) > 1,
954 "Need more than one range to concatenate!");
955 return detail::concat_range<ValueT, RangeTs...>(
956 std::forward<RangeTs>(Ranges)...);
957}
958
959//===----------------------------------------------------------------------===//
960// Extra additions to <utility>
961//===----------------------------------------------------------------------===//
962
963/// Function object to check whether the first component of a std::pair
964/// compares less than the first component of another std::pair.
965struct less_first {
966 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
967 return lhs.first < rhs.first;
968 }
969};
970
971/// Function object to check whether the second component of a std::pair
972/// compares less than the second component of another std::pair.
973struct less_second {
974 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
975 return lhs.second < rhs.second;
976 }
977};
978
979/// \brief Function object to apply a binary function to the first component of
980/// a std::pair.
981template<typename FuncTy>
982struct on_first {
983 FuncTy func;
984
985 template <typename T>
986 auto operator()(const T &lhs, const T &rhs) const
987 -> decltype(func(lhs.first, rhs.first)) {
988 return func(lhs.first, rhs.first);
989 }
990};
991
992/// Utility type to build an inheritance chain that makes it easy to rank
993/// overload candidates.
994template <int N> struct rank : rank<N - 1> {};
995template <> struct rank<0> {};
996
997/// traits class for checking whether type T is one of any of the given
998/// types in the variadic list.
999template <typename T, typename... Ts> struct is_one_of {
1000 static const bool value = false;
1001};
1002
1003template <typename T, typename U, typename... Ts>
1004struct is_one_of<T, U, Ts...> {
1005 static const bool value =
1006 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
1007};
1008
1009/// traits class for checking whether type T is a base class for all
1010/// the given types in the variadic list.
1011template <typename T, typename... Ts> struct are_base_of {
1012 static const bool value = true;
1013};
1014
1015template <typename T, typename U, typename... Ts>
1016struct are_base_of<T, U, Ts...> {
1017 static const bool value =
1018 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
1019};
1020
1021//===----------------------------------------------------------------------===//
1022// Extra additions for arrays
1023//===----------------------------------------------------------------------===//
1024
1025/// Find the length of an array.
1026template <class T, std::size_t N>
1027constexpr inline size_t array_lengthof(T (&)[N]) {
1028 return N;
1029}
1030
1031/// Adapt std::less<T> for array_pod_sort.
1032template<typename T>
1033inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1034 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1035 *reinterpret_cast<const T*>(P2)))
1036 return -1;
1037 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1038 *reinterpret_cast<const T*>(P1)))
1039 return 1;
1040 return 0;
1041}
1042
1043/// get_array_pod_sort_comparator - This is an internal helper function used to
1044/// get type deduction of T right.
1045template<typename T>
1046inline int (*get_array_pod_sort_comparator(const T &))
1047 (const void*, const void*) {
1048 return array_pod_sort_comparator<T>;
1049}
1050
1051#ifdef EXPENSIVE_CHECKS
1052namespace detail {
1053
1054inline unsigned presortShuffleEntropy() {
1055 static unsigned Result(std::random_device{}());
1056 return Result;
1057}
1058
1059template <class IteratorTy>
1060inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1061 std::mt19937 Generator(presortShuffleEntropy());
1062 std::shuffle(Start, End, Generator);
1063}
1064
1065} // end namespace detail
1066#endif
1067
1068/// array_pod_sort - This sorts an array with the specified start and end
1069/// extent. This is just like std::sort, except that it calls qsort instead of
1070/// using an inlined template. qsort is slightly slower than std::sort, but
1071/// most sorts are not performance critical in LLVM and std::sort has to be
1072/// template instantiated for each type, leading to significant measured code
1073/// bloat. This function should generally be used instead of std::sort where
1074/// possible.
1075///
1076/// This function assumes that you have simple POD-like types that can be
1077/// compared with std::less and can be moved with memcpy. If this isn't true,
1078/// you should use std::sort.
1079///
1080/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1081/// default to std::less.
1082template<class IteratorTy>
1083inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1084 // Don't inefficiently call qsort with one element or trigger undefined
1085 // behavior with an empty sequence.
1086 auto NElts = End - Start;
1087 if (NElts <= 1) return;
1088#ifdef EXPENSIVE_CHECKS
1089 detail::presortShuffle<IteratorTy>(Start, End);
1090#endif
1091 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1092}
1093
1094template <class IteratorTy>
1095inline void array_pod_sort(
1096 IteratorTy Start, IteratorTy End,
1097 int (*Compare)(
1098 const typename std::iterator_traits<IteratorTy>::value_type *,
1099 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1100 // Don't inefficiently call qsort with one element or trigger undefined
1101 // behavior with an empty sequence.
1102 auto NElts = End - Start;
1103 if (NElts <= 1) return;
1104#ifdef EXPENSIVE_CHECKS
1105 detail::presortShuffle<IteratorTy>(Start, End);
1106#endif
1107 qsort(&*Start, NElts, sizeof(*Start),
1108 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1109}
1110
1111// Provide wrappers to std::sort which shuffle the elements before sorting
1112// to help uncover non-deterministic behavior (PR35135).
1113template <typename IteratorTy>
1114inline void sort(IteratorTy Start, IteratorTy End) {
1115#ifdef EXPENSIVE_CHECKS
1116 detail::presortShuffle<IteratorTy>(Start, End);
1117#endif
1118 std::sort(Start, End);
1119}
1120
1121template <typename Container> inline void sort(Container &&C) {
1122 llvm::sort(adl_begin(C), adl_end(C));
1123}
1124
1125template <typename IteratorTy, typename Compare>
1126inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1127#ifdef EXPENSIVE_CHECKS
1128 detail::presortShuffle<IteratorTy>(Start, End);
1129#endif
1130 std::sort(Start, End, Comp);
1131}
1132
1133template <typename Container, typename Compare>
1134inline void sort(Container &&C, Compare Comp) {
1135 llvm::sort(adl_begin(C), adl_end(C), Comp);
1136}
1137
1138//===----------------------------------------------------------------------===//
1139// Extra additions to <algorithm>
1140//===----------------------------------------------------------------------===//
1141
1142/// For a container of pointers, deletes the pointers and then clears the
1143/// container.
1144template<typename Container>
1145void DeleteContainerPointers(Container &C) {
1146 for (auto V : C)
1147 delete V;
1148 C.clear();
1149}
1150
1151/// In a container of pairs (usually a map) whose second element is a pointer,
1152/// deletes the second elements and then clears the container.
1153template<typename Container>
1154void DeleteContainerSeconds(Container &C) {
1155 for (auto &V : C)
1156 delete V.second;
1157 C.clear();
1158}
1159
1160/// Get the size of a range. This is a wrapper function around std::distance
1161/// which is only enabled when the operation is O(1).
1162template <typename R>
1163auto size(R &&Range, typename std::enable_if<
1164 std::is_same<typename std::iterator_traits<decltype(
1165 Range.begin())>::iterator_category,
1166 std::random_access_iterator_tag>::value,
1167 void>::type * = nullptr)
1168 -> decltype(std::distance(Range.begin(), Range.end())) {
1169 return std::distance(Range.begin(), Range.end());
1170}
1171
1172/// Provide wrappers to std::for_each which take ranges instead of having to
1173/// pass begin/end explicitly.
1174template <typename R, typename UnaryPredicate>
1175UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1176 return std::for_each(adl_begin(Range), adl_end(Range), P);
1177}
1178
1179/// Provide wrappers to std::all_of which take ranges instead of having to pass
1180/// begin/end explicitly.
1181template <typename R, typename UnaryPredicate>
1182bool all_of(R &&Range, UnaryPredicate P) {
1183 return std::all_of(adl_begin(Range), adl_end(Range), P);
1184}
1185
1186/// Provide wrappers to std::any_of which take ranges instead of having to pass
1187/// begin/end explicitly.
1188template <typename R, typename UnaryPredicate>
1189bool any_of(R &&Range, UnaryPredicate P) {
1190 return std::any_of(adl_begin(Range), adl_end(Range), P);
1191}
1192
1193/// Provide wrappers to std::none_of which take ranges instead of having to pass
1194/// begin/end explicitly.
1195template <typename R, typename UnaryPredicate>
1196bool none_of(R &&Range, UnaryPredicate P) {
1197 return std::none_of(adl_begin(Range), adl_end(Range), P);
1198}
1199
1200/// Provide wrappers to std::find which take ranges instead of having to pass
1201/// begin/end explicitly.
1202template <typename R, typename T>
1203auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1204 return std::find(adl_begin(Range), adl_end(Range), Val);
1205}
1206
1207/// Provide wrappers to std::find_if which take ranges instead of having to pass
1208/// begin/end explicitly.
1209template <typename R, typename UnaryPredicate>
1210auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1211 return std::find_if(adl_begin(Range), adl_end(Range), P);
1212}
1213
1214template <typename R, typename UnaryPredicate>
1215auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1216 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1217}
1218
1219/// Provide wrappers to std::remove_if which take ranges instead of having to
1220/// pass begin/end explicitly.
1221template <typename R, typename UnaryPredicate>
1222auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1223 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1224}
1225
1226/// Provide wrappers to std::copy_if which take ranges instead of having to
1227/// pass begin/end explicitly.
1228template <typename R, typename OutputIt, typename UnaryPredicate>
1229OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1230 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1231}
1232
1233template <typename R, typename OutputIt>
1234OutputIt copy(R &&Range, OutputIt Out) {
1235 return std::copy(adl_begin(Range), adl_end(Range), Out);
1236}
1237
1238/// Wrapper function around std::find to detect if an element exists
1239/// in a container.
1240template <typename R, typename E>
1241bool is_contained(R &&Range, const E &Element) {
1242 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
9
Assuming the condition is false
10
Returning zero, which participates in a condition later
1243}
1244
1245/// Wrapper function around std::count to count the number of times an element
1246/// \p Element occurs in the given range \p Range.
1247template <typename R, typename E>
1248auto count(R &&Range, const E &Element) ->
1249 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1250 return std::count(adl_begin(Range), adl_end(Range), Element);
1251}
1252
1253/// Wrapper function around std::count_if to count the number of times an
1254/// element satisfying a given predicate occurs in a range.
1255template <typename R, typename UnaryPredicate>
1256auto count_if(R &&Range, UnaryPredicate P) ->
1257 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1258 return std::count_if(adl_begin(Range), adl_end(Range), P);
1259}
1260
1261/// Wrapper function around std::transform to apply a function to a range and
1262/// store the result elsewhere.
1263template <typename R, typename OutputIt, typename UnaryPredicate>
1264OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1265 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1266}
1267
1268/// Provide wrappers to std::partition which take ranges instead of having to
1269/// pass begin/end explicitly.
1270template <typename R, typename UnaryPredicate>
1271auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1272 return std::partition(adl_begin(Range), adl_end(Range), P);
1273}
1274
1275/// Provide wrappers to std::lower_bound which take ranges instead of having to
1276/// pass begin/end explicitly.
1277template <typename R, typename T>
1278auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) {
1279 return std::lower_bound(adl_begin(Range), adl_end(Range),
1280 std::forward<T>(Value));
1281}
1282
1283template <typename R, typename T, typename Compare>
1284auto lower_bound(R &&Range, T &&Value, Compare C)
1285 -> decltype(adl_begin(Range)) {
1286 return std::lower_bound(adl_begin(Range), adl_end(Range),
1287 std::forward<T>(Value), C);
1288}
1289
1290/// Provide wrappers to std::upper_bound which take ranges instead of having to
1291/// pass begin/end explicitly.
1292template <typename R, typename T>
1293auto upper_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) {
1294 return std::upper_bound(adl_begin(Range), adl_end(Range),
1295 std::forward<T>(Value));
1296}
1297
1298template <typename R, typename T, typename Compare>
1299auto upper_bound(R &&Range, T &&Value, Compare C)
1300 -> decltype(adl_begin(Range)) {
1301 return std::upper_bound(adl_begin(Range), adl_end(Range),
1302 std::forward<T>(Value), C);
1303}
1304
1305template <typename R>
1306void stable_sort(R &&Range) {
1307 std::stable_sort(adl_begin(Range), adl_end(Range));
1308}
1309
1310template <typename R, typename Compare>
1311void stable_sort(R &&Range, Compare C) {
1312 std::stable_sort(adl_begin(Range), adl_end(Range), C);
1313}
1314
1315/// Binary search for the first iterator in a range where a predicate is false.
1316/// Requires that C is always true below some limit, and always false above it.
1317template <typename R, typename Predicate,
1318 typename Val = decltype(*adl_begin(std::declval<R>()))>
1319auto partition_point(R &&Range, Predicate P) -> decltype(adl_begin(Range)) {
1320 return std::partition_point(adl_begin(Range), adl_end(Range), P);
1321}
1322
1323/// Wrapper function around std::equal to detect if all elements
1324/// in a container are same.
1325template <typename R>
1326bool is_splat(R &&Range) {
1327 size_t range_size = size(Range);
1328 return range_size != 0 && (range_size == 1 ||
1329 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1330}
1331
1332/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1333/// `erase_if` which is equivalent to:
1334///
1335/// C.erase(remove_if(C, pred), C.end());
1336///
1337/// This version works for any container with an erase method call accepting
1338/// two iterators.
1339template <typename Container, typename UnaryPredicate>
1340void erase_if(Container &C, UnaryPredicate P) {
1341 C.erase(remove_if(C, P), C.end());
1342}
1343
1344/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1345/// the range [ValIt, ValEnd) (which is not from the same container).
1346template<typename Container, typename RandomAccessIterator>
1347void replace(Container &Cont, typename Container::iterator ContIt,
1348 typename Container::iterator ContEnd, RandomAccessIterator ValIt,
1349 RandomAccessIterator ValEnd) {
1350 while (true) {
1351 if (ValIt == ValEnd) {
1352 Cont.erase(ContIt, ContEnd);
1353 return;
1354 } else if (ContIt == ContEnd) {
1355 Cont.insert(ContIt, ValIt, ValEnd);
1356 return;
1357 }
1358 *ContIt++ = *ValIt++;
1359 }
1360}
1361
1362/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1363/// the range R.
1364template<typename Container, typename Range = std::initializer_list<
1365 typename Container::value_type>>
1366void replace(Container &Cont, typename Container::iterator ContIt,
1367 typename Container::iterator ContEnd, Range R) {
1368 replace(Cont, ContIt, ContEnd, R.begin(), R.end());
1369}
1370
1371//===----------------------------------------------------------------------===//
1372// Extra additions to <memory>
1373//===----------------------------------------------------------------------===//
1374
1375struct FreeDeleter {
1376 void operator()(void* v) {
1377 ::free(v);
1378 }
1379};
1380
1381template<typename First, typename Second>
1382struct pair_hash {
1383 size_t operator()(const std::pair<First, Second> &P) const {
1384 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1385 }
1386};
1387
1388/// Binary functor that adapts to any other binary functor after dereferencing
1389/// operands.
1390template <typename T> struct deref {
1391 T func;
1392
1393 // Could be further improved to cope with non-derivable functors and
1394 // non-binary functors (should be a variadic template member function
1395 // operator()).
1396 template <typename A, typename B>
1397 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1398 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 1398, __PRETTY_FUNCTION__))
;
1399 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 1399, __PRETTY_FUNCTION__))
;
1400 return func(*lhs, *rhs);
1401 }
1402};
1403
1404namespace detail {
1405
1406template <typename R> class enumerator_iter;
1407
1408template <typename R> struct result_pair {
1409 using value_reference =
1410 typename std::iterator_traits<IterOfRange<R>>::reference;
1411
1412 friend class enumerator_iter<R>;
1413
1414 result_pair() = default;
1415 result_pair(std::size_t Index, IterOfRange<R> Iter)
1416 : Index(Index), Iter(Iter) {}
1417
1418 result_pair<R>(const result_pair<R> &Other)
1419 : Index(Other.Index), Iter(Other.Iter) {}
1420 result_pair<R> &operator=(const result_pair<R> &Other) {
1421 Index = Other.Index;
1422 Iter = Other.Iter;
1423 return *this;
1424 }
1425
1426 std::size_t index() const { return Index; }
1427 const value_reference value() const { return *Iter; }
1428 value_reference value() { return *Iter; }
1429
1430private:
1431 std::size_t Index = std::numeric_limits<std::size_t>::max();
1432 IterOfRange<R> Iter;
1433};
1434
1435template <typename R>
1436class enumerator_iter
1437 : public iterator_facade_base<
1438 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1439 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1440 typename std::iterator_traits<IterOfRange<R>>::pointer,
1441 typename std::iterator_traits<IterOfRange<R>>::reference> {
1442 using result_type = result_pair<R>;
1443
1444public:
1445 explicit enumerator_iter(IterOfRange<R> EndIter)
1446 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1447
1448 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1449 : Result(Index, Iter) {}
1450
1451 result_type &operator*() { return Result; }
1452 const result_type &operator*() const { return Result; }
1453
1454 enumerator_iter<R> &operator++() {
1455 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/STLExtras.h"
, 1455, __PRETTY_FUNCTION__))
;
1456 ++Result.Iter;
1457 ++Result.Index;
1458 return *this;
1459 }
1460
1461 bool operator==(const enumerator_iter<R> &RHS) const {
1462 // Don't compare indices here, only iterators. It's possible for an end
1463 // iterator to have different indices depending on whether it was created
1464 // by calling std::end() versus incrementing a valid iterator.
1465 return Result.Iter == RHS.Result.Iter;
1466 }
1467
1468 enumerator_iter<R>(const enumerator_iter<R> &Other) : Result(Other.Result) {}
1469 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1470 Result = Other.Result;
1471 return *this;
1472 }
1473
1474private:
1475 result_type Result;
1476};
1477
1478template <typename R> class enumerator {
1479public:
1480 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1481
1482 enumerator_iter<R> begin() {
1483 return enumerator_iter<R>(0, std::begin(TheRange));
1484 }
1485
1486 enumerator_iter<R> end() {
1487 return enumerator_iter<R>(std::end(TheRange));
1488 }
1489
1490private:
1491 R TheRange;
1492};
1493
1494} // end namespace detail
1495
1496/// Given an input range, returns a new range whose values are are pair (A,B)
1497/// such that A is the 0-based index of the item in the sequence, and B is
1498/// the value from the original sequence. Example:
1499///
1500/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1501/// for (auto X : enumerate(Items)) {
1502/// printf("Item %d - %c\n", X.index(), X.value());
1503/// }
1504///
1505/// Output:
1506/// Item 0 - A
1507/// Item 1 - B
1508/// Item 2 - C
1509/// Item 3 - D
1510///
1511template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1512 return detail::enumerator<R>(std::forward<R>(TheRange));
1513}
1514
1515namespace detail {
1516
1517template <typename F, typename Tuple, std::size_t... I>
1518auto apply_tuple_impl(F &&f, Tuple &&t, std::index_sequence<I...>)
1519 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1520 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1521}
1522
1523} // end namespace detail
1524
1525/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1526/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1527/// return the result.
1528template <typename F, typename Tuple>
1529auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1530 std::forward<F>(f), std::forward<Tuple>(t),
1531 std::make_index_sequence<
1532 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1533 using Indices = std::make_index_sequence<
1534 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1535
1536 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1537 Indices{});
1538}
1539
1540/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
1541/// time. Not meant for use with random-access iterators.
1542template <typename IterTy>
1543bool hasNItems(
1544 IterTy &&Begin, IterTy &&End, unsigned N,
1545 typename std::enable_if<
1546 !std::is_same<
1547 typename std::iterator_traits<typename std::remove_reference<
1548 decltype(Begin)>::type>::iterator_category,
1549 std::random_access_iterator_tag>::value,
1550 void>::type * = nullptr) {
1551 for (; N; --N, ++Begin)
1552 if (Begin == End)
1553 return false; // Too few.
1554 return Begin == End;
1555}
1556
1557/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
1558/// time. Not meant for use with random-access iterators.
1559template <typename IterTy>
1560bool hasNItemsOrMore(
1561 IterTy &&Begin, IterTy &&End, unsigned N,
1562 typename std::enable_if<
1563 !std::is_same<
1564 typename std::iterator_traits<typename std::remove_reference<
1565 decltype(Begin)>::type>::iterator_category,
1566 std::random_access_iterator_tag>::value,
1567 void>::type * = nullptr) {
1568 for (; N; --N, ++Begin)
1569 if (Begin == End)
1570 return false; // Too few.
1571 return true;
1572}
1573
1574/// Returns a raw pointer that represents the same address as the argument.
1575///
1576/// The late bound return should be removed once we move to C++14 to better
1577/// align with the C++20 declaration. Also, this implementation can be removed
1578/// once we move to C++20 where it's defined as std::to_addres()
1579///
1580/// The std::pointer_traits<>::to_address(p) variations of these overloads has
1581/// not been implemented.
1582template <class Ptr> auto to_address(const Ptr &P) -> decltype(P.operator->()) {
1583 return P.operator->();
1584}
1585template <class T> constexpr T *to_address(T *P) { return P; }
1586
1587} // end namespace llvm
1588
1589#endif // LLVM_ADT_STLEXTRAS_H

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h

1//===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- 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 contains the declaration of the MachineInstr class, which is the
10// basic representation for all target dependent machine instructions used by
11// the back end.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_MACHINEINSTR_H
16#define LLVM_CODEGEN_MACHINEINSTR_H
17
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerSumType.h"
20#include "llvm/ADT/ilist.h"
21#include "llvm/ADT/ilist_node.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/CodeGen/MachineMemOperand.h"
24#include "llvm/CodeGen/MachineOperand.h"
25#include "llvm/CodeGen/TargetOpcodes.h"
26#include "llvm/IR/DebugLoc.h"
27#include "llvm/IR/InlineAsm.h"
28#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/ArrayRecycler.h"
31#include "llvm/Support/TrailingObjects.h"
32#include <algorithm>
33#include <cassert>
34#include <cstdint>
35#include <utility>
36
37namespace llvm {
38
39class AAResults;
40template <typename T> class ArrayRef;
41class DIExpression;
42class DILocalVariable;
43class MachineBasicBlock;
44class MachineFunction;
45class MachineMemOperand;
46class MachineRegisterInfo;
47class ModuleSlotTracker;
48class raw_ostream;
49template <typename T> class SmallVectorImpl;
50class SmallBitVector;
51class StringRef;
52class TargetInstrInfo;
53class TargetRegisterClass;
54class TargetRegisterInfo;
55
56//===----------------------------------------------------------------------===//
57/// Representation of each machine instruction.
58///
59/// This class isn't a POD type, but it must have a trivial destructor. When a
60/// MachineFunction is deleted, all the contained MachineInstrs are deallocated
61/// without having their destructor called.
62///
63class MachineInstr
64 : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
65 ilist_sentinel_tracking<true>> {
66public:
67 using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
68
69 /// Flags to specify different kinds of comments to output in
70 /// assembly code. These flags carry semantic information not
71 /// otherwise easily derivable from the IR text.
72 ///
73 enum CommentFlag {
74 ReloadReuse = 0x1, // higher bits are reserved for target dep comments.
75 NoSchedComment = 0x2,
76 TAsmComments = 0x4 // Target Asm comments should start from this value.
77 };
78
79 enum MIFlag {
80 NoFlags = 0,
81 FrameSetup = 1 << 0, // Instruction is used as a part of
82 // function frame setup code.
83 FrameDestroy = 1 << 1, // Instruction is used as a part of
84 // function frame destruction code.
85 BundledPred = 1 << 2, // Instruction has bundled predecessors.
86 BundledSucc = 1 << 3, // Instruction has bundled successors.
87 FmNoNans = 1 << 4, // Instruction does not support Fast
88 // math nan values.
89 FmNoInfs = 1 << 5, // Instruction does not support Fast
90 // math infinity values.
91 FmNsz = 1 << 6, // Instruction is not required to retain
92 // signed zero values.
93 FmArcp = 1 << 7, // Instruction supports Fast math
94 // reciprocal approximations.
95 FmContract = 1 << 8, // Instruction supports Fast math
96 // contraction operations like fma.
97 FmAfn = 1 << 9, // Instruction may map to Fast math
98 // instrinsic approximation.
99 FmReassoc = 1 << 10, // Instruction supports Fast math
100 // reassociation of operand order.
101 NoUWrap = 1 << 11, // Instruction supports binary operator
102 // no unsigned wrap.
103 NoSWrap = 1 << 12, // Instruction supports binary operator
104 // no signed wrap.
105 IsExact = 1 << 13, // Instruction supports division is
106 // known to be exact.
107 NoFPExcept = 1 << 14, // Instruction does not raise
108 // floatint-point exceptions.
109 };
110
111private:
112 const MCInstrDesc *MCID; // Instruction descriptor.
113 MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block.
114
115 // Operands are allocated by an ArrayRecycler.
116 MachineOperand *Operands = nullptr; // Pointer to the first operand.
117 unsigned NumOperands = 0; // Number of operands on instruction.
118 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
119 OperandCapacity CapOperands; // Capacity of the Operands array.
120
121 uint16_t Flags = 0; // Various bits of additional
122 // information about machine
123 // instruction.
124
125 uint8_t AsmPrinterFlags = 0; // Various bits of information used by
126 // the AsmPrinter to emit helpful
127 // comments. This is *not* semantic
128 // information. Do not use this for
129 // anything other than to convey comment
130 // information to AsmPrinter.
131
132 /// Internal implementation detail class that provides out-of-line storage for
133 /// extra info used by the machine instruction when this info cannot be stored
134 /// in-line within the instruction itself.
135 ///
136 /// This has to be defined eagerly due to the implementation constraints of
137 /// `PointerSumType` where it is used.
138 class ExtraInfo final
139 : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> {
140 public:
141 static ExtraInfo *create(BumpPtrAllocator &Allocator,
142 ArrayRef<MachineMemOperand *> MMOs,
143 MCSymbol *PreInstrSymbol = nullptr,
144 MCSymbol *PostInstrSymbol = nullptr,
145 MDNode *HeapAllocMarker = nullptr) {
146 bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
147 bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
148 bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
149 auto *Result = new (Allocator.Allocate(
150 totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>(
151 MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
152 HasHeapAllocMarker),
153 alignof(ExtraInfo)))
154 ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
155 HasHeapAllocMarker);
156
157 // Copy the actual data into the trailing objects.
158 std::copy(MMOs.begin(), MMOs.end(),
159 Result->getTrailingObjects<MachineMemOperand *>());
160
161 if (HasPreInstrSymbol)
162 Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
163 if (HasPostInstrSymbol)
164 Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
165 PostInstrSymbol;
166 if (HasHeapAllocMarker)
167 Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
168
169 return Result;
170 }
171
172 ArrayRef<MachineMemOperand *> getMMOs() const {
173 return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
174 }
175
176 MCSymbol *getPreInstrSymbol() const {
177 return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
178 }
179
180 MCSymbol *getPostInstrSymbol() const {
181 return HasPostInstrSymbol
182 ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
183 : nullptr;
184 }
185
186 MDNode *getHeapAllocMarker() const {
187 return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
188 }
189
190 private:
191 friend TrailingObjects;
192
193 // Description of the extra info, used to interpret the actual optional
194 // data appended.
195 //
196 // Note that this is not terribly space optimized. This leaves a great deal
197 // of flexibility to fit more in here later.
198 const int NumMMOs;
199 const bool HasPreInstrSymbol;
200 const bool HasPostInstrSymbol;
201 const bool HasHeapAllocMarker;
202
203 // Implement the `TrailingObjects` internal API.
204 size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
205 return NumMMOs;
206 }
207 size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
208 return HasPreInstrSymbol + HasPostInstrSymbol;
209 }
210 size_t numTrailingObjects(OverloadToken<MDNode *>) const {
211 return HasHeapAllocMarker;
212 }
213
214 // Just a boring constructor to allow us to initialize the sizes. Always use
215 // the `create` routine above.
216 ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
217 bool HasHeapAllocMarker)
218 : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
219 HasPostInstrSymbol(HasPostInstrSymbol),
220 HasHeapAllocMarker(HasHeapAllocMarker) {}
221 };
222
223 /// Enumeration of the kinds of inline extra info available. It is important
224 /// that the `MachineMemOperand` inline kind has a tag value of zero to make
225 /// it accessible as an `ArrayRef`.
226 enum ExtraInfoInlineKinds {
227 EIIK_MMO = 0,
228 EIIK_PreInstrSymbol,
229 EIIK_PostInstrSymbol,
230 EIIK_OutOfLine
231 };
232
233 // We store extra information about the instruction here. The common case is
234 // expected to be nothing or a single pointer (typically a MMO or a symbol).
235 // We work to optimize this common case by storing it inline here rather than
236 // requiring a separate allocation, but we fall back to an allocation when
237 // multiple pointers are needed.
238 PointerSumType<ExtraInfoInlineKinds,
239 PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
240 PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
241 PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
242 PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
243 Info;
244
245 DebugLoc debugLoc; // Source line information.
246
247 // Intrusive list support
248 friend struct ilist_traits<MachineInstr>;
249 friend struct ilist_callback_traits<MachineBasicBlock>;
250 void setParent(MachineBasicBlock *P) { Parent = P; }
251
252 /// This constructor creates a copy of the given
253 /// MachineInstr in the given MachineFunction.
254 MachineInstr(MachineFunction &, const MachineInstr &);
255
256 /// This constructor create a MachineInstr and add the implicit operands.
257 /// It reserves space for number of operands specified by
258 /// MCInstrDesc. An explicit DebugLoc is supplied.
259 MachineInstr(MachineFunction &, const MCInstrDesc &tid, DebugLoc dl,
260 bool NoImp = false);
261
262 // MachineInstrs are pool-allocated and owned by MachineFunction.
263 friend class MachineFunction;
264
265public:
266 MachineInstr(const MachineInstr &) = delete;
267 MachineInstr &operator=(const MachineInstr &) = delete;
268 // Use MachineFunction::DeleteMachineInstr() instead.
269 ~MachineInstr() = delete;
270
271 const MachineBasicBlock* getParent() const { return Parent; }
272 MachineBasicBlock* getParent() { return Parent; }
273
274 /// Return the function that contains the basic block that this instruction
275 /// belongs to.
276 ///
277 /// Note: this is undefined behaviour if the instruction does not have a
278 /// parent.
279 const MachineFunction *getMF() const;
280 MachineFunction *getMF() {
281 return const_cast<MachineFunction *>(
282 static_cast<const MachineInstr *>(this)->getMF());
283 }
284
285 /// Return the asm printer flags bitvector.
286 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
287
288 /// Clear the AsmPrinter bitvector.
289 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
290
291 /// Return whether an AsmPrinter flag is set.
292 bool getAsmPrinterFlag(CommentFlag Flag) const {
293 return AsmPrinterFlags & Flag;
294 }
295
296 /// Set a flag for the AsmPrinter.
297 void setAsmPrinterFlag(uint8_t Flag) {
298 AsmPrinterFlags |= Flag;
299 }
300
301 /// Clear specific AsmPrinter flags.
302 void clearAsmPrinterFlag(CommentFlag Flag) {
303 AsmPrinterFlags &= ~Flag;
304 }
305
306 /// Return the MI flags bitvector.
307 uint16_t getFlags() const {
308 return Flags;
309 }
310
311 /// Return whether an MI flag is set.
312 bool getFlag(MIFlag Flag) const {
313 return Flags & Flag;
314 }
315
316 /// Set a MI flag.
317 void setFlag(MIFlag Flag) {
318 Flags |= (uint16_t)Flag;
319 }
320
321 void setFlags(unsigned flags) {
322 // Filter out the automatically maintained flags.
323 unsigned Mask = BundledPred | BundledSucc;
324 Flags = (Flags & Mask) | (flags & ~Mask);
325 }
326
327 /// clearFlag - Clear a MI flag.
328 void clearFlag(MIFlag Flag) {
329 Flags &= ~((uint16_t)Flag);
330 }
331
332 /// Return true if MI is in a bundle (but not the first MI in a bundle).
333 ///
334 /// A bundle looks like this before it's finalized:
335 /// ----------------
336 /// | MI |
337 /// ----------------
338 /// |
339 /// ----------------
340 /// | MI * |
341 /// ----------------
342 /// |
343 /// ----------------
344 /// | MI * |
345 /// ----------------
346 /// In this case, the first MI starts a bundle but is not inside a bundle, the
347 /// next 2 MIs are considered "inside" the bundle.
348 ///
349 /// After a bundle is finalized, it looks like this:
350 /// ----------------
351 /// | Bundle |
352 /// ----------------
353 /// |
354 /// ----------------
355 /// | MI * |
356 /// ----------------
357 /// |
358 /// ----------------
359 /// | MI * |
360 /// ----------------
361 /// |
362 /// ----------------
363 /// | MI * |
364 /// ----------------
365 /// The first instruction has the special opcode "BUNDLE". It's not "inside"
366 /// a bundle, but the next three MIs are.
367 bool isInsideBundle() const {
368 return getFlag(BundledPred);
369 }
370
371 /// Return true if this instruction part of a bundle. This is true
372 /// if either itself or its following instruction is marked "InsideBundle".
373 bool isBundled() const {
374 return isBundledWithPred() || isBundledWithSucc();
375 }
376
377 /// Return true if this instruction is part of a bundle, and it is not the
378 /// first instruction in the bundle.
379 bool isBundledWithPred() const { return getFlag(BundledPred); }
380
381 /// Return true if this instruction is part of a bundle, and it is not the
382 /// last instruction in the bundle.
383 bool isBundledWithSucc() const { return getFlag(BundledSucc); }
384
385 /// Bundle this instruction with its predecessor. This can be an unbundled
386 /// instruction, or it can be the first instruction in a bundle.
387 void bundleWithPred();
388
389 /// Bundle this instruction with its successor. This can be an unbundled
390 /// instruction, or it can be the last instruction in a bundle.
391 void bundleWithSucc();
392
393 /// Break bundle above this instruction.
394 void unbundleFromPred();
395
396 /// Break bundle below this instruction.
397 void unbundleFromSucc();
398
399 /// Returns the debug location id of this MachineInstr.
400 const DebugLoc &getDebugLoc() const { return debugLoc; }
401
402 /// Return the debug variable referenced by
403 /// this DBG_VALUE instruction.
404 const DILocalVariable *getDebugVariable() const;
405
406 /// Return the complex address expression referenced by
407 /// this DBG_VALUE instruction.
408 const DIExpression *getDebugExpression() const;
409
410 /// Return the debug label referenced by
411 /// this DBG_LABEL instruction.
412 const DILabel *getDebugLabel() const;
413
414 /// Emit an error referring to the source location of this instruction.
415 /// This should only be used for inline assembly that is somehow
416 /// impossible to compile. Other errors should have been handled much
417 /// earlier.
418 ///
419 /// If this method returns, the caller should try to recover from the error.
420 void emitError(StringRef Msg) const;
421
422 /// Returns the target instruction descriptor of this MachineInstr.
423 const MCInstrDesc &getDesc() const { return *MCID; }
424
425 /// Returns the opcode of this MachineInstr.
426 unsigned getOpcode() const { return MCID->Opcode; }
427
428 /// Retuns the total number of operands.
429 unsigned getNumOperands() const { return NumOperands; }
430
431 const MachineOperand& getOperand(unsigned i) const {
432 assert(i < getNumOperands() && "getOperand() out of range!")((i < getNumOperands() && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumOperands() && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 432, __PRETTY_FUNCTION__))
;
433 return Operands[i];
434 }
435 MachineOperand& getOperand(unsigned i) {
436 assert(i < getNumOperands() && "getOperand() out of range!")((i < getNumOperands() && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumOperands() && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 436, __PRETTY_FUNCTION__))
;
437 return Operands[i];
438 }
439
440 /// Returns the total number of definitions.
441 unsigned getNumDefs() const {
442 return getNumExplicitDefs() + MCID->getNumImplicitDefs();
443 }
444
445 /// Returns true if the instruction has implicit definition.
446 bool hasImplicitDef() const {
447 for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
448 I != E; ++I) {
449 const MachineOperand &MO = getOperand(I);
450 if (MO.isDef() && MO.isImplicit())
451 return true;
452 }
453 return false;
454 }
455
456 /// Returns the implicit operands number.
457 unsigned getNumImplicitOperands() const {
458 return getNumOperands() - getNumExplicitOperands();
459 }
460
461 /// Return true if operand \p OpIdx is a subregister index.
462 bool isOperandSubregIdx(unsigned OpIdx) const {
463 assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&((getOperand(OpIdx).getType() == MachineOperand::MO_Immediate
&& "Expected MO_Immediate operand type.") ? static_cast
<void> (0) : __assert_fail ("getOperand(OpIdx).getType() == MachineOperand::MO_Immediate && \"Expected MO_Immediate operand type.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 464, __PRETTY_FUNCTION__))
464 "Expected MO_Immediate operand type.")((getOperand(OpIdx).getType() == MachineOperand::MO_Immediate
&& "Expected MO_Immediate operand type.") ? static_cast
<void> (0) : __assert_fail ("getOperand(OpIdx).getType() == MachineOperand::MO_Immediate && \"Expected MO_Immediate operand type.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 464, __PRETTY_FUNCTION__))
;
465 if (isExtractSubreg() && OpIdx == 2)
466 return true;
467 if (isInsertSubreg() && OpIdx == 3)
468 return true;
469 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
470 return true;
471 if (isSubregToReg() && OpIdx == 3)
472 return true;
473 return false;
474 }
475
476 /// Returns the number of non-implicit operands.
477 unsigned getNumExplicitOperands() const;
478
479 /// Returns the number of non-implicit definitions.
480 unsigned getNumExplicitDefs() const;
481
482 /// iterator/begin/end - Iterate over all operands of a machine instruction.
483 using mop_iterator = MachineOperand *;
484 using const_mop_iterator = const MachineOperand *;
485
486 mop_iterator operands_begin() { return Operands; }
487 mop_iterator operands_end() { return Operands + NumOperands; }
488
489 const_mop_iterator operands_begin() const { return Operands; }
490 const_mop_iterator operands_end() const { return Operands + NumOperands; }
491
492 iterator_range<mop_iterator> operands() {
493 return make_range(operands_begin(), operands_end());
494 }
495 iterator_range<const_mop_iterator> operands() const {
496 return make_range(operands_begin(), operands_end());
497 }
498 iterator_range<mop_iterator> explicit_operands() {
499 return make_range(operands_begin(),
500 operands_begin() + getNumExplicitOperands());
501 }
502 iterator_range<const_mop_iterator> explicit_operands() const {
503 return make_range(operands_begin(),
504 operands_begin() + getNumExplicitOperands());
505 }
506 iterator_range<mop_iterator> implicit_operands() {
507 return make_range(explicit_operands().end(), operands_end());
508 }
509 iterator_range<const_mop_iterator> implicit_operands() const {
510 return make_range(explicit_operands().end(), operands_end());
511 }
512 /// Returns a range over all explicit operands that are register definitions.
513 /// Implicit definition are not included!
514 iterator_range<mop_iterator> defs() {
515 return make_range(operands_begin(),
516 operands_begin() + getNumExplicitDefs());
517 }
518 /// \copydoc defs()
519 iterator_range<const_mop_iterator> defs() const {
520 return make_range(operands_begin(),
521 operands_begin() + getNumExplicitDefs());
522 }
523 /// Returns a range that includes all operands that are register uses.
524 /// This may include unrelated operands which are not register uses.
525 iterator_range<mop_iterator> uses() {
526 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
527 }
528 /// \copydoc uses()
529 iterator_range<const_mop_iterator> uses() const {
530 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
531 }
532 iterator_range<mop_iterator> explicit_uses() {
533 return make_range(operands_begin() + getNumExplicitDefs(),
534 operands_begin() + getNumExplicitOperands());
535 }
536 iterator_range<const_mop_iterator> explicit_uses() const {
537 return make_range(operands_begin() + getNumExplicitDefs(),
538 operands_begin() + getNumExplicitOperands());
539 }
540
541 /// Returns the number of the operand iterator \p I points to.
542 unsigned getOperandNo(const_mop_iterator I) const {
543 return I - operands_begin();
544 }
545
546 /// Access to memory operands of the instruction. If there are none, that does
547 /// not imply anything about whether the function accesses memory. Instead,
548 /// the caller must behave conservatively.
549 ArrayRef<MachineMemOperand *> memoperands() const {
550 if (!Info)
551 return {};
552
553 if (Info.is<EIIK_MMO>())
554 return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
555
556 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
557 return EI->getMMOs();
558
559 return {};
560 }
561
562 /// Access to memory operands of the instruction.
563 ///
564 /// If `memoperands_begin() == memoperands_end()`, that does not imply
565 /// anything about whether the function accesses memory. Instead, the caller
566 /// must behave conservatively.
567 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
568
569 /// Access to memory operands of the instruction.
570 ///
571 /// If `memoperands_begin() == memoperands_end()`, that does not imply
572 /// anything about whether the function accesses memory. Instead, the caller
573 /// must behave conservatively.
574 mmo_iterator memoperands_end() const { return memoperands().end(); }
575
576 /// Return true if we don't have any memory operands which described the
577 /// memory access done by this instruction. If this is true, calling code
578 /// must be conservative.
579 bool memoperands_empty() const { return memoperands().empty(); }
580
581 /// Return true if this instruction has exactly one MachineMemOperand.
582 bool hasOneMemOperand() const { return memoperands().size() == 1; }
583
584 /// Return the number of memory operands.
585 unsigned getNumMemOperands() const { return memoperands().size(); }
586
587 /// Helper to extract a pre-instruction symbol if one has been added.
588 MCSymbol *getPreInstrSymbol() const {
589 if (!Info)
590 return nullptr;
591 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
592 return S;
593 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
594 return EI->getPreInstrSymbol();
595
596 return nullptr;
597 }
598
599 /// Helper to extract a post-instruction symbol if one has been added.
600 MCSymbol *getPostInstrSymbol() const {
601 if (!Info)
602 return nullptr;
603 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
604 return S;
605 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
606 return EI->getPostInstrSymbol();
607
608 return nullptr;
609 }
610
611 /// Helper to extract a heap alloc marker if one has been added.
612 MDNode *getHeapAllocMarker() const {
613 if (!Info)
614 return nullptr;
615 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
616 return EI->getHeapAllocMarker();
617
618 return nullptr;
619 }
620
621 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
622 /// queries but they are bundle aware.
623
624 enum QueryType {
625 IgnoreBundle, // Ignore bundles
626 AnyInBundle, // Return true if any instruction in bundle has property
627 AllInBundle // Return true if all instructions in bundle have property
628 };
629
630 /// Return true if the instruction (or in the case of a bundle,
631 /// the instructions inside the bundle) has the specified property.
632 /// The first argument is the property being queried.
633 /// The second argument indicates whether the query should look inside
634 /// instruction bundles.
635 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
636 assert(MCFlag < 64 &&((MCFlag < 64 && "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."
) ? static_cast<void> (0) : __assert_fail ("MCFlag < 64 && \"MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 637, __PRETTY_FUNCTION__))
637 "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.")((MCFlag < 64 && "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."
) ? static_cast<void> (0) : __assert_fail ("MCFlag < 64 && \"MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 637, __PRETTY_FUNCTION__))
;
638 // Inline the fast path for unbundled or bundle-internal instructions.
639 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
640 return getDesc().getFlags() & (1ULL << MCFlag);
641
642 // If this is the first instruction in a bundle, take the slow path.
643 return hasPropertyInBundle(1ULL << MCFlag, Type);
644 }
645
646 /// Return true if this is an instruction that should go through the usual
647 /// legalization steps.
648 bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
649 return hasProperty(MCID::PreISelOpcode, Type);
650 }
651
652 /// Return true if this instruction can have a variable number of operands.
653 /// In this case, the variable operands will be after the normal
654 /// operands but before the implicit definitions and uses (if any are
655 /// present).
656 bool isVariadic(QueryType Type = IgnoreBundle) const {
657 return hasProperty(MCID::Variadic, Type);
658 }
659
660 /// Set if this instruction has an optional definition, e.g.
661 /// ARM instructions which can set condition code if 's' bit is set.
662 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
663 return hasProperty(MCID::HasOptionalDef, Type);
664 }
665
666 /// Return true if this is a pseudo instruction that doesn't
667 /// correspond to a real machine instruction.
668 bool isPseudo(QueryType Type = IgnoreBundle) const {
669 return hasProperty(MCID::Pseudo, Type);
670 }
671
672 bool isReturn(QueryType Type = AnyInBundle) const {
673 return hasProperty(MCID::Return, Type);
674 }
675
676 /// Return true if this is an instruction that marks the end of an EH scope,
677 /// i.e., a catchpad or a cleanuppad instruction.
678 bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
679 return hasProperty(MCID::EHScopeReturn, Type);
680 }
681
682 bool isCall(QueryType Type = AnyInBundle) const {
683 return hasProperty(MCID::Call, Type);
684 }
685
686 /// Returns true if the specified instruction stops control flow
687 /// from executing the instruction immediately following it. Examples include
688 /// unconditional branches and return instructions.
689 bool isBarrier(QueryType Type = AnyInBundle) const {
690 return hasProperty(MCID::Barrier, Type);
691 }
692
693 /// Returns true if this instruction part of the terminator for a basic block.
694 /// Typically this is things like return and branch instructions.
695 ///
696 /// Various passes use this to insert code into the bottom of a basic block,
697 /// but before control flow occurs.
698 bool isTerminator(QueryType Type = AnyInBundle) const {
699 return hasProperty(MCID::Terminator, Type);
700 }
701
702 /// Returns true if this is a conditional, unconditional, or indirect branch.
703 /// Predicates below can be used to discriminate between
704 /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
705 /// get more information.
706 bool isBranch(QueryType Type = AnyInBundle) const {
707 return hasProperty(MCID::Branch, Type);
708 }
709
710 /// Return true if this is an indirect branch, such as a
711 /// branch through a register.
712 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
713 return hasProperty(MCID::IndirectBranch, Type);
714 }
715
716 /// Return true if this is a branch which may fall
717 /// through to the next instruction or may transfer control flow to some other
718 /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
719 /// information about this branch.
720 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
721 return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
722 }
723
724 /// Return true if this is a branch which always
725 /// transfers control flow to some other block. The
726 /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
727 /// about this branch.
728 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
729 return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
730 }
731
732 /// Return true if this instruction has a predicate operand that
733 /// controls execution. It may be set to 'always', or may be set to other
734 /// values. There are various methods in TargetInstrInfo that can be used to
735 /// control and modify the predicate in this instruction.
736 bool isPredicable(QueryType Type = AllInBundle) const {
737 // If it's a bundle than all bundled instructions must be predicable for this
738 // to return true.
739 return hasProperty(MCID::Predicable, Type);
740 }
741
742 /// Return true if this instruction is a comparison.
743 bool isCompare(QueryType Type = IgnoreBundle) const {
744 return hasProperty(MCID::Compare, Type);
745 }
746
747 /// Return true if this instruction is a move immediate
748 /// (including conditional moves) instruction.
749 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
750 return hasProperty(MCID::MoveImm, Type);
751 }
752
753 /// Return true if this instruction is a register move.
754 /// (including moving values from subreg to reg)
755 bool isMoveReg(QueryType Type = IgnoreBundle) const {
756 return hasProperty(MCID::MoveReg, Type);
757 }
758
759 /// Return true if this instruction is a bitcast instruction.
760 bool isBitcast(QueryType Type = IgnoreBundle) const {
761 return hasProperty(MCID::Bitcast, Type);
762 }
763
764 /// Return true if this instruction is a select instruction.
765 bool isSelect(QueryType Type = IgnoreBundle) const {
766 return hasProperty(MCID::Select, Type);
767 }
768
769 /// Return true if this instruction cannot be safely duplicated.
770 /// For example, if the instruction has a unique labels attached
771 /// to it, duplicating it would cause multiple definition errors.
772 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
773 return hasProperty(MCID::NotDuplicable, Type);
774 }
775
776 /// Return true if this instruction is convergent.
777 /// Convergent instructions can not be made control-dependent on any
778 /// additional values.
779 bool isConvergent(QueryType Type = AnyInBundle) const {
780 if (isInlineAsm()) {
781 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
782 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
783 return true;
784 }
785 return hasProperty(MCID::Convergent, Type);
786 }
787
788 /// Returns true if the specified instruction has a delay slot
789 /// which must be filled by the code generator.
790 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
791 return hasProperty(MCID::DelaySlot, Type);
792 }
793
794 /// Return true for instructions that can be folded as
795 /// memory operands in other instructions. The most common use for this
796 /// is instructions that are simple loads from memory that don't modify
797 /// the loaded value in any way, but it can also be used for instructions
798 /// that can be expressed as constant-pool loads, such as V_SETALLONES
799 /// on x86, to allow them to be folded when it is beneficial.
800 /// This should only be set on instructions that return a value in their
801 /// only virtual register definition.
802 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
803 return hasProperty(MCID::FoldableAsLoad, Type);
804 }
805
806 /// Return true if this instruction behaves
807 /// the same way as the generic REG_SEQUENCE instructions.
808 /// E.g., on ARM,
809 /// dX VMOVDRR rY, rZ
810 /// is equivalent to
811 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
812 ///
813 /// Note that for the optimizers to be able to take advantage of
814 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
815 /// override accordingly.
816 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
817 return hasProperty(MCID::RegSequence, Type);
818 }
819
820 /// Return true if this instruction behaves
821 /// the same way as the generic EXTRACT_SUBREG instructions.
822 /// E.g., on ARM,
823 /// rX, rY VMOVRRD dZ
824 /// is equivalent to two EXTRACT_SUBREG:
825 /// rX = EXTRACT_SUBREG dZ, ssub_0
826 /// rY = EXTRACT_SUBREG dZ, ssub_1
827 ///
828 /// Note that for the optimizers to be able to take advantage of
829 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
830 /// override accordingly.
831 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
832 return hasProperty(MCID::ExtractSubreg, Type);
833 }
834
835 /// Return true if this instruction behaves
836 /// the same way as the generic INSERT_SUBREG instructions.
837 /// E.g., on ARM,
838 /// dX = VSETLNi32 dY, rZ, Imm
839 /// is equivalent to a INSERT_SUBREG:
840 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
841 ///
842 /// Note that for the optimizers to be able to take advantage of
843 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
844 /// override accordingly.
845 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
846 return hasProperty(MCID::InsertSubreg, Type);
847 }
848
849 //===--------------------------------------------------------------------===//
850 // Side Effect Analysis
851 //===--------------------------------------------------------------------===//
852
853 /// Return true if this instruction could possibly read memory.
854 /// Instructions with this flag set are not necessarily simple load
855 /// instructions, they may load a value and modify it, for example.
856 bool mayLoad(QueryType Type = AnyInBundle) const {
857 if (isInlineAsm()) {
858 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
859 if (ExtraInfo & InlineAsm::Extra_MayLoad)
860 return true;
861 }
862 return hasProperty(MCID::MayLoad, Type);
863 }
864
865 /// Return true if this instruction could possibly modify memory.
866 /// Instructions with this flag set are not necessarily simple store
867 /// instructions, they may store a modified value based on their operands, or
868 /// may not actually modify anything, for example.
869 bool mayStore(QueryType Type = AnyInBundle) const {
870 if (isInlineAsm()) {
871 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
872 if (ExtraInfo & InlineAsm::Extra_MayStore)
873 return true;
874 }
875 return hasProperty(MCID::MayStore, Type);
876 }
877
878 /// Return true if this instruction could possibly read or modify memory.
879 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
880 return mayLoad(Type) || mayStore(Type);
881 }
882
883 /// Return true if this instruction could possibly raise a floating-point
884 /// exception. This is the case if the instruction is a floating-point
885 /// instruction that can in principle raise an exception, as indicated
886 /// by the MCID::MayRaiseFPException property, *and* at the same time,
887 /// the instruction is used in a context where we expect floating-point
888 /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
889 bool mayRaiseFPException() const {
890 return hasProperty(MCID::MayRaiseFPException) &&
891 !getFlag(MachineInstr::MIFlag::NoFPExcept);
892 }
893
894 //===--------------------------------------------------------------------===//
895 // Flags that indicate whether an instruction can be modified by a method.
896 //===--------------------------------------------------------------------===//
897
898 /// Return true if this may be a 2- or 3-address
899 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
900 /// result if Y and Z are exchanged. If this flag is set, then the
901 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
902 /// instruction.
903 ///
904 /// Note that this flag may be set on instructions that are only commutable
905 /// sometimes. In these cases, the call to commuteInstruction will fail.
906 /// Also note that some instructions require non-trivial modification to
907 /// commute them.
908 bool isCommutable(QueryType Type = IgnoreBundle) const {
909 return hasProperty(MCID::Commutable, Type);
910 }
911
912 /// Return true if this is a 2-address instruction
913 /// which can be changed into a 3-address instruction if needed. Doing this
914 /// transformation can be profitable in the register allocator, because it
915 /// means that the instruction can use a 2-address form if possible, but
916 /// degrade into a less efficient form if the source and dest register cannot
917 /// be assigned to the same register. For example, this allows the x86
918 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
919 /// is the same speed as the shift but has bigger code size.
920 ///
921 /// If this returns true, then the target must implement the
922 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
923 /// is allowed to fail if the transformation isn't valid for this specific
924 /// instruction (e.g. shl reg, 4 on x86).
925 ///
926 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
927 return hasProperty(MCID::ConvertibleTo3Addr, Type);
928 }
929
930 /// Return true if this instruction requires
931 /// custom insertion support when the DAG scheduler is inserting it into a
932 /// machine basic block. If this is true for the instruction, it basically
933 /// means that it is a pseudo instruction used at SelectionDAG time that is
934 /// expanded out into magic code by the target when MachineInstrs are formed.
935 ///
936 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
937 /// is used to insert this into the MachineBasicBlock.
938 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
939 return hasProperty(MCID::UsesCustomInserter, Type);
940 }
941
942 /// Return true if this instruction requires *adjustment*
943 /// after instruction selection by calling a target hook. For example, this
944 /// can be used to fill in ARM 's' optional operand depending on whether
945 /// the conditional flag register is used.
946 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
947 return hasProperty(MCID::HasPostISelHook, Type);
948 }
949
950 /// Returns true if this instruction is a candidate for remat.
951 /// This flag is deprecated, please don't use it anymore. If this
952 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
953 /// verify the instruction is really rematable.
954 bool isRematerializable(QueryType Type = AllInBundle) const {
955 // It's only possible to re-mat a bundle if all bundled instructions are
956 // re-materializable.
957 return hasProperty(MCID::Rematerializable, Type);
958 }
959
960 /// Returns true if this instruction has the same cost (or less) than a move
961 /// instruction. This is useful during certain types of optimizations
962 /// (e.g., remat during two-address conversion or machine licm)
963 /// where we would like to remat or hoist the instruction, but not if it costs
964 /// more than moving the instruction into the appropriate register. Note, we
965 /// are not marking copies from and to the same register class with this flag.
966 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
967 // Only returns true for a bundle if all bundled instructions are cheap.
968 return hasProperty(MCID::CheapAsAMove, Type);
969 }
970
971 /// Returns true if this instruction source operands
972 /// have special register allocation requirements that are not captured by the
973 /// operand register classes. e.g. ARM::STRD's two source registers must be an
974 /// even / odd pair, ARM::STM registers have to be in ascending order.
975 /// Post-register allocation passes should not attempt to change allocations
976 /// for sources of instructions with this flag.
977 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
978 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
979 }
980
981 /// Returns true if this instruction def operands
982 /// have special register allocation requirements that are not captured by the
983 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
984 /// even / odd pair, ARM::LDM registers have to be in ascending order.
985 /// Post-register allocation passes should not attempt to change allocations
986 /// for definitions of instructions with this flag.
987 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
988 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
989 }
990
991 enum MICheckType {
992 CheckDefs, // Check all operands for equality
993 CheckKillDead, // Check all operands including kill / dead markers
994 IgnoreDefs, // Ignore all definitions
995 IgnoreVRegDefs // Ignore virtual register definitions
996 };
997
998 /// Return true if this instruction is identical to \p Other.
999 /// Two instructions are identical if they have the same opcode and all their
1000 /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1001 /// Note that this means liveness related flags (dead, undef, kill) do not
1002 /// affect the notion of identical.
1003 bool isIdenticalTo(const MachineInstr &Other,
1004 MICheckType Check = CheckDefs) const;
1005
1006 /// Unlink 'this' from the containing basic block, and return it without
1007 /// deleting it.
1008 ///
1009 /// This function can not be used on bundled instructions, use
1010 /// removeFromBundle() to remove individual instructions from a bundle.
1011 MachineInstr *removeFromParent();
1012
1013 /// Unlink this instruction from its basic block and return it without
1014 /// deleting it.
1015 ///
1016 /// If the instruction is part of a bundle, the other instructions in the
1017 /// bundle remain bundled.
1018 MachineInstr *removeFromBundle();
1019
1020 /// Unlink 'this' from the containing basic block and delete it.
1021 ///
1022 /// If this instruction is the header of a bundle, the whole bundle is erased.
1023 /// This function can not be used for instructions inside a bundle, use
1024 /// eraseFromBundle() to erase individual bundled instructions.
1025 void eraseFromParent();
1026
1027 /// Unlink 'this' from the containing basic block and delete it.
1028 ///
1029 /// For all definitions mark their uses in DBG_VALUE nodes
1030 /// as undefined. Otherwise like eraseFromParent().
1031 void eraseFromParentAndMarkDBGValuesForRemoval();
1032
1033 /// Unlink 'this' form its basic block and delete it.
1034 ///
1035 /// If the instruction is part of a bundle, the other instructions in the
1036 /// bundle remain bundled.
1037 void eraseFromBundle();
1038
1039 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1040 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1041 bool isAnnotationLabel() const {
1042 return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1043 }
1044
1045 /// Returns true if the MachineInstr represents a label.
1046 bool isLabel() const {
1047 return isEHLabel() || isGCLabel() || isAnnotationLabel();
1048 }
1049
1050 bool isCFIInstruction() const {
1051 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1052 }
1053
1054 // True if the instruction represents a position in the function.
1055 bool isPosition() const { return isLabel() || isCFIInstruction(); }
1056
1057 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1058 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1059 bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
1060
1061 /// A DBG_VALUE is indirect iff the first operand is a register and
1062 /// the second operand is an immediate.
1063 bool isIndirectDebugValue() const {
1064 return isDebugValue()
1065 && getOperand(0).isReg()
1066 && getOperand(1).isImm();
1067 }
1068
1069 /// A DBG_VALUE is an entry value iff its debug expression contains the
1070 /// DW_OP_LLVM_entry_value operation.
1071 bool isDebugEntryValue() const;
1072
1073 /// Return true if the instruction is a debug value which describes a part of
1074 /// a variable as unavailable.
1075 bool isUndefDebugValue() const {
1076 return isDebugValue() && getOperand(0).isReg() && !getOperand(0).getReg().isValid();
1077 }
1078
1079 bool isPHI() const {
1080 return getOpcode() == TargetOpcode::PHI ||
1081 getOpcode() == TargetOpcode::G_PHI;
1082 }
1083 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1084 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1085 bool isInlineAsm() const {
1086 return getOpcode() == TargetOpcode::INLINEASM ||
1087 getOpcode() == TargetOpcode::INLINEASM_BR;
1088 }
1089
1090 /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1091 /// specific, be attached to a generic MachineInstr.
1092 bool isMSInlineAsm() const {
1093 return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1094 }
1095
1096 bool isStackAligningInlineAsm() const;
1097 InlineAsm::AsmDialect getInlineAsmDialect() const;
1098
1099 bool isInsertSubreg() const {
1100 return getOpcode() == TargetOpcode::INSERT_SUBREG;
1101 }
1102
1103 bool isSubregToReg() const {
1104 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1105 }
1106
1107 bool isRegSequence() const {
1108 return getOpcode() == TargetOpcode::REG_SEQUENCE;
1109 }
1110
1111 bool isBundle() const {
1112 return getOpcode() == TargetOpcode::BUNDLE;
1113 }
1114
1115 bool isCopy() const {
1116 return getOpcode() == TargetOpcode::COPY;
19
Assuming the condition is true
20
Returning the value 1, which participates in a condition later
1117 }
1118
1119 bool isFullCopy() const {
1120 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
26
Assuming the condition is false
27
Returning zero, which participates in a condition later
1121 }
1122
1123 bool isExtractSubreg() const {
1124 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1125 }
1126
1127 /// Return true if the instruction behaves like a copy.
1128 /// This does not include native copy instructions.
1129 bool isCopyLike() const {
1130 return isCopy() || isSubregToReg();
1131 }
1132
1133 /// Return true is the instruction is an identity copy.
1134 bool isIdentityCopy() const {
1135 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1136 getOperand(0).getSubReg() == getOperand(1).getSubReg();
1137 }
1138
1139 /// Return true if this instruction doesn't produce any output in the form of
1140 /// executable instructions.
1141 bool isMetaInstruction() const {
1142 switch (getOpcode()) {
1143 default:
1144 return false;
1145 case TargetOpcode::IMPLICIT_DEF:
1146 case TargetOpcode::KILL:
1147 case TargetOpcode::CFI_INSTRUCTION:
1148 case TargetOpcode::EH_LABEL:
1149 case TargetOpcode::GC_LABEL:
1150 case TargetOpcode::DBG_VALUE:
1151 case TargetOpcode::DBG_LABEL:
1152 case TargetOpcode::LIFETIME_START:
1153 case TargetOpcode::LIFETIME_END:
1154 return true;
1155 }
1156 }
1157
1158 /// Return true if this is a transient instruction that is either very likely
1159 /// to be eliminated during register allocation (such as copy-like
1160 /// instructions), or if this instruction doesn't have an execution-time cost.
1161 bool isTransient() const {
1162 switch (getOpcode()) {
1163 default:
1164 return isMetaInstruction();
1165 // Copy-like instructions are usually eliminated during register allocation.
1166 case TargetOpcode::PHI:
1167 case TargetOpcode::G_PHI:
1168 case TargetOpcode::COPY:
1169 case TargetOpcode::INSERT_SUBREG:
1170 case TargetOpcode::SUBREG_TO_REG:
1171 case TargetOpcode::REG_SEQUENCE:
1172 return true;
1173 }
1174 }
1175
1176 /// Return the number of instructions inside the MI bundle, excluding the
1177 /// bundle header.
1178 ///
1179 /// This is the number of instructions that MachineBasicBlock::iterator
1180 /// skips, 0 for unbundled instructions.
1181 unsigned getBundleSize() const;
1182
1183 /// Return true if the MachineInstr reads the specified register.
1184 /// If TargetRegisterInfo is passed, then it also checks if there
1185 /// is a read of a super-register.
1186 /// This does not count partial redefines of virtual registers as reads:
1187 /// %reg1024:6 = OP.
1188 bool readsRegister(Register Reg,
1189 const TargetRegisterInfo *TRI = nullptr) const {
1190 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1191 }
1192
1193 /// Return true if the MachineInstr reads the specified virtual register.
1194 /// Take into account that a partial define is a
1195 /// read-modify-write operation.
1196 bool readsVirtualRegister(Register Reg) const {
1197 return readsWritesVirtualRegister(Reg).first;
1198 }
1199
1200 /// Return a pair of bools (reads, writes) indicating if this instruction
1201 /// reads or writes Reg. This also considers partial defines.
1202 /// If Ops is not null, all operand indices for Reg are added.
1203 std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1204 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1205
1206 /// Return true if the MachineInstr kills the specified register.
1207 /// If TargetRegisterInfo is passed, then it also checks if there is
1208 /// a kill of a super-register.
1209 bool killsRegister(Register Reg,
1210 const TargetRegisterInfo *TRI = nullptr) const {
1211 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1212 }
1213
1214 /// Return true if the MachineInstr fully defines the specified register.
1215 /// If TargetRegisterInfo is passed, then it also checks
1216 /// if there is a def of a super-register.
1217 /// NOTE: It's ignoring subreg indices on virtual registers.
1218 bool definesRegister(Register Reg,
1219 const TargetRegisterInfo *TRI = nullptr) const {
1220 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1221 }
1222
1223 /// Return true if the MachineInstr modifies (fully define or partially
1224 /// define) the specified register.
1225 /// NOTE: It's ignoring subreg indices on virtual registers.
1226 bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1227 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1228 }
1229
1230 /// Returns true if the register is dead in this machine instruction.
1231 /// If TargetRegisterInfo is passed, then it also checks
1232 /// if there is a dead def of a super-register.
1233 bool registerDefIsDead(Register Reg,
1234 const TargetRegisterInfo *TRI = nullptr) const {
1235 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1236 }
1237
1238 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1239 /// the given register (not considering sub/super-registers).
1240 bool hasRegisterImplicitUseOperand(Register Reg) const;
1241
1242 /// Returns the operand index that is a use of the specific register or -1
1243 /// if it is not found. It further tightens the search criteria to a use
1244 /// that kills the register if isKill is true.
1245 int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1246 const TargetRegisterInfo *TRI = nullptr) const;
1247
1248 /// Wrapper for findRegisterUseOperandIdx, it returns
1249 /// a pointer to the MachineOperand rather than an index.
1250 MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1251 const TargetRegisterInfo *TRI = nullptr) {
1252 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1253 return (Idx == -1) ? nullptr : &getOperand(Idx);
1254 }
1255
1256 const MachineOperand *findRegisterUseOperand(
1257 Register Reg, bool isKill = false,
1258 const TargetRegisterInfo *TRI = nullptr) const {
1259 return const_cast<MachineInstr *>(this)->
1260 findRegisterUseOperand(Reg, isKill, TRI);
1261 }
1262
1263 /// Returns the operand index that is a def of the specified register or
1264 /// -1 if it is not found. If isDead is true, defs that are not dead are
1265 /// skipped. If Overlap is true, then it also looks for defs that merely
1266 /// overlap the specified register. If TargetRegisterInfo is non-null,
1267 /// then it also checks if there is a def of a super-register.
1268 /// This may also return a register mask operand when Overlap is true.
1269 int findRegisterDefOperandIdx(Register Reg,
1270 bool isDead = false, bool Overlap = false,
1271 const TargetRegisterInfo *TRI = nullptr) const;
1272
1273 /// Wrapper for findRegisterDefOperandIdx, it returns
1274 /// a pointer to the MachineOperand rather than an index.
1275 MachineOperand *
1276 findRegisterDefOperand(Register Reg, bool isDead = false,
1277 bool Overlap = false,
1278 const TargetRegisterInfo *TRI = nullptr) {
1279 int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1280 return (Idx == -1) ? nullptr : &getOperand(Idx);
1281 }
1282
1283 const MachineOperand *
1284 findRegisterDefOperand(Register Reg, bool isDead = false,
1285 bool Overlap = false,
1286 const TargetRegisterInfo *TRI = nullptr) const {
1287 return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1288 Reg, isDead, Overlap, TRI);
1289 }
1290
1291 /// Find the index of the first operand in the
1292 /// operand list that is used to represent the predicate. It returns -1 if
1293 /// none is found.
1294 int findFirstPredOperandIdx() const;
1295
1296 /// Find the index of the flag word operand that
1297 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
1298 /// getOperand(OpIdx) does not belong to an inline asm operand group.
1299 ///
1300 /// If GroupNo is not NULL, it will receive the number of the operand group
1301 /// containing OpIdx.
1302 ///
1303 /// The flag operand is an immediate that can be decoded with methods like
1304 /// InlineAsm::hasRegClassConstraint().
1305 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1306
1307 /// Compute the static register class constraint for operand OpIdx.
1308 /// For normal instructions, this is derived from the MCInstrDesc.
1309 /// For inline assembly it is derived from the flag words.
1310 ///
1311 /// Returns NULL if the static register class constraint cannot be
1312 /// determined.
1313 const TargetRegisterClass*
1314 getRegClassConstraint(unsigned OpIdx,
1315 const TargetInstrInfo *TII,
1316 const TargetRegisterInfo *TRI) const;
1317
1318 /// Applies the constraints (def/use) implied by this MI on \p Reg to
1319 /// the given \p CurRC.
1320 /// If \p ExploreBundle is set and MI is part of a bundle, all the
1321 /// instructions inside the bundle will be taken into account. In other words,
1322 /// this method accumulates all the constraints of the operand of this MI and
1323 /// the related bundle if MI is a bundle or inside a bundle.
1324 ///
1325 /// Returns the register class that satisfies both \p CurRC and the
1326 /// constraints set by MI. Returns NULL if such a register class does not
1327 /// exist.
1328 ///
1329 /// \pre CurRC must not be NULL.
1330 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1331 Register Reg, const TargetRegisterClass *CurRC,
1332 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1333 bool ExploreBundle = false) const;
1334
1335 /// Applies the constraints (def/use) implied by the \p OpIdx operand
1336 /// to the given \p CurRC.
1337 ///
1338 /// Returns the register class that satisfies both \p CurRC and the
1339 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1340 /// does not exist.
1341 ///
1342 /// \pre CurRC must not be NULL.
1343 /// \pre The operand at \p OpIdx must be a register.
1344 const TargetRegisterClass *
1345 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1346 const TargetInstrInfo *TII,
1347 const TargetRegisterInfo *TRI) const;
1348
1349 /// Add a tie between the register operands at DefIdx and UseIdx.
1350 /// The tie will cause the register allocator to ensure that the two
1351 /// operands are assigned the same physical register.
1352 ///
1353 /// Tied operands are managed automatically for explicit operands in the
1354 /// MCInstrDesc. This method is for exceptional cases like inline asm.
1355 void tieOperands(unsigned DefIdx, unsigned UseIdx);
1356
1357 /// Given the index of a tied register operand, find the
1358 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1359 /// index of the tied operand which must exist.
1360 unsigned findTiedOperandIdx(unsigned OpIdx) const;
1361
1362 /// Given the index of a register def operand,
1363 /// check if the register def is tied to a source operand, due to either
1364 /// two-address elimination or inline assembly constraints. Returns the
1365 /// first tied use operand index by reference if UseOpIdx is not null.
1366 bool isRegTiedToUseOperand(unsigned DefOpIdx,
1367 unsigned *UseOpIdx = nullptr) const {
1368 const MachineOperand &MO = getOperand(DefOpIdx);
1369 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1370 return false;
1371 if (UseOpIdx)
1372 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1373 return true;
1374 }
1375
1376 /// Return true if the use operand of the specified index is tied to a def
1377 /// operand. It also returns the def operand index by reference if DefOpIdx
1378 /// is not null.
1379 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1380 unsigned *DefOpIdx = nullptr) const {
1381 const MachineOperand &MO = getOperand(UseOpIdx);
1382 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1383 return false;
1384 if (DefOpIdx)
1385 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1386 return true;
1387 }
1388
1389 /// Clears kill flags on all operands.
1390 void clearKillInfo();
1391
1392 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1393 /// properly composing subreg indices where necessary.
1394 void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1395 const TargetRegisterInfo &RegInfo);
1396
1397 /// We have determined MI kills a register. Look for the
1398 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1399 /// add a implicit operand if it's not found. Returns true if the operand
1400 /// exists / is added.
1401 bool addRegisterKilled(Register IncomingReg,
1402 const TargetRegisterInfo *RegInfo,
1403 bool AddIfNotFound = false);
1404
1405 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes
1406 /// all aliasing registers.
1407 void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1408
1409 /// We have determined MI defined a register without a use.
1410 /// Look for the operand that defines it and mark it as IsDead. If
1411 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1412 /// true if the operand exists / is added.
1413 bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1414 bool AddIfNotFound = false);
1415
1416 /// Clear all dead flags on operands defining register @p Reg.
1417 void clearRegisterDeads(Register Reg);
1418
1419 /// Mark all subregister defs of register @p Reg with the undef flag.
1420 /// This function is used when we determined to have a subregister def in an
1421 /// otherwise undefined super register.
1422 void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1423
1424 /// We have determined MI defines a register. Make sure there is an operand
1425 /// defining Reg.
1426 void addRegisterDefined(Register Reg,
1427 const TargetRegisterInfo *RegInfo = nullptr);
1428
1429 /// Mark every physreg used by this instruction as
1430 /// dead except those in the UsedRegs list.
1431 ///
1432 /// On instructions with register mask operands, also add implicit-def
1433 /// operands for all registers in UsedRegs.
1434 void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1435 const TargetRegisterInfo &TRI);
1436
1437 /// Return true if it is safe to move this instruction. If
1438 /// SawStore is set to true, it means that there is a store (or call) between
1439 /// the instruction's location and its intended destination.
1440 bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1441
1442 /// Returns true if this instruction's memory access aliases the memory
1443 /// access of Other.
1444 //
1445 /// Assumes any physical registers used to compute addresses
1446 /// have the same value for both instructions. Returns false if neither
1447 /// instruction writes to memory.
1448 ///
1449 /// @param AA Optional alias analysis, used to compare memory operands.
1450 /// @param Other MachineInstr to check aliasing against.
1451 /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1452 bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1453
1454 /// Return true if this instruction may have an ordered
1455 /// or volatile memory reference, or if the information describing the memory
1456 /// reference is not available. Return false if it is known to have no
1457 /// ordered or volatile memory references.
1458 bool hasOrderedMemoryRef() const;
1459
1460 /// Return true if this load instruction never traps and points to a memory
1461 /// location whose value doesn't change during the execution of this function.
1462 ///
1463 /// Examples include loading a value from the constant pool or from the
1464 /// argument area of a function (if it does not change). If the instruction
1465 /// does multiple loads, this returns true only if all of the loads are
1466 /// dereferenceable and invariant.
1467 bool isDereferenceableInvariantLoad(AAResults *AA) const;
1468
1469 /// If the specified instruction is a PHI that always merges together the
1470 /// same virtual register, return the register, otherwise return 0.
1471 unsigned isConstantValuePHI() const;
1472
1473 /// Return true if this instruction has side effects that are not modeled
1474 /// by mayLoad / mayStore, etc.
1475 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1476 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1477 /// INLINEASM instruction, in which case the side effect property is encoded
1478 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1479 ///
1480 bool hasUnmodeledSideEffects() const;
1481
1482 /// Returns true if it is illegal to fold a load across this instruction.
1483 bool isLoadFoldBarrier() const;
1484
1485 /// Return true if all the defs of this instruction are dead.
1486 bool allDefsAreDead() const;
1487
1488 /// Return a valid size if the instruction is a spill instruction.
1489 Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1490
1491 /// Return a valid size if the instruction is a folded spill instruction.
1492 Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1493
1494 /// Return a valid size if the instruction is a restore instruction.
1495 Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1496
1497 /// Return a valid size if the instruction is a folded restore instruction.
1498 Optional<unsigned>
1499 getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1500
1501 /// Copy implicit register operands from specified
1502 /// instruction to this instruction.
1503 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1504
1505 /// Debugging support
1506 /// @{
1507 /// Determine the generic type to be printed (if needed) on uses and defs.
1508 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1509 const MachineRegisterInfo &MRI) const;
1510
1511 /// Return true when an instruction has tied register that can't be determined
1512 /// by the instruction's descriptor. This is useful for MIR printing, to
1513 /// determine whether we need to print the ties or not.
1514 bool hasComplexRegisterTies() const;
1515
1516 /// Print this MI to \p OS.
1517 /// Don't print information that can be inferred from other instructions if
1518 /// \p IsStandalone is false. It is usually true when only a fragment of the
1519 /// function is printed.
1520 /// Only print the defs and the opcode if \p SkipOpers is true.
1521 /// Otherwise, also print operands if \p SkipDebugLoc is true.
1522 /// Otherwise, also print the debug loc, with a terminating newline.
1523 /// \p TII is used to print the opcode name. If it's not present, but the
1524 /// MI is in a function, the opcode will be printed using the function's TII.
1525 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1526 bool SkipDebugLoc = false, bool AddNewLine = true,
1527 const TargetInstrInfo *TII = nullptr) const;
1528 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1529 bool SkipOpers = false, bool SkipDebugLoc = false,
1530 bool AddNewLine = true,
1531 const TargetInstrInfo *TII = nullptr) const;
1532 void dump() const;
1533 /// @}
1534
1535 //===--------------------------------------------------------------------===//
1536 // Accessors used to build up machine instructions.
1537
1538 /// Add the specified operand to the instruction. If it is an implicit
1539 /// operand, it is added to the end of the operand list. If it is an
1540 /// explicit operand it is added at the end of the explicit operand list
1541 /// (before the first implicit operand).
1542 ///
1543 /// MF must be the machine function that was used to allocate this
1544 /// instruction.
1545 ///
1546 /// MachineInstrBuilder provides a more convenient interface for creating
1547 /// instructions and adding operands.
1548 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1549
1550 /// Add an operand without providing an MF reference. This only works for
1551 /// instructions that are inserted in a basic block.
1552 ///
1553 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1554 /// preferred.
1555 void addOperand(const MachineOperand &Op);
1556
1557 /// Replace the instruction descriptor (thus opcode) of
1558 /// the current instruction with a new one.
1559 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1560
1561 /// Replace current source information with new such.
1562 /// Avoid using this, the constructor argument is preferable.
1563 void setDebugLoc(DebugLoc dl) {
1564 debugLoc = std::move(dl);
1565 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor"
) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h"
, 1565, __PRETTY_FUNCTION__))
;
1566 }
1567
1568 /// Erase an operand from an instruction, leaving it with one
1569 /// fewer operand than it started with.
1570 void RemoveOperand(unsigned OpNo);
1571
1572 /// Clear this MachineInstr's memory reference descriptor list. This resets
1573 /// the memrefs to their most conservative state. This should be used only
1574 /// as a last resort since it greatly pessimizes our knowledge of the memory
1575 /// access performed by the instruction.
1576 void dropMemRefs(MachineFunction &MF);
1577
1578 /// Assign this MachineInstr's memory reference descriptor list.
1579 ///
1580 /// Unlike other methods, this *will* allocate them into a new array
1581 /// associated with the provided `MachineFunction`.
1582 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1583
1584 /// Add a MachineMemOperand to the machine instruction.
1585 /// This function should be used only occasionally. The setMemRefs function
1586 /// is the primary method for setting up a MachineInstr's MemRefs list.
1587 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1588
1589 /// Clone another MachineInstr's memory reference descriptor list and replace
1590 /// ours with it.
1591 ///
1592 /// Note that `*this` may be the incoming MI!
1593 ///
1594 /// Prefer this API whenever possible as it can avoid allocations in common
1595 /// cases.
1596 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1597
1598 /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1599 /// list and replace ours with it.
1600 ///
1601 /// Note that `*this` may be one of the incoming MIs!
1602 ///
1603 /// Prefer this API whenever possible as it can avoid allocations in common
1604 /// cases.
1605 void cloneMergedMemRefs(MachineFunction &MF,
1606 ArrayRef<const MachineInstr *> MIs);
1607
1608 /// Set a symbol that will be emitted just prior to the instruction itself.
1609 ///
1610 /// Setting this to a null pointer will remove any such symbol.
1611 ///
1612 /// FIXME: This is not fully implemented yet.
1613 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1614
1615 /// Set a symbol that will be emitted just after the instruction itself.
1616 ///
1617 /// Setting this to a null pointer will remove any such symbol.
1618 ///
1619 /// FIXME: This is not fully implemented yet.
1620 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1621
1622 /// Clone another MachineInstr's pre- and post- instruction symbols and
1623 /// replace ours with it.
1624 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1625
1626 /// Set a marker on instructions that denotes where we should create and emit
1627 /// heap alloc site labels. This waits until after instruction selection and
1628 /// optimizations to create the label, so it should still work if the
1629 /// instruction is removed or duplicated.
1630 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1631
1632 /// Return the MIFlags which represent both MachineInstrs. This
1633 /// should be used when merging two MachineInstrs into one. This routine does
1634 /// not modify the MIFlags of this MachineInstr.
1635 uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1636
1637 static uint16_t copyFlagsFromInstruction(const Instruction &I);
1638
1639 /// Copy all flags to MachineInst MIFlags
1640 void copyIRFlags(const Instruction &I);
1641
1642 /// Break any tie involving OpIdx.
1643 void untieRegOperand(unsigned OpIdx) {
1644 MachineOperand &MO = getOperand(OpIdx);
1645 if (MO.isReg() && MO.isTied()) {
1646 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1647 MO.TiedTo = 0;
1648 }
1649 }
1650
1651 /// Add all implicit def and use operands to this instruction.
1652 void addImplicitDefUseOperands(MachineFunction &MF);
1653
1654 /// Scan instructions immediately following MI and collect any matching
1655 /// DBG_VALUEs.
1656 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1657
1658 /// Find all DBG_VALUEs that point to the register def in this instruction
1659 /// and point them to \p Reg instead.
1660 void changeDebugValuesDefReg(Register Reg);
1661
1662 /// Returns the Intrinsic::ID for this instruction.
1663 /// \pre Must have an intrinsic ID operand.
1664 unsigned getIntrinsicID() const {
1665 return getOperand(getNumExplicitDefs()).getIntrinsicID();
1666 }
1667
1668private:
1669 /// If this instruction is embedded into a MachineFunction, return the
1670 /// MachineRegisterInfo object for the current function, otherwise
1671 /// return null.
1672 MachineRegisterInfo *getRegInfo();
1673
1674 /// Unlink all of the register operands in this instruction from their
1675 /// respective use lists. This requires that the operands already be on their
1676 /// use lists.
1677 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1678
1679 /// Add all of the register operands in this instruction from their
1680 /// respective use lists. This requires that the operands not be on their
1681 /// use lists yet.
1682 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1683
1684 /// Slow path for hasProperty when we're dealing with a bundle.
1685 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1686
1687 /// Implements the logic of getRegClassConstraintEffectForVReg for the
1688 /// this MI and the given operand index \p OpIdx.
1689 /// If the related operand does not constrained Reg, this returns CurRC.
1690 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1691 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
1692 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1693
1694 /// Stores extra instruction information inline or allocates as ExtraInfo
1695 /// based on the number of pointers.
1696 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1697 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1698 MDNode *HeapAllocMarker);
1699};
1700
1701/// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1702/// instruction rather than by pointer value.
1703/// The hashing and equality testing functions ignore definitions so this is
1704/// useful for CSE, etc.
1705struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1706 static inline MachineInstr *getEmptyKey() {
1707 return nullptr;
1708 }
1709
1710 static inline MachineInstr *getTombstoneKey() {
1711 return reinterpret_cast<MachineInstr*>(-1);
1712 }
1713
1714 static unsigned getHashValue(const MachineInstr* const &MI);
1715
1716 static bool isEqual(const MachineInstr* const &LHS,
1717 const MachineInstr* const &RHS) {
1718 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1719 LHS == getEmptyKey() || LHS == getTombstoneKey())
1720 return LHS == RHS;
1721 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1722 }
1723};
1724
1725//===----------------------------------------------------------------------===//
1726// Debugging Support
1727
1728inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1729 MI.print(OS);
1730 return OS;
1731}
1732
1733} // end namespace llvm
1734
1735#endif // LLVM_CODEGEN_MACHINEINSTR_H

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h

1//===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TARGET_TARGETINSTRINFO_H
14#define LLVM_TARGET_TARGETINSTRINFO_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/None.h"
20#include "llvm/CodeGen/LiveRegUnits.h"
21#include "llvm/CodeGen/MIRFormatter.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineCombinerPattern.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineOperand.h"
28#include "llvm/CodeGen/MachineOutliner.h"
29#include "llvm/CodeGen/PseudoSourceValue.h"
30#include "llvm/CodeGen/VirtRegMap.h"
31#include "llvm/MC/MCInstrInfo.h"
32#include "llvm/Support/BranchProbability.h"
33#include "llvm/Support/ErrorHandling.h"
34#include <cassert>
35#include <cstddef>
36#include <cstdint>
37#include <utility>
38#include <vector>
39
40namespace llvm {
41
42class AAResults;
43class DFAPacketizer;
44class InstrItineraryData;
45class LiveIntervals;
46class LiveVariables;
47class MachineLoop;
48class MachineMemOperand;
49class MachineRegisterInfo;
50class MCAsmInfo;
51class MCInst;
52struct MCSchedModel;
53class Module;
54class ScheduleDAG;
55class ScheduleHazardRecognizer;
56class SDNode;
57class SelectionDAG;
58class RegScavenger;
59class TargetRegisterClass;
60class TargetRegisterInfo;
61class TargetSchedModel;
62class TargetSubtargetInfo;
63
64template <class T> class SmallVectorImpl;
65
66using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
67
68struct DestSourcePair {
69 const MachineOperand *Destination;
70 const MachineOperand *Source;
71
72 DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
73 : Destination(&Dest), Source(&Src) {}
74};
75
76/// Used to describe a register and immediate addition.
77struct RegImmPair {
78 Register Reg;
79 int64_t Imm;
80
81 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
82};
83
84//---------------------------------------------------------------------------
85///
86/// TargetInstrInfo - Interface to description of machine instruction set
87///
88class TargetInstrInfo : public MCInstrInfo {
89public:
90 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
91 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
92 : CallFrameSetupOpcode(CFSetupOpcode),
93 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
94 ReturnOpcode(ReturnOpcode) {}
95 TargetInstrInfo(const TargetInstrInfo &) = delete;
96 TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
97 virtual ~TargetInstrInfo();
98
99 static bool isGenericOpcode(unsigned Opc) {
100 return Opc <= TargetOpcode::GENERIC_OP_END;
101 }
102
103 /// Given a machine instruction descriptor, returns the register
104 /// class constraint for OpNum, or NULL.
105 virtual
106 const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
107 const TargetRegisterInfo *TRI,
108 const MachineFunction &MF) const;
109
110 /// Return true if the instruction is trivially rematerializable, meaning it
111 /// has no side effects and requires no operands that aren't always available.
112 /// This means the only allowed uses are constants and unallocatable physical
113 /// registers so that the instructions result is independent of the place
114 /// in the function.
115 bool isTriviallyReMaterializable(const MachineInstr &MI,
116 AAResults *AA = nullptr) const {
117 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
118 (MI.getDesc().isRematerializable() &&
119 (isReallyTriviallyReMaterializable(MI, AA) ||
120 isReallyTriviallyReMaterializableGeneric(MI, AA)));
121 }
122
123protected:
124 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
125 /// set, this hook lets the target specify whether the instruction is actually
126 /// trivially rematerializable, taking into consideration its operands. This
127 /// predicate must return false if the instruction has any side effects other
128 /// than producing a value, or if it requres any address registers that are
129 /// not always available.
130 /// Requirements must be check as stated in isTriviallyReMaterializable() .
131 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
132 AAResults *AA) const {
133 return false;
134 }
135
136 /// This method commutes the operands of the given machine instruction MI.
137 /// The operands to be commuted are specified by their indices OpIdx1 and
138 /// OpIdx2.
139 ///
140 /// If a target has any instructions that are commutable but require
141 /// converting to different instructions or making non-trivial changes
142 /// to commute them, this method can be overloaded to do that.
143 /// The default implementation simply swaps the commutable operands.
144 ///
145 /// If NewMI is false, MI is modified in place and returned; otherwise, a
146 /// new machine instruction is created and returned.
147 ///
148 /// Do not call this method for a non-commutable instruction.
149 /// Even though the instruction is commutable, the method may still
150 /// fail to commute the operands, null pointer is returned in such cases.
151 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
152 unsigned OpIdx1,
153 unsigned OpIdx2) const;
154
155 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
156 /// operand indices to (ResultIdx1, ResultIdx2).
157 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
158 /// predefined to some indices or be undefined (designated by the special
159 /// value 'CommuteAnyOperandIndex').
160 /// The predefined result indices cannot be re-defined.
161 /// The function returns true iff after the result pair redefinition
162 /// the fixed result pair is equal to or equivalent to the source pair of
163 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
164 /// the pairs (x,y) and (y,x) are equivalent.
165 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
166 unsigned CommutableOpIdx1,
167 unsigned CommutableOpIdx2);
168
169private:
170 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
171 /// set and the target hook isReallyTriviallyReMaterializable returns false,
172 /// this function does target-independent tests to determine if the
173 /// instruction is really trivially rematerializable.
174 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
175 AAResults *AA) const;
176
177public:
178 /// These methods return the opcode of the frame setup/destroy instructions
179 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
180 /// order to abstract away the difference between operating with a frame
181 /// pointer and operating without, through the use of these two instructions.
182 ///
183 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
184 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
185
186 /// Returns true if the argument is a frame pseudo instruction.
187 bool isFrameInstr(const MachineInstr &I) const {
188 return I.getOpcode() == getCallFrameSetupOpcode() ||
189 I.getOpcode() == getCallFrameDestroyOpcode();
190 }
191
192 /// Returns true if the argument is a frame setup pseudo instruction.
193 bool isFrameSetup(const MachineInstr &I) const {
194 return I.getOpcode() == getCallFrameSetupOpcode();
195 }
196
197 /// Returns size of the frame associated with the given frame instruction.
198 /// For frame setup instruction this is frame that is set up space set up
199 /// after the instruction. For frame destroy instruction this is the frame
200 /// freed by the caller.
201 /// Note, in some cases a call frame (or a part of it) may be prepared prior
202 /// to the frame setup instruction. It occurs in the calls that involve
203 /// inalloca arguments. This function reports only the size of the frame part
204 /// that is set up between the frame setup and destroy pseudo instructions.
205 int64_t getFrameSize(const MachineInstr &I) const {
206 assert(isFrameInstr(I) && "Not a frame instruction")((isFrameInstr(I) && "Not a frame instruction") ? static_cast
<void> (0) : __assert_fail ("isFrameInstr(I) && \"Not a frame instruction\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 206, __PRETTY_FUNCTION__))
;
207 assert(I.getOperand(0).getImm() >= 0)((I.getOperand(0).getImm() >= 0) ? static_cast<void>
(0) : __assert_fail ("I.getOperand(0).getImm() >= 0", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 207, __PRETTY_FUNCTION__))
;
208 return I.getOperand(0).getImm();
209 }
210
211 /// Returns the total frame size, which is made up of the space set up inside
212 /// the pair of frame start-stop instructions and the space that is set up
213 /// prior to the pair.
214 int64_t getFrameTotalSize(const MachineInstr &I) const {
215 if (isFrameSetup(I)) {
216 assert(I.getOperand(1).getImm() >= 0 &&((I.getOperand(1).getImm() >= 0 && "Frame size must not be negative"
) ? static_cast<void> (0) : __assert_fail ("I.getOperand(1).getImm() >= 0 && \"Frame size must not be negative\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 217, __PRETTY_FUNCTION__))
217 "Frame size must not be negative")((I.getOperand(1).getImm() >= 0 && "Frame size must not be negative"
) ? static_cast<void> (0) : __assert_fail ("I.getOperand(1).getImm() >= 0 && \"Frame size must not be negative\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 217, __PRETTY_FUNCTION__))
;
218 return getFrameSize(I) + I.getOperand(1).getImm();
219 }
220 return getFrameSize(I);
221 }
222
223 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
224 unsigned getReturnOpcode() const { return ReturnOpcode; }
225
226 /// Returns the actual stack pointer adjustment made by an instruction
227 /// as part of a call sequence. By default, only call frame setup/destroy
228 /// instructions adjust the stack, but targets may want to override this
229 /// to enable more fine-grained adjustment, or adjust by a different value.
230 virtual int getSPAdjust(const MachineInstr &MI) const;
231
232 /// Return true if the instruction is a "coalescable" extension instruction.
233 /// That is, it's like a copy where it's legal for the source to overlap the
234 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
235 /// expected the pre-extension value is available as a subreg of the result
236 /// register. This also returns the sub-register index in SubIdx.
237 virtual bool isCoalescableExtInstr(const MachineInstr &MI, unsigned &SrcReg,
238 unsigned &DstReg, unsigned &SubIdx) const {
239 return false;
240 }
241
242 /// If the specified machine instruction is a direct
243 /// load from a stack slot, return the virtual or physical register number of
244 /// the destination along with the FrameIndex of the loaded stack slot. If
245 /// not, return 0. This predicate must return 0 if the instruction has
246 /// any side effects other than loading from the stack slot.
247 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
248 int &FrameIndex) const {
249 return 0;
250 }
251
252 /// Optional extension of isLoadFromStackSlot that returns the number of
253 /// bytes loaded from the stack. This must be implemented if a backend
254 /// supports partial stack slot spills/loads to further disambiguate
255 /// what the load does.
256 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
257 int &FrameIndex,
258 unsigned &MemBytes) const {
259 MemBytes = 0;
260 return isLoadFromStackSlot(MI, FrameIndex);
261 }
262
263 /// Check for post-frame ptr elimination stack locations as well.
264 /// This uses a heuristic so it isn't reliable for correctness.
265 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
266 int &FrameIndex) const {
267 return 0;
268 }
269
270 /// If the specified machine instruction has a load from a stack slot,
271 /// return true along with the FrameIndices of the loaded stack slot and the
272 /// machine mem operands containing the reference.
273 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
274 /// any instructions that loads from the stack. This is just a hint, as some
275 /// cases may be missed.
276 virtual bool hasLoadFromStackSlot(
277 const MachineInstr &MI,
278 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
279
280 /// If the specified machine instruction is a direct
281 /// store to a stack slot, return the virtual or physical register number of
282 /// the source reg along with the FrameIndex of the loaded stack slot. If
283 /// not, return 0. This predicate must return 0 if the instruction has
284 /// any side effects other than storing to the stack slot.
285 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
286 int &FrameIndex) const {
287 return 0;
35
Returning without writing to 'FrameIndex'
288 }
289
290 /// Optional extension of isStoreToStackSlot that returns the number of
291 /// bytes stored to the stack. This must be implemented if a backend
292 /// supports partial stack slot spills/loads to further disambiguate
293 /// what the store does.
294 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
295 int &FrameIndex,
296 unsigned &MemBytes) const {
297 MemBytes = 0;
298 return isStoreToStackSlot(MI, FrameIndex);
299 }
300
301 /// Check for post-frame ptr elimination stack locations as well.
302 /// This uses a heuristic, so it isn't reliable for correctness.
303 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
304 int &FrameIndex) const {
305 return 0;
306 }
307
308 /// If the specified machine instruction has a store to a stack slot,
309 /// return true along with the FrameIndices of the loaded stack slot and the
310 /// machine mem operands containing the reference.
311 /// If not, return false. Unlike isStoreToStackSlot,
312 /// this returns true for any instructions that stores to the
313 /// stack. This is just a hint, as some cases may be missed.
314 virtual bool hasStoreToStackSlot(
315 const MachineInstr &MI,
316 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
317
318 /// Return true if the specified machine instruction
319 /// is a copy of one stack slot to another and has no other effect.
320 /// Provide the identity of the two frame indices.
321 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
322 int &SrcFrameIndex) const {
323 return false;
324 }
325
326 /// Compute the size in bytes and offset within a stack slot of a spilled
327 /// register or subregister.
328 ///
329 /// \param [out] Size in bytes of the spilled value.
330 /// \param [out] Offset in bytes within the stack slot.
331 /// \returns true if both Size and Offset are successfully computed.
332 ///
333 /// Not all subregisters have computable spill slots. For example,
334 /// subregisters registers may not be byte-sized, and a pair of discontiguous
335 /// subregisters has no single offset.
336 ///
337 /// Targets with nontrivial bigendian implementations may need to override
338 /// this, particularly to support spilled vector registers.
339 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
340 unsigned &Size, unsigned &Offset,
341 const MachineFunction &MF) const;
342
343 /// Returns the size in bytes of the specified MachineInstr, or ~0U
344 /// when this function is not implemented by a target.
345 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
346 return ~0U;
347 }
348
349 /// Return true if the instruction is as cheap as a move instruction.
350 ///
351 /// Targets for different archs need to override this, and different
352 /// micro-architectures can also be finely tuned inside.
353 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
354 return MI.isAsCheapAsAMove();
355 }
356
357 /// Return true if the instruction should be sunk by MachineSink.
358 ///
359 /// MachineSink determines on its own whether the instruction is safe to sink;
360 /// this gives the target a hook to override the default behavior with regards
361 /// to which instructions should be sunk.
362 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
363
364 /// Re-issue the specified 'original' instruction at the
365 /// specific location targeting a new destination register.
366 /// The register in Orig->getOperand(0).getReg() will be substituted by
367 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
368 /// SubIdx.
369 virtual void reMaterialize(MachineBasicBlock &MBB,
370 MachineBasicBlock::iterator MI, unsigned DestReg,
371 unsigned SubIdx, const MachineInstr &Orig,
372 const TargetRegisterInfo &TRI) const;
373
374 /// Clones instruction or the whole instruction bundle \p Orig and
375 /// insert into \p MBB before \p InsertBefore. The target may update operands
376 /// that are required to be unique.
377 ///
378 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
379 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
380 MachineBasicBlock::iterator InsertBefore,
381 const MachineInstr &Orig) const;
382
383 /// This method must be implemented by targets that
384 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
385 /// may be able to convert a two-address instruction into one or more true
386 /// three-address instructions on demand. This allows the X86 target (for
387 /// example) to convert ADD and SHL instructions into LEA instructions if they
388 /// would require register copies due to two-addressness.
389 ///
390 /// This method returns a null pointer if the transformation cannot be
391 /// performed, otherwise it returns the last new instruction.
392 ///
393 virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
394 MachineInstr &MI,
395 LiveVariables *LV) const {
396 return nullptr;
397 }
398
399 // This constant can be used as an input value of operand index passed to
400 // the method findCommutedOpIndices() to tell the method that the
401 // corresponding operand index is not pre-defined and that the method
402 // can pick any commutable operand.
403 static const unsigned CommuteAnyOperandIndex = ~0U;
404
405 /// This method commutes the operands of the given machine instruction MI.
406 ///
407 /// The operands to be commuted are specified by their indices OpIdx1 and
408 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
409 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
410 /// any arbitrarily chosen commutable operand. If both arguments are set to
411 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
412 /// operands; then commutes them if such operands could be found.
413 ///
414 /// If NewMI is false, MI is modified in place and returned; otherwise, a
415 /// new machine instruction is created and returned.
416 ///
417 /// Do not call this method for a non-commutable instruction or
418 /// for non-commuable operands.
419 /// Even though the instruction is commutable, the method may still
420 /// fail to commute the operands, null pointer is returned in such cases.
421 MachineInstr *
422 commuteInstruction(MachineInstr &MI, bool NewMI = false,
423 unsigned OpIdx1 = CommuteAnyOperandIndex,
424 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
425
426 /// Returns true iff the routine could find two commutable operands in the
427 /// given machine instruction.
428 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
429 /// If any of the INPUT values is set to the special value
430 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
431 /// operand, then returns its index in the corresponding argument.
432 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
433 /// looks for 2 commutable operands.
434 /// If INPUT values refer to some operands of MI, then the method simply
435 /// returns true if the corresponding operands are commutable and returns
436 /// false otherwise.
437 ///
438 /// For example, calling this method this way:
439 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
440 /// findCommutedOpIndices(MI, Op1, Op2);
441 /// can be interpreted as a query asking to find an operand that would be
442 /// commutable with the operand#1.
443 virtual bool findCommutedOpIndices(const MachineInstr &MI,
444 unsigned &SrcOpIdx1,
445 unsigned &SrcOpIdx2) const;
446
447 /// A pair composed of a register and a sub-register index.
448 /// Used to give some type checking when modeling Reg:SubReg.
449 struct RegSubRegPair {
450 unsigned Reg;
451 unsigned SubReg;
452
453 RegSubRegPair(unsigned Reg = 0, unsigned SubReg = 0)
454 : Reg(Reg), SubReg(SubReg) {}
455
456 bool operator==(const RegSubRegPair& P) const {
457 return Reg == P.Reg && SubReg == P.SubReg;
458 }
459 bool operator!=(const RegSubRegPair& P) const {
460 return !(*this == P);
461 }
462 };
463
464 /// A pair composed of a pair of a register and a sub-register index,
465 /// and another sub-register index.
466 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
467 struct RegSubRegPairAndIdx : RegSubRegPair {
468 unsigned SubIdx;
469
470 RegSubRegPairAndIdx(unsigned Reg = 0, unsigned SubReg = 0,
471 unsigned SubIdx = 0)
472 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
473 };
474
475 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
476 /// and \p DefIdx.
477 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
478 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
479 /// flag are not added to this list.
480 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
481 /// two elements:
482 /// - %1:sub1, sub0
483 /// - %2<:0>, sub1
484 ///
485 /// \returns true if it is possible to build such an input sequence
486 /// with the pair \p MI, \p DefIdx. False otherwise.
487 ///
488 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
489 ///
490 /// \note The generic implementation does not provide any support for
491 /// MI.isRegSequenceLike(). In other words, one has to override
492 /// getRegSequenceLikeInputs for target specific instructions.
493 bool
494 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
495 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
496
497 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
498 /// and \p DefIdx.
499 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
500 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
501 /// - %1:sub1, sub0
502 ///
503 /// \returns true if it is possible to build such an input sequence
504 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
505 /// False otherwise.
506 ///
507 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
508 ///
509 /// \note The generic implementation does not provide any support for
510 /// MI.isExtractSubregLike(). In other words, one has to override
511 /// getExtractSubregLikeInputs for target specific instructions.
512 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
513 RegSubRegPairAndIdx &InputReg) const;
514
515 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
516 /// and \p DefIdx.
517 /// \p [out] BaseReg and \p [out] InsertedReg contain
518 /// the equivalent inputs of INSERT_SUBREG.
519 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
520 /// - BaseReg: %0:sub0
521 /// - InsertedReg: %1:sub1, sub3
522 ///
523 /// \returns true if it is possible to build such an input sequence
524 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
525 /// False otherwise.
526 ///
527 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
528 ///
529 /// \note The generic implementation does not provide any support for
530 /// MI.isInsertSubregLike(). In other words, one has to override
531 /// getInsertSubregLikeInputs for target specific instructions.
532 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
533 RegSubRegPair &BaseReg,
534 RegSubRegPairAndIdx &InsertedReg) const;
535
536 /// Return true if two machine instructions would produce identical values.
537 /// By default, this is only true when the two instructions
538 /// are deemed identical except for defs. If this function is called when the
539 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
540 /// aggressive checks.
541 virtual bool produceSameValue(const MachineInstr &MI0,
542 const MachineInstr &MI1,
543 const MachineRegisterInfo *MRI = nullptr) const;
544
545 /// \returns true if a branch from an instruction with opcode \p BranchOpc
546 /// bytes is capable of jumping to a position \p BrOffset bytes away.
547 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
548 int64_t BrOffset) const {
549 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 549)
;
550 }
551
552 /// \returns The block that branch instruction \p MI jumps to.
553 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
554 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 554)
;
555 }
556
557 /// Insert an unconditional indirect branch at the end of \p MBB to \p
558 /// NewDestBB. \p BrOffset indicates the offset of \p NewDestBB relative to
559 /// the offset of the position to insert the new branch.
560 ///
561 /// \returns The number of bytes added to the block.
562 virtual unsigned insertIndirectBranch(MachineBasicBlock &MBB,
563 MachineBasicBlock &NewDestBB,
564 const DebugLoc &DL,
565 int64_t BrOffset = 0,
566 RegScavenger *RS = nullptr) const {
567 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 567)
;
568 }
569
570 /// Analyze the branching code at the end of MBB, returning
571 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
572 /// implemented for a target). Upon success, this returns false and returns
573 /// with the following information in various cases:
574 ///
575 /// 1. If this block ends with no branches (it just falls through to its succ)
576 /// just return false, leaving TBB/FBB null.
577 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
578 /// the destination block.
579 /// 3. If this block ends with a conditional branch and it falls through to a
580 /// successor block, it sets TBB to be the branch destination block and a
581 /// list of operands that evaluate the condition. These operands can be
582 /// passed to other TargetInstrInfo methods to create new branches.
583 /// 4. If this block ends with a conditional branch followed by an
584 /// unconditional branch, it returns the 'true' destination in TBB, the
585 /// 'false' destination in FBB, and a list of operands that evaluate the
586 /// condition. These operands can be passed to other TargetInstrInfo
587 /// methods to create new branches.
588 ///
589 /// Note that removeBranch and insertBranch must be implemented to support
590 /// cases where this method returns success.
591 ///
592 /// If AllowModify is true, then this routine is allowed to modify the basic
593 /// block (e.g. delete instructions after the unconditional branch).
594 ///
595 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
596 /// before calling this function.
597 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
598 MachineBasicBlock *&FBB,
599 SmallVectorImpl<MachineOperand> &Cond,
600 bool AllowModify = false) const {
601 return true;
602 }
603
604 /// Represents a predicate at the MachineFunction level. The control flow a
605 /// MachineBranchPredicate represents is:
606 ///
607 /// Reg = LHS `Predicate` RHS == ConditionDef
608 /// if Reg then goto TrueDest else goto FalseDest
609 ///
610 struct MachineBranchPredicate {
611 enum ComparePredicate {
612 PRED_EQ, // True if two values are equal
613 PRED_NE, // True if two values are not equal
614 PRED_INVALID // Sentinel value
615 };
616
617 ComparePredicate Predicate = PRED_INVALID;
618 MachineOperand LHS = MachineOperand::CreateImm(0);
619 MachineOperand RHS = MachineOperand::CreateImm(0);
620 MachineBasicBlock *TrueDest = nullptr;
621 MachineBasicBlock *FalseDest = nullptr;
622 MachineInstr *ConditionDef = nullptr;
623
624 /// SingleUseCondition is true if ConditionDef is dead except for the
625 /// branch(es) at the end of the basic block.
626 ///
627 bool SingleUseCondition = false;
628
629 explicit MachineBranchPredicate() = default;
630 };
631
632 /// Analyze the branching code at the end of MBB and parse it into the
633 /// MachineBranchPredicate structure if possible. Returns false on success
634 /// and true on failure.
635 ///
636 /// If AllowModify is true, then this routine is allowed to modify the basic
637 /// block (e.g. delete instructions after the unconditional branch).
638 ///
639 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
640 MachineBranchPredicate &MBP,
641 bool AllowModify = false) const {
642 return true;
643 }
644
645 /// Remove the branching code at the end of the specific MBB.
646 /// This is only invoked in cases where AnalyzeBranch returns success. It
647 /// returns the number of instructions that were removed.
648 /// If \p BytesRemoved is non-null, report the change in code size from the
649 /// removed instructions.
650 virtual unsigned removeBranch(MachineBasicBlock &MBB,
651 int *BytesRemoved = nullptr) const {
652 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::removeBranch!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 652)
;
653 }
654
655 /// Insert branch code into the end of the specified MachineBasicBlock. The
656 /// operands to this method are the same as those returned by AnalyzeBranch.
657 /// This is only invoked in cases where AnalyzeBranch returns success. It
658 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
659 /// report the change in code size from the added instructions.
660 ///
661 /// It is also invoked by tail merging to add unconditional branches in
662 /// cases where AnalyzeBranch doesn't apply because there was no original
663 /// branch to analyze. At least this much must be implemented, else tail
664 /// merging needs to be disabled.
665 ///
666 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
667 /// before calling this function.
668 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
669 MachineBasicBlock *FBB,
670 ArrayRef<MachineOperand> Cond,
671 const DebugLoc &DL,
672 int *BytesAdded = nullptr) const {
673 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertBranch!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 673)
;
674 }
675
676 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
677 MachineBasicBlock *DestBB,
678 const DebugLoc &DL,
679 int *BytesAdded = nullptr) const {
680 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
681 BytesAdded);
682 }
683
684 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
685 /// implementations to query attributes of the loop being pipelined and to
686 /// apply target-specific updates to the loop once pipelining is complete.
687 class PipelinerLoopInfo {
688 public:
689 virtual ~PipelinerLoopInfo();
690 /// Return true if the given instruction should not be pipelined and should
691 /// be ignored. An example could be a loop comparison, or induction variable
692 /// update with no users being pipelined.
693 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
694
695 /// Create a condition to determine if the trip count of the loop is greater
696 /// than TC.
697 ///
698 /// If the trip count is statically known to be greater than TC, return
699 /// true. If the trip count is statically known to be not greater than TC,
700 /// return false. Otherwise return nullopt and fill out Cond with the test
701 /// condition.
702 virtual Optional<bool>
703 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
704 SmallVectorImpl<MachineOperand> &Cond) = 0;
705
706 /// Modify the loop such that the trip count is
707 /// OriginalTC + TripCountAdjust.
708 virtual void adjustTripCount(int TripCountAdjust) = 0;
709
710 /// Called when the loop's preheader has been modified to NewPreheader.
711 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
712
713 /// Called when the loop is being removed. Any instructions in the preheader
714 /// should be removed.
715 ///
716 /// Once this function is called, no other functions on this object are
717 /// valid; the loop has been removed.
718 virtual void disposed() = 0;
719 };
720
721 /// Analyze loop L, which must be a single-basic-block loop, and if the
722 /// conditions can be understood enough produce a PipelinerLoopInfo object.
723 virtual std::unique_ptr<PipelinerLoopInfo>
724 analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
725 return nullptr;
726 }
727
728 /// Analyze the loop code, return true if it cannot be understoo. Upon
729 /// success, this function returns false and returns information about the
730 /// induction variable and compare instruction used at the end.
731 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
732 MachineInstr *&CmpInst) const {
733 return true;
734 }
735
736 /// Generate code to reduce the loop iteration by one and check if the loop
737 /// is finished. Return the value/register of the new loop count. We need
738 /// this function when peeling off one or more iterations of a loop. This
739 /// function assumes the nth iteration is peeled first.
740 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
741 MachineBasicBlock &PreHeader,
742 MachineInstr *IndVar, MachineInstr &Cmp,
743 SmallVectorImpl<MachineOperand> &Cond,
744 SmallVectorImpl<MachineInstr *> &PrevInsts,
745 unsigned Iter, unsigned MaxIter) const {
746 llvm_unreachable("Target didn't implement ReduceLoopCount")::llvm::llvm_unreachable_internal("Target didn't implement ReduceLoopCount"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 746)
;
747 }
748
749 /// Delete the instruction OldInst and everything after it, replacing it with
750 /// an unconditional branch to NewDest. This is used by the tail merging pass.
751 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
752 MachineBasicBlock *NewDest) const;
753
754 /// Return true if it's legal to split the given basic
755 /// block at the specified instruction (i.e. instruction would be the start
756 /// of a new basic block).
757 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
758 MachineBasicBlock::iterator MBBI) const {
759 return true;
760 }
761
762 /// Return true if it's profitable to predicate
763 /// instructions with accumulated instruction latency of "NumCycles"
764 /// of the specified basic block, where the probability of the instructions
765 /// being executed is given by Probability, and Confidence is a measure
766 /// of our confidence that it will be properly predicted.
767 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
768 unsigned ExtraPredCycles,
769 BranchProbability Probability) const {
770 return