Bug Summary

File:llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 302, column 61
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-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/InlineSpiller.cpp

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

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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 ScheduleDAGMI;
56class ScheduleHazardRecognizer;
57class SDNode;
58class SelectionDAG;
59class RegScavenger;
60class TargetRegisterClass;
61class TargetRegisterInfo;
62class TargetSchedModel;
63class TargetSubtargetInfo;
64
65template <class T> class SmallVectorImpl;
66
67using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
68
69struct DestSourcePair {
70 const MachineOperand *Destination;
71 const MachineOperand *Source;
72
73 DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
74 : Destination(&Dest), Source(&Src) {}
75};
76
77/// Used to describe a register and immediate addition.
78struct RegImmPair {
79 Register Reg;
80 int64_t Imm;
81
82 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
83};
84
85//---------------------------------------------------------------------------
86///
87/// TargetInstrInfo - Interface to description of machine instruction set
88///
89class TargetInstrInfo : public MCInstrInfo {
90public:
91 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
92 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
93 : CallFrameSetupOpcode(CFSetupOpcode),
94 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
95 ReturnOpcode(ReturnOpcode) {}
96 TargetInstrInfo(const TargetInstrInfo &) = delete;
97 TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
98 virtual ~TargetInstrInfo();
99
100 static bool isGenericOpcode(unsigned Opc) {
101 return Opc <= TargetOpcode::GENERIC_OP_END;
102 }
103
104 /// Given a machine instruction descriptor, returns the register
105 /// class constraint for OpNum, or NULL.
106 virtual
107 const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
108 const TargetRegisterInfo *TRI,
109 const MachineFunction &MF) const;
110
111 /// Return true if the instruction is trivially rematerializable, meaning it
112 /// has no side effects and requires no operands that aren't always available.
113 /// This means the only allowed uses are constants and unallocatable physical
114 /// registers so that the instructions result is independent of the place
115 /// in the function.
116 bool isTriviallyReMaterializable(const MachineInstr &MI,
117 AAResults *AA = nullptr) const {
118 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
119 (MI.getDesc().isRematerializable() &&
120 (isReallyTriviallyReMaterializable(MI, AA) ||
121 isReallyTriviallyReMaterializableGeneric(MI, AA)));
122 }
123
124protected:
125 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
126 /// set, this hook lets the target specify whether the instruction is actually
127 /// trivially rematerializable, taking into consideration its operands. This
128 /// predicate must return false if the instruction has any side effects other
129 /// than producing a value, or if it requres any address registers that are
130 /// not always available.
131 /// Requirements must be check as stated in isTriviallyReMaterializable() .
132 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
133 AAResults *AA) const {
134 return false;
135 }
136
137 /// This method commutes the operands of the given machine instruction MI.
138 /// The operands to be commuted are specified by their indices OpIdx1 and
139 /// OpIdx2.
140 ///
141 /// If a target has any instructions that are commutable but require
142 /// converting to different instructions or making non-trivial changes
143 /// to commute them, this method can be overloaded to do that.
144 /// The default implementation simply swaps the commutable operands.
145 ///
146 /// If NewMI is false, MI is modified in place and returned; otherwise, a
147 /// new machine instruction is created and returned.
148 ///
149 /// Do not call this method for a non-commutable instruction.
150 /// Even though the instruction is commutable, the method may still
151 /// fail to commute the operands, null pointer is returned in such cases.
152 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
153 unsigned OpIdx1,
154 unsigned OpIdx2) const;
155
156 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
157 /// operand indices to (ResultIdx1, ResultIdx2).
158 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
159 /// predefined to some indices or be undefined (designated by the special
160 /// value 'CommuteAnyOperandIndex').
161 /// The predefined result indices cannot be re-defined.
162 /// The function returns true iff after the result pair redefinition
163 /// the fixed result pair is equal to or equivalent to the source pair of
164 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
165 /// the pairs (x,y) and (y,x) are equivalent.
166 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
167 unsigned CommutableOpIdx1,
168 unsigned CommutableOpIdx2);
169
170private:
171 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
172 /// set and the target hook isReallyTriviallyReMaterializable returns false,
173 /// this function does target-independent tests to determine if the
174 /// instruction is really trivially rematerializable.
175 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
176 AAResults *AA) const;
177
178public:
179 /// These methods return the opcode of the frame setup/destroy instructions
180 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
181 /// order to abstract away the difference between operating with a frame
182 /// pointer and operating without, through the use of these two instructions.
183 ///
184 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
185 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
186
187 /// Returns true if the argument is a frame pseudo instruction.
188 bool isFrameInstr(const MachineInstr &I) const {
189 return I.getOpcode() == getCallFrameSetupOpcode() ||
190 I.getOpcode() == getCallFrameDestroyOpcode();
191 }
192
193 /// Returns true if the argument is a frame setup pseudo instruction.
194 bool isFrameSetup(const MachineInstr &I) const {
195 return I.getOpcode() == getCallFrameSetupOpcode();
196 }
197
198 /// Returns size of the frame associated with the given frame instruction.
199 /// For frame setup instruction this is frame that is set up space set up
200 /// after the instruction. For frame destroy instruction this is the frame
201 /// freed by the caller.
202 /// Note, in some cases a call frame (or a part of it) may be prepared prior
203 /// to the frame setup instruction. It occurs in the calls that involve
204 /// inalloca arguments. This function reports only the size of the frame part
205 /// that is set up between the frame setup and destroy pseudo instructions.
206 int64_t getFrameSize(const MachineInstr &I) const {
207 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 207, __PRETTY_FUNCTION__))
;
208 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 208, __PRETTY_FUNCTION__))
;
209 return I.getOperand(0).getImm();
210 }
211
212 /// Returns the total frame size, which is made up of the space set up inside
213 /// the pair of frame start-stop instructions and the space that is set up
214 /// prior to the pair.
215 int64_t getFrameTotalSize(const MachineInstr &I) const {
216 if (isFrameSetup(I)) {
217 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 218, __PRETTY_FUNCTION__))
218 "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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 218, __PRETTY_FUNCTION__))
;
219 return getFrameSize(I) + I.getOperand(1).getImm();
220 }
221 return getFrameSize(I);
222 }
223
224 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
225 unsigned getReturnOpcode() const { return ReturnOpcode; }
226
227 /// Returns the actual stack pointer adjustment made by an instruction
228 /// as part of a call sequence. By default, only call frame setup/destroy
229 /// instructions adjust the stack, but targets may want to override this
230 /// to enable more fine-grained adjustment, or adjust by a different value.
231 virtual int getSPAdjust(const MachineInstr &MI) const;
232
233 /// Return true if the instruction is a "coalescable" extension instruction.
234 /// That is, it's like a copy where it's legal for the source to overlap the
235 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
236 /// expected the pre-extension value is available as a subreg of the result
237 /// register. This also returns the sub-register index in SubIdx.
238 virtual bool isCoalescableExtInstr(const MachineInstr &MI, unsigned &SrcReg,
239 unsigned &DstReg, unsigned &SubIdx) const {
240 return false;
241 }
242
243 /// If the specified machine instruction is a direct
244 /// load from a stack slot, return the virtual or physical register number of
245 /// the destination along with the FrameIndex of the loaded stack slot. If
246 /// not, return 0. This predicate must return 0 if the instruction has
247 /// any side effects other than loading from the stack slot.
248 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
249 int &FrameIndex) const {
250 return 0;
15
Returning without writing to 'FrameIndex'
251 }
252
253 /// Optional extension of isLoadFromStackSlot that returns the number of
254 /// bytes loaded from the stack. This must be implemented if a backend
255 /// supports partial stack slot spills/loads to further disambiguate
256 /// what the load does.
257 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
258 int &FrameIndex,
259 unsigned &MemBytes) const {
260 MemBytes = 0;
261 return isLoadFromStackSlot(MI, FrameIndex);
262 }
263
264 /// Check for post-frame ptr elimination stack locations as well.
265 /// This uses a heuristic so it isn't reliable for correctness.
266 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
267 int &FrameIndex) const {
268 return 0;
269 }
270
271 /// If the specified machine instruction has a load from a stack slot,
272 /// return true along with the FrameIndices of the loaded stack slot and the
273 /// machine mem operands containing the reference.
274 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
275 /// any instructions that loads from the stack. This is just a hint, as some
276 /// cases may be missed.
277 virtual bool hasLoadFromStackSlot(
278 const MachineInstr &MI,
279 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
280
281 /// If the specified machine instruction is a direct
282 /// store to a stack slot, return the virtual or physical register number of
283 /// the source reg along with the FrameIndex of the loaded stack slot. If
284 /// not, return 0. This predicate must return 0 if the instruction has
285 /// any side effects other than storing to the stack slot.
286 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
287 int &FrameIndex) const {
288 return 0;
289 }
290
291 /// Optional extension of isStoreToStackSlot that returns the number of
292 /// bytes stored to the stack. This must be implemented if a backend
293 /// supports partial stack slot spills/loads to further disambiguate
294 /// what the store does.
295 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
296 int &FrameIndex,
297 unsigned &MemBytes) const {
298 MemBytes = 0;
299 return isStoreToStackSlot(MI, FrameIndex);
300 }
301
302 /// Check for post-frame ptr elimination stack locations as well.
303 /// This uses a heuristic, so it isn't reliable for correctness.
304 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
305 int &FrameIndex) const {
306 return 0;
307 }
308
309 /// If the specified machine instruction has a store to a stack slot,
310 /// return true along with the FrameIndices of the loaded stack slot and the
311 /// machine mem operands containing the reference.
312 /// If not, return false. Unlike isStoreToStackSlot,
313 /// this returns true for any instructions that stores to the
314 /// stack. This is just a hint, as some cases may be missed.
315 virtual bool hasStoreToStackSlot(
316 const MachineInstr &MI,
317 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
318
319 /// Return true if the specified machine instruction
320 /// is a copy of one stack slot to another and has no other effect.
321 /// Provide the identity of the two frame indices.
322 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
323 int &SrcFrameIndex) const {
324 return false;
325 }
326
327 /// Compute the size in bytes and offset within a stack slot of a spilled
328 /// register or subregister.
329 ///
330 /// \param [out] Size in bytes of the spilled value.
331 /// \param [out] Offset in bytes within the stack slot.
332 /// \returns true if both Size and Offset are successfully computed.
333 ///
334 /// Not all subregisters have computable spill slots. For example,
335 /// subregisters registers may not be byte-sized, and a pair of discontiguous
336 /// subregisters has no single offset.
337 ///
338 /// Targets with nontrivial bigendian implementations may need to override
339 /// this, particularly to support spilled vector registers.
340 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
341 unsigned &Size, unsigned &Offset,
342 const MachineFunction &MF) const;
343
344 /// Returns the size in bytes of the specified MachineInstr, or ~0U
345 /// when this function is not implemented by a target.
346 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
347 return ~0U;
348 }
349
350 /// Return true if the instruction is as cheap as a move instruction.
351 ///
352 /// Targets for different archs need to override this, and different
353 /// micro-architectures can also be finely tuned inside.
354 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
355 return MI.isAsCheapAsAMove();
356 }
357
358 /// Return true if the instruction should be sunk by MachineSink.
359 ///
360 /// MachineSink determines on its own whether the instruction is safe to sink;
361 /// this gives the target a hook to override the default behavior with regards
362 /// to which instructions should be sunk.
363 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
364
365 /// Re-issue the specified 'original' instruction at the
366 /// specific location targeting a new destination register.
367 /// The register in Orig->getOperand(0).getReg() will be substituted by
368 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
369 /// SubIdx.
370 virtual void reMaterialize(MachineBasicBlock &MBB,
371 MachineBasicBlock::iterator MI, unsigned DestReg,
372 unsigned SubIdx, const MachineInstr &Orig,
373 const TargetRegisterInfo &TRI) const;
374
375 /// Clones instruction or the whole instruction bundle \p Orig and
376 /// insert into \p MBB before \p InsertBefore. The target may update operands
377 /// that are required to be unique.
378 ///
379 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
380 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
381 MachineBasicBlock::iterator InsertBefore,
382 const MachineInstr &Orig) const;
383
384 /// This method must be implemented by targets that
385 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
386 /// may be able to convert a two-address instruction into one or more true
387 /// three-address instructions on demand. This allows the X86 target (for
388 /// example) to convert ADD and SHL instructions into LEA instructions if they
389 /// would require register copies due to two-addressness.
390 ///
391 /// This method returns a null pointer if the transformation cannot be
392 /// performed, otherwise it returns the last new instruction.
393 ///
394 virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
395 MachineInstr &MI,
396 LiveVariables *LV) const {
397 return nullptr;
398 }
399
400 // This constant can be used as an input value of operand index passed to
401 // the method findCommutedOpIndices() to tell the method that the
402 // corresponding operand index is not pre-defined and that the method
403 // can pick any commutable operand.
404 static const unsigned CommuteAnyOperandIndex = ~0U;
405
406 /// This method commutes the operands of the given machine instruction MI.
407 ///
408 /// The operands to be commuted are specified by their indices OpIdx1 and
409 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
410 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
411 /// any arbitrarily chosen commutable operand. If both arguments are set to
412 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
413 /// operands; then commutes them if such operands could be found.
414 ///
415 /// If NewMI is false, MI is modified in place and returned; otherwise, a
416 /// new machine instruction is created and returned.
417 ///
418 /// Do not call this method for a non-commutable instruction or
419 /// for non-commuable operands.
420 /// Even though the instruction is commutable, the method may still
421 /// fail to commute the operands, null pointer is returned in such cases.
422 MachineInstr *
423 commuteInstruction(MachineInstr &MI, bool NewMI = false,
424 unsigned OpIdx1 = CommuteAnyOperandIndex,
425 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
426
427 /// Returns true iff the routine could find two commutable operands in the
428 /// given machine instruction.
429 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
430 /// If any of the INPUT values is set to the special value
431 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
432 /// operand, then returns its index in the corresponding argument.
433 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
434 /// looks for 2 commutable operands.
435 /// If INPUT values refer to some operands of MI, then the method simply
436 /// returns true if the corresponding operands are commutable and returns
437 /// false otherwise.
438 ///
439 /// For example, calling this method this way:
440 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
441 /// findCommutedOpIndices(MI, Op1, Op2);
442 /// can be interpreted as a query asking to find an operand that would be
443 /// commutable with the operand#1.
444 virtual bool findCommutedOpIndices(const MachineInstr &MI,
445 unsigned &SrcOpIdx1,
446 unsigned &SrcOpIdx2) const;
447
448 /// A pair composed of a register and a sub-register index.
449 /// Used to give some type checking when modeling Reg:SubReg.
450 struct RegSubRegPair {
451 unsigned Reg;
452 unsigned SubReg;
453
454 RegSubRegPair(unsigned Reg = 0, unsigned SubReg = 0)
455 : Reg(Reg), SubReg(SubReg) {}
456
457 bool operator==(const RegSubRegPair& P) const {
458 return Reg == P.Reg && SubReg == P.SubReg;
459 }
460 bool operator!=(const RegSubRegPair& P) const {
461 return !(*this == P);
462 }
463 };
464
465 /// A pair composed of a pair of a register and a sub-register index,
466 /// and another sub-register index.
467 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
468 struct RegSubRegPairAndIdx : RegSubRegPair {
469 unsigned SubIdx;
470
471 RegSubRegPairAndIdx(unsigned Reg = 0, unsigned SubReg = 0,
472 unsigned SubIdx = 0)
473 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
474 };
475
476 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
477 /// and \p DefIdx.
478 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
479 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
480 /// flag are not added to this list.
481 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
482 /// two elements:
483 /// - %1:sub1, sub0
484 /// - %2<:0>, sub1
485 ///
486 /// \returns true if it is possible to build such an input sequence
487 /// with the pair \p MI, \p DefIdx. False otherwise.
488 ///
489 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
490 ///
491 /// \note The generic implementation does not provide any support for
492 /// MI.isRegSequenceLike(). In other words, one has to override
493 /// getRegSequenceLikeInputs for target specific instructions.
494 bool
495 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
496 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
497
498 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
499 /// and \p DefIdx.
500 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
501 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
502 /// - %1:sub1, sub0
503 ///
504 /// \returns true if it is possible to build such an input sequence
505 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
506 /// False otherwise.
507 ///
508 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
509 ///
510 /// \note The generic implementation does not provide any support for
511 /// MI.isExtractSubregLike(). In other words, one has to override
512 /// getExtractSubregLikeInputs for target specific instructions.
513 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
514 RegSubRegPairAndIdx &InputReg) const;
515
516 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
517 /// and \p DefIdx.
518 /// \p [out] BaseReg and \p [out] InsertedReg contain
519 /// the equivalent inputs of INSERT_SUBREG.
520 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
521 /// - BaseReg: %0:sub0
522 /// - InsertedReg: %1:sub1, sub3
523 ///
524 /// \returns true if it is possible to build such an input sequence
525 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
526 /// False otherwise.
527 ///
528 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
529 ///
530 /// \note The generic implementation does not provide any support for
531 /// MI.isInsertSubregLike(). In other words, one has to override
532 /// getInsertSubregLikeInputs for target specific instructions.
533 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
534 RegSubRegPair &BaseReg,
535 RegSubRegPairAndIdx &InsertedReg) const;
536
537 /// Return true if two machine instructions would produce identical values.
538 /// By default, this is only true when the two instructions
539 /// are deemed identical except for defs. If this function is called when the
540 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
541 /// aggressive checks.
542 virtual bool produceSameValue(const MachineInstr &MI0,
543 const MachineInstr &MI1,
544 const MachineRegisterInfo *MRI = nullptr) const;
545
546 /// \returns true if a branch from an instruction with opcode \p BranchOpc
547 /// bytes is capable of jumping to a position \p BrOffset bytes away.
548 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
549 int64_t BrOffset) const {
550 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 550)
;
551 }
552
553 /// \returns The block that branch instruction \p MI jumps to.
554 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
555 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 555)
;
556 }
557
558 /// Insert an unconditional indirect branch at the end of \p MBB to \p
559 /// NewDestBB. \p BrOffset indicates the offset of \p NewDestBB relative to
560 /// the offset of the position to insert the new branch.
561 ///
562 /// \returns The number of bytes added to the block.
563 virtual unsigned insertIndirectBranch(MachineBasicBlock &MBB,
564 MachineBasicBlock &NewDestBB,
565 const DebugLoc &DL,
566 int64_t BrOffset = 0,
567 RegScavenger *RS = nullptr) const {
568 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 568)
;
569 }
570
571 /// Analyze the branching code at the end of MBB, returning
572 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
573 /// implemented for a target). Upon success, this returns false and returns
574 /// with the following information in various cases:
575 ///
576 /// 1. If this block ends with no branches (it just falls through to its succ)
577 /// just return false, leaving TBB/FBB null.
578 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
579 /// the destination block.
580 /// 3. If this block ends with a conditional branch and it falls through to a
581 /// successor block, it sets TBB to be the branch destination block and a
582 /// list of operands that evaluate the condition. These operands can be
583 /// passed to other TargetInstrInfo methods to create new branches.
584 /// 4. If this block ends with a conditional branch followed by an
585 /// unconditional branch, it returns the 'true' destination in TBB, the
586 /// 'false' destination in FBB, and a list of operands that evaluate the
587 /// condition. These operands can be passed to other TargetInstrInfo
588 /// methods to create new branches.
589 ///
590 /// Note that removeBranch and insertBranch must be implemented to support
591 /// cases where this method returns success.
592 ///
593 /// If AllowModify is true, then this routine is allowed to modify the basic
594 /// block (e.g. delete instructions after the unconditional branch).
595 ///
596 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
597 /// before calling this function.
598 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
599 MachineBasicBlock *&FBB,
600 SmallVectorImpl<MachineOperand> &Cond,
601 bool AllowModify = false) const {
602 return true;
603 }
604
605 /// Represents a predicate at the MachineFunction level. The control flow a
606 /// MachineBranchPredicate represents is:
607 ///
608 /// Reg = LHS `Predicate` RHS == ConditionDef
609 /// if Reg then goto TrueDest else goto FalseDest
610 ///
611 struct MachineBranchPredicate {
612 enum ComparePredicate {
613 PRED_EQ, // True if two values are equal
614 PRED_NE, // True if two values are not equal
615 PRED_INVALID // Sentinel value
616 };
617
618 ComparePredicate Predicate = PRED_INVALID;
619 MachineOperand LHS = MachineOperand::CreateImm(0);
620 MachineOperand RHS = MachineOperand::CreateImm(0);
621 MachineBasicBlock *TrueDest = nullptr;
622 MachineBasicBlock *FalseDest = nullptr;
623 MachineInstr *ConditionDef = nullptr;
624
625 /// SingleUseCondition is true if ConditionDef is dead except for the
626 /// branch(es) at the end of the basic block.
627 ///
628 bool SingleUseCondition = false;
629
630 explicit MachineBranchPredicate() = default;
631 };
632
633 /// Analyze the branching code at the end of MBB and parse it into the
634 /// MachineBranchPredicate structure if possible. Returns false on success
635 /// and true on failure.
636 ///
637 /// If AllowModify is true, then this routine is allowed to modify the basic
638 /// block (e.g. delete instructions after the unconditional branch).
639 ///
640 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
641 MachineBranchPredicate &MBP,
642 bool AllowModify = false) const {
643 return true;
644 }
645
646 /// Remove the branching code at the end of the specific MBB.
647 /// This is only invoked in cases where analyzeBranch returns success. It
648 /// returns the number of instructions that were removed.
649 /// If \p BytesRemoved is non-null, report the change in code size from the
650 /// removed instructions.
651 virtual unsigned removeBranch(MachineBasicBlock &MBB,
652 int *BytesRemoved = nullptr) const {
653 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::removeBranch!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 653)
;
654 }
655
656 /// Insert branch code into the end of the specified MachineBasicBlock. The
657 /// operands to this method are the same as those returned by analyzeBranch.
658 /// This is only invoked in cases where analyzeBranch returns success. It
659 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
660 /// report the change in code size from the added instructions.
661 ///
662 /// It is also invoked by tail merging to add unconditional branches in
663 /// cases where analyzeBranch doesn't apply because there was no original
664 /// branch to analyze. At least this much must be implemented, else tail
665 /// merging needs to be disabled.
666 ///
667 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
668 /// before calling this function.
669 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
670 MachineBasicBlock *FBB,
671 ArrayRef<MachineOperand> Cond,
672 const DebugLoc &DL,
673 int *BytesAdded = nullptr) const {
674 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertBranch!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 674)
;
675 }
676
677 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
678 MachineBasicBlock *DestBB,
679 const DebugLoc &DL,
680 int *BytesAdded = nullptr) const {
681 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
682 BytesAdded);
683 }
684
685 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
686 /// implementations to query attributes of the loop being pipelined and to
687 /// apply target-specific updates to the loop once pipelining is complete.
688 class PipelinerLoopInfo {
689 public:
690 virtual ~PipelinerLoopInfo();
691 /// Return true if the given instruction should not be pipelined and should
692 /// be ignored. An example could be a loop comparison, or induction variable
693 /// update with no users being pipelined.
694 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
695
696 /// Create a condition to determine if the trip count of the loop is greater
697 /// than TC.
698 ///
699 /// If the trip count is statically known to be greater than TC, return
700 /// true. If the trip count is statically known to be not greater than TC,
701 /// return false. Otherwise return nullopt and fill out Cond with the test
702 /// condition.
703 virtual Optional<bool>
704 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
705 SmallVectorImpl<MachineOperand> &Cond) = 0;
706
707 /// Modify the loop such that the trip count is
708 /// OriginalTC + TripCountAdjust.
709 virtual void adjustTripCount(int TripCountAdjust) = 0;
710
711 /// Called when the loop's preheader has been modified to NewPreheader.
712 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
713
714 /// Called when the loop is being removed. Any instructions in the preheader
715 /// should be removed.
716 ///
717 /// Once this function is called, no other functions on this object are
718 /// valid; the loop has been removed.
719 virtual void disposed() = 0;
720 };
721
722 /// Analyze loop L, which must be a single-basic-block loop, and if the
723 /// conditions can be understood enough produce a PipelinerLoopInfo object.
724 virtual std::unique_ptr<PipelinerLoopInfo>
725 analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
726 return nullptr;
727 }
728
729 /// Analyze the loop code, return true if it cannot be understoo. Upon
730 /// success, this function returns false and returns information about the
731 /// induction variable and compare instruction used at the end.
732 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
733 MachineInstr *&CmpInst) const {
734 return true;
735 }
736
737 /// Generate code to reduce the loop iteration by one and check if the loop
738 /// is finished. Return the value/register of the new loop count. We need
739 /// this function when peeling off one or more iterations of a loop. This
740 /// function assumes the nth iteration is peeled first.
741 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
742 MachineBasicBlock &PreHeader,
743 MachineInstr *IndVar, MachineInstr &Cmp,
744 SmallVectorImpl<MachineOperand> &Cond,
745 SmallVectorImpl<MachineInstr *> &PrevInsts,
746 unsigned Iter, unsigned MaxIter) const {
747 llvm_unreachable("Target didn't implement ReduceLoopCount")::llvm::llvm_unreachable_internal("Target didn't implement ReduceLoopCount"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 747)
;
748 }
749
750 /// Delete the instruction OldInst and everything after it, replacing it with
751 /// an unconditional branch to NewDest. This is used by the tail merging pass.
752 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
753 MachineBasicBlock *NewDest) const;
754
755 /// Return true if it's legal to split the given basic
756 /// block at the specified instruction (i.e. instruction would be the start
757 /// of a new basic block).
758 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
759 MachineBasicBlock::iterator MBBI) const {
760 return true;
761 }
762
763 /// Return true if it's profitable to predicate
764 /// instructions with accumulated instruction latency of "NumCycles"
765 /// of the specified basic block, where the probability of the instructions
766 /// being executed is given by Probability, and Confidence is a measure
767 /// of our confidence that it will be properly predicted.
768 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
769 unsigned ExtraPredCycles,
770 BranchProbability Probability) const {
771 return false;
772 }
773
774 /// Second variant of isProfitableToIfCvt. This one
775 /// checks for the case where two basic blocks from true and false path
776 /// of a if-then-else (diamond) are predicated on mutally exclusive
777 /// predicates, where the probability of the true path being taken is given
778 /// by Probability, and Confidence is a measure of our confidence that it
779 /// will be properly predicted.
780 virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
781 unsigned ExtraTCycles,
782 MachineBasicBlock &FMBB, unsigned NumFCycles,
783 unsigned ExtraFCycles,
784 BranchProbability Probability) const {
785 return false;
786 }
787
788 /// Return true if it's profitable for if-converter to duplicate instructions
789 /// of specified accumulated instruction latencies in the specified MBB to
790 /// enable if-conversion.
791 /// The probability of the instructions being executed is given by
792 /// Probability, and Confidence is a measure of our confidence that it
793 /// will be properly predicted.
794 virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
795 unsigned NumCycles,
796 BranchProbability Probability) const {
797 return false;
798 }
799
800 /// Return the increase in code size needed to predicate a contiguous run of
801 /// NumInsts instructions.
802 virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF,
803 unsigned NumInsts) const {
804 return 0;
805 }
806
807 /// Return an estimate for the code size reduction (in bytes) which will be
808 /// caused by removing the given branch instruction during if-conversion.
809 virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
810 return getInstSizeInBytes(MI);
811 }
812
813 /// Return true if it's profitable to unpredicate
814 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
815 /// exclusive predicates.
816 /// e.g.
817 /// subeq r0, r1, #1
818 /// addne r0, r1, #1
819 /// =>
820 /// sub r0, r1, #1
821 /// addne r0, r1, #1
822 ///
823 /// This may be profitable is conditional instructions are always executed.
824 virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
825 MachineBasicBlock &FMBB) const {
826 return false;
827 }
828
829 /// Return true if it is possible to insert a select
830 /// instruction that chooses between TrueReg and FalseReg based on the
831 /// condition code in Cond.
832 ///
833 /// When successful, also return the latency in cycles from TrueReg,
834 /// FalseReg, and Cond to the destination register. In most cases, a select
835 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
836 ///
837 /// Some x86 implementations have 2-cycle cmov instructions.
838 ///
839 /// @param MBB Block where select instruction would be inserted.
840 /// @param Cond Condition returned by analyzeBranch.
841 /// @param DstReg Virtual dest register that the result should write to.
842 /// @param TrueReg Virtual register to select when Cond is true.
843 /// @param FalseReg Virtual register to select when Cond is false.
844 /// @param CondCycles Latency from Cond+Branch to select output.
845 /// @param TrueCycles Latency from TrueReg to select output.
846 /// @param FalseCycles Latency from FalseReg to select output.
847 virtual bool canInsertSelect(const MachineBasicBlock &MBB,
848 ArrayRef<MachineOperand> Cond, unsigned DstReg,
849 unsigned TrueReg, unsigned FalseReg,
850 int &CondCycles, int &TrueCycles,
851 int &FalseCycles) const {
852 return false;
853 }
854
855 /// Insert a select instruction into MBB before I that will copy TrueReg to
856 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
857 ///
858 /// This function can only be called after canInsertSelect() returned true.
859 /// The condition in Cond comes from analyzeBranch, and it can be assumed
860 /// that the same flags or registers required by Cond are available at the
861 /// insertion point.
862 ///
863 /// @param MBB Block where select instruction should be inserted.
864 /// @param I Insertion point.
865 /// @param DL Source location for debugging.
866 /// @param DstReg Virtual register to be defined by select instruction.
867 /// @param Cond Condition as computed by analyzeBranch.
868 /// @param TrueReg Virtual register to copy when Cond is true.
869 /// @param FalseReg Virtual register to copy when Cons is false.
870 virtual void insertSelect(MachineBasicBlock &MBB,
871 MachineBasicBlock::iterator I, const DebugLoc &DL,
872 unsigned DstReg, ArrayRef<MachineOperand> Cond,
873 unsigned TrueReg, unsigned FalseReg) const {
874 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertSelect!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 874)
;
875 }
876
877 /// Analyze the given select instruction, returning true if
878 /// it cannot be understood. It is assumed that MI->isSelect() is true.
879 ///
880 /// When successful, return the controlling condition and the operands that
881 /// determine the true and false result values.
882 ///
883 /// Result = SELECT Cond, TrueOp, FalseOp
884 ///
885 /// Some targets can optimize select instructions, for example by predicating
886 /// the instruction defining one of the operands. Such targets should set
887 /// Optimizable.
888 ///
889 /// @param MI Select instruction to analyze.
890 /// @param Cond Condition controlling the select.
891 /// @param TrueOp Operand number of the value selected when Cond is true.
892 /// @param FalseOp Operand number of the value selected when Cond is false.
893 /// @param Optimizable Returned as true if MI is optimizable.
894 /// @returns False on success.
895 virtual bool analyzeSelect(const MachineInstr &MI,
896 SmallVectorImpl<MachineOperand> &Cond,
897 unsigned &TrueOp, unsigned &FalseOp,
898 bool &Optimizable) const {
899 assert(MI.getDesc().isSelect() && "MI must be a select instruction")((MI.getDesc().isSelect() && "MI must be a select instruction"
) ? static_cast<void> (0) : __assert_fail ("MI.getDesc().isSelect() && \"MI must be a select instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 899, __PRETTY_FUNCTION__))
;
900 return true;
901 }
902
903 /// Given a select instruction that was understood by
904 /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
905 /// merging it with one of its operands. Returns NULL on failure.
906 ///
907 /// When successful, returns the new select instruction. The client is
908 /// responsible for deleting MI.
909 ///
910 /// If both sides of the select can be optimized, PreferFalse is used to pick
911 /// a side.
912 ///
913 /// @param MI Optimizable select instruction.
914 /// @param NewMIs Set that record all MIs in the basic block up to \p
915 /// MI. Has to be updated with any newly created MI or deleted ones.
916 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
917 /// @returns Optimized instruction or NULL.
918 virtual MachineInstr *optimizeSelect(MachineInstr &MI,
919 SmallPtrSetImpl<MachineInstr *> &NewMIs,
920 bool PreferFalse = false) const {
921 // This function must be implemented if Optimizable is ever set.
922 llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!")::llvm::llvm_unreachable_internal("Target must implement TargetInstrInfo::optimizeSelect!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 922)
;
923 }
924
925 /// Emit instructions to copy a pair of physical registers.
926 ///
927 /// This function should support copies within any legal register class as
928 /// well as any cross-class copies created during instruction selection.
929 ///
930 /// The source and destination registers may overlap, which may require a
931 /// careful implementation when multiple copy instructions are required for
932 /// large registers. See for example the ARM target.
933 virtual void copyPhysReg(MachineBasicBlock &MBB,
934 MachineBasicBlock::iterator MI, const DebugLoc &DL,
935 MCRegister DestReg, MCRegister SrcReg,
936 bool KillSrc) const {
937 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::copyPhysReg!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 937)
;
938 }
939
940protected:
941 /// Target-dependent implementation for IsCopyInstr.
942 /// If the specific machine instruction is a instruction that moves/copies
943 /// value from one register to another register return destination and source
944 /// registers as machine operands.
945 virtual Optional<DestSourcePair>
946 isCopyInstrImpl(const MachineInstr &MI) const {
947 return None;
948 }
949
950public:
951 /// If the specific machine instruction is a instruction that moves/copies
952 /// value from one register to another register return destination and source
953 /// registers as machine operands.
954 /// For COPY-instruction the method naturally returns destination and source
955 /// registers as machine operands, for all other instructions the method calls
956 /// target-dependent implementation.
957 Optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
958 if (MI.isCopy()) {
959 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
960 }
961 return isCopyInstrImpl(MI);
962 }
963
964 /// If the specific machine instruction is an instruction that adds an
965 /// immediate value and a physical register, and stores the result in
966 /// the given physical register \c Reg, return a pair of the source
967 /// register and the offset which has been added.
968 virtual Optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
969 Register Reg) const {
970 return None;
971 }
972
973 /// Store the specified register of the given register class to the specified
974 /// stack frame index. The store instruction is to be added to the given
975 /// machine basic block before the specified machine instruction. If isKill
976 /// is true, the register operand is the last use and must be marked kill.
977 virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
978 MachineBasicBlock::iterator MI,
979 Register SrcReg, bool isKill, int FrameIndex,
980 const TargetRegisterClass *RC,
981 const TargetRegisterInfo *TRI) const {
982 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::storeRegToStackSlot!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 983)
983 "TargetInstrInfo::storeRegToStackSlot!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::storeRegToStackSlot!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 983)
;
984 }
985
986 /// Load the specified register of the given register class from the specified
987 /// stack frame index. The load instruction is to be added to the given
988 /// machine basic block before the specified machine instruction.
989 virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
990 MachineBasicBlock::iterator MI,
991 Register DestReg, int FrameIndex,
992 const TargetRegisterClass *RC,
993 const TargetRegisterInfo *TRI) const {
994 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::loadRegFromStackSlot!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 995)
995 "TargetInstrInfo::loadRegFromStackSlot!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::loadRegFromStackSlot!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 995)
;
996 }
997
998 /// This function is called for all pseudo instructions
999 /// that remain after register allocation. Many pseudo instructions are
1000 /// created to help register allocation. This is the place to convert them
1001 /// into real instructions. The target can edit MI in place, or it can insert
1002 /// new instructions and erase MI. The function should return true if
1003 /// anything was changed.
1004 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
1005
1006 /// Check whether the target can fold a load that feeds a subreg operand
1007 /// (or a subreg operand that feeds a store).
1008 /// For example, X86 may want to return true if it can fold
1009 /// movl (%esp), %eax
1010 /// subb, %al, ...
1011 /// Into:
1012 /// subb (%esp), ...
1013 ///
1014 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
1015 /// reject subregs - but since this behavior used to be enforced in the
1016 /// target-independent code, moving this responsibility to the targets
1017 /// has the potential of causing nasty silent breakage in out-of-tree targets.
1018 virtual bool isSubregFoldable() const { return false; }
1019
1020 /// Attempt to fold a load or store of the specified stack
1021 /// slot into the specified machine instruction for the specified operand(s).
1022 /// If this is possible, a new instruction is returned with the specified
1023 /// operand folded, otherwise NULL is returned.
1024 /// The new instruction is inserted before MI, and the client is responsible
1025 /// for removing the old instruction.
1026 /// If VRM is passed, the assigned physregs can be inspected by target to
1027 /// decide on using an opcode (note that those assignments can still change).
1028 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1029 int FI,
1030 LiveIntervals *LIS = nullptr,
1031 VirtRegMap *VRM = nullptr) const;
1032
1033 /// Same as the previous version except it allows folding of any load and
1034 /// store from / to any address, not just from a specific stack slot.
1035 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1036 MachineInstr &LoadMI,
1037 LiveIntervals *LIS = nullptr) const;
1038
1039 /// Return true when there is potentially a faster code sequence
1040 /// for an instruction chain ending in \p Root. All potential patterns are
1041 /// returned in the \p Pattern vector. Pattern should be sorted in priority
1042 /// order since the pattern evaluator stops checking as soon as it finds a
1043 /// faster sequence.
1044 /// \param Root - Instruction that could be combined with one of its operands
1045 /// \param Patterns - Vector of possible combination patterns
1046 virtual bool getMachineCombinerPatterns(
1047 MachineInstr &Root,
1048 SmallVectorImpl<MachineCombinerPattern> &Patterns) const;
1049
1050 /// Return true when a code sequence can improve throughput. It
1051 /// should be called only for instructions in loops.
1052 /// \param Pattern - combiner pattern
1053 virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
1054
1055 /// Return true if the input \P Inst is part of a chain of dependent ops
1056 /// that are suitable for reassociation, otherwise return false.
1057 /// If the instruction's operands must be commuted to have a previous
1058 /// instruction of the same type define the first source operand, \P Commuted
1059 /// will be set to true.
1060 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
1061
1062 /// Return true when \P Inst is both associative and commutative.
1063 virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
1064 return false;
1065 }
1066
1067 /// Return true when \P Inst has reassociable operands in the same \P MBB.
1068 virtual bool hasReassociableOperands(const MachineInstr &Inst,
1069 const MachineBasicBlock *MBB) const;
1070
1071 /// Return true when \P Inst has reassociable sibling.
1072 bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
1073
1074 /// When getMachineCombinerPatterns() finds patterns, this function generates
1075 /// the instructions that could replace the original code sequence. The client
1076 /// has to decide whether the actual replacement is beneficial or not.
1077 /// \param Root - Instruction that could be combined with one of its operands
1078 /// \param Pattern - Combination pattern for Root
1079 /// \param InsInstrs - Vector of new instructions that implement P
1080 /// \param DelInstrs - Old instructions, including Root, that could be
1081 /// replaced by InsInstr
1082 /// \param InstIdxForVirtReg - map of virtual register to instruction in
1083 /// InsInstr that defines it
1084 virtual void genAlternativeCodeSequence(
1085 MachineInstr &Root, MachineCombinerPattern Pattern,
1086 SmallVectorImpl<MachineInstr *> &InsInstrs,
1087 SmallVectorImpl<MachineInstr *> &DelInstrs,
1088 DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const;
1089
1090 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
1091 /// reduce critical path length.
1092 void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
1093 MachineCombinerPattern Pattern,
1094 SmallVectorImpl<MachineInstr *> &InsInstrs,
1095 SmallVectorImpl<MachineInstr *> &DelInstrs,
1096 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
1097
1098 /// This is an architecture-specific helper function of reassociateOps.
1099 /// Set special operand attributes for new instructions after reassociation.
1100 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
1101 MachineInstr &NewMI1,
1102 MachineInstr &NewMI2) const {}
1103
1104 /// Return true when a target supports MachineCombiner.
1105 virtual bool useMachineCombiner() const { return false; }
1106
1107 /// Return true if the given SDNode can be copied during scheduling
1108 /// even if it has glue.
1109 virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
1110
1111protected:
1112 /// Target-dependent implementation for foldMemoryOperand.
1113 /// Target-independent code in foldMemoryOperand will
1114 /// take care of adding a MachineMemOperand to the newly created instruction.
1115 /// The instruction and any auxiliary instructions necessary will be inserted
1116 /// at InsertPt.
1117 virtual MachineInstr *
1118 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
1119 ArrayRef<unsigned> Ops,
1120 MachineBasicBlock::iterator InsertPt, int FrameIndex,
1121 LiveIntervals *LIS = nullptr,
1122 VirtRegMap *VRM = nullptr) const {
1123 return nullptr;
1124 }
1125
1126 /// Target-dependent implementation for foldMemoryOperand.
1127 /// Target-independent code in foldMemoryOperand will
1128 /// take care of adding a MachineMemOperand to the newly created instruction.
1129 /// The instruction and any auxiliary instructions necessary will be inserted
1130 /// at InsertPt.
1131 virtual MachineInstr *foldMemoryOperandImpl(
1132 MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
1133 MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
1134 LiveIntervals *LIS = nullptr) const {
1135 return nullptr;
1136 }
1137
1138 /// Target-dependent implementation of getRegSequenceInputs.
1139 ///
1140 /// \returns true if it is possible to build the equivalent
1141 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
1142 ///
1143 /// \pre MI.isRegSequenceLike().
1144 ///
1145 /// \see TargetInstrInfo::getRegSequenceInputs.
1146 virtual bool getRegSequenceLikeInputs(
1147 const MachineInstr &MI, unsigned DefIdx,
1148 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1149 return false;
1150 }
1151
1152 /// Target-dependent implementation of getExtractSubregInputs.
1153 ///
1154 /// \returns true if it is possible to build the equivalent
1155 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1156 ///
1157 /// \pre MI.isExtractSubregLike().
1158 ///
1159 /// \see TargetInstrInfo::getExtractSubregInputs.
1160 virtual bool getExtractSubregLikeInputs(const MachineInstr &MI,
1161 unsigned DefIdx,
1162 RegSubRegPairAndIdx &InputReg) const {
1163 return false;
1164 }
1165
1166 /// Target-dependent implementation of getInsertSubregInputs.
1167 ///
1168 /// \returns true if it is possible to build the equivalent
1169 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1170 ///
1171 /// \pre MI.isInsertSubregLike().
1172 ///
1173 /// \see TargetInstrInfo::getInsertSubregInputs.
1174 virtual bool
1175 getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
1176 RegSubRegPair &BaseReg,
1177 RegSubRegPairAndIdx &InsertedReg) const {
1178 return false;
1179 }
1180
1181public:
1182 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
1183 /// (e.g. stack) the target returns the corresponding address space.
1184 virtual unsigned
1185 getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
1186 return 0;
1187 }
1188
1189 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
1190 /// a store or a load and a store into two or more instruction. If this is
1191 /// possible, returns true as well as the new instructions by reference.
1192 virtual bool
1193 unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
1194 bool UnfoldLoad, bool UnfoldStore,
1195 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1196 return false;
1197 }
1198
1199 virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
1200 SmallVectorImpl<SDNode *> &NewNodes) const {
1201 return false;
1202 }
1203
1204 /// Returns the opcode of the would be new
1205 /// instruction after load / store are unfolded from an instruction of the
1206 /// specified opcode. It returns zero if the specified unfolding is not
1207 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1208 /// index of the operand which will hold the register holding the loaded
1209 /// value.
1210 virtual unsigned
1211 getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
1212 unsigned *LoadRegIndex = nullptr) const {
1213 return 0;
1214 }
1215
1216 /// This is used by the pre-regalloc scheduler to determine if two loads are
1217 /// loading from the same base address. It should only return true if the base
1218 /// pointers are the same and the only differences between the two addresses
1219 /// are the offset. It also returns the offsets by reference.
1220 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1221 int64_t &Offset1,
1222 int64_t &Offset2) const {
1223 return false;
1224 }
1225
1226 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1227 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1228 /// On some targets if two loads are loading from
1229 /// addresses in the same cache line, it's better if they are scheduled
1230 /// together. This function takes two integers that represent the load offsets
1231 /// from the common base address. It returns true if it decides it's desirable
1232 /// to schedule the two loads together. "NumLoads" is the number of loads that
1233 /// have already been scheduled after Load1.
1234 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1235 int64_t Offset1, int64_t Offset2,
1236 unsigned NumLoads) const {
1237 return false;
1238 }
1239
1240 /// Get the base operand and byte offset of an instruction that reads/writes
1241 /// memory. This is a convenience function for callers that are only prepared
1242 /// to handle a single base operand.
1243 bool getMemOperandWithOffset(const MachineInstr &MI,
1244 const MachineOperand *&BaseOp, int64_t &Offset,
1245 bool &OffsetIsScalable,
1246 const TargetRegisterInfo *TRI) const;
1247
1248 /// Get the base operands and byte offset of an instruction that reads/writes
1249 /// memory.
1250 /// It returns false if MI does not read/write memory.
1251 /// It returns false if no base operands and offset was found.
1252 /// It is not guaranteed to always recognize base operands and offsets in all
1253 /// cases.
1254 virtual bool
1255 getMemOperandsWithOffset(const MachineInstr &MI,
1256 SmallVectorImpl<const MachineOperand *> &BaseOps,
1257 int64_t &Offset, bool &OffsetIsScalable,
1258 const TargetRegisterInfo *TRI) const {
1259 return false;
1260 }
1261
1262 /// Return true if the instruction contains a base register and offset. If
1263 /// true, the function also sets the operand position in the instruction
1264 /// for the base register and offset.
1265 virtual bool getBaseAndOffsetPosition(const MachineInstr &MI,
1266 unsigned &BasePos,
1267 unsigned &OffsetPos) const {
1268 return false;
1269 }
1270
1271 /// If the instruction is an increment of a constant value, return the amount.
1272 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1273 return false;
1274 }
1275
1276 /// Returns true if the two given memory operations should be scheduled
1277 /// adjacent. Note that you have to add:
1278 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1279 /// or
1280 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1281 /// to TargetPassConfig::createMachineScheduler() to have an effect.
1282 ///
1283 /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
1284 /// \p NumLoads is the number of loads that will be in the cluster if this
1285 /// hook returns true.
1286 virtual bool shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
1287 ArrayRef<const MachineOperand *> BaseOps2,
1288 unsigned NumLoads) const {
1289 llvm_unreachable("target did not implement shouldClusterMemOps()")::llvm::llvm_unreachable_internal("target did not implement shouldClusterMemOps()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1289)
;
1290 }
1291
1292 /// Reverses the branch condition of the specified condition list,
1293 /// returning false on success and true if it cannot be reversed.
1294 virtual bool
1295 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1296 return true;
1297 }
1298
1299 /// Insert a noop into the instruction stream at the specified point.
1300 virtual void insertNoop(MachineBasicBlock &MBB,
1301 MachineBasicBlock::iterator MI) const;
1302
1303 /// Return the noop instruction to use for a noop.
1304 virtual void getNoop(MCInst &NopInst) const;
1305
1306 /// Return true for post-incremented instructions.
1307 virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
1308
1309 /// Returns true if the instruction is already predicated.
1310 virtual bool isPredicated(const MachineInstr &MI) const { return false; }
1311
1312 // Returns a MIRPrinter comment for this machine operand.
1313 virtual std::string createMIROperandComment(const MachineInstr &MI,
1314 const MachineOperand &Op,
1315 unsigned OpIdx) const {
1316 return std::string();
1317 };
1318
1319 /// Returns true if the instruction is a
1320 /// terminator instruction that has not been predicated.
1321 virtual bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1322
1323 /// Returns true if MI is an unconditional tail call.
1324 virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
1325 return false;
1326 }
1327
1328 /// Returns true if the tail call can be made conditional on BranchCond.
1329 virtual bool canMakeTailCallConditional(SmallVectorImpl<MachineOperand> &Cond,
1330 const MachineInstr &TailCall) const {
1331 return false;
1332 }
1333
1334 /// Replace the conditional branch in MBB with a conditional tail call.
1335 virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB,
1336 SmallVectorImpl<MachineOperand> &Cond,
1337 const MachineInstr &TailCall) const {
1338 llvm_unreachable("Target didn't implement replaceBranchWithTailCall!")::llvm::llvm_unreachable_internal("Target didn't implement replaceBranchWithTailCall!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1338)
;
1339 }
1340
1341 /// Convert the instruction into a predicated instruction.
1342 /// It returns true if the operation was successful.
1343 virtual bool PredicateInstruction(MachineInstr &MI,
1344 ArrayRef<MachineOperand> Pred) const;
1345
1346 /// Returns true if the first specified predicate
1347 /// subsumes the second, e.g. GE subsumes GT.
1348 virtual bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1349 ArrayRef<MachineOperand> Pred2) const {
1350 return false;
1351 }
1352
1353 /// If the specified instruction defines any predicate
1354 /// or condition code register(s) used for predication, returns true as well
1355 /// as the definition predicate(s) by reference.
1356 virtual bool DefinesPredicate(MachineInstr &MI,
1357 std::vector<MachineOperand> &Pred) const {
1358 return false;
1359 }
1360
1361 /// Return true if the specified instruction can be predicated.
1362 /// By default, this returns true for every instruction with a
1363 /// PredicateOperand.
1364 virtual bool isPredicable(const MachineInstr &MI) const {
1365 return MI.getDesc().isPredicable();
1366 }
1367
1368 /// Return true if it's safe to move a machine
1369 /// instruction that defines the specified register class.
1370 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1371 return true;
1372 }
1373
1374 /// Test if the given instruction should be considered a scheduling boundary.
1375 /// This primarily includes labels and terminators.
1376 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1377 const MachineBasicBlock *MBB,
1378 const MachineFunction &MF) const;
1379
1380 /// Measure the specified inline asm to determine an approximation of its
1381 /// length.
1382 virtual unsigned getInlineAsmLength(
1383 const char *Str, const MCAsmInfo &MAI,
1384 const TargetSubtargetInfo *STI = nullptr) const;
1385
1386 /// Allocate and return a hazard recognizer to use for this target when
1387 /// scheduling the machine instructions before register allocation.
1388 virtual ScheduleHazardRecognizer *
1389 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1390 const ScheduleDAG *DAG) const;
1391
1392 /// Allocate and return a hazard recognizer to use for this target when
1393 /// scheduling the machine instructions before register allocation.
1394 virtual ScheduleHazardRecognizer *
1395 CreateTargetMIHazardRecognizer(const InstrItineraryData *,
1396 const ScheduleDAGMI *DAG) const;
1397
1398 /// Allocate and return a hazard recognizer to use for this target when
1399 /// scheduling the machine instructions after register allocation.
1400 virtual ScheduleHazardRecognizer *
1401 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
1402 const ScheduleDAG *DAG) const;
1403
1404 /// Allocate and return a hazard recognizer to use for by non-scheduling
1405 /// passes.
1406 virtual ScheduleHazardRecognizer *
1407 CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
1408 return nullptr;
1409 }
1410
1411 /// Provide a global flag for disabling the PreRA hazard recognizer that
1412 /// targets may choose to honor.
1413 bool usePreRAHazardRecognizer() const;
1414
1415 /// For a comparison instruction, return the source registers
1416 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1417 /// compares against in CmpValue. Return true if the comparison instruction
1418 /// can be analyzed.
1419 virtual bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1420 unsigned &SrcReg2, int &Mask, int &Value) const {
1421 return false;
1422 }
1423
1424 /// See if the comparison instruction can be converted
1425 /// into something more efficient. E.g., on ARM most instructions can set the
1426 /// flags register, obviating the need for a separate CMP.
1427 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1428 unsigned SrcReg2, int Mask, int Value,
1429 const MachineRegisterInfo *MRI) const {
1430 return false;
1431 }
1432 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1433
1434 /// Try to remove the load by folding it to a register operand at the use.
1435 /// We fold the load instructions if and only if the
1436 /// def and use are in the same BB. We only look at one load and see
1437 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1438 /// defined by the load we are trying to fold. DefMI returns the machine
1439 /// instruction that defines FoldAsLoadDefReg, and the function returns
1440 /// the machine instruction generated due to folding.
1441 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1442 const MachineRegisterInfo *MRI,
1443 unsigned &FoldAsLoadDefReg,
1444 MachineInstr *&DefMI) const {
1445 return nullptr;
1446 }
1447
1448 /// 'Reg' is known to be defined by a move immediate instruction,
1449 /// try to fold the immediate into the use instruction.
1450 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1451 /// then the caller may assume that DefMI has been erased from its parent
1452 /// block. The caller may assume that it will not be erased by this
1453 /// function otherwise.
1454 virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1455 unsigned Reg, MachineRegisterInfo *MRI) const {
1456 return false;
1457 }
1458
1459 /// Return the number of u-operations the given machine
1460 /// instruction will be decoded to on the target cpu. The itinerary's
1461 /// IssueWidth is the number of microops that can be dispatched each
1462 /// cycle. An instruction with zero microops takes no dispatch resources.
1463 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1464 const MachineInstr &MI) const;
1465
1466 /// Return true for pseudo instructions that don't consume any
1467 /// machine resources in their current form. These are common cases that the
1468 /// scheduler should consider free, rather than conservatively handling them
1469 /// as instructions with no itinerary.
1470 bool isZeroCost(unsigned Opcode) const {
1471 return Opcode <= TargetOpcode::COPY;
1472 }
1473
1474 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1475 SDNode *DefNode, unsigned DefIdx,
1476 SDNode *UseNode, unsigned UseIdx) const;
1477
1478 /// Compute and return the use operand latency of a given pair of def and use.
1479 /// In most cases, the static scheduling itinerary was enough to determine the
1480 /// operand latency. But it may not be possible for instructions with variable
1481 /// number of defs / uses.
1482 ///
1483 /// This is a raw interface to the itinerary that may be directly overridden
1484 /// by a target. Use computeOperandLatency to get the best estimate of
1485 /// latency.
1486 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1487 const MachineInstr &DefMI, unsigned DefIdx,
1488 const MachineInstr &UseMI,
1489 unsigned UseIdx) const;
1490
1491 /// Compute the instruction latency of a given instruction.
1492 /// If the instruction has higher cost when predicated, it's returned via
1493 /// PredCost.
1494 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1495 const MachineInstr &MI,
1496 unsigned *PredCost = nullptr) const;
1497
1498 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1499
1500 virtual int getInstrLatency(const InstrItineraryData *ItinData,
1501 SDNode *Node) const;
1502
1503 /// Return the default expected latency for a def based on its opcode.
1504 unsigned defaultDefLatency(const MCSchedModel &SchedModel,
1505 const MachineInstr &DefMI) const;
1506
1507 int computeDefOperandLatency(const InstrItineraryData *ItinData,
1508 const MachineInstr &DefMI) const;
1509
1510 /// Return true if this opcode has high latency to its result.
1511 virtual bool isHighLatencyDef(int opc) const { return false; }
1512
1513 /// Compute operand latency between a def of 'Reg'
1514 /// and a use in the current loop. Return true if the target considered
1515 /// it 'high'. This is used by optimization passes such as machine LICM to
1516 /// determine whether it makes sense to hoist an instruction out even in a
1517 /// high register pressure situation.
1518 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1519 const MachineRegisterInfo *MRI,
1520 const MachineInstr &DefMI, unsigned DefIdx,
1521 const MachineInstr &UseMI,
1522 unsigned UseIdx) const {
1523 return false;
1524 }
1525
1526 /// Compute operand latency of a def of 'Reg'. Return true
1527 /// if the target considered it 'low'.
1528 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1529 const MachineInstr &DefMI,
1530 unsigned DefIdx) const;
1531
1532 /// Perform target-specific instruction verification.
1533 virtual bool verifyInstruction(const MachineInstr &MI,
1534 StringRef &ErrInfo) const {
1535 return true;
1536 }
1537
1538 /// Return the current execution domain and bit mask of
1539 /// possible domains for instruction.
1540 ///
1541 /// Some micro-architectures have multiple execution domains, and multiple
1542 /// opcodes that perform the same operation in different domains. For
1543 /// example, the x86 architecture provides the por, orps, and orpd
1544 /// instructions that all do the same thing. There is a latency penalty if a
1545 /// register is written in one domain and read in another.
1546 ///
1547 /// This function returns a pair (domain, mask) containing the execution
1548 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1549 /// function can be used to change the opcode to one of the domains in the
1550 /// bit mask. Instructions whose execution domain can't be changed should
1551 /// return a 0 mask.
1552 ///
1553 /// The execution domain numbers don't have any special meaning except domain
1554 /// 0 is used for instructions that are not associated with any interesting
1555 /// execution domain.
1556 ///
1557 virtual std::pair<uint16_t, uint16_t>
1558 getExecutionDomain(const MachineInstr &MI) const {
1559 return std::make_pair(0, 0);
1560 }
1561
1562 /// Change the opcode of MI to execute in Domain.
1563 ///
1564 /// The bit (1 << Domain) must be set in the mask returned from
1565 /// getExecutionDomain(MI).
1566 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1567
1568 /// Returns the preferred minimum clearance
1569 /// before an instruction with an unwanted partial register update.
1570 ///
1571 /// Some instructions only write part of a register, and implicitly need to
1572 /// read the other parts of the register. This may cause unwanted stalls
1573 /// preventing otherwise unrelated instructions from executing in parallel in
1574 /// an out-of-order CPU.
1575 ///
1576 /// For example, the x86 instruction cvtsi2ss writes its result to bits
1577 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1578 /// the instruction needs to wait for the old value of the register to become
1579 /// available:
1580 ///
1581 /// addps %xmm1, %xmm0
1582 /// movaps %xmm0, (%rax)
1583 /// cvtsi2ss %rbx, %xmm0
1584 ///
1585 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1586 /// instruction before it can issue, even though the high bits of %xmm0
1587 /// probably aren't needed.
1588 ///
1589 /// This hook returns the preferred clearance before MI, measured in
1590 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
1591 /// instructions before MI. It should only return a positive value for
1592 /// unwanted dependencies. If the old bits of the defined register have
1593 /// useful values, or if MI is determined to otherwise read the dependency,
1594 /// the hook should return 0.
1595 ///
1596 /// The unwanted dependency may be handled by:
1597 ///
1598 /// 1. Allocating the same register for an MI def and use. That makes the
1599 /// unwanted dependency identical to a required dependency.
1600 ///
1601 /// 2. Allocating a register for the def that has no defs in the previous N
1602 /// instructions.
1603 ///
1604 /// 3. Calling breakPartialRegDependency() with the same arguments. This
1605 /// allows the target to insert a dependency breaking instruction.
1606 ///
1607 virtual unsigned
1608 getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
1609 const TargetRegisterInfo *TRI) const {
1610 // The default implementation returns 0 for no partial register dependency.
1611 return 0;
1612 }
1613
1614 /// Return the minimum clearance before an instruction that reads an
1615 /// unused register.
1616 ///
1617 /// For example, AVX instructions may copy part of a register operand into
1618 /// the unused high bits of the destination register.
1619 ///
1620 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
1621 ///
1622 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
1623 /// false dependence on any previous write to %xmm0.
1624 ///
1625 /// This hook works similarly to getPartialRegUpdateClearance, except that it
1626 /// does not take an operand index. Instead sets \p OpNum to the index of the
1627 /// unused register.
1628 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned &OpNum,
1629 const TargetRegisterInfo *TRI) const {
1630 // The default implementation returns 0 for no undef register dependency.
1631 return 0;
1632 }
1633
1634 /// Insert a dependency-breaking instruction
1635 /// before MI to eliminate an unwanted dependency on OpNum.
1636 ///
1637 /// If it wasn't possible to avoid a def in the last N instructions before MI
1638 /// (see getPartialRegUpdateClearance), this hook will be called to break the
1639 /// unwanted dependency.
1640 ///
1641 /// On x86, an xorps instruction can be used as a dependency breaker:
1642 ///
1643 /// addps %xmm1, %xmm0
1644 /// movaps %xmm0, (%rax)
1645 /// xorps %xmm0, %xmm0
1646 /// cvtsi2ss %rbx, %xmm0
1647 ///
1648 /// An <imp-kill> operand should be added to MI if an instruction was
1649 /// inserted. This ties the instructions together in the post-ra scheduler.
1650 ///
1651 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
1652 const TargetRegisterInfo *TRI) const {}
1653
1654 /// Create machine specific model for scheduling.
1655 virtual DFAPacketizer *
1656 CreateTargetScheduleState(const TargetSubtargetInfo &) const {
1657 return nullptr;
1658 }
1659
1660 /// Sometimes, it is possible for the target
1661 /// to tell, even without aliasing information, that two MIs access different
1662 /// memory addresses. This function returns true if two MIs access different
1663 /// memory addresses and false otherwise.
1664 ///
1665 /// Assumes any physical registers used to compute addresses have the same
1666 /// value for both instructions. (This is the most useful assumption for
1667 /// post-RA scheduling.)
1668 ///
1669 /// See also MachineInstr::mayAlias, which is implemented on top of this
1670 /// function.
1671 virtual bool
1672 areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
1673 const MachineInstr &MIb) const {
1674 assert(MIa.mayLoadOrStore() &&((MIa.mayLoadOrStore() && "MIa must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIa.mayLoadOrStore() && \"MIa must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1675, __PRETTY_FUNCTION__))
1675 "MIa must load from or modify a memory location")((MIa.mayLoadOrStore() && "MIa must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIa.mayLoadOrStore() && \"MIa must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1675, __PRETTY_FUNCTION__))
;
1676 assert(MIb.mayLoadOrStore() &&((MIb.mayLoadOrStore() && "MIb must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIb.mayLoadOrStore() && \"MIb must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1677, __PRETTY_FUNCTION__))
1677 "MIb must load from or modify a memory location")((MIb.mayLoadOrStore() && "MIb must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIb.mayLoadOrStore() && \"MIb must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1677, __PRETTY_FUNCTION__))
;
1678 return false;
1679 }
1680
1681 /// Return the value to use for the MachineCSE's LookAheadLimit,
1682 /// which is a heuristic used for CSE'ing phys reg defs.
1683 virtual unsigned getMachineCSELookAheadLimit() const {
1684 // The default lookahead is small to prevent unprofitable quadratic
1685 // behavior.
1686 return 5;
1687 }
1688
1689 /// Return an array that contains the ids of the target indices (used for the
1690 /// TargetIndex machine operand) and their names.
1691 ///
1692 /// MIR Serialization is able to serialize only the target indices that are
1693 /// defined by this method.
1694 virtual ArrayRef<std::pair<int, const char *>>
1695 getSerializableTargetIndices() const {
1696 return None;
1697 }
1698
1699 /// Decompose the machine operand's target flags into two values - the direct
1700 /// target flag value and any of bit flags that are applied.
1701 virtual std::pair<unsigned, unsigned>
1702 decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
1703 return std::make_pair(0u, 0u);
1704 }
1705
1706 /// Return an array that contains the direct target flag values and their
1707 /// names.
1708 ///
1709 /// MIR Serialization is able to serialize only the target flags that are
1710 /// defined by this method.
1711 virtual ArrayRef<std::pair<unsigned, const char *>>
1712 getSerializableDirectMachineOperandTargetFlags() const {
1713 return None;
1714 }
1715
1716 /// Return an array that contains the bitmask target flag values and their
1717 /// names.
1718 ///
1719 /// MIR Serialization is able to serialize only the target flags that are
1720 /// defined by this method.
1721 virtual ArrayRef<std::pair<unsigned, const char *>>
1722 getSerializableBitmaskMachineOperandTargetFlags() const {
1723 return None;
1724 }
1725
1726 /// Return an array that contains the MMO target flag values and their
1727 /// names.
1728 ///
1729 /// MIR Serialization is able to serialize only the MMO target flags that are
1730 /// defined by this method.
1731 virtual ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
1732 getSerializableMachineMemOperandTargetFlags() const {
1733 return None;
1734 }
1735
1736 /// Determines whether \p Inst is a tail call instruction. Override this
1737 /// method on targets that do not properly set MCID::Return and MCID::Call on
1738 /// tail call instructions."
1739 virtual bool isTailCall(const MachineInstr &Inst) const {
1740 return Inst.isReturn() && Inst.isCall();
1741 }
1742
1743 /// True if the instruction is bound to the top of its basic block and no
1744 /// other instructions shall be inserted before it. This can be implemented
1745 /// to prevent register allocator to insert spills before such instructions.
1746 virtual bool isBasicBlockPrologue(const MachineInstr &MI) const {
1747 return false;
1748 }
1749
1750 /// During PHI eleimination lets target to make necessary checks and
1751 /// insert the copy to the PHI destination register in a target specific
1752 /// manner.
1753 virtual MachineInstr *createPHIDestinationCopy(
1754 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
1755 const DebugLoc &DL, Register Src, Register Dst) const {
1756 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1757 .addReg(Src);
1758 }
1759
1760 /// During PHI eleimination lets target to make necessary checks and
1761 /// insert the copy to the PHI destination register in a target specific
1762 /// manner.
1763 virtual MachineInstr *createPHISourceCopy(MachineBasicBlock &MBB,
1764 MachineBasicBlock::iterator InsPt,
1765 const DebugLoc &DL, Register Src,
1766 unsigned SrcSubReg,
1767 Register Dst) const {
1768 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1769 .addReg(Src, 0, SrcSubReg);
1770 }
1771
1772 /// Returns a \p outliner::OutlinedFunction struct containing target-specific
1773 /// information for a set of outlining candidates.
1774 virtual outliner::OutlinedFunction getOutliningCandidateInfo(
1775 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
1776 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1777)
1777 "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1777)
;
1778 }
1779
1780 /// Returns how or if \p MI should be outlined.
1781 virtual outliner::InstrType
1782 getOutliningType(MachineBasicBlock::iterator &MIT, unsigned Flags) const {
1783 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningType!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1784)
1784 "Target didn't implement TargetInstrInfo::getOutliningType!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningType!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1784)
;
1785 }
1786
1787 /// Optional target hook that returns true if \p MBB is safe to outline from,
1788 /// and returns any target-specific information in \p Flags.
1789 virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
1790 unsigned &Flags) const {
1791 return true;
1792 }
1793
1794 /// Insert a custom frame for outlined functions.
1795 virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
1796 const outliner::OutlinedFunction &OF) const {
1797 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::buildOutlinedFrame!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1798)
1798 "Target didn't implement TargetInstrInfo::buildOutlinedFrame!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::buildOutlinedFrame!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1798)
;
1799 }
1800
1801 /// Insert a call to an outlined function into the program.
1802 /// Returns an iterator to the spot where we inserted the call. This must be
1803 /// implemented by the target.
1804 virtual MachineBasicBlock::iterator
1805 insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
1806 MachineBasicBlock::iterator &It, MachineFunction &MF,
1807 const outliner::Candidate &C) const {
1808 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertOutlinedCall!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1809)
1809 "Target didn't implement TargetInstrInfo::insertOutlinedCall!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertOutlinedCall!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1809)
;
1810 }
1811
1812 /// Return true if the function can safely be outlined from.
1813 /// A function \p MF is considered safe for outlining if an outlined function
1814 /// produced from instructions in F will produce a program which produces the
1815 /// same output for any set of given inputs.
1816 virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF,
1817 bool OutlineFromLinkOnceODRs) const {
1818 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::isFunctionSafeToOutlineFrom!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1819)
1819 "TargetInstrInfo::isFunctionSafeToOutlineFrom!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::isFunctionSafeToOutlineFrom!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1819)
;
1820 }
1821
1822 /// Return true if the function should be outlined from by default.
1823 virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const {
1824 return false;
1825 }
1826
1827 /// Produce the expression describing the \p MI loading a value into
1828 /// the physical register \p Reg. This hook should only be used with
1829 /// \p MIs belonging to VReg-less functions.
1830 virtual Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
1831 Register Reg) const;
1832
1833 /// Return MIR formatter to format/parse MIR operands. Target can override
1834 /// this virtual function and return target specific MIR formatter.
1835 virtual const MIRFormatter *getMIRFormatter() const {
1836 if (!Formatter.get())
1837 Formatter = std::make_unique<MIRFormatter>();
1838 return Formatter.get();
1839 }
1840
1841private:
1842 mutable std::unique_ptr<MIRFormatter> Formatter;
1843 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
1844 unsigned CatchRetOpcode;
1845 unsigned ReturnOpcode;
1846};
1847
1848/// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
1849template <> struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
1850 using RegInfo = DenseMapInfo<unsigned>;
1851
1852 static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
1853 return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
1854 RegInfo::getEmptyKey());
1855 }
1856
1857 static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
1858 return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
1859 RegInfo::getTombstoneKey());
1860 }
1861
1862 /// Reuse getHashValue implementation from
1863 /// std::pair<unsigned, unsigned>.
1864 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
1865 std::pair<unsigned, unsigned> PairVal = std::make_pair(Val.Reg, Val.SubReg);
1866 return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
1867 }
1868
1869 static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
1870 const TargetInstrInfo::RegSubRegPair &RHS) {
1871 return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
1872 RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
1873 }
1874};
1875
1876} // end namespace llvm
1877
1878#endif // LLVM_TARGET_TARGETINSTRINFO_H