Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen/MachineInstr.cpp
Warning:line 1833, column 7
Value stored to 'HaveSemi' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MachineInstr.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/CodeGen/MachineInstr.cpp
1//===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
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// Methods common to all machine instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/MachineInstr.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/Hashing.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallBitVector.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/MemoryLocation.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineInstrBundle.h"
27#include "llvm/CodeGen/MachineMemOperand.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/CodeGen/MachineOperand.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/PseudoSourceValue.h"
32#include "llvm/CodeGen/StackMaps.h"
33#include "llvm/CodeGen/TargetInstrInfo.h"
34#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/CodeGen/TargetSubtargetInfo.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DebugInfoMetadata.h"
38#include "llvm/IR/DebugLoc.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/ModuleSlotTracker.h"
45#include "llvm/IR/Operator.h"
46#include "llvm/MC/MCInstrDesc.h"
47#include "llvm/MC/MCRegisterInfo.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FormattedStream.h"
53#include "llvm/Support/LowLevelTypeImpl.h"
54#include "llvm/Support/raw_ostream.h"
55#include "llvm/Target/TargetMachine.h"
56#include <algorithm>
57#include <cassert>
58#include <cstdint>
59#include <cstring>
60#include <utility>
61
62using namespace llvm;
63
64static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
65 if (const MachineBasicBlock *MBB = MI.getParent())
66 if (const MachineFunction *MF = MBB->getParent())
67 return MF;
68 return nullptr;
69}
70
71// Try to crawl up to the machine function and get TRI and IntrinsicInfo from
72// it.
73static void tryToGetTargetInfo(const MachineInstr &MI,
74 const TargetRegisterInfo *&TRI,
75 const MachineRegisterInfo *&MRI,
76 const TargetIntrinsicInfo *&IntrinsicInfo,
77 const TargetInstrInfo *&TII) {
78
79 if (const MachineFunction *MF = getMFIfAvailable(MI)) {
80 TRI = MF->getSubtarget().getRegisterInfo();
81 MRI = &MF->getRegInfo();
82 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
83 TII = MF->getSubtarget().getInstrInfo();
84 }
85}
86
87void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
88 if (MCID->ImplicitDefs)
89 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
90 ++ImpDefs)
91 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
92 if (MCID->ImplicitUses)
93 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
94 ++ImpUses)
95 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
96}
97
98/// MachineInstr ctor - This constructor creates a MachineInstr and adds the
99/// implicit operands. It reserves space for the number of operands specified by
100/// the MCInstrDesc.
101MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &TID,
102 DebugLoc DL, bool NoImp)
103 : MCID(&TID), DbgLoc(std::move(DL)), DebugInstrNum(0) {
104 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (DbgLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("DbgLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 104, __extension__ __PRETTY_FUNCTION__
))
;
105
106 // Reserve space for the expected number of operands.
107 if (unsigned NumOps = MCID->getNumOperands() +
108 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
109 CapOperands = OperandCapacity::get(NumOps);
110 Operands = MF.allocateOperandArray(CapOperands);
111 }
112
113 if (!NoImp)
114 addImplicitDefUseOperands(MF);
115}
116
117/// MachineInstr ctor - Copies MachineInstr arg exactly.
118/// Does not copy the number from debug instruction numbering, to preserve
119/// uniqueness.
120MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
121 : MCID(&MI.getDesc()), Info(MI.Info), DbgLoc(MI.getDebugLoc()),
122 DebugInstrNum(0) {
123 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (DbgLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("DbgLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 123, __extension__ __PRETTY_FUNCTION__
))
;
124
125 CapOperands = OperandCapacity::get(MI.getNumOperands());
126 Operands = MF.allocateOperandArray(CapOperands);
127
128 // Copy operands.
129 for (const MachineOperand &MO : MI.operands())
130 addOperand(MF, MO);
131
132 // Copy all the sensible flags.
133 setFlags(MI.Flags);
134}
135
136void MachineInstr::moveBefore(MachineInstr *MovePos) {
137 MovePos->getParent()->splice(MovePos, getParent(), getIterator());
138}
139
140/// getRegInfo - If this instruction is embedded into a MachineFunction,
141/// return the MachineRegisterInfo object for the current function, otherwise
142/// return null.
143MachineRegisterInfo *MachineInstr::getRegInfo() {
144 if (MachineBasicBlock *MBB = getParent())
145 return &MBB->getParent()->getRegInfo();
146 return nullptr;
147}
148
149void MachineInstr::removeRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
150 for (MachineOperand &MO : operands())
151 if (MO.isReg())
152 MRI.removeRegOperandFromUseList(&MO);
153}
154
155void MachineInstr::addRegOperandsToUseLists(MachineRegisterInfo &MRI) {
156 for (MachineOperand &MO : operands())
157 if (MO.isReg())
158 MRI.addRegOperandToUseList(&MO);
159}
160
161void MachineInstr::addOperand(const MachineOperand &Op) {
162 MachineBasicBlock *MBB = getParent();
163 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs")(static_cast <bool> (MBB && "Use MachineInstrBuilder to add operands to dangling instrs"
) ? void (0) : __assert_fail ("MBB && \"Use MachineInstrBuilder to add operands to dangling instrs\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 163, __extension__ __PRETTY_FUNCTION__
))
;
164 MachineFunction *MF = MBB->getParent();
165 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs")(static_cast <bool> (MF && "Use MachineInstrBuilder to add operands to dangling instrs"
) ? void (0) : __assert_fail ("MF && \"Use MachineInstrBuilder to add operands to dangling instrs\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 165, __extension__ __PRETTY_FUNCTION__
))
;
166 addOperand(*MF, Op);
167}
168
169/// Move NumOps MachineOperands from Src to Dst, with support for overlapping
170/// ranges. If MRI is non-null also update use-def chains.
171static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
172 unsigned NumOps, MachineRegisterInfo *MRI) {
173 if (MRI)
174 return MRI->moveOperands(Dst, Src, NumOps);
175 // MachineOperand is a trivially copyable type so we can just use memmove.
176 assert(Dst && Src && "Unknown operands")(static_cast <bool> (Dst && Src && "Unknown operands"
) ? void (0) : __assert_fail ("Dst && Src && \"Unknown operands\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 176, __extension__ __PRETTY_FUNCTION__
))
;
177 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
178}
179
180/// addOperand - Add the specified operand to the instruction. If it is an
181/// implicit operand, it is added to the end of the operand list. If it is
182/// an explicit operand it is added at the end of the explicit operand list
183/// (before the first implicit operand).
184void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
185 assert(MCID && "Cannot add operands before providing an instr descriptor")(static_cast <bool> (MCID && "Cannot add operands before providing an instr descriptor"
) ? void (0) : __assert_fail ("MCID && \"Cannot add operands before providing an instr descriptor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 185, __extension__ __PRETTY_FUNCTION__
))
;
186
187 // Check if we're adding one of our existing operands.
188 if (&Op >= Operands && &Op < Operands + NumOperands) {
189 // This is unusual: MI->addOperand(MI->getOperand(i)).
190 // If adding Op requires reallocating or moving existing operands around,
191 // the Op reference could go stale. Support it by copying Op.
192 MachineOperand CopyOp(Op);
193 return addOperand(MF, CopyOp);
194 }
195
196 // Find the insert location for the new operand. Implicit registers go at
197 // the end, everything else goes before the implicit regs.
198 //
199 // FIXME: Allow mixed explicit and implicit operands on inline asm.
200 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
201 // implicit-defs, but they must not be moved around. See the FIXME in
202 // InstrEmitter.cpp.
203 unsigned OpNo = getNumOperands();
204 bool isImpReg = Op.isReg() && Op.isImplicit();
205 if (!isImpReg && !isInlineAsm()) {
206 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
207 --OpNo;
208 assert(!Operands[OpNo].isTied() && "Cannot move tied operands")(static_cast <bool> (!Operands[OpNo].isTied() &&
"Cannot move tied operands") ? void (0) : __assert_fail ("!Operands[OpNo].isTied() && \"Cannot move tied operands\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 208, __extension__ __PRETTY_FUNCTION__
))
;
209 }
210 }
211
212 // OpNo now points as the desired insertion point. Unless this is a variadic
213 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
214 // RegMask operands go between the explicit and implicit operands.
215 assert((MCID->isVariadic() || OpNo < MCID->getNumOperands() ||(static_cast <bool> ((MCID->isVariadic() || OpNo <
MCID->getNumOperands() || Op.isValidExcessOperand()) &&
"Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(MCID->isVariadic() || OpNo < MCID->getNumOperands() || Op.isValidExcessOperand()) && \"Trying to add an operand to a machine instr that is already done!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 217, __extension__ __PRETTY_FUNCTION__
))
216 Op.isValidExcessOperand()) &&(static_cast <bool> ((MCID->isVariadic() || OpNo <
MCID->getNumOperands() || Op.isValidExcessOperand()) &&
"Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(MCID->isVariadic() || OpNo < MCID->getNumOperands() || Op.isValidExcessOperand()) && \"Trying to add an operand to a machine instr that is already done!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 217, __extension__ __PRETTY_FUNCTION__
))
217 "Trying to add an operand to a machine instr that is already done!")(static_cast <bool> ((MCID->isVariadic() || OpNo <
MCID->getNumOperands() || Op.isValidExcessOperand()) &&
"Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(MCID->isVariadic() || OpNo < MCID->getNumOperands() || Op.isValidExcessOperand()) && \"Trying to add an operand to a machine instr that is already done!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 217, __extension__ __PRETTY_FUNCTION__
))
;
218
219 MachineRegisterInfo *MRI = getRegInfo();
220
221 // Determine if the Operands array needs to be reallocated.
222 // Save the old capacity and operand array.
223 OperandCapacity OldCap = CapOperands;
224 MachineOperand *OldOperands = Operands;
225 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
226 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
227 Operands = MF.allocateOperandArray(CapOperands);
228 // Move the operands before the insertion point.
229 if (OpNo)
230 moveOperands(Operands, OldOperands, OpNo, MRI);
231 }
232
233 // Move the operands following the insertion point.
234 if (OpNo != NumOperands)
235 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
236 MRI);
237 ++NumOperands;
238
239 // Deallocate the old operand array.
240 if (OldOperands != Operands && OldOperands)
241 MF.deallocateOperandArray(OldCap, OldOperands);
242
243 // Copy Op into place. It still needs to be inserted into the MRI use lists.
244 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
245 NewMO->ParentMI = this;
246
247 // When adding a register operand, tell MRI about it.
248 if (NewMO->isReg()) {
249 // Ensure isOnRegUseList() returns false, regardless of Op's status.
250 NewMO->Contents.Reg.Prev = nullptr;
251 // Ignore existing ties. This is not a property that can be copied.
252 NewMO->TiedTo = 0;
253 // Add the new operand to MRI, but only for instructions in an MBB.
254 if (MRI)
255 MRI->addRegOperandToUseList(NewMO);
256 // The MCID operand information isn't accurate until we start adding
257 // explicit operands. The implicit operands are added first, then the
258 // explicits are inserted before them.
259 if (!isImpReg) {
260 // Tie uses to defs as indicated in MCInstrDesc.
261 if (NewMO->isUse()) {
262 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
263 if (DefIdx != -1)
264 tieOperands(DefIdx, OpNo);
265 }
266 // If the register operand is flagged as early, mark the operand as such.
267 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
268 NewMO->setIsEarlyClobber(true);
269 }
270 // Ensure debug instructions set debug flag on register uses.
271 if (NewMO->isUse() && isDebugInstr())
272 NewMO->setIsDebug();
273 }
274}
275
276void MachineInstr::removeOperand(unsigned OpNo) {
277 assert(OpNo < getNumOperands() && "Invalid operand number")(static_cast <bool> (OpNo < getNumOperands() &&
"Invalid operand number") ? void (0) : __assert_fail ("OpNo < getNumOperands() && \"Invalid operand number\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 277, __extension__ __PRETTY_FUNCTION__
))
;
278 untieRegOperand(OpNo);
279
280#ifndef NDEBUG
281 // Moving tied operands would break the ties.
282 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
283 if (Operands[i].isReg())
284 assert(!Operands[i].isTied() && "Cannot move tied operands")(static_cast <bool> (!Operands[i].isTied() && "Cannot move tied operands"
) ? void (0) : __assert_fail ("!Operands[i].isTied() && \"Cannot move tied operands\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 284, __extension__ __PRETTY_FUNCTION__
))
;
285#endif
286
287 MachineRegisterInfo *MRI = getRegInfo();
288 if (MRI && Operands[OpNo].isReg())
289 MRI->removeRegOperandFromUseList(Operands + OpNo);
290
291 // Don't call the MachineOperand destructor. A lot of this code depends on
292 // MachineOperand having a trivial destructor anyway, and adding a call here
293 // wouldn't make it 'destructor-correct'.
294
295 if (unsigned N = NumOperands - 1 - OpNo)
296 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
297 --NumOperands;
298}
299
300void MachineInstr::setExtraInfo(MachineFunction &MF,
301 ArrayRef<MachineMemOperand *> MMOs,
302 MCSymbol *PreInstrSymbol,
303 MCSymbol *PostInstrSymbol,
304 MDNode *HeapAllocMarker, uint32_t CFIType) {
305 bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
306 bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
307 bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
308 bool HasCFIType = CFIType != 0;
309 int NumPointers = MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol +
310 HasHeapAllocMarker + HasCFIType;
311
312 // Drop all extra info if there is none.
313 if (NumPointers <= 0) {
314 Info.clear();
315 return;
316 }
317
318 // If more than one pointer, then store out of line. Store heap alloc markers
319 // out of line because PointerSumType cannot hold more than 4 tag types with
320 // 32-bit pointers.
321 // FIXME: Maybe we should make the symbols in the extra info mutable?
322 else if (NumPointers > 1 || HasHeapAllocMarker || HasCFIType) {
323 Info.set<EIIK_OutOfLine>(MF.createMIExtraInfo(
324 MMOs, PreInstrSymbol, PostInstrSymbol, HeapAllocMarker, CFIType));
325 return;
326 }
327
328 // Otherwise store the single pointer inline.
329 if (HasPreInstrSymbol)
330 Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol);
331 else if (HasPostInstrSymbol)
332 Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol);
333 else
334 Info.set<EIIK_MMO>(MMOs[0]);
335}
336
337void MachineInstr::dropMemRefs(MachineFunction &MF) {
338 if (memoperands_empty())
339 return;
340
341 setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(),
342 getHeapAllocMarker(), getCFIType());
343}
344
345void MachineInstr::setMemRefs(MachineFunction &MF,
346 ArrayRef<MachineMemOperand *> MMOs) {
347 if (MMOs.empty()) {
348 dropMemRefs(MF);
349 return;
350 }
351
352 setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(),
353 getHeapAllocMarker(), getCFIType());
354}
355
356void MachineInstr::addMemOperand(MachineFunction &MF,
357 MachineMemOperand *MO) {
358 SmallVector<MachineMemOperand *, 2> MMOs;
359 MMOs.append(memoperands_begin(), memoperands_end());
360 MMOs.push_back(MO);
361 setMemRefs(MF, MMOs);
362}
363
364void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
365 if (this == &MI)
366 // Nothing to do for a self-clone!
367 return;
368
369 assert(&MF == MI.getMF() &&(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning memory refrences!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory refrences!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 370, __extension__ __PRETTY_FUNCTION__
))
370 "Invalid machine functions when cloning memory refrences!")(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning memory refrences!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory refrences!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 370, __extension__ __PRETTY_FUNCTION__
))
;
371 // See if we can just steal the extra info already allocated for the
372 // instruction. We can do this whenever the pre- and post-instruction symbols
373 // are the same (including null).
374 if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
375 getPostInstrSymbol() == MI.getPostInstrSymbol() &&
376 getHeapAllocMarker() == MI.getHeapAllocMarker()) {
377 Info = MI.Info;
378 return;
379 }
380
381 // Otherwise, fall back on a copy-based clone.
382 setMemRefs(MF, MI.memoperands());
383}
384
385/// Check to see if the MMOs pointed to by the two MemRefs arrays are
386/// identical.
387static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
388 ArrayRef<MachineMemOperand *> RHS) {
389 if (LHS.size() != RHS.size())
390 return false;
391
392 auto LHSPointees = make_pointee_range(LHS);
393 auto RHSPointees = make_pointee_range(RHS);
394 return std::equal(LHSPointees.begin(), LHSPointees.end(),
395 RHSPointees.begin());
396}
397
398void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
399 ArrayRef<const MachineInstr *> MIs) {
400 // Try handling easy numbers of MIs with simpler mechanisms.
401 if (MIs.empty()) {
402 dropMemRefs(MF);
403 return;
404 }
405 if (MIs.size() == 1) {
406 cloneMemRefs(MF, *MIs[0]);
407 return;
408 }
409 // Because an empty memoperands list provides *no* information and must be
410 // handled conservatively (assuming the instruction can do anything), the only
411 // way to merge with it is to drop all other memoperands.
412 if (MIs[0]->memoperands_empty()) {
413 dropMemRefs(MF);
414 return;
415 }
416
417 // Handle the general case.
418 SmallVector<MachineMemOperand *, 2> MergedMMOs;
419 // Start with the first instruction.
420 assert(&MF == MIs[0]->getMF() &&(static_cast <bool> (&MF == MIs[0]->getMF() &&
"Invalid machine functions when cloning memory references!")
? void (0) : __assert_fail ("&MF == MIs[0]->getMF() && \"Invalid machine functions when cloning memory references!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 421, __extension__ __PRETTY_FUNCTION__
))
421 "Invalid machine functions when cloning memory references!")(static_cast <bool> (&MF == MIs[0]->getMF() &&
"Invalid machine functions when cloning memory references!")
? void (0) : __assert_fail ("&MF == MIs[0]->getMF() && \"Invalid machine functions when cloning memory references!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 421, __extension__ __PRETTY_FUNCTION__
))
;
422 MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
423 // Now walk all the other instructions and accumulate any different MMOs.
424 for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
425 assert(&MF == MI.getMF() &&(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning memory references!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory references!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 426, __extension__ __PRETTY_FUNCTION__
))
426 "Invalid machine functions when cloning memory references!")(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning memory references!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory references!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 426, __extension__ __PRETTY_FUNCTION__
))
;
427
428 // Skip MIs with identical operands to the first. This is a somewhat
429 // arbitrary hack but will catch common cases without being quadratic.
430 // TODO: We could fully implement merge semantics here if needed.
431 if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
432 continue;
433
434 // Because an empty memoperands list provides *no* information and must be
435 // handled conservatively (assuming the instruction can do anything), the
436 // only way to merge with it is to drop all other memoperands.
437 if (MI.memoperands_empty()) {
438 dropMemRefs(MF);
439 return;
440 }
441
442 // Otherwise accumulate these into our temporary buffer of the merged state.
443 MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
444 }
445
446 setMemRefs(MF, MergedMMOs);
447}
448
449void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
450 // Do nothing if old and new symbols are the same.
451 if (Symbol == getPreInstrSymbol())
452 return;
453
454 // If there was only one symbol and we're removing it, just clear info.
455 if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) {
456 Info.clear();
457 return;
458 }
459
460 setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(),
461 getHeapAllocMarker(), getCFIType());
462}
463
464void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
465 // Do nothing if old and new symbols are the same.
466 if (Symbol == getPostInstrSymbol())
467 return;
468
469 // If there was only one symbol and we're removing it, just clear info.
470 if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) {
471 Info.clear();
472 return;
473 }
474
475 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol,
476 getHeapAllocMarker(), getCFIType());
477}
478
479void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) {
480 // Do nothing if old and new symbols are the same.
481 if (Marker == getHeapAllocMarker())
482 return;
483
484 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
485 Marker, getCFIType());
486}
487
488void MachineInstr::setCFIType(MachineFunction &MF, uint32_t Type) {
489 // Do nothing if old and new types are the same.
490 if (Type == getCFIType())
491 return;
492
493 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
494 getHeapAllocMarker(), Type);
495}
496
497void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
498 const MachineInstr &MI) {
499 if (this == &MI)
500 // Nothing to do for a self-clone!
501 return;
502
503 assert(&MF == MI.getMF() &&(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning instruction symbols!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning instruction symbols!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 504, __extension__ __PRETTY_FUNCTION__
))
504 "Invalid machine functions when cloning instruction symbols!")(static_cast <bool> (&MF == MI.getMF() && "Invalid machine functions when cloning instruction symbols!"
) ? void (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning instruction symbols!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 504, __extension__ __PRETTY_FUNCTION__
))
;
505
506 setPreInstrSymbol(MF, MI.getPreInstrSymbol());
507 setPostInstrSymbol(MF, MI.getPostInstrSymbol());
508 setHeapAllocMarker(MF, MI.getHeapAllocMarker());
509}
510
511uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
512 // For now, the just return the union of the flags. If the flags get more
513 // complicated over time, we might need more logic here.
514 return getFlags() | Other.getFlags();
515}
516
517uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
518 uint16_t MIFlags = 0;
519 // Copy the wrapping flags.
520 if (const OverflowingBinaryOperator *OB =
521 dyn_cast<OverflowingBinaryOperator>(&I)) {
522 if (OB->hasNoSignedWrap())
523 MIFlags |= MachineInstr::MIFlag::NoSWrap;
524 if (OB->hasNoUnsignedWrap())
525 MIFlags |= MachineInstr::MIFlag::NoUWrap;
526 }
527
528 // Copy the exact flag.
529 if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
530 if (PE->isExact())
531 MIFlags |= MachineInstr::MIFlag::IsExact;
532
533 // Copy the fast-math flags.
534 if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
535 const FastMathFlags Flags = FP->getFastMathFlags();
536 if (Flags.noNaNs())
537 MIFlags |= MachineInstr::MIFlag::FmNoNans;
538 if (Flags.noInfs())
539 MIFlags |= MachineInstr::MIFlag::FmNoInfs;
540 if (Flags.noSignedZeros())
541 MIFlags |= MachineInstr::MIFlag::FmNsz;
542 if (Flags.allowReciprocal())
543 MIFlags |= MachineInstr::MIFlag::FmArcp;
544 if (Flags.allowContract())
545 MIFlags |= MachineInstr::MIFlag::FmContract;
546 if (Flags.approxFunc())
547 MIFlags |= MachineInstr::MIFlag::FmAfn;
548 if (Flags.allowReassoc())
549 MIFlags |= MachineInstr::MIFlag::FmReassoc;
550 }
551
552 return MIFlags;
553}
554
555void MachineInstr::copyIRFlags(const Instruction &I) {
556 Flags = copyFlagsFromInstruction(I);
557}
558
559bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
560 assert(!isBundledWithPred() && "Must be called on bundle header")(static_cast <bool> (!isBundledWithPred() && "Must be called on bundle header"
) ? void (0) : __assert_fail ("!isBundledWithPred() && \"Must be called on bundle header\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 560, __extension__ __PRETTY_FUNCTION__
))
;
561 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
562 if (MII->getDesc().getFlags() & Mask) {
563 if (Type == AnyInBundle)
564 return true;
565 } else {
566 if (Type == AllInBundle && !MII->isBundle())
567 return false;
568 }
569 // This was the last instruction in the bundle.
570 if (!MII->isBundledWithSucc())
571 return Type == AllInBundle;
572 }
573}
574
575bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
576 MICheckType Check) const {
577 // If opcodes or number of operands are not the same then the two
578 // instructions are obviously not identical.
579 if (Other.getOpcode() != getOpcode() ||
580 Other.getNumOperands() != getNumOperands())
581 return false;
582
583 if (isBundle()) {
584 // We have passed the test above that both instructions have the same
585 // opcode, so we know that both instructions are bundles here. Let's compare
586 // MIs inside the bundle.
587 assert(Other.isBundle() && "Expected that both instructions are bundles.")(static_cast <bool> (Other.isBundle() && "Expected that both instructions are bundles."
) ? void (0) : __assert_fail ("Other.isBundle() && \"Expected that both instructions are bundles.\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 587, __extension__ __PRETTY_FUNCTION__
))
;
588 MachineBasicBlock::const_instr_iterator I1 = getIterator();
589 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
590 // Loop until we analysed the last intruction inside at least one of the
591 // bundles.
592 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
593 ++I1;
594 ++I2;
595 if (!I1->isIdenticalTo(*I2, Check))
596 return false;
597 }
598 // If we've reached the end of just one of the two bundles, but not both,
599 // the instructions are not identical.
600 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
601 return false;
602 }
603
604 // Check operands to make sure they match.
605 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
606 const MachineOperand &MO = getOperand(i);
607 const MachineOperand &OMO = Other.getOperand(i);
608 if (!MO.isReg()) {
609 if (!MO.isIdenticalTo(OMO))
610 return false;
611 continue;
612 }
613
614 // Clients may or may not want to ignore defs when testing for equality.
615 // For example, machine CSE pass only cares about finding common
616 // subexpressions, so it's safe to ignore virtual register defs.
617 if (MO.isDef()) {
618 if (Check == IgnoreDefs)
619 continue;
620 else if (Check == IgnoreVRegDefs) {
621 if (!Register::isVirtualRegister(MO.getReg()) ||
622 !Register::isVirtualRegister(OMO.getReg()))
623 if (!MO.isIdenticalTo(OMO))
624 return false;
625 } else {
626 if (!MO.isIdenticalTo(OMO))
627 return false;
628 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
629 return false;
630 }
631 } else {
632 if (!MO.isIdenticalTo(OMO))
633 return false;
634 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
635 return false;
636 }
637 }
638 // If DebugLoc does not match then two debug instructions are not identical.
639 if (isDebugInstr())
640 if (getDebugLoc() && Other.getDebugLoc() &&
641 getDebugLoc() != Other.getDebugLoc())
642 return false;
643 // If pre- or post-instruction symbols do not match then the two instructions
644 // are not identical.
645 if (getPreInstrSymbol() != Other.getPreInstrSymbol() ||
646 getPostInstrSymbol() != Other.getPostInstrSymbol())
647 return false;
648 // Call instructions with different CFI types are not identical.
649 if (isCall() && getCFIType() != Other.getCFIType())
650 return false;
651
652 return true;
653}
654
655const MachineFunction *MachineInstr::getMF() const {
656 return getParent()->getParent();
657}
658
659MachineInstr *MachineInstr::removeFromParent() {
660 assert(getParent() && "Not embedded in a basic block!")(static_cast <bool> (getParent() && "Not embedded in a basic block!"
) ? void (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 660, __extension__ __PRETTY_FUNCTION__
))
;
661 return getParent()->remove(this);
662}
663
664MachineInstr *MachineInstr::removeFromBundle() {
665 assert(getParent() && "Not embedded in a basic block!")(static_cast <bool> (getParent() && "Not embedded in a basic block!"
) ? void (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 665, __extension__ __PRETTY_FUNCTION__
))
;
666 return getParent()->remove_instr(this);
667}
668
669void MachineInstr::eraseFromParent() {
670 assert(getParent() && "Not embedded in a basic block!")(static_cast <bool> (getParent() && "Not embedded in a basic block!"
) ? void (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 670, __extension__ __PRETTY_FUNCTION__
))
;
671 getParent()->erase(this);
672}
673
674void MachineInstr::eraseFromBundle() {
675 assert(getParent() && "Not embedded in a basic block!")(static_cast <bool> (getParent() && "Not embedded in a basic block!"
) ? void (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 675, __extension__ __PRETTY_FUNCTION__
))
;
676 getParent()->erase_instr(this);
677}
678
679bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const {
680 if (!isCall(Type))
681 return false;
682 switch (getOpcode()) {
683 case TargetOpcode::PATCHPOINT:
684 case TargetOpcode::STACKMAP:
685 case TargetOpcode::STATEPOINT:
686 case TargetOpcode::FENTRY_CALL:
687 return false;
688 }
689 return true;
690}
691
692bool MachineInstr::shouldUpdateCallSiteInfo() const {
693 if (isBundle())
694 return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle);
695 return isCandidateForCallSiteEntry();
696}
697
698unsigned MachineInstr::getNumExplicitOperands() const {
699 unsigned NumOperands = MCID->getNumOperands();
700 if (!MCID->isVariadic())
701 return NumOperands;
702
703 for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
704 const MachineOperand &MO = getOperand(I);
705 // The operands must always be in the following order:
706 // - explicit reg defs,
707 // - other explicit operands (reg uses, immediates, etc.),
708 // - implicit reg defs
709 // - implicit reg uses
710 if (MO.isReg() && MO.isImplicit())
711 break;
712 ++NumOperands;
713 }
714 return NumOperands;
715}
716
717unsigned MachineInstr::getNumExplicitDefs() const {
718 unsigned NumDefs = MCID->getNumDefs();
719 if (!MCID->isVariadic())
720 return NumDefs;
721
722 for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
723 const MachineOperand &MO = getOperand(I);
724 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
725 break;
726 ++NumDefs;
727 }
728 return NumDefs;
729}
730
731void MachineInstr::bundleWithPred() {
732 assert(!isBundledWithPred() && "MI is already bundled with its predecessor")(static_cast <bool> (!isBundledWithPred() && "MI is already bundled with its predecessor"
) ? void (0) : __assert_fail ("!isBundledWithPred() && \"MI is already bundled with its predecessor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 732, __extension__ __PRETTY_FUNCTION__
))
;
733 setFlag(BundledPred);
734 MachineBasicBlock::instr_iterator Pred = getIterator();
735 --Pred;
736 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags")(static_cast <bool> (!Pred->isBundledWithSucc() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("!Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 736, __extension__ __PRETTY_FUNCTION__
))
;
737 Pred->setFlag(BundledSucc);
738}
739
740void MachineInstr::bundleWithSucc() {
741 assert(!isBundledWithSucc() && "MI is already bundled with its successor")(static_cast <bool> (!isBundledWithSucc() && "MI is already bundled with its successor"
) ? void (0) : __assert_fail ("!isBundledWithSucc() && \"MI is already bundled with its successor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 741, __extension__ __PRETTY_FUNCTION__
))
;
742 setFlag(BundledSucc);
743 MachineBasicBlock::instr_iterator Succ = getIterator();
744 ++Succ;
745 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags")(static_cast <bool> (!Succ->isBundledWithPred() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("!Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 745, __extension__ __PRETTY_FUNCTION__
))
;
746 Succ->setFlag(BundledPred);
747}
748
749void MachineInstr::unbundleFromPred() {
750 assert(isBundledWithPred() && "MI isn't bundled with its predecessor")(static_cast <bool> (isBundledWithPred() && "MI isn't bundled with its predecessor"
) ? void (0) : __assert_fail ("isBundledWithPred() && \"MI isn't bundled with its predecessor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 750, __extension__ __PRETTY_FUNCTION__
))
;
751 clearFlag(BundledPred);
752 MachineBasicBlock::instr_iterator Pred = getIterator();
753 --Pred;
754 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags")(static_cast <bool> (Pred->isBundledWithSucc() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 754, __extension__ __PRETTY_FUNCTION__
))
;
755 Pred->clearFlag(BundledSucc);
756}
757
758void MachineInstr::unbundleFromSucc() {
759 assert(isBundledWithSucc() && "MI isn't bundled with its successor")(static_cast <bool> (isBundledWithSucc() && "MI isn't bundled with its successor"
) ? void (0) : __assert_fail ("isBundledWithSucc() && \"MI isn't bundled with its successor\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 759, __extension__ __PRETTY_FUNCTION__
))
;
760 clearFlag(BundledSucc);
761 MachineBasicBlock::instr_iterator Succ = getIterator();
762 ++Succ;
763 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags")(static_cast <bool> (Succ->isBundledWithPred() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 763, __extension__ __PRETTY_FUNCTION__
))
;
764 Succ->clearFlag(BundledPred);
765}
766
767bool MachineInstr::isStackAligningInlineAsm() const {
768 if (isInlineAsm()) {
769 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
770 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
771 return true;
772 }
773 return false;
774}
775
776InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
777 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!")(static_cast <bool> (isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"
) ? void (0) : __assert_fail ("isInlineAsm() && \"getInlineAsmDialect() only works for inline asms!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 777, __extension__ __PRETTY_FUNCTION__
))
;
778 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
779 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
780}
781
782int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
783 unsigned *GroupNo) const {
784 assert(isInlineAsm() && "Expected an inline asm instruction")(static_cast <bool> (isInlineAsm() && "Expected an inline asm instruction"
) ? void (0) : __assert_fail ("isInlineAsm() && \"Expected an inline asm instruction\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 784, __extension__ __PRETTY_FUNCTION__
))
;
785 assert(OpIdx < getNumOperands() && "OpIdx out of range")(static_cast <bool> (OpIdx < getNumOperands() &&
"OpIdx out of range") ? void (0) : __assert_fail ("OpIdx < getNumOperands() && \"OpIdx out of range\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 785, __extension__ __PRETTY_FUNCTION__
))
;
786
787 // Ignore queries about the initial operands.
788 if (OpIdx < InlineAsm::MIOp_FirstOperand)
789 return -1;
790
791 unsigned Group = 0;
792 unsigned NumOps;
793 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
794 i += NumOps) {
795 const MachineOperand &FlagMO = getOperand(i);
796 // If we reach the implicit register operands, stop looking.
797 if (!FlagMO.isImm())
798 return -1;
799 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
800 if (i + NumOps > OpIdx) {
801 if (GroupNo)
802 *GroupNo = Group;
803 return i;
804 }
805 ++Group;
806 }
807 return -1;
808}
809
810const DILabel *MachineInstr::getDebugLabel() const {
811 assert(isDebugLabel() && "not a DBG_LABEL")(static_cast <bool> (isDebugLabel() && "not a DBG_LABEL"
) ? void (0) : __assert_fail ("isDebugLabel() && \"not a DBG_LABEL\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 811, __extension__ __PRETTY_FUNCTION__
))
;
812 return cast<DILabel>(getOperand(0).getMetadata());
813}
814
815const MachineOperand &MachineInstr::getDebugVariableOp() const {
816 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*")(static_cast <bool> ((isDebugValue() || isDebugRef()) &&
"not a DBG_VALUE*") ? void (0) : __assert_fail ("(isDebugValue() || isDebugRef()) && \"not a DBG_VALUE*\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 816, __extension__ __PRETTY_FUNCTION__
))
;
817 unsigned VariableOp = isDebugValueList() ? 0 : 2;
818 return getOperand(VariableOp);
819}
820
821MachineOperand &MachineInstr::getDebugVariableOp() {
822 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*")(static_cast <bool> ((isDebugValue() || isDebugRef()) &&
"not a DBG_VALUE*") ? void (0) : __assert_fail ("(isDebugValue() || isDebugRef()) && \"not a DBG_VALUE*\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 822, __extension__ __PRETTY_FUNCTION__
))
;
823 unsigned VariableOp = isDebugValueList() ? 0 : 2;
824 return getOperand(VariableOp);
825}
826
827const DILocalVariable *MachineInstr::getDebugVariable() const {
828 return cast<DILocalVariable>(getDebugVariableOp().getMetadata());
829}
830
831const MachineOperand &MachineInstr::getDebugExpressionOp() const {
832 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*")(static_cast <bool> ((isDebugValue() || isDebugRef()) &&
"not a DBG_VALUE*") ? void (0) : __assert_fail ("(isDebugValue() || isDebugRef()) && \"not a DBG_VALUE*\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 832, __extension__ __PRETTY_FUNCTION__
))
;
833 unsigned ExpressionOp = isDebugValueList() ? 1 : 3;
834 return getOperand(ExpressionOp);
835}
836
837MachineOperand &MachineInstr::getDebugExpressionOp() {
838 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*")(static_cast <bool> ((isDebugValue() || isDebugRef()) &&
"not a DBG_VALUE*") ? void (0) : __assert_fail ("(isDebugValue() || isDebugRef()) && \"not a DBG_VALUE*\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 838, __extension__ __PRETTY_FUNCTION__
))
;
839 unsigned ExpressionOp = isDebugValueList() ? 1 : 3;
840 return getOperand(ExpressionOp);
841}
842
843const DIExpression *MachineInstr::getDebugExpression() const {
844 return cast<DIExpression>(getDebugExpressionOp().getMetadata());
845}
846
847bool MachineInstr::isDebugEntryValue() const {
848 return isDebugValue() && getDebugExpression()->isEntryValue();
849}
850
851const TargetRegisterClass*
852MachineInstr::getRegClassConstraint(unsigned OpIdx,
853 const TargetInstrInfo *TII,
854 const TargetRegisterInfo *TRI) const {
855 assert(getParent() && "Can't have an MBB reference here!")(static_cast <bool> (getParent() && "Can't have an MBB reference here!"
) ? void (0) : __assert_fail ("getParent() && \"Can't have an MBB reference here!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 855, __extension__ __PRETTY_FUNCTION__
))
;
856 assert(getMF() && "Can't have an MF reference here!")(static_cast <bool> (getMF() && "Can't have an MF reference here!"
) ? void (0) : __assert_fail ("getMF() && \"Can't have an MF reference here!\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 856, __extension__ __PRETTY_FUNCTION__
))
;
857 const MachineFunction &MF = *getMF();
858
859 // Most opcodes have fixed constraints in their MCInstrDesc.
860 if (!isInlineAsm())
861 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
862
863 if (!getOperand(OpIdx).isReg())
864 return nullptr;
865
866 // For tied uses on inline asm, get the constraint from the def.
867 unsigned DefIdx;
868 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
869 OpIdx = DefIdx;
870
871 // Inline asm stores register class constraints in the flag word.
872 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
873 if (FlagIdx < 0)
874 return nullptr;
875
876 unsigned Flag = getOperand(FlagIdx).getImm();
877 unsigned RCID;
878 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
879 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
880 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
881 InlineAsm::hasRegClassConstraint(Flag, RCID))
882 return TRI->getRegClass(RCID);
883
884 // Assume that all registers in a memory operand are pointers.
885 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
886 return TRI->getPointerRegClass(MF);
887
888 return nullptr;
889}
890
891const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
892 Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
893 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
894 // Check every operands inside the bundle if we have
895 // been asked to.
896 if (ExploreBundle)
897 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
898 ++OpndIt)
899 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
900 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
901 else
902 // Otherwise, just check the current operands.
903 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
904 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
905 return CurRC;
906}
907
908const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
909 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
910 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
911 assert(CurRC && "Invalid initial register class")(static_cast <bool> (CurRC && "Invalid initial register class"
) ? void (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 911, __extension__ __PRETTY_FUNCTION__
))
;
912 // Check if Reg is constrained by some of its use/def from MI.
913 const MachineOperand &MO = getOperand(OpIdx);
914 if (!MO.isReg() || MO.getReg() != Reg)
915 return CurRC;
916 // If yes, accumulate the constraints through the operand.
917 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
918}
919
920const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
921 unsigned OpIdx, const TargetRegisterClass *CurRC,
922 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
923 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
924 const MachineOperand &MO = getOperand(OpIdx);
925 assert(MO.isReg() &&(static_cast <bool> (MO.isReg() && "Cannot get register constraints for non-register operand"
) ? void (0) : __assert_fail ("MO.isReg() && \"Cannot get register constraints for non-register operand\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 926, __extension__ __PRETTY_FUNCTION__
))
926 "Cannot get register constraints for non-register operand")(static_cast <bool> (MO.isReg() && "Cannot get register constraints for non-register operand"
) ? void (0) : __assert_fail ("MO.isReg() && \"Cannot get register constraints for non-register operand\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 926, __extension__ __PRETTY_FUNCTION__
))
;
927 assert(CurRC && "Invalid initial register class")(static_cast <bool> (CurRC && "Invalid initial register class"
) ? void (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 927, __extension__ __PRETTY_FUNCTION__
))
;
928 if (unsigned SubIdx = MO.getSubReg()) {
929 if (OpRC)
930 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
931 else
932 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
933 } else if (OpRC)
934 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
935 return CurRC;
936}
937
938/// Return the number of instructions inside the MI bundle, not counting the
939/// header instruction.
940unsigned MachineInstr::getBundleSize() const {
941 MachineBasicBlock::const_instr_iterator I = getIterator();
942 unsigned Size = 0;
943 while (I->isBundledWithSucc()) {
944 ++Size;
945 ++I;
946 }
947 return Size;
948}
949
950/// Returns true if the MachineInstr has an implicit-use operand of exactly
951/// the given register (not considering sub/super-registers).
952bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
953 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
954 const MachineOperand &MO = getOperand(i);
955 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
956 return true;
957 }
958 return false;
959}
960
961/// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
962/// the specific register or -1 if it is not found. It further tightens
963/// the search criteria to a use that kills the register if isKill is true.
964int MachineInstr::findRegisterUseOperandIdx(
965 Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
966 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
967 const MachineOperand &MO = getOperand(i);
968 if (!MO.isReg() || !MO.isUse())
969 continue;
970 Register MOReg = MO.getReg();
971 if (!MOReg)
972 continue;
973 if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
974 if (!isKill || MO.isKill())
975 return i;
976 }
977 return -1;
978}
979
980/// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
981/// indicating if this instruction reads or writes Reg. This also considers
982/// partial defines.
983std::pair<bool,bool>
984MachineInstr::readsWritesVirtualRegister(Register Reg,
985 SmallVectorImpl<unsigned> *Ops) const {
986 bool PartDef = false; // Partial redefine.
987 bool FullDef = false; // Full define.
988 bool Use = false;
989
990 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
991 const MachineOperand &MO = getOperand(i);
992 if (!MO.isReg() || MO.getReg() != Reg)
993 continue;
994 if (Ops)
995 Ops->push_back(i);
996 if (MO.isUse())
997 Use |= !MO.isUndef();
998 else if (MO.getSubReg() && !MO.isUndef())
999 // A partial def undef doesn't count as reading the register.
1000 PartDef = true;
1001 else
1002 FullDef = true;
1003 }
1004 // A partial redefine uses Reg unless there is also a full define.
1005 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1006}
1007
1008/// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1009/// the specified register or -1 if it is not found. If isDead is true, defs
1010/// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1011/// also checks if there is a def of a super-register.
1012int
1013MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
1014 const TargetRegisterInfo *TRI) const {
1015 bool isPhys = Register::isPhysicalRegister(Reg);
1016 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1017 const MachineOperand &MO = getOperand(i);
1018 // Accept regmask operands when Overlap is set.
1019 // Ignore them when looking for a specific def operand (Overlap == false).
1020 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1021 return i;
1022 if (!MO.isReg() || !MO.isDef())
1023 continue;
1024 Register MOReg = MO.getReg();
1025 bool Found = (MOReg == Reg);
1026 if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) {
1027 if (Overlap)
1028 Found = TRI->regsOverlap(MOReg, Reg);
1029 else
1030 Found = TRI->isSubRegister(MOReg, Reg);
1031 }
1032 if (Found && (!isDead || MO.isDead()))
1033 return i;
1034 }
1035 return -1;
1036}
1037
1038/// findFirstPredOperandIdx() - Find the index of the first operand in the
1039/// operand list that is used to represent the predicate. It returns -1 if
1040/// none is found.
1041int MachineInstr::findFirstPredOperandIdx() const {
1042 // Don't call MCID.findFirstPredOperandIdx() because this variant
1043 // is sometimes called on an instruction that's not yet complete, and
1044 // so the number of operands is less than the MCID indicates. In
1045 // particular, the PTX target does this.
1046 const MCInstrDesc &MCID = getDesc();
1047 if (MCID.isPredicable()) {
1048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1049 if (MCID.OpInfo[i].isPredicate())
1050 return i;
1051 }
1052
1053 return -1;
1054}
1055
1056// MachineOperand::TiedTo is 4 bits wide.
1057const unsigned TiedMax = 15;
1058
1059/// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1060///
1061/// Use and def operands can be tied together, indicated by a non-zero TiedTo
1062/// field. TiedTo can have these values:
1063///
1064/// 0: Operand is not tied to anything.
1065/// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1066/// TiedMax: Tied to an operand >= TiedMax-1.
1067///
1068/// The tied def must be one of the first TiedMax operands on a normal
1069/// instruction. INLINEASM instructions allow more tied defs.
1070///
1071void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1072 MachineOperand &DefMO = getOperand(DefIdx);
1073 MachineOperand &UseMO = getOperand(UseIdx);
1074 assert(DefMO.isDef() && "DefIdx must be a def operand")(static_cast <bool> (DefMO.isDef() && "DefIdx must be a def operand"
) ? void (0) : __assert_fail ("DefMO.isDef() && \"DefIdx must be a def operand\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1074, __extension__ __PRETTY_FUNCTION__
))
;
1075 assert(UseMO.isUse() && "UseIdx must be a use operand")(static_cast <bool> (UseMO.isUse() && "UseIdx must be a use operand"
) ? void (0) : __assert_fail ("UseMO.isUse() && \"UseIdx must be a use operand\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1075, __extension__ __PRETTY_FUNCTION__
))
;
1076 assert(!DefMO.isTied() && "Def is already tied to another use")(static_cast <bool> (!DefMO.isTied() && "Def is already tied to another use"
) ? void (0) : __assert_fail ("!DefMO.isTied() && \"Def is already tied to another use\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1076, __extension__ __PRETTY_FUNCTION__
))
;
1077 assert(!UseMO.isTied() && "Use is already tied to another def")(static_cast <bool> (!UseMO.isTied() && "Use is already tied to another def"
) ? void (0) : __assert_fail ("!UseMO.isTied() && \"Use is already tied to another def\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1077, __extension__ __PRETTY_FUNCTION__
))
;
1078
1079 if (DefIdx < TiedMax)
1080 UseMO.TiedTo = DefIdx + 1;
1081 else {
1082 // Inline asm can use the group descriptors to find tied operands,
1083 // statepoint tied operands are trivial to match (1-1 reg def with reg use),
1084 // but on normal instruction, the tied def must be within the first TiedMax
1085 // operands.
1086 assert((isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) &&(static_cast <bool> ((isInlineAsm() || getOpcode() == TargetOpcode
::STATEPOINT) && "DefIdx out of range") ? void (0) : __assert_fail
("(isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) && \"DefIdx out of range\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1087, __extension__ __PRETTY_FUNCTION__
))
1087 "DefIdx out of range")(static_cast <bool> ((isInlineAsm() || getOpcode() == TargetOpcode
::STATEPOINT) && "DefIdx out of range") ? void (0) : __assert_fail
("(isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) && \"DefIdx out of range\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1087, __extension__ __PRETTY_FUNCTION__
))
;
1088 UseMO.TiedTo = TiedMax;
1089 }
1090
1091 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1092 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1093}
1094
1095/// Given the index of a tied register operand, find the operand it is tied to.
1096/// Defs are tied to uses and vice versa. Returns the index of the tied operand
1097/// which must exist.
1098unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1099 const MachineOperand &MO = getOperand(OpIdx);
1100 assert(MO.isTied() && "Operand isn't tied")(static_cast <bool> (MO.isTied() && "Operand isn't tied"
) ? void (0) : __assert_fail ("MO.isTied() && \"Operand isn't tied\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1100, __extension__ __PRETTY_FUNCTION__
))
;
1101
1102 // Normally TiedTo is in range.
1103 if (MO.TiedTo < TiedMax)
1104 return MO.TiedTo - 1;
1105
1106 // Uses on normal instructions can be out of range.
1107 if (!isInlineAsm() && getOpcode() != TargetOpcode::STATEPOINT) {
1108 // Normal tied defs must be in the 0..TiedMax-1 range.
1109 if (MO.isUse())
1110 return TiedMax - 1;
1111 // MO is a def. Search for the tied use.
1112 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1113 const MachineOperand &UseMO = getOperand(i);
1114 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1115 return i;
1116 }
1117 llvm_unreachable("Can't find tied use")::llvm::llvm_unreachable_internal("Can't find tied use", "llvm/lib/CodeGen/MachineInstr.cpp"
, 1117)
;
1118 }
1119
1120 if (getOpcode() == TargetOpcode::STATEPOINT) {
1121 // In STATEPOINT defs correspond 1-1 to GC pointer operands passed
1122 // on registers.
1123 StatepointOpers SO(this);
1124 unsigned CurUseIdx = SO.getFirstGCPtrIdx();
1125 assert(CurUseIdx != -1U && "only gc pointer statepoint operands can be tied")(static_cast <bool> (CurUseIdx != -1U && "only gc pointer statepoint operands can be tied"
) ? void (0) : __assert_fail ("CurUseIdx != -1U && \"only gc pointer statepoint operands can be tied\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1125, __extension__ __PRETTY_FUNCTION__
))
;
1126 unsigned NumDefs = getNumDefs();
1127 for (unsigned CurDefIdx = 0; CurDefIdx < NumDefs; ++CurDefIdx) {
1128 while (!getOperand(CurUseIdx).isReg())
1129 CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1130 if (OpIdx == CurDefIdx)
1131 return CurUseIdx;
1132 if (OpIdx == CurUseIdx)
1133 return CurDefIdx;
1134 CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1135 }
1136 llvm_unreachable("Can't find tied use")::llvm::llvm_unreachable_internal("Can't find tied use", "llvm/lib/CodeGen/MachineInstr.cpp"
, 1136)
;
1137 }
1138
1139 // Now deal with inline asm by parsing the operand group descriptor flags.
1140 // Find the beginning of each operand group.
1141 SmallVector<unsigned, 8> GroupIdx;
1142 unsigned OpIdxGroup = ~0u;
1143 unsigned NumOps;
1144 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1145 i += NumOps) {
1146 const MachineOperand &FlagMO = getOperand(i);
1147 assert(FlagMO.isImm() && "Invalid tied operand on inline asm")(static_cast <bool> (FlagMO.isImm() && "Invalid tied operand on inline asm"
) ? void (0) : __assert_fail ("FlagMO.isImm() && \"Invalid tied operand on inline asm\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1147, __extension__ __PRETTY_FUNCTION__
))
;
1148 unsigned CurGroup = GroupIdx.size();
1149 GroupIdx.push_back(i);
1150 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1151 // OpIdx belongs to this operand group.
1152 if (OpIdx > i && OpIdx < i + NumOps)
1153 OpIdxGroup = CurGroup;
1154 unsigned TiedGroup;
1155 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1156 continue;
1157 // Operands in this group are tied to operands in TiedGroup which must be
1158 // earlier. Find the number of operands between the two groups.
1159 unsigned Delta = i - GroupIdx[TiedGroup];
1160
1161 // OpIdx is a use tied to TiedGroup.
1162 if (OpIdxGroup == CurGroup)
1163 return OpIdx - Delta;
1164
1165 // OpIdx is a def tied to this use group.
1166 if (OpIdxGroup == TiedGroup)
1167 return OpIdx + Delta;
1168 }
1169 llvm_unreachable("Invalid tied operand on inline asm")::llvm::llvm_unreachable_internal("Invalid tied operand on inline asm"
, "llvm/lib/CodeGen/MachineInstr.cpp", 1169)
;
1170}
1171
1172/// clearKillInfo - Clears kill flags on all operands.
1173///
1174void MachineInstr::clearKillInfo() {
1175 for (MachineOperand &MO : operands()) {
1176 if (MO.isReg() && MO.isUse())
1177 MO.setIsKill(false);
1178 }
1179}
1180
1181void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
1182 unsigned SubIdx,
1183 const TargetRegisterInfo &RegInfo) {
1184 if (Register::isPhysicalRegister(ToReg)) {
1185 if (SubIdx)
1186 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1187 for (MachineOperand &MO : operands()) {
1188 if (!MO.isReg() || MO.getReg() != FromReg)
1189 continue;
1190 MO.substPhysReg(ToReg, RegInfo);
1191 }
1192 } else {
1193 for (MachineOperand &MO : operands()) {
1194 if (!MO.isReg() || MO.getReg() != FromReg)
1195 continue;
1196 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1197 }
1198 }
1199}
1200
1201/// isSafeToMove - Return true if it is safe to move this instruction. If
1202/// SawStore is set to true, it means that there is a store (or call) between
1203/// the instruction's location and its intended destination.
1204bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const {
1205 // Ignore stuff that we obviously can't move.
1206 //
1207 // Treat volatile loads as stores. This is not strictly necessary for
1208 // volatiles, but it is required for atomic loads. It is not allowed to move
1209 // a load across an atomic load with Ordering > Monotonic.
1210 if (mayStore() || isCall() || isPHI() ||
1211 (mayLoad() && hasOrderedMemoryRef())) {
1212 SawStore = true;
1213 return false;
1214 }
1215
1216 if (isPosition() || isDebugInstr() || isTerminator() ||
1217 mayRaiseFPException() || hasUnmodeledSideEffects())
1218 return false;
1219
1220 // See if this instruction does a load. If so, we have to guarantee that the
1221 // loaded value doesn't change between the load and the its intended
1222 // destination. The check for isInvariantLoad gives the target the chance to
1223 // classify the load as always returning a constant, e.g. a constant pool
1224 // load.
1225 if (mayLoad() && !isDereferenceableInvariantLoad())
1226 // Otherwise, this is a real load. If there is a store between the load and
1227 // end of block, we can't move it.
1228 return !SawStore;
1229
1230 return true;
1231}
1232
1233static bool MemOperandsHaveAlias(const MachineFrameInfo &MFI, AAResults *AA,
1234 bool UseTBAA, const MachineMemOperand *MMOa,
1235 const MachineMemOperand *MMOb) {
1236 // The following interface to AA is fashioned after DAGCombiner::isAlias and
1237 // operates with MachineMemOperand offset with some important assumptions:
1238 // - LLVM fundamentally assumes flat address spaces.
1239 // - MachineOperand offset can *only* result from legalization and cannot
1240 // affect queries other than the trivial case of overlap checking.
1241 // - These offsets never wrap and never step outside of allocated objects.
1242 // - There should never be any negative offsets here.
1243 //
1244 // FIXME: Modify API to hide this math from "user"
1245 // Even before we go to AA we can reason locally about some memory objects. It
1246 // can save compile time, and possibly catch some corner cases not currently
1247 // covered.
1248
1249 int64_t OffsetA = MMOa->getOffset();
1250 int64_t OffsetB = MMOb->getOffset();
1251 int64_t MinOffset = std::min(OffsetA, OffsetB);
1252
1253 uint64_t WidthA = MMOa->getSize();
1254 uint64_t WidthB = MMOb->getSize();
1255 bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
1256 bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
1257
1258 const Value *ValA = MMOa->getValue();
1259 const Value *ValB = MMOb->getValue();
1260 bool SameVal = (ValA && ValB && (ValA == ValB));
1261 if (!SameVal) {
1262 const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1263 const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1264 if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1265 return false;
1266 if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1267 return false;
1268 if (PSVa && PSVb && (PSVa == PSVb))
1269 SameVal = true;
1270 }
1271
1272 if (SameVal) {
1273 if (!KnownWidthA || !KnownWidthB)
1274 return true;
1275 int64_t MaxOffset = std::max(OffsetA, OffsetB);
1276 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1277 return (MinOffset + LowWidth > MaxOffset);
1278 }
1279
1280 if (!AA)
1281 return true;
1282
1283 if (!ValA || !ValB)
1284 return true;
1285
1286 assert((OffsetA >= 0) && "Negative MachineMemOperand offset")(static_cast <bool> ((OffsetA >= 0) && "Negative MachineMemOperand offset"
) ? void (0) : __assert_fail ("(OffsetA >= 0) && \"Negative MachineMemOperand offset\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1286, __extension__ __PRETTY_FUNCTION__
))
;
1287 assert((OffsetB >= 0) && "Negative MachineMemOperand offset")(static_cast <bool> ((OffsetB >= 0) && "Negative MachineMemOperand offset"
) ? void (0) : __assert_fail ("(OffsetB >= 0) && \"Negative MachineMemOperand offset\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1287, __extension__ __PRETTY_FUNCTION__
))
;
1288
1289 int64_t OverlapA =
1290 KnownWidthA ? WidthA + OffsetA - MinOffset : MemoryLocation::UnknownSize;
1291 int64_t OverlapB =
1292 KnownWidthB ? WidthB + OffsetB - MinOffset : MemoryLocation::UnknownSize;
1293
1294 return !AA->isNoAlias(
1295 MemoryLocation(ValA, OverlapA, UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1296 MemoryLocation(ValB, OverlapB,
1297 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1298}
1299
1300bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other,
1301 bool UseTBAA) const {
1302 const MachineFunction *MF = getMF();
1303 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1304 const MachineFrameInfo &MFI = MF->getFrameInfo();
1305
1306 // Exclude call instruction which may alter the memory but can not be handled
1307 // by this function.
1308 if (isCall() || Other.isCall())
1309 return true;
1310
1311 // If neither instruction stores to memory, they can't alias in any
1312 // meaningful way, even if they read from the same address.
1313 if (!mayStore() && !Other.mayStore())
1314 return false;
1315
1316 // Both instructions must be memory operations to be able to alias.
1317 if (!mayLoadOrStore() || !Other.mayLoadOrStore())
1318 return false;
1319
1320 // Let the target decide if memory accesses cannot possibly overlap.
1321 if (TII->areMemAccessesTriviallyDisjoint(*this, Other))
1322 return false;
1323
1324 // Memory operations without memory operands may access anything. Be
1325 // conservative and assume `MayAlias`.
1326 if (memoperands_empty() || Other.memoperands_empty())
1327 return true;
1328
1329 // Skip if there are too many memory operands.
1330 auto NumChecks = getNumMemOperands() * Other.getNumMemOperands();
1331 if (NumChecks > TII->getMemOperandAACheckLimit())
1332 return true;
1333
1334 // Check each pair of memory operands from both instructions, which can't
1335 // alias only if all pairs won't alias.
1336 for (auto *MMOa : memoperands())
1337 for (auto *MMOb : Other.memoperands())
1338 if (MemOperandsHaveAlias(MFI, AA, UseTBAA, MMOa, MMOb))
1339 return true;
1340
1341 return false;
1342}
1343
1344/// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1345/// or volatile memory reference, or if the information describing the memory
1346/// reference is not available. Return false if it is known to have no ordered
1347/// memory references.
1348bool MachineInstr::hasOrderedMemoryRef() const {
1349 // An instruction known never to access memory won't have a volatile access.
1350 if (!mayStore() &&
1351 !mayLoad() &&
1352 !isCall() &&
1353 !hasUnmodeledSideEffects())
1354 return false;
1355
1356 // Otherwise, if the instruction has no memory reference information,
1357 // conservatively assume it wasn't preserved.
1358 if (memoperands_empty())
1359 return true;
1360
1361 // Check if any of our memory operands are ordered.
1362 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1363 return !MMO->isUnordered();
1364 });
1365}
1366
1367/// isDereferenceableInvariantLoad - Return true if this instruction will never
1368/// trap and is loading from a location whose value is invariant across a run of
1369/// this function.
1370bool MachineInstr::isDereferenceableInvariantLoad() const {
1371 // If the instruction doesn't load at all, it isn't an invariant load.
1372 if (!mayLoad())
1373 return false;
1374
1375 // If the instruction has lost its memoperands, conservatively assume that
1376 // it may not be an invariant load.
1377 if (memoperands_empty())
1378 return false;
1379
1380 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1381
1382 for (MachineMemOperand *MMO : memoperands()) {
1383 if (!MMO->isUnordered())
1384 // If the memory operand has ordering side effects, we can't move the
1385 // instruction. Such an instruction is technically an invariant load,
1386 // but the caller code would need updated to expect that.
1387 return false;
1388 if (MMO->isStore()) return false;
1389 if (MMO->isInvariant() && MMO->isDereferenceable())
1390 continue;
1391
1392 // A load from a constant PseudoSourceValue is invariant.
1393 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
1394 if (PSV->isConstant(&MFI))
1395 continue;
1396 }
1397
1398 // Otherwise assume conservatively.
1399 return false;
1400 }
1401
1402 // Everything checks out.
1403 return true;
1404}
1405
1406/// isConstantValuePHI - If the specified instruction is a PHI that always
1407/// merges together the same virtual register, return the register, otherwise
1408/// return 0.
1409unsigned MachineInstr::isConstantValuePHI() const {
1410 if (!isPHI())
1411 return 0;
1412 assert(getNumOperands() >= 3 &&(static_cast <bool> (getNumOperands() >= 3 &&
"It's illegal to have a PHI without source operands") ? void
(0) : __assert_fail ("getNumOperands() >= 3 && \"It's illegal to have a PHI without source operands\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1413, __extension__ __PRETTY_FUNCTION__
))
1413 "It's illegal to have a PHI without source operands")(static_cast <bool> (getNumOperands() >= 3 &&
"It's illegal to have a PHI without source operands") ? void
(0) : __assert_fail ("getNumOperands() >= 3 && \"It's illegal to have a PHI without source operands\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1413, __extension__ __PRETTY_FUNCTION__
))
;
1414
1415 Register Reg = getOperand(1).getReg();
1416 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1417 if (getOperand(i).getReg() != Reg)
1418 return 0;
1419 return Reg;
1420}
1421
1422bool MachineInstr::hasUnmodeledSideEffects() const {
1423 if (hasProperty(MCID::UnmodeledSideEffects))
1424 return true;
1425 if (isInlineAsm()) {
1426 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1427 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1428 return true;
1429 }
1430
1431 return false;
1432}
1433
1434bool MachineInstr::isLoadFoldBarrier() const {
1435 return mayStore() || isCall() ||
1436 (hasUnmodeledSideEffects() && !isPseudoProbe());
1437}
1438
1439/// allDefsAreDead - Return true if all the defs of this instruction are dead.
1440///
1441bool MachineInstr::allDefsAreDead() const {
1442 for (const MachineOperand &MO : operands()) {
1443 if (!MO.isReg() || MO.isUse())
1444 continue;
1445 if (!MO.isDead())
1446 return false;
1447 }
1448 return true;
1449}
1450
1451/// copyImplicitOps - Copy implicit register operands from specified
1452/// instruction to this instruction.
1453void MachineInstr::copyImplicitOps(MachineFunction &MF,
1454 const MachineInstr &MI) {
1455 for (const MachineOperand &MO :
1456 llvm::drop_begin(MI.operands(), MI.getDesc().getNumOperands()))
1457 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1458 addOperand(MF, MO);
1459}
1460
1461bool MachineInstr::hasComplexRegisterTies() const {
1462 const MCInstrDesc &MCID = getDesc();
1463 if (MCID.Opcode == TargetOpcode::STATEPOINT)
1464 return true;
1465 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1466 const auto &Operand = getOperand(I);
1467 if (!Operand.isReg() || Operand.isDef())
1468 // Ignore the defined registers as MCID marks only the uses as tied.
1469 continue;
1470 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
1471 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
1472 if (ExpectedTiedIdx != TiedIdx)
1473 return true;
1474 }
1475 return false;
1476}
1477
1478LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1479 const MachineRegisterInfo &MRI) const {
1480 const MachineOperand &Op = getOperand(OpIdx);
1481 if (!Op.isReg())
1482 return LLT{};
1483
1484 if (isVariadic() || OpIdx >= getNumExplicitOperands())
1485 return MRI.getType(Op.getReg());
1486
1487 auto &OpInfo = getDesc().OpInfo[OpIdx];
1488 if (!OpInfo.isGenericType())
1489 return MRI.getType(Op.getReg());
1490
1491 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
1492 return LLT{};
1493
1494 LLT TypeToPrint = MRI.getType(Op.getReg());
1495 // Don't mark the type index printed if it wasn't actually printed: maybe
1496 // another operand with the same type index has an actual type attached:
1497 if (TypeToPrint.isValid())
1498 PrintedTypes.set(OpInfo.getGenericTypeIndex());
1499 return TypeToPrint;
1500}
1501
1502#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1503LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dump() const {
1504 dbgs() << " ";
1505 print(dbgs());
1506}
1507
1508LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dumprImpl(
1509 const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
1510 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const {
1511 if (Depth >= MaxDepth)
1512 return;
1513 if (!AlreadySeenInstrs.insert(this).second)
1514 return;
1515 // PadToColumn always inserts at least one space.
1516 // Don't mess up the alignment if we don't want any space.
1517 if (Depth)
1518 fdbgs().PadToColumn(Depth * 2);
1519 print(fdbgs());
1520 for (const MachineOperand &MO : operands()) {
1521 if (!MO.isReg() || MO.isDef())
1522 continue;
1523 Register Reg = MO.getReg();
1524 if (Reg.isPhysical())
1525 continue;
1526 const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg);
1527 if (NewMI == nullptr)
1528 continue;
1529 NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs);
1530 }
1531}
1532
1533LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dumpr(const MachineRegisterInfo &MRI,
1534 unsigned MaxDepth) const {
1535 SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs;
1536 dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs);
1537}
1538#endif
1539
1540void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
1541 bool SkipDebugLoc, bool AddNewLine,
1542 const TargetInstrInfo *TII) const {
1543 const Module *M = nullptr;
1544 const Function *F = nullptr;
1545 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1546 F = &MF->getFunction();
1547 M = F->getParent();
1548 if (!TII)
1549 TII = MF->getSubtarget().getInstrInfo();
1550 }
1551
1552 ModuleSlotTracker MST(M);
1553 if (F)
1554 MST.incorporateFunction(*F);
1555 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
1556}
1557
1558void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1559 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
1560 bool AddNewLine, const TargetInstrInfo *TII) const {
1561 // We can be a bit tidier if we know the MachineFunction.
1562 const TargetRegisterInfo *TRI = nullptr;
1563 const MachineRegisterInfo *MRI = nullptr;
1564 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1565 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
1566
1567 if (isCFIInstruction())
1568 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction")(static_cast <bool> (getNumOperands() == 1 && "Expected 1 operand in CFI instruction"
) ? void (0) : __assert_fail ("getNumOperands() == 1 && \"Expected 1 operand in CFI instruction\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 1568, __extension__ __PRETTY_FUNCTION__
))
;
1569
1570 SmallBitVector PrintedTypes(8);
1571 bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
1572 auto getTiedOperandIdx = [&](unsigned OpIdx) {
1573 if (!ShouldPrintRegisterTies)
1574 return 0U;
1575 const MachineOperand &MO = getOperand(OpIdx);
1576 if (MO.isReg() && MO.isTied() && !MO.isDef())
1577 return findTiedOperandIdx(OpIdx);
1578 return 0U;
1579 };
1580 unsigned StartOp = 0;
1581 unsigned e = getNumOperands();
1582
1583 // Print explicitly defined operands on the left of an assignment syntax.
1584 while (StartOp < e) {
1585 const MachineOperand &MO = getOperand(StartOp);
1586 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
1587 break;
1588
1589 if (StartOp != 0)
1590 OS << ", ";
1591
1592 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
1593 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
1594 MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone,
1595 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1596 ++StartOp;
1597 }
1598
1599 if (StartOp != 0)
1600 OS << " = ";
1601
1602 if (getFlag(MachineInstr::FrameSetup))
1603 OS << "frame-setup ";
1604 if (getFlag(MachineInstr::FrameDestroy))
1605 OS << "frame-destroy ";
1606 if (getFlag(MachineInstr::FmNoNans))
1607 OS << "nnan ";
1608 if (getFlag(MachineInstr::FmNoInfs))
1609 OS << "ninf ";
1610 if (getFlag(MachineInstr::FmNsz))
1611 OS << "nsz ";
1612 if (getFlag(MachineInstr::FmArcp))
1613 OS << "arcp ";
1614 if (getFlag(MachineInstr::FmContract))
1615 OS << "contract ";
1616 if (getFlag(MachineInstr::FmAfn))
1617 OS << "afn ";
1618 if (getFlag(MachineInstr::FmReassoc))
1619 OS << "reassoc ";
1620 if (getFlag(MachineInstr::NoUWrap))
1621 OS << "nuw ";
1622 if (getFlag(MachineInstr::NoSWrap))
1623 OS << "nsw ";
1624 if (getFlag(MachineInstr::IsExact))
1625 OS << "exact ";
1626 if (getFlag(MachineInstr::NoFPExcept))
1627 OS << "nofpexcept ";
1628 if (getFlag(MachineInstr::NoMerge))
1629 OS << "nomerge ";
1630
1631 // Print the opcode name.
1632 if (TII)
1633 OS << TII->getName(getOpcode());
1634 else
1635 OS << "UNKNOWN";
1636
1637 if (SkipOpers)
1638 return;
1639
1640 // Print the rest of the operands.
1641 bool FirstOp = true;
1642 unsigned AsmDescOp = ~0u;
1643 unsigned AsmOpCount = 0;
1644
1645 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1646 // Print asm string.
1647 OS << " ";
1648 const unsigned OpIdx = InlineAsm::MIOp_AsmString;
1649 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
1650 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
1651 getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone,
1652 ShouldPrintRegisterTies, TiedOperandIdx, TRI,
1653 IntrinsicInfo);
1654
1655 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1656 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1657 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1658 OS << " [sideeffect]";
1659 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1660 OS << " [mayload]";
1661 if (ExtraInfo & InlineAsm::Extra_MayStore)
1662 OS << " [maystore]";
1663 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1664 OS << " [isconvergent]";
1665 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1666 OS << " [alignstack]";
1667 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1668 OS << " [attdialect]";
1669 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1670 OS << " [inteldialect]";
1671
1672 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1673 FirstOp = false;
1674 }
1675
1676 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1677 const MachineOperand &MO = getOperand(i);
1678
1679 if (FirstOp) FirstOp = false; else OS << ",";
1680 OS << " ";
1681
1682 if (isDebugValue() && MO.isMetadata()) {
1683 // Pretty print DBG_VALUE* instructions.
1684 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1685 if (DIV && !DIV->getName().empty())
1686 OS << "!\"" << DIV->getName() << '\"';
1687 else {
1688 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1689 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1690 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1691 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1692 }
1693 } else if (isDebugLabel() && MO.isMetadata()) {
1694 // Pretty print DBG_LABEL instructions.
1695 auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
1696 if (DIL && !DIL->getName().empty())
1697 OS << "\"" << DIL->getName() << '\"';
1698 else {
1699 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1700 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1701 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1702 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1703 }
1704 } else if (i == AsmDescOp && MO.isImm()) {
1705 // Pretty print the inline asm operand descriptor.
1706 OS << '$' << AsmOpCount++;
1707 unsigned Flag = MO.getImm();
1708 OS << ":[";
1709 OS << InlineAsm::getKindName(InlineAsm::getKind(Flag));
1710
1711 unsigned RCID = 0;
1712 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1713 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1714 if (TRI) {
1715 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1716 } else
1717 OS << ":RC" << RCID;
1718 }
1719
1720 if (InlineAsm::isMemKind(Flag)) {
1721 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1722 OS << ":" << InlineAsm::getMemConstraintName(MCID);
1723 }
1724
1725 unsigned TiedTo = 0;
1726 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1727 OS << " tiedto:$" << TiedTo;
1728
1729 OS << ']';
1730
1731 // Compute the index of the next operand descriptor.
1732 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1733 } else {
1734 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1735 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1736 if (MO.isImm() && isOperandSubregIdx(i))
1737 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
1738 else
1739 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1740 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1741 }
1742 }
1743
1744 // Print any optional symbols attached to this instruction as-if they were
1745 // operands.
1746 if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
1747 if (!FirstOp) {
1748 FirstOp = false;
1749 OS << ',';
1750 }
1751 OS << " pre-instr-symbol ";
1752 MachineOperand::printSymbol(OS, *PreInstrSymbol);
1753 }
1754 if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
1755 if (!FirstOp) {
1756 FirstOp = false;
1757 OS << ',';
1758 }
1759 OS << " post-instr-symbol ";
1760 MachineOperand::printSymbol(OS, *PostInstrSymbol);
1761 }
1762 if (MDNode *HeapAllocMarker = getHeapAllocMarker()) {
1763 if (!FirstOp) {
1764 FirstOp = false;
1765 OS << ',';
1766 }
1767 OS << " heap-alloc-marker ";
1768 HeapAllocMarker->printAsOperand(OS, MST);
1769 }
1770 if (uint32_t CFIType = getCFIType()) {
1771 if (!FirstOp)
1772 OS << ',';
1773 OS << " cfi-type " << CFIType;
1774 }
1775
1776 if (DebugInstrNum) {
1777 if (!FirstOp)
1778 OS << ",";
1779 OS << " debug-instr-number " << DebugInstrNum;
1780 }
1781
1782 if (!SkipDebugLoc) {
1783 if (const DebugLoc &DL = getDebugLoc()) {
1784 if (!FirstOp)
1785 OS << ',';
1786 OS << " debug-location ";
1787 DL->printAsOperand(OS, MST);
1788 }
1789 }
1790
1791 if (!memoperands_empty()) {
1792 SmallVector<StringRef, 0> SSNs;
1793 const LLVMContext *Context = nullptr;
1794 std::unique_ptr<LLVMContext> CtxPtr;
1795 const MachineFrameInfo *MFI = nullptr;
1796 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1797 MFI = &MF->getFrameInfo();
1798 Context = &MF->getFunction().getContext();
1799 } else {
1800 CtxPtr = std::make_unique<LLVMContext>();
1801 Context = CtxPtr.get();
1802 }
1803
1804 OS << " :: ";
1805 bool NeedComma = false;
1806 for (const MachineMemOperand *Op : memoperands()) {
1807 if (NeedComma)
1808 OS << ", ";
1809 Op->print(OS, MST, SSNs, *Context, MFI, TII);
1810 NeedComma = true;
1811 }
1812 }
1813
1814 if (SkipDebugLoc)
1815 return;
1816
1817 bool HaveSemi = false;
1818
1819 // Print debug location information.
1820 if (const DebugLoc &DL = getDebugLoc()) {
1821 if (!HaveSemi) {
1822 OS << ';';
1823 HaveSemi = true;
1824 }
1825 OS << ' ';
1826 DL.print(OS);
1827 }
1828
1829 // Print extra comments for DEBUG_VALUE.
1830 if (isDebugValue() && getDebugVariableOp().isMetadata()) {
1831 if (!HaveSemi) {
1832 OS << ";";
1833 HaveSemi = true;
Value stored to 'HaveSemi' is never read
1834 }
1835 auto *DV = getDebugVariable();
1836 OS << " line no:" << DV->getLine();
1837 if (isIndirectDebugValue())
1838 OS << " indirect";
1839 }
1840 // TODO: DBG_LABEL
1841
1842 if (AddNewLine)
1843 OS << '\n';
1844}
1845
1846bool MachineInstr::addRegisterKilled(Register IncomingReg,
1847 const TargetRegisterInfo *RegInfo,
1848 bool AddIfNotFound) {
1849 bool isPhysReg = Register::isPhysicalRegister(IncomingReg);
1850 bool hasAliases = isPhysReg &&
1851 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1852 bool Found = false;
1853 SmallVector<unsigned,4> DeadOps;
1854 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1855 MachineOperand &MO = getOperand(i);
1856 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1857 continue;
1858
1859 // DEBUG_VALUE nodes do not contribute to code generation and should
1860 // always be ignored. Failure to do so may result in trying to modify
1861 // KILL flags on DEBUG_VALUE nodes.
1862 if (MO.isDebug())
1863 continue;
1864
1865 Register Reg = MO.getReg();
1866 if (!Reg)
1867 continue;
1868
1869 if (Reg == IncomingReg) {
1870 if (!Found) {
1871 if (MO.isKill())
1872 // The register is already marked kill.
1873 return true;
1874 if (isPhysReg && isRegTiedToDefOperand(i))
1875 // Two-address uses of physregs must not be marked kill.
1876 return true;
1877 MO.setIsKill();
1878 Found = true;
1879 }
1880 } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) {
1881 // A super-register kill already exists.
1882 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1883 return true;
1884 if (RegInfo->isSubRegister(IncomingReg, Reg))
1885 DeadOps.push_back(i);
1886 }
1887 }
1888
1889 // Trim unneeded kill operands.
1890 while (!DeadOps.empty()) {
1891 unsigned OpIdx = DeadOps.back();
1892 if (getOperand(OpIdx).isImplicit() &&
1893 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1894 removeOperand(OpIdx);
1895 else
1896 getOperand(OpIdx).setIsKill(false);
1897 DeadOps.pop_back();
1898 }
1899
1900 // If not found, this means an alias of one of the operands is killed. Add a
1901 // new implicit operand if required.
1902 if (!Found && AddIfNotFound) {
1903 addOperand(MachineOperand::CreateReg(IncomingReg,
1904 false /*IsDef*/,
1905 true /*IsImp*/,
1906 true /*IsKill*/));
1907 return true;
1908 }
1909 return Found;
1910}
1911
1912void MachineInstr::clearRegisterKills(Register Reg,
1913 const TargetRegisterInfo *RegInfo) {
1914 if (!Register::isPhysicalRegister(Reg))
1915 RegInfo = nullptr;
1916 for (MachineOperand &MO : operands()) {
1917 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1918 continue;
1919 Register OpReg = MO.getReg();
1920 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1921 MO.setIsKill(false);
1922 }
1923}
1924
1925bool MachineInstr::addRegisterDead(Register Reg,
1926 const TargetRegisterInfo *RegInfo,
1927 bool AddIfNotFound) {
1928 bool isPhysReg = Register::isPhysicalRegister(Reg);
1929 bool hasAliases = isPhysReg &&
1930 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1931 bool Found = false;
1932 SmallVector<unsigned,4> DeadOps;
1933 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1934 MachineOperand &MO = getOperand(i);
1935 if (!MO.isReg() || !MO.isDef())
1936 continue;
1937 Register MOReg = MO.getReg();
1938 if (!MOReg)
1939 continue;
1940
1941 if (MOReg == Reg) {
1942 MO.setIsDead();
1943 Found = true;
1944 } else if (hasAliases && MO.isDead() &&
1945 Register::isPhysicalRegister(MOReg)) {
1946 // There exists a super-register that's marked dead.
1947 if (RegInfo->isSuperRegister(Reg, MOReg))
1948 return true;
1949 if (RegInfo->isSubRegister(Reg, MOReg))
1950 DeadOps.push_back(i);
1951 }
1952 }
1953
1954 // Trim unneeded dead operands.
1955 while (!DeadOps.empty()) {
1956 unsigned OpIdx = DeadOps.back();
1957 if (getOperand(OpIdx).isImplicit() &&
1958 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1959 removeOperand(OpIdx);
1960 else
1961 getOperand(OpIdx).setIsDead(false);
1962 DeadOps.pop_back();
1963 }
1964
1965 // If not found, this means an alias of one of the operands is dead. Add a
1966 // new implicit operand if required.
1967 if (Found || !AddIfNotFound)
1968 return Found;
1969
1970 addOperand(MachineOperand::CreateReg(Reg,
1971 true /*IsDef*/,
1972 true /*IsImp*/,
1973 false /*IsKill*/,
1974 true /*IsDead*/));
1975 return true;
1976}
1977
1978void MachineInstr::clearRegisterDeads(Register Reg) {
1979 for (MachineOperand &MO : operands()) {
1980 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
1981 continue;
1982 MO.setIsDead(false);
1983 }
1984}
1985
1986void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
1987 for (MachineOperand &MO : operands()) {
1988 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
1989 continue;
1990 MO.setIsUndef(IsUndef);
1991 }
1992}
1993
1994void MachineInstr::addRegisterDefined(Register Reg,
1995 const TargetRegisterInfo *RegInfo) {
1996 if (Register::isPhysicalRegister(Reg)) {
1997 MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
1998 if (MO)
1999 return;
2000 } else {
2001 for (const MachineOperand &MO : operands()) {
2002 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2003 MO.getSubReg() == 0)
2004 return;
2005 }
2006 }
2007 addOperand(MachineOperand::CreateReg(Reg,
2008 true /*IsDef*/,
2009 true /*IsImp*/));
2010}
2011
2012void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
2013 const TargetRegisterInfo &TRI) {
2014 bool HasRegMask = false;
2015 for (MachineOperand &MO : operands()) {
2016 if (MO.isRegMask()) {
2017 HasRegMask = true;
2018 continue;
2019 }
2020 if (!MO.isReg() || !MO.isDef()) continue;
2021 Register Reg = MO.getReg();
2022 if (!Reg.isPhysical())
2023 continue;
2024 // If there are no uses, including partial uses, the def is dead.
2025 if (llvm::none_of(UsedRegs,
2026 [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
2027 MO.setIsDead();
2028 }
2029
2030 // This is a call with a register mask operand.
2031 // Mask clobbers are always dead, so add defs for the non-dead defines.
2032 if (HasRegMask)
2033 for (const Register &UsedReg : UsedRegs)
2034 addRegisterDefined(UsedReg, &TRI);
2035}
2036
2037unsigned
2038MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2039 // Build up a buffer of hash code components.
2040 SmallVector<size_t, 16> HashComponents;
2041 HashComponents.reserve(MI->getNumOperands() + 1);
2042 HashComponents.push_back(MI->getOpcode());
2043 for (const MachineOperand &MO : MI->operands()) {
2044 if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
2045 continue; // Skip virtual register defs.
2046
2047 HashComponents.push_back(hash_value(MO));
2048 }
2049 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2050}
2051
2052void MachineInstr::emitError(StringRef Msg) const {
2053 // Find the source location cookie.
2054 uint64_t LocCookie = 0;
2055 const MDNode *LocMD = nullptr;
2056 for (unsigned i = getNumOperands(); i != 0; --i) {
2057 if (getOperand(i-1).isMetadata() &&
2058 (LocMD = getOperand(i-1).getMetadata()) &&
2059 LocMD->getNumOperands() != 0) {
2060 if (const ConstantInt *CI =
2061 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2062 LocCookie = CI->getZExtValue();
2063 break;
2064 }
2065 }
2066 }
2067
2068 if (const MachineBasicBlock *MBB = getParent())
2069 if (const MachineFunction *MF = MBB->getParent())
2070 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2071 report_fatal_error(Msg);
2072}
2073
2074MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2075 const MCInstrDesc &MCID, bool IsIndirect,
2076 Register Reg, const MDNode *Variable,
2077 const MDNode *Expr) {
2078 assert(isa<DILocalVariable>(Variable) && "not a variable")(static_cast <bool> (isa<DILocalVariable>(Variable
) && "not a variable") ? void (0) : __assert_fail ("isa<DILocalVariable>(Variable) && \"not a variable\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2078, __extension__ __PRETTY_FUNCTION__
))
;
2079 assert(cast<DIExpression>(Expr)->isValid() && "not an expression")(static_cast <bool> (cast<DIExpression>(Expr)->
isValid() && "not an expression") ? void (0) : __assert_fail
("cast<DIExpression>(Expr)->isValid() && \"not an expression\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2079, __extension__ __PRETTY_FUNCTION__
))
;
2080 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2081, __extension__ __PRETTY_FUNCTION__
))
2081 "Expected inlined-at fields to agree")(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2081, __extension__ __PRETTY_FUNCTION__
))
;
2082 auto MIB = BuildMI(MF, DL, MCID).addReg(Reg);
2083 if (IsIndirect)
2084 MIB.addImm(0U);
2085 else
2086 MIB.addReg(0U);
2087 return MIB.addMetadata(Variable).addMetadata(Expr);
2088}
2089
2090MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2091 const MCInstrDesc &MCID, bool IsIndirect,
2092 const MachineOperand &MO,
2093 const MDNode *Variable, const MDNode *Expr) {
2094 assert(isa<DILocalVariable>(Variable) && "not a variable")(static_cast <bool> (isa<DILocalVariable>(Variable
) && "not a variable") ? void (0) : __assert_fail ("isa<DILocalVariable>(Variable) && \"not a variable\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2094, __extension__ __PRETTY_FUNCTION__
))
;
2095 assert(cast<DIExpression>(Expr)->isValid() && "not an expression")(static_cast <bool> (cast<DIExpression>(Expr)->
isValid() && "not an expression") ? void (0) : __assert_fail
("cast<DIExpression>(Expr)->isValid() && \"not an expression\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2095, __extension__ __PRETTY_FUNCTION__
))
;
2096 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2097, __extension__ __PRETTY_FUNCTION__
))
2097 "Expected inlined-at fields to agree")(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2097, __extension__ __PRETTY_FUNCTION__
))
;
2098 if (MO.isReg())
2099 return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
2100
2101 auto MIB = BuildMI(MF, DL, MCID).add(MO);
2102 if (IsIndirect)
2103 MIB.addImm(0U);
2104 else
2105 MIB.addReg(0U);
2106 return MIB.addMetadata(Variable).addMetadata(Expr);
2107}
2108
2109MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2110 const MCInstrDesc &MCID, bool IsIndirect,
2111 ArrayRef<MachineOperand> MOs,
2112 const MDNode *Variable, const MDNode *Expr) {
2113 assert(isa<DILocalVariable>(Variable) && "not a variable")(static_cast <bool> (isa<DILocalVariable>(Variable
) && "not a variable") ? void (0) : __assert_fail ("isa<DILocalVariable>(Variable) && \"not a variable\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2113, __extension__ __PRETTY_FUNCTION__
))
;
2114 assert(cast<DIExpression>(Expr)->isValid() && "not an expression")(static_cast <bool> (cast<DIExpression>(Expr)->
isValid() && "not an expression") ? void (0) : __assert_fail
("cast<DIExpression>(Expr)->isValid() && \"not an expression\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2114, __extension__ __PRETTY_FUNCTION__
))
;
2115 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2116, __extension__ __PRETTY_FUNCTION__
))
2116 "Expected inlined-at fields to agree")(static_cast <bool> (cast<DILocalVariable>(Variable
)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2116, __extension__ __PRETTY_FUNCTION__
))
;
2117 if (MCID.Opcode == TargetOpcode::DBG_VALUE)
2118 return BuildMI(MF, DL, MCID, IsIndirect, MOs[0], Variable, Expr);
2119
2120 auto MIB = BuildMI(MF, DL, MCID);
2121 MIB.addMetadata(Variable).addMetadata(Expr);
2122 for (const MachineOperand &MO : MOs)
2123 if (MO.isReg())
2124 MIB.addReg(MO.getReg());
2125 else
2126 MIB.add(MO);
2127 return MIB;
2128}
2129
2130MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2131 MachineBasicBlock::iterator I,
2132 const DebugLoc &DL, const MCInstrDesc &MCID,
2133 bool IsIndirect, Register Reg,
2134 const MDNode *Variable, const MDNode *Expr) {
2135 MachineFunction &MF = *BB.getParent();
2136 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2137 BB.insert(I, MI);
2138 return MachineInstrBuilder(MF, MI);
2139}
2140
2141MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2142 MachineBasicBlock::iterator I,
2143 const DebugLoc &DL, const MCInstrDesc &MCID,
2144 bool IsIndirect, MachineOperand &MO,
2145 const MDNode *Variable, const MDNode *Expr) {
2146 MachineFunction &MF = *BB.getParent();
2147 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
2148 BB.insert(I, MI);
2149 return MachineInstrBuilder(MF, *MI);
2150}
2151
2152MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2153 MachineBasicBlock::iterator I,
2154 const DebugLoc &DL, const MCInstrDesc &MCID,
2155 bool IsIndirect, ArrayRef<MachineOperand> MOs,
2156 const MDNode *Variable, const MDNode *Expr) {
2157 MachineFunction &MF = *BB.getParent();
2158 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MOs, Variable, Expr);
2159 BB.insert(I, MI);
2160 return MachineInstrBuilder(MF, *MI);
2161}
2162
2163/// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2164/// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2165static const DIExpression *
2166computeExprForSpill(const MachineInstr &MI,
2167 SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
2168 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&(static_cast <bool> (MI.getDebugVariable()->isValidLocationForIntrinsic
(MI.getDebugLoc()) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2169, __extension__ __PRETTY_FUNCTION__
))
2169 "Expected inlined-at fields to agree")(static_cast <bool> (MI.getDebugVariable()->isValidLocationForIntrinsic
(MI.getDebugLoc()) && "Expected inlined-at fields to agree"
) ? void (0) : __assert_fail ("MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2169, __extension__ __PRETTY_FUNCTION__
))
;
2170
2171 const DIExpression *Expr = MI.getDebugExpression();
2172 if (MI.isIndirectDebugValue()) {
2173 assert(MI.getDebugOffset().getImm() == 0 &&(static_cast <bool> (MI.getDebugOffset().getImm() == 0 &&
"DBG_VALUE with nonzero offset") ? void (0) : __assert_fail (
"MI.getDebugOffset().getImm() == 0 && \"DBG_VALUE with nonzero offset\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2174, __extension__ __PRETTY_FUNCTION__
))
2174 "DBG_VALUE with nonzero offset")(static_cast <bool> (MI.getDebugOffset().getImm() == 0 &&
"DBG_VALUE with nonzero offset") ? void (0) : __assert_fail (
"MI.getDebugOffset().getImm() == 0 && \"DBG_VALUE with nonzero offset\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2174, __extension__ __PRETTY_FUNCTION__
))
;
2175 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2176 } else if (MI.isDebugValueList()) {
2177 // We will replace the spilled register with a frame index, so
2178 // immediately deref all references to the spilled register.
2179 std::array<uint64_t, 1> Ops{{dwarf::DW_OP_deref}};
2180 for (const MachineOperand *Op : SpilledOperands) {
2181 unsigned OpIdx = MI.getDebugOperandIndex(Op);
2182 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx);
2183 }
2184 }
2185 return Expr;
2186}
2187static const DIExpression *computeExprForSpill(const MachineInstr &MI,
2188 Register SpillReg) {
2189 assert(MI.hasDebugOperandForReg(SpillReg) && "Spill Reg is not used in MI.")(static_cast <bool> (MI.hasDebugOperandForReg(SpillReg)
&& "Spill Reg is not used in MI.") ? void (0) : __assert_fail
("MI.hasDebugOperandForReg(SpillReg) && \"Spill Reg is not used in MI.\""
, "llvm/lib/CodeGen/MachineInstr.cpp", 2189, __extension__ __PRETTY_FUNCTION__
))
;
2190 SmallVector<const MachineOperand *> SpillOperands;
2191 for (const MachineOperand &Op : MI.getDebugOperandsForReg(SpillReg))
2192 SpillOperands.push_back(&Op);
2193 return computeExprForSpill(MI, SpillOperands);
2194}
2195
2196MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2197 MachineBasicBlock::iterator I,
2198 const MachineInstr &Orig,
2199 int FrameIndex, Register SpillReg) {
2200 const DIExpression *Expr = computeExprForSpill(Orig, SpillReg);
2201 MachineInstrBuilder NewMI =
2202 BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
2203 // Non-Variadic Operands: Location, Offset, Variable, Expression
2204 // Variadic Operands: Variable, Expression, Locations...
2205 if (Orig.isNonListDebugValue())
2206 NewMI.addFrameIndex(FrameIndex).addImm(0U);
2207 NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
2208 if (Orig.isDebugValueList()) {
2209 for (const MachineOperand &Op : Orig.debug_operands())
2210 if (Op.isReg() && Op.getReg() == SpillReg)
2211 NewMI.addFrameIndex(FrameIndex);
2212 else
2213 NewMI.add(MachineOperand(Op));
2214 }
2215 return NewMI;
2216}
2217MachineInstr *llvm::buildDbgValueForSpill(
2218 MachineBasicBlock &BB, MachineBasicBlock::iterator I,
2219 const MachineInstr &Orig, int FrameIndex,
2220 SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
2221 const DIExpression *Expr = computeExprForSpill(Orig, SpilledOperands);
2222 MachineInstrBuilder NewMI =
2223 BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
2224 // Non-Variadic Operands: Location, Offset, Variable, Expression
2225 // Variadic Operands: Variable, Expression, Locations...
2226 if (Orig.isNonListDebugValue())
2227 NewMI.addFrameIndex(FrameIndex).addImm(0U);
2228 NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
2229 if (Orig.isDebugValueList()) {
2230 for (const MachineOperand &Op : Orig.debug_operands())
2231 if (is_contained(SpilledOperands, &Op))
2232 NewMI.addFrameIndex(FrameIndex);
2233 else
2234 NewMI.add(MachineOperand(Op));
2235 }
2236 return NewMI;
2237}
2238
2239void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex,
2240 Register Reg) {
2241 const DIExpression *Expr = computeExprForSpill(Orig, Reg);
2242 if (Orig.isNonListDebugValue())
2243 Orig.getDebugOffset().ChangeToImmediate(0U);
2244 for (MachineOperand &Op : Orig.getDebugOperandsForReg(Reg))
2245 Op.ChangeToFrameIndex(FrameIndex);
2246 Orig.getDebugExpressionOp().setMetadata(Expr);
2247}
2248
2249void MachineInstr::collectDebugValues(
2250 SmallVectorImpl<MachineInstr *> &DbgValues) {
2251 MachineInstr &MI = *this;
2252 if (!MI.getOperand(0).isReg())
2253 return;
2254
2255 MachineBasicBlock::iterator DI = MI; ++DI;
2256 for (MachineBasicBlock::iterator DE = MI.getParent()->end();
2257 DI != DE; ++DI) {
2258 if (!DI->isDebugValue())
2259 return;
2260 if (DI->hasDebugOperandForReg(MI.getOperand(0).getReg()))
2261 DbgValues.push_back(&*DI);
2262 }
2263}
2264
2265void MachineInstr::changeDebugValuesDefReg(Register Reg) {
2266 // Collect matching debug values.
2267 SmallVector<MachineInstr *, 2> DbgValues;
2268
2269 if (!getOperand(0).isReg())
2270 return;
2271
2272 Register DefReg = getOperand(0).getReg();
2273 auto *MRI = getRegInfo();
2274 for (auto &MO : MRI->use_operands(DefReg)) {
2275 auto *DI = MO.getParent();
2276 if (!DI->isDebugValue())
2277 continue;
2278 if (DI->hasDebugOperandForReg(DefReg)) {
2279 DbgValues.push_back(DI);
2280 }
2281 }
2282
2283 // Propagate Reg to debug value instructions.
2284 for (auto *DBI : DbgValues)
2285 for (MachineOperand &Op : DBI->getDebugOperandsForReg(DefReg))
2286 Op.setReg(Reg);
2287}
2288
2289using MMOList = SmallVector<const MachineMemOperand *, 2>;
2290
2291static unsigned getSpillSlotSize(const MMOList &Accesses,
2292 const MachineFrameInfo &MFI) {
2293 unsigned Size = 0;
2294 for (const auto *A : Accesses)
2295 if (MFI.isSpillSlotObjectIndex(
2296 cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
2297 ->getFrameIndex()))
2298 Size += A->getSize();
2299 return Size;
2300}
2301
2302Optional<unsigned>
2303MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
2304 int FI;
2305 if (TII->isStoreToStackSlotPostFE(*this, FI)) {
2306 const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2307 if (MFI.isSpillSlotObjectIndex(FI))
2308 return (*memoperands_begin())->getSize();
2309 }
2310 return None;
2311}
2312
2313Optional<unsigned>
2314MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
2315 MMOList Accesses;
2316 if (TII->hasStoreToStackSlot(*this, Accesses))
2317 return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2318 return None;
2319}
2320
2321Optional<unsigned>
2322MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
2323 int FI;
2324 if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
2325 const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2326 if (MFI.isSpillSlotObjectIndex(FI))
2327 return (*memoperands_begin())->getSize();
2328 }
2329 return None;
2330}
2331
2332Optional<unsigned>
2333MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
2334 MMOList Accesses;
2335 if (TII->hasLoadFromStackSlot(*this, Accesses))
2336 return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2337 return None;
2338}
2339
2340unsigned MachineInstr::getDebugInstrNum() {
2341 if (DebugInstrNum == 0)
2342 DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum();
2343 return DebugInstrNum;
2344}
2345
2346unsigned MachineInstr::getDebugInstrNum(MachineFunction &MF) {
2347 if (DebugInstrNum == 0)
2348 DebugInstrNum = MF.getNewDebugInstrNum();
2349 return DebugInstrNum;
2350}