1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/Loads.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineInstrBundle.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/Config/llvm-config.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfoMetadata.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/ModuleSlotTracker.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/MC/MCInstrDesc.h"
56 #include "llvm/MC/MCRegisterInfo.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/LowLevelTypeImpl.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetIntrinsicInfo.h"
67 #include "llvm/Target/TargetMachine.h"
78 static const MachineFunction
*getMFIfAvailable(const MachineInstr
&MI
) {
79 if (const MachineBasicBlock
*MBB
= MI
.getParent())
80 if (const MachineFunction
*MF
= MBB
->getParent())
85 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
87 static void tryToGetTargetInfo(const MachineInstr
&MI
,
88 const TargetRegisterInfo
*&TRI
,
89 const MachineRegisterInfo
*&MRI
,
90 const TargetIntrinsicInfo
*&IntrinsicInfo
,
91 const TargetInstrInfo
*&TII
) {
93 if (const MachineFunction
*MF
= getMFIfAvailable(MI
)) {
94 TRI
= MF
->getSubtarget().getRegisterInfo();
95 MRI
= &MF
->getRegInfo();
96 IntrinsicInfo
= MF
->getTarget().getIntrinsicInfo();
97 TII
= MF
->getSubtarget().getInstrInfo();
101 void MachineInstr::addImplicitDefUseOperands(MachineFunction
&MF
) {
102 if (MCID
->ImplicitDefs
)
103 for (const MCPhysReg
*ImpDefs
= MCID
->getImplicitDefs(); *ImpDefs
;
105 addOperand(MF
, MachineOperand::CreateReg(*ImpDefs
, true, true));
106 if (MCID
->ImplicitUses
)
107 for (const MCPhysReg
*ImpUses
= MCID
->getImplicitUses(); *ImpUses
;
109 addOperand(MF
, MachineOperand::CreateReg(*ImpUses
, false, true));
112 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
113 /// implicit operands. It reserves space for the number of operands specified by
115 MachineInstr::MachineInstr(MachineFunction
&MF
, const MCInstrDesc
&tid
,
116 DebugLoc dl
, bool NoImp
)
117 : MCID(&tid
), debugLoc(std::move(dl
)) {
118 assert(debugLoc
.hasTrivialDestructor() && "Expected trivial destructor");
120 // Reserve space for the expected number of operands.
121 if (unsigned NumOps
= MCID
->getNumOperands() +
122 MCID
->getNumImplicitDefs() + MCID
->getNumImplicitUses()) {
123 CapOperands
= OperandCapacity::get(NumOps
);
124 Operands
= MF
.allocateOperandArray(CapOperands
);
128 addImplicitDefUseOperands(MF
);
131 /// MachineInstr ctor - Copies MachineInstr arg exactly
133 MachineInstr::MachineInstr(MachineFunction
&MF
, const MachineInstr
&MI
)
134 : MCID(&MI
.getDesc()), Info(MI
.Info
), debugLoc(MI
.getDebugLoc()) {
135 assert(debugLoc
.hasTrivialDestructor() && "Expected trivial destructor");
137 CapOperands
= OperandCapacity::get(MI
.getNumOperands());
138 Operands
= MF
.allocateOperandArray(CapOperands
);
141 for (const MachineOperand
&MO
: MI
.operands())
144 // Copy all the sensible flags.
148 /// getRegInfo - If this instruction is embedded into a MachineFunction,
149 /// return the MachineRegisterInfo object for the current function, otherwise
151 MachineRegisterInfo
*MachineInstr::getRegInfo() {
152 if (MachineBasicBlock
*MBB
= getParent())
153 return &MBB
->getParent()->getRegInfo();
157 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
158 /// this instruction from their respective use lists. This requires that the
159 /// operands already be on their use lists.
160 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo
&MRI
) {
161 for (MachineOperand
&MO
: operands())
163 MRI
.removeRegOperandFromUseList(&MO
);
166 /// AddRegOperandsToUseLists - Add all of the register operands in
167 /// this instruction from their respective use lists. This requires that the
168 /// operands not be on their use lists yet.
169 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo
&MRI
) {
170 for (MachineOperand
&MO
: operands())
172 MRI
.addRegOperandToUseList(&MO
);
175 void MachineInstr::addOperand(const MachineOperand
&Op
) {
176 MachineBasicBlock
*MBB
= getParent();
177 assert(MBB
&& "Use MachineInstrBuilder to add operands to dangling instrs");
178 MachineFunction
*MF
= MBB
->getParent();
179 assert(MF
&& "Use MachineInstrBuilder to add operands to dangling instrs");
183 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
184 /// ranges. If MRI is non-null also update use-def chains.
185 static void moveOperands(MachineOperand
*Dst
, MachineOperand
*Src
,
186 unsigned NumOps
, MachineRegisterInfo
*MRI
) {
188 return MRI
->moveOperands(Dst
, Src
, NumOps
);
190 // MachineOperand is a trivially copyable type so we can just use memmove.
191 std::memmove(Dst
, Src
, NumOps
* sizeof(MachineOperand
));
194 /// addOperand - Add the specified operand to the instruction. If it is an
195 /// implicit operand, it is added to the end of the operand list. If it is
196 /// an explicit operand it is added at the end of the explicit operand list
197 /// (before the first implicit operand).
198 void MachineInstr::addOperand(MachineFunction
&MF
, const MachineOperand
&Op
) {
199 assert(MCID
&& "Cannot add operands before providing an instr descriptor");
201 // Check if we're adding one of our existing operands.
202 if (&Op
>= Operands
&& &Op
< Operands
+ NumOperands
) {
203 // This is unusual: MI->addOperand(MI->getOperand(i)).
204 // If adding Op requires reallocating or moving existing operands around,
205 // the Op reference could go stale. Support it by copying Op.
206 MachineOperand
CopyOp(Op
);
207 return addOperand(MF
, CopyOp
);
210 // Find the insert location for the new operand. Implicit registers go at
211 // the end, everything else goes before the implicit regs.
213 // FIXME: Allow mixed explicit and implicit operands on inline asm.
214 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
215 // implicit-defs, but they must not be moved around. See the FIXME in
217 unsigned OpNo
= getNumOperands();
218 bool isImpReg
= Op
.isReg() && Op
.isImplicit();
219 if (!isImpReg
&& !isInlineAsm()) {
220 while (OpNo
&& Operands
[OpNo
-1].isReg() && Operands
[OpNo
-1].isImplicit()) {
222 assert(!Operands
[OpNo
].isTied() && "Cannot move tied operands");
227 bool isMetaDataOp
= Op
.getType() == MachineOperand::MO_Metadata
;
228 // OpNo now points as the desired insertion point. Unless this is a variadic
229 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
230 // RegMask operands go between the explicit and implicit operands.
231 assert((isImpReg
|| Op
.isRegMask() || MCID
->isVariadic() ||
232 OpNo
< MCID
->getNumOperands() || isMetaDataOp
) &&
233 "Trying to add an operand to a machine instr that is already done!");
236 MachineRegisterInfo
*MRI
= getRegInfo();
238 // Determine if the Operands array needs to be reallocated.
239 // Save the old capacity and operand array.
240 OperandCapacity OldCap
= CapOperands
;
241 MachineOperand
*OldOperands
= Operands
;
242 if (!OldOperands
|| OldCap
.getSize() == getNumOperands()) {
243 CapOperands
= OldOperands
? OldCap
.getNext() : OldCap
.get(1);
244 Operands
= MF
.allocateOperandArray(CapOperands
);
245 // Move the operands before the insertion point.
247 moveOperands(Operands
, OldOperands
, OpNo
, MRI
);
250 // Move the operands following the insertion point.
251 if (OpNo
!= NumOperands
)
252 moveOperands(Operands
+ OpNo
+ 1, OldOperands
+ OpNo
, NumOperands
- OpNo
,
256 // Deallocate the old operand array.
257 if (OldOperands
!= Operands
&& OldOperands
)
258 MF
.deallocateOperandArray(OldCap
, OldOperands
);
260 // Copy Op into place. It still needs to be inserted into the MRI use lists.
261 MachineOperand
*NewMO
= new (Operands
+ OpNo
) MachineOperand(Op
);
262 NewMO
->ParentMI
= this;
264 // When adding a register operand, tell MRI about it.
265 if (NewMO
->isReg()) {
266 // Ensure isOnRegUseList() returns false, regardless of Op's status.
267 NewMO
->Contents
.Reg
.Prev
= nullptr;
268 // Ignore existing ties. This is not a property that can be copied.
270 // Add the new operand to MRI, but only for instructions in an MBB.
272 MRI
->addRegOperandToUseList(NewMO
);
273 // The MCID operand information isn't accurate until we start adding
274 // explicit operands. The implicit operands are added first, then the
275 // explicits are inserted before them.
277 // Tie uses to defs as indicated in MCInstrDesc.
278 if (NewMO
->isUse()) {
279 int DefIdx
= MCID
->getOperandConstraint(OpNo
, MCOI::TIED_TO
);
281 tieOperands(DefIdx
, OpNo
);
283 // If the register operand is flagged as early, mark the operand as such.
284 if (MCID
->getOperandConstraint(OpNo
, MCOI::EARLY_CLOBBER
) != -1)
285 NewMO
->setIsEarlyClobber(true);
290 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
291 /// fewer operand than it started with.
293 void MachineInstr::RemoveOperand(unsigned OpNo
) {
294 assert(OpNo
< getNumOperands() && "Invalid operand number");
295 untieRegOperand(OpNo
);
298 // Moving tied operands would break the ties.
299 for (unsigned i
= OpNo
+ 1, e
= getNumOperands(); i
!= e
; ++i
)
300 if (Operands
[i
].isReg())
301 assert(!Operands
[i
].isTied() && "Cannot move tied operands");
304 MachineRegisterInfo
*MRI
= getRegInfo();
305 if (MRI
&& Operands
[OpNo
].isReg())
306 MRI
->removeRegOperandFromUseList(Operands
+ OpNo
);
308 // Don't call the MachineOperand destructor. A lot of this code depends on
309 // MachineOperand having a trivial destructor anyway, and adding a call here
310 // wouldn't make it 'destructor-correct'.
312 if (unsigned N
= NumOperands
- 1 - OpNo
)
313 moveOperands(Operands
+ OpNo
, Operands
+ OpNo
+ 1, N
, MRI
);
317 void MachineInstr::dropMemRefs(MachineFunction
&MF
) {
318 if (memoperands_empty())
321 // See if we can just drop all of our extra info.
322 if (!getPreInstrSymbol() && !getPostInstrSymbol()) {
326 if (!getPostInstrSymbol()) {
327 Info
.set
<EIIK_PreInstrSymbol
>(getPreInstrSymbol());
330 if (!getPreInstrSymbol()) {
331 Info
.set
<EIIK_PostInstrSymbol
>(getPostInstrSymbol());
335 // Otherwise allocate a fresh extra info with just these symbols.
336 Info
.set
<EIIK_OutOfLine
>(
337 MF
.createMIExtraInfo({}, getPreInstrSymbol(), getPostInstrSymbol()));
340 void MachineInstr::setMemRefs(MachineFunction
&MF
,
341 ArrayRef
<MachineMemOperand
*> MMOs
) {
347 // Try to store a single MMO inline.
348 if (MMOs
.size() == 1 && !getPreInstrSymbol() && !getPostInstrSymbol()) {
349 Info
.set
<EIIK_MMO
>(MMOs
[0]);
353 // Otherwise create an extra info struct with all of our info.
354 Info
.set
<EIIK_OutOfLine
>(
355 MF
.createMIExtraInfo(MMOs
, getPreInstrSymbol(), getPostInstrSymbol()));
358 void MachineInstr::addMemOperand(MachineFunction
&MF
,
359 MachineMemOperand
*MO
) {
360 SmallVector
<MachineMemOperand
*, 2> MMOs
;
361 MMOs
.append(memoperands_begin(), memoperands_end());
363 setMemRefs(MF
, MMOs
);
366 void MachineInstr::cloneMemRefs(MachineFunction
&MF
, const MachineInstr
&MI
) {
368 // Nothing to do for a self-clone!
371 assert(&MF
== MI
.getMF() &&
372 "Invalid machine functions when cloning memory refrences!");
373 // See if we can just steal the extra info already allocated for the
374 // instruction. We can do this whenever the pre- and post-instruction symbols
375 // are the same (including null).
376 if (getPreInstrSymbol() == MI
.getPreInstrSymbol() &&
377 getPostInstrSymbol() == MI
.getPostInstrSymbol()) {
382 // Otherwise, fall back on a copy-based clone.
383 setMemRefs(MF
, MI
.memoperands());
386 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
388 static bool hasIdenticalMMOs(ArrayRef
<MachineMemOperand
*> LHS
,
389 ArrayRef
<MachineMemOperand
*> RHS
) {
390 if (LHS
.size() != RHS
.size())
393 auto LHSPointees
= make_pointee_range(LHS
);
394 auto RHSPointees
= make_pointee_range(RHS
);
395 return std::equal(LHSPointees
.begin(), LHSPointees
.end(),
396 RHSPointees
.begin());
399 void MachineInstr::cloneMergedMemRefs(MachineFunction
&MF
,
400 ArrayRef
<const MachineInstr
*> MIs
) {
401 // Try handling easy numbers of MIs with simpler mechanisms.
406 if (MIs
.size() == 1) {
407 cloneMemRefs(MF
, *MIs
[0]);
410 // Because an empty memoperands list provides *no* information and must be
411 // handled conservatively (assuming the instruction can do anything), the only
412 // way to merge with it is to drop all other memoperands.
413 if (MIs
[0]->memoperands_empty()) {
418 // Handle the general case.
419 SmallVector
<MachineMemOperand
*, 2> MergedMMOs
;
420 // Start with the first instruction.
421 assert(&MF
== MIs
[0]->getMF() &&
422 "Invalid machine functions when cloning memory references!");
423 MergedMMOs
.append(MIs
[0]->memoperands_begin(), MIs
[0]->memoperands_end());
424 // Now walk all the other instructions and accumulate any different MMOs.
425 for (const MachineInstr
&MI
: make_pointee_range(MIs
.slice(1))) {
426 assert(&MF
== MI
.getMF() &&
427 "Invalid machine functions when cloning memory references!");
429 // Skip MIs with identical operands to the first. This is a somewhat
430 // arbitrary hack but will catch common cases without being quadratic.
431 // TODO: We could fully implement merge semantics here if needed.
432 if (hasIdenticalMMOs(MIs
[0]->memoperands(), MI
.memoperands()))
435 // Because an empty memoperands list provides *no* information and must be
436 // handled conservatively (assuming the instruction can do anything), the
437 // only way to merge with it is to drop all other memoperands.
438 if (MI
.memoperands_empty()) {
443 // Otherwise accumulate these into our temporary buffer of the merged state.
444 MergedMMOs
.append(MI
.memoperands_begin(), MI
.memoperands_end());
447 setMemRefs(MF
, MergedMMOs
);
450 void MachineInstr::setPreInstrSymbol(MachineFunction
&MF
, MCSymbol
*Symbol
) {
451 MCSymbol
*OldSymbol
= getPreInstrSymbol();
452 if (OldSymbol
== Symbol
)
454 if (OldSymbol
&& !Symbol
) {
455 // We're removing a symbol rather than adding one. Try to clean up any
456 // extra info carried around.
457 if (Info
.is
<EIIK_PreInstrSymbol
>()) {
462 if (memoperands_empty()) {
463 assert(getPostInstrSymbol() &&
464 "Should never have only a single symbol allocated out-of-line!");
465 Info
.set
<EIIK_PostInstrSymbol
>(getPostInstrSymbol());
469 // Otherwise fallback on the generic update.
470 } else if (!Info
|| Info
.is
<EIIK_PreInstrSymbol
>()) {
471 // If we don't have any other extra info, we can store this inline.
472 Info
.set
<EIIK_PreInstrSymbol
>(Symbol
);
476 // Otherwise, allocate a full new set of extra info.
477 // FIXME: Maybe we should make the symbols in the extra info mutable?
478 Info
.set
<EIIK_OutOfLine
>(
479 MF
.createMIExtraInfo(memoperands(), Symbol
, getPostInstrSymbol()));
482 void MachineInstr::setPostInstrSymbol(MachineFunction
&MF
, MCSymbol
*Symbol
) {
483 MCSymbol
*OldSymbol
= getPostInstrSymbol();
484 if (OldSymbol
== Symbol
)
486 if (OldSymbol
&& !Symbol
) {
487 // We're removing a symbol rather than adding one. Try to clean up any
488 // extra info carried around.
489 if (Info
.is
<EIIK_PostInstrSymbol
>()) {
494 if (memoperands_empty()) {
495 assert(getPreInstrSymbol() &&
496 "Should never have only a single symbol allocated out-of-line!");
497 Info
.set
<EIIK_PreInstrSymbol
>(getPreInstrSymbol());
501 // Otherwise fallback on the generic update.
502 } else if (!Info
|| Info
.is
<EIIK_PostInstrSymbol
>()) {
503 // If we don't have any other extra info, we can store this inline.
504 Info
.set
<EIIK_PostInstrSymbol
>(Symbol
);
508 // Otherwise, allocate a full new set of extra info.
509 // FIXME: Maybe we should make the symbols in the extra info mutable?
510 Info
.set
<EIIK_OutOfLine
>(
511 MF
.createMIExtraInfo(memoperands(), getPreInstrSymbol(), Symbol
));
514 uint16_t MachineInstr::mergeFlagsWith(const MachineInstr
&Other
) const {
515 // For now, the just return the union of the flags. If the flags get more
516 // complicated over time, we might need more logic here.
517 return getFlags() | Other
.getFlags();
520 bool MachineInstr::hasPropertyInBundle(uint64_t Mask
, QueryType Type
) const {
521 assert(!isBundledWithPred() && "Must be called on bundle header");
522 for (MachineBasicBlock::const_instr_iterator MII
= getIterator();; ++MII
) {
523 if (MII
->getDesc().getFlags() & Mask
) {
524 if (Type
== AnyInBundle
)
527 if (Type
== AllInBundle
&& !MII
->isBundle())
530 // This was the last instruction in the bundle.
531 if (!MII
->isBundledWithSucc())
532 return Type
== AllInBundle
;
536 bool MachineInstr::isIdenticalTo(const MachineInstr
&Other
,
537 MICheckType Check
) const {
538 // If opcodes or number of operands are not the same then the two
539 // instructions are obviously not identical.
540 if (Other
.getOpcode() != getOpcode() ||
541 Other
.getNumOperands() != getNumOperands())
545 // We have passed the test above that both instructions have the same
546 // opcode, so we know that both instructions are bundles here. Let's compare
547 // MIs inside the bundle.
548 assert(Other
.isBundle() && "Expected that both instructions are bundles.");
549 MachineBasicBlock::const_instr_iterator I1
= getIterator();
550 MachineBasicBlock::const_instr_iterator I2
= Other
.getIterator();
551 // Loop until we analysed the last intruction inside at least one of the
553 while (I1
->isBundledWithSucc() && I2
->isBundledWithSucc()) {
556 if (!I1
->isIdenticalTo(*I2
, Check
))
559 // If we've reached the end of just one of the two bundles, but not both,
560 // the instructions are not identical.
561 if (I1
->isBundledWithSucc() || I2
->isBundledWithSucc())
565 // Check operands to make sure they match.
566 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
567 const MachineOperand
&MO
= getOperand(i
);
568 const MachineOperand
&OMO
= Other
.getOperand(i
);
570 if (!MO
.isIdenticalTo(OMO
))
575 // Clients may or may not want to ignore defs when testing for equality.
576 // For example, machine CSE pass only cares about finding common
577 // subexpressions, so it's safe to ignore virtual register defs.
579 if (Check
== IgnoreDefs
)
581 else if (Check
== IgnoreVRegDefs
) {
582 if (!TargetRegisterInfo::isVirtualRegister(MO
.getReg()) ||
583 !TargetRegisterInfo::isVirtualRegister(OMO
.getReg()))
584 if (!MO
.isIdenticalTo(OMO
))
587 if (!MO
.isIdenticalTo(OMO
))
589 if (Check
== CheckKillDead
&& MO
.isDead() != OMO
.isDead())
593 if (!MO
.isIdenticalTo(OMO
))
595 if (Check
== CheckKillDead
&& MO
.isKill() != OMO
.isKill())
599 // If DebugLoc does not match then two debug instructions are not identical.
601 if (getDebugLoc() && Other
.getDebugLoc() &&
602 getDebugLoc() != Other
.getDebugLoc())
607 const MachineFunction
*MachineInstr::getMF() const {
608 return getParent()->getParent();
611 MachineInstr
*MachineInstr::removeFromParent() {
612 assert(getParent() && "Not embedded in a basic block!");
613 return getParent()->remove(this);
616 MachineInstr
*MachineInstr::removeFromBundle() {
617 assert(getParent() && "Not embedded in a basic block!");
618 return getParent()->remove_instr(this);
621 void MachineInstr::eraseFromParent() {
622 assert(getParent() && "Not embedded in a basic block!");
623 getParent()->erase(this);
626 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
627 assert(getParent() && "Not embedded in a basic block!");
628 MachineBasicBlock
*MBB
= getParent();
629 MachineFunction
*MF
= MBB
->getParent();
630 assert(MF
&& "Not embedded in a function!");
632 MachineInstr
*MI
= (MachineInstr
*)this;
633 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
635 for (const MachineOperand
&MO
: MI
->operands()) {
636 if (!MO
.isReg() || !MO
.isDef())
638 unsigned Reg
= MO
.getReg();
639 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
641 MRI
.markUsesInDebugValueAsUndef(Reg
);
643 MI
->eraseFromParent();
646 void MachineInstr::eraseFromBundle() {
647 assert(getParent() && "Not embedded in a basic block!");
648 getParent()->erase_instr(this);
651 unsigned MachineInstr::getNumExplicitOperands() const {
652 unsigned NumOperands
= MCID
->getNumOperands();
653 if (!MCID
->isVariadic())
656 for (unsigned I
= NumOperands
, E
= getNumOperands(); I
!= E
; ++I
) {
657 const MachineOperand
&MO
= getOperand(I
);
658 // The operands must always be in the following order:
659 // - explicit reg defs,
660 // - other explicit operands (reg uses, immediates, etc.),
661 // - implicit reg defs
662 // - implicit reg uses
663 if (MO
.isReg() && MO
.isImplicit())
670 unsigned MachineInstr::getNumExplicitDefs() const {
671 unsigned NumDefs
= MCID
->getNumDefs();
672 if (!MCID
->isVariadic())
675 for (unsigned I
= NumDefs
, E
= getNumOperands(); I
!= E
; ++I
) {
676 const MachineOperand
&MO
= getOperand(I
);
677 if (!MO
.isReg() || !MO
.isDef() || MO
.isImplicit())
684 void MachineInstr::bundleWithPred() {
685 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
686 setFlag(BundledPred
);
687 MachineBasicBlock::instr_iterator Pred
= getIterator();
689 assert(!Pred
->isBundledWithSucc() && "Inconsistent bundle flags");
690 Pred
->setFlag(BundledSucc
);
693 void MachineInstr::bundleWithSucc() {
694 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
695 setFlag(BundledSucc
);
696 MachineBasicBlock::instr_iterator Succ
= getIterator();
698 assert(!Succ
->isBundledWithPred() && "Inconsistent bundle flags");
699 Succ
->setFlag(BundledPred
);
702 void MachineInstr::unbundleFromPred() {
703 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
704 clearFlag(BundledPred
);
705 MachineBasicBlock::instr_iterator Pred
= getIterator();
707 assert(Pred
->isBundledWithSucc() && "Inconsistent bundle flags");
708 Pred
->clearFlag(BundledSucc
);
711 void MachineInstr::unbundleFromSucc() {
712 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
713 clearFlag(BundledSucc
);
714 MachineBasicBlock::instr_iterator Succ
= getIterator();
716 assert(Succ
->isBundledWithPred() && "Inconsistent bundle flags");
717 Succ
->clearFlag(BundledPred
);
720 bool MachineInstr::isStackAligningInlineAsm() const {
722 unsigned ExtraInfo
= getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
723 if (ExtraInfo
& InlineAsm::Extra_IsAlignStack
)
729 InlineAsm::AsmDialect
MachineInstr::getInlineAsmDialect() const {
730 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
731 unsigned ExtraInfo
= getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
732 return InlineAsm::AsmDialect((ExtraInfo
& InlineAsm::Extra_AsmDialect
) != 0);
735 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx
,
736 unsigned *GroupNo
) const {
737 assert(isInlineAsm() && "Expected an inline asm instruction");
738 assert(OpIdx
< getNumOperands() && "OpIdx out of range");
740 // Ignore queries about the initial operands.
741 if (OpIdx
< InlineAsm::MIOp_FirstOperand
)
746 for (unsigned i
= InlineAsm::MIOp_FirstOperand
, e
= getNumOperands(); i
< e
;
748 const MachineOperand
&FlagMO
= getOperand(i
);
749 // If we reach the implicit register operands, stop looking.
752 NumOps
= 1 + InlineAsm::getNumOperandRegisters(FlagMO
.getImm());
753 if (i
+ NumOps
> OpIdx
) {
763 const DILabel
*MachineInstr::getDebugLabel() const {
764 assert(isDebugLabel() && "not a DBG_LABEL");
765 return cast
<DILabel
>(getOperand(0).getMetadata());
768 const DILocalVariable
*MachineInstr::getDebugVariable() const {
769 assert(isDebugValue() && "not a DBG_VALUE");
770 return cast
<DILocalVariable
>(getOperand(2).getMetadata());
773 const DIExpression
*MachineInstr::getDebugExpression() const {
774 assert(isDebugValue() && "not a DBG_VALUE");
775 return cast
<DIExpression
>(getOperand(3).getMetadata());
778 const TargetRegisterClass
*
779 MachineInstr::getRegClassConstraint(unsigned OpIdx
,
780 const TargetInstrInfo
*TII
,
781 const TargetRegisterInfo
*TRI
) const {
782 assert(getParent() && "Can't have an MBB reference here!");
783 assert(getMF() && "Can't have an MF reference here!");
784 const MachineFunction
&MF
= *getMF();
786 // Most opcodes have fixed constraints in their MCInstrDesc.
788 return TII
->getRegClass(getDesc(), OpIdx
, TRI
, MF
);
790 if (!getOperand(OpIdx
).isReg())
793 // For tied uses on inline asm, get the constraint from the def.
795 if (getOperand(OpIdx
).isUse() && isRegTiedToDefOperand(OpIdx
, &DefIdx
))
798 // Inline asm stores register class constraints in the flag word.
799 int FlagIdx
= findInlineAsmFlagIdx(OpIdx
);
803 unsigned Flag
= getOperand(FlagIdx
).getImm();
805 if ((InlineAsm::getKind(Flag
) == InlineAsm::Kind_RegUse
||
806 InlineAsm::getKind(Flag
) == InlineAsm::Kind_RegDef
||
807 InlineAsm::getKind(Flag
) == InlineAsm::Kind_RegDefEarlyClobber
) &&
808 InlineAsm::hasRegClassConstraint(Flag
, RCID
))
809 return TRI
->getRegClass(RCID
);
811 // Assume that all registers in a memory operand are pointers.
812 if (InlineAsm::getKind(Flag
) == InlineAsm::Kind_Mem
)
813 return TRI
->getPointerRegClass(MF
);
818 const TargetRegisterClass
*MachineInstr::getRegClassConstraintEffectForVReg(
819 unsigned Reg
, const TargetRegisterClass
*CurRC
, const TargetInstrInfo
*TII
,
820 const TargetRegisterInfo
*TRI
, bool ExploreBundle
) const {
821 // Check every operands inside the bundle if we have
824 for (ConstMIBundleOperands
OpndIt(*this); OpndIt
.isValid() && CurRC
;
826 CurRC
= OpndIt
->getParent()->getRegClassConstraintEffectForVRegImpl(
827 OpndIt
.getOperandNo(), Reg
, CurRC
, TII
, TRI
);
829 // Otherwise, just check the current operands.
830 for (unsigned i
= 0, e
= NumOperands
; i
< e
&& CurRC
; ++i
)
831 CurRC
= getRegClassConstraintEffectForVRegImpl(i
, Reg
, CurRC
, TII
, TRI
);
835 const TargetRegisterClass
*MachineInstr::getRegClassConstraintEffectForVRegImpl(
836 unsigned OpIdx
, unsigned Reg
, const TargetRegisterClass
*CurRC
,
837 const TargetInstrInfo
*TII
, const TargetRegisterInfo
*TRI
) const {
838 assert(CurRC
&& "Invalid initial register class");
839 // Check if Reg is constrained by some of its use/def from MI.
840 const MachineOperand
&MO
= getOperand(OpIdx
);
841 if (!MO
.isReg() || MO
.getReg() != Reg
)
843 // If yes, accumulate the constraints through the operand.
844 return getRegClassConstraintEffect(OpIdx
, CurRC
, TII
, TRI
);
847 const TargetRegisterClass
*MachineInstr::getRegClassConstraintEffect(
848 unsigned OpIdx
, const TargetRegisterClass
*CurRC
,
849 const TargetInstrInfo
*TII
, const TargetRegisterInfo
*TRI
) const {
850 const TargetRegisterClass
*OpRC
= getRegClassConstraint(OpIdx
, TII
, TRI
);
851 const MachineOperand
&MO
= getOperand(OpIdx
);
853 "Cannot get register constraints for non-register operand");
854 assert(CurRC
&& "Invalid initial register class");
855 if (unsigned SubIdx
= MO
.getSubReg()) {
857 CurRC
= TRI
->getMatchingSuperRegClass(CurRC
, OpRC
, SubIdx
);
859 CurRC
= TRI
->getSubClassWithSubReg(CurRC
, SubIdx
);
861 CurRC
= TRI
->getCommonSubClass(CurRC
, OpRC
);
865 /// Return the number of instructions inside the MI bundle, not counting the
866 /// header instruction.
867 unsigned MachineInstr::getBundleSize() const {
868 MachineBasicBlock::const_instr_iterator I
= getIterator();
870 while (I
->isBundledWithSucc()) {
877 /// Returns true if the MachineInstr has an implicit-use operand of exactly
878 /// the given register (not considering sub/super-registers).
879 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg
) const {
880 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
881 const MachineOperand
&MO
= getOperand(i
);
882 if (MO
.isReg() && MO
.isUse() && MO
.isImplicit() && MO
.getReg() == Reg
)
888 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
889 /// the specific register or -1 if it is not found. It further tightens
890 /// the search criteria to a use that kills the register if isKill is true.
891 int MachineInstr::findRegisterUseOperandIdx(
892 unsigned Reg
, bool isKill
, const TargetRegisterInfo
*TRI
) const {
893 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
894 const MachineOperand
&MO
= getOperand(i
);
895 if (!MO
.isReg() || !MO
.isUse())
897 unsigned MOReg
= MO
.getReg();
900 if (MOReg
== Reg
|| (TRI
&& TargetRegisterInfo::isPhysicalRegister(MOReg
) &&
901 TargetRegisterInfo::isPhysicalRegister(Reg
) &&
902 TRI
->isSubRegister(MOReg
, Reg
)))
903 if (!isKill
|| MO
.isKill())
909 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
910 /// indicating if this instruction reads or writes Reg. This also considers
913 MachineInstr::readsWritesVirtualRegister(unsigned Reg
,
914 SmallVectorImpl
<unsigned> *Ops
) const {
915 bool PartDef
= false; // Partial redefine.
916 bool FullDef
= false; // Full define.
919 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
920 const MachineOperand
&MO
= getOperand(i
);
921 if (!MO
.isReg() || MO
.getReg() != Reg
)
926 Use
|= !MO
.isUndef();
927 else if (MO
.getSubReg() && !MO
.isUndef())
928 // A partial def undef doesn't count as reading the register.
933 // A partial redefine uses Reg unless there is also a full define.
934 return std::make_pair(Use
|| (PartDef
&& !FullDef
), PartDef
|| FullDef
);
937 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
938 /// the specified register or -1 if it is not found. If isDead is true, defs
939 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
940 /// also checks if there is a def of a super-register.
942 MachineInstr::findRegisterDefOperandIdx(unsigned Reg
, bool isDead
, bool Overlap
,
943 const TargetRegisterInfo
*TRI
) const {
944 bool isPhys
= TargetRegisterInfo::isPhysicalRegister(Reg
);
945 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
946 const MachineOperand
&MO
= getOperand(i
);
947 // Accept regmask operands when Overlap is set.
948 // Ignore them when looking for a specific def operand (Overlap == false).
949 if (isPhys
&& Overlap
&& MO
.isRegMask() && MO
.clobbersPhysReg(Reg
))
951 if (!MO
.isReg() || !MO
.isDef())
953 unsigned MOReg
= MO
.getReg();
954 bool Found
= (MOReg
== Reg
);
955 if (!Found
&& TRI
&& isPhys
&&
956 TargetRegisterInfo::isPhysicalRegister(MOReg
)) {
958 Found
= TRI
->regsOverlap(MOReg
, Reg
);
960 Found
= TRI
->isSubRegister(MOReg
, Reg
);
962 if (Found
&& (!isDead
|| MO
.isDead()))
968 /// findFirstPredOperandIdx() - Find the index of the first operand in the
969 /// operand list that is used to represent the predicate. It returns -1 if
971 int MachineInstr::findFirstPredOperandIdx() const {
972 // Don't call MCID.findFirstPredOperandIdx() because this variant
973 // is sometimes called on an instruction that's not yet complete, and
974 // so the number of operands is less than the MCID indicates. In
975 // particular, the PTX target does this.
976 const MCInstrDesc
&MCID
= getDesc();
977 if (MCID
.isPredicable()) {
978 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
979 if (MCID
.OpInfo
[i
].isPredicate())
986 // MachineOperand::TiedTo is 4 bits wide.
987 const unsigned TiedMax
= 15;
989 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
991 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
992 /// field. TiedTo can have these values:
994 /// 0: Operand is not tied to anything.
995 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
996 /// TiedMax: Tied to an operand >= TiedMax-1.
998 /// The tied def must be one of the first TiedMax operands on a normal
999 /// instruction. INLINEASM instructions allow more tied defs.
1001 void MachineInstr::tieOperands(unsigned DefIdx
, unsigned UseIdx
) {
1002 MachineOperand
&DefMO
= getOperand(DefIdx
);
1003 MachineOperand
&UseMO
= getOperand(UseIdx
);
1004 assert(DefMO
.isDef() && "DefIdx must be a def operand");
1005 assert(UseMO
.isUse() && "UseIdx must be a use operand");
1006 assert(!DefMO
.isTied() && "Def is already tied to another use");
1007 assert(!UseMO
.isTied() && "Use is already tied to another def");
1009 if (DefIdx
< TiedMax
)
1010 UseMO
.TiedTo
= DefIdx
+ 1;
1012 // Inline asm can use the group descriptors to find tied operands, but on
1013 // normal instruction, the tied def must be within the first TiedMax
1015 assert(isInlineAsm() && "DefIdx out of range");
1016 UseMO
.TiedTo
= TiedMax
;
1019 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1020 DefMO
.TiedTo
= std::min(UseIdx
+ 1, TiedMax
);
1023 /// Given the index of a tied register operand, find the operand it is tied to.
1024 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1025 /// which must exist.
1026 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx
) const {
1027 const MachineOperand
&MO
= getOperand(OpIdx
);
1028 assert(MO
.isTied() && "Operand isn't tied");
1030 // Normally TiedTo is in range.
1031 if (MO
.TiedTo
< TiedMax
)
1032 return MO
.TiedTo
- 1;
1034 // Uses on normal instructions can be out of range.
1035 if (!isInlineAsm()) {
1036 // Normal tied defs must be in the 0..TiedMax-1 range.
1039 // MO is a def. Search for the tied use.
1040 for (unsigned i
= TiedMax
- 1, e
= getNumOperands(); i
!= e
; ++i
) {
1041 const MachineOperand
&UseMO
= getOperand(i
);
1042 if (UseMO
.isReg() && UseMO
.isUse() && UseMO
.TiedTo
== OpIdx
+ 1)
1045 llvm_unreachable("Can't find tied use");
1048 // Now deal with inline asm by parsing the operand group descriptor flags.
1049 // Find the beginning of each operand group.
1050 SmallVector
<unsigned, 8> GroupIdx
;
1051 unsigned OpIdxGroup
= ~0u;
1053 for (unsigned i
= InlineAsm::MIOp_FirstOperand
, e
= getNumOperands(); i
< e
;
1055 const MachineOperand
&FlagMO
= getOperand(i
);
1056 assert(FlagMO
.isImm() && "Invalid tied operand on inline asm");
1057 unsigned CurGroup
= GroupIdx
.size();
1058 GroupIdx
.push_back(i
);
1059 NumOps
= 1 + InlineAsm::getNumOperandRegisters(FlagMO
.getImm());
1060 // OpIdx belongs to this operand group.
1061 if (OpIdx
> i
&& OpIdx
< i
+ NumOps
)
1062 OpIdxGroup
= CurGroup
;
1064 if (!InlineAsm::isUseOperandTiedToDef(FlagMO
.getImm(), TiedGroup
))
1066 // Operands in this group are tied to operands in TiedGroup which must be
1067 // earlier. Find the number of operands between the two groups.
1068 unsigned Delta
= i
- GroupIdx
[TiedGroup
];
1070 // OpIdx is a use tied to TiedGroup.
1071 if (OpIdxGroup
== CurGroup
)
1072 return OpIdx
- Delta
;
1074 // OpIdx is a def tied to this use group.
1075 if (OpIdxGroup
== TiedGroup
)
1076 return OpIdx
+ Delta
;
1078 llvm_unreachable("Invalid tied operand on inline asm");
1081 /// clearKillInfo - Clears kill flags on all operands.
1083 void MachineInstr::clearKillInfo() {
1084 for (MachineOperand
&MO
: operands()) {
1085 if (MO
.isReg() && MO
.isUse())
1086 MO
.setIsKill(false);
1090 void MachineInstr::substituteRegister(unsigned FromReg
, unsigned ToReg
,
1092 const TargetRegisterInfo
&RegInfo
) {
1093 if (TargetRegisterInfo::isPhysicalRegister(ToReg
)) {
1095 ToReg
= RegInfo
.getSubReg(ToReg
, SubIdx
);
1096 for (MachineOperand
&MO
: operands()) {
1097 if (!MO
.isReg() || MO
.getReg() != FromReg
)
1099 MO
.substPhysReg(ToReg
, RegInfo
);
1102 for (MachineOperand
&MO
: operands()) {
1103 if (!MO
.isReg() || MO
.getReg() != FromReg
)
1105 MO
.substVirtReg(ToReg
, SubIdx
, RegInfo
);
1110 /// isSafeToMove - Return true if it is safe to move this instruction. If
1111 /// SawStore is set to true, it means that there is a store (or call) between
1112 /// the instruction's location and its intended destination.
1113 bool MachineInstr::isSafeToMove(AliasAnalysis
*AA
, bool &SawStore
) const {
1114 // Ignore stuff that we obviously can't move.
1116 // Treat volatile loads as stores. This is not strictly necessary for
1117 // volatiles, but it is required for atomic loads. It is not allowed to move
1118 // a load across an atomic load with Ordering > Monotonic.
1119 if (mayStore() || isCall() || isPHI() ||
1120 (mayLoad() && hasOrderedMemoryRef())) {
1125 if (isPosition() || isDebugInstr() || isTerminator() ||
1126 hasUnmodeledSideEffects())
1129 // See if this instruction does a load. If so, we have to guarantee that the
1130 // loaded value doesn't change between the load and the its intended
1131 // destination. The check for isInvariantLoad gives the targe the chance to
1132 // classify the load as always returning a constant, e.g. a constant pool
1134 if (mayLoad() && !isDereferenceableInvariantLoad(AA
))
1135 // Otherwise, this is a real load. If there is a store between the load and
1136 // end of block, we can't move it.
1142 bool MachineInstr::mayAlias(AliasAnalysis
*AA
, MachineInstr
&Other
,
1144 const MachineFunction
*MF
= getMF();
1145 const TargetInstrInfo
*TII
= MF
->getSubtarget().getInstrInfo();
1146 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
1148 // If neither instruction stores to memory, they can't alias in any
1149 // meaningful way, even if they read from the same address.
1150 if (!mayStore() && !Other
.mayStore())
1153 // Let the target decide if memory accesses cannot possibly overlap.
1154 if (TII
->areMemAccessesTriviallyDisjoint(*this, Other
, AA
))
1157 // FIXME: Need to handle multiple memory operands to support all targets.
1158 if (!hasOneMemOperand() || !Other
.hasOneMemOperand())
1161 MachineMemOperand
*MMOa
= *memoperands_begin();
1162 MachineMemOperand
*MMOb
= *Other
.memoperands_begin();
1164 // The following interface to AA is fashioned after DAGCombiner::isAlias
1165 // and operates with MachineMemOperand offset with some important
1167 // - LLVM fundamentally assumes flat address spaces.
1168 // - MachineOperand offset can *only* result from legalization and
1169 // cannot affect queries other than the trivial case of overlap
1171 // - These offsets never wrap and never step outside
1172 // of allocated objects.
1173 // - There should never be any negative offsets here.
1175 // FIXME: Modify API to hide this math from "user"
1176 // Even before we go to AA we can reason locally about some
1177 // memory objects. It can save compile time, and possibly catch some
1178 // corner cases not currently covered.
1180 int64_t OffsetA
= MMOa
->getOffset();
1181 int64_t OffsetB
= MMOb
->getOffset();
1182 int64_t MinOffset
= std::min(OffsetA
, OffsetB
);
1184 uint64_t WidthA
= MMOa
->getSize();
1185 uint64_t WidthB
= MMOb
->getSize();
1186 bool KnownWidthA
= WidthA
!= MemoryLocation::UnknownSize
;
1187 bool KnownWidthB
= WidthB
!= MemoryLocation::UnknownSize
;
1189 const Value
*ValA
= MMOa
->getValue();
1190 const Value
*ValB
= MMOb
->getValue();
1191 bool SameVal
= (ValA
&& ValB
&& (ValA
== ValB
));
1193 const PseudoSourceValue
*PSVa
= MMOa
->getPseudoValue();
1194 const PseudoSourceValue
*PSVb
= MMOb
->getPseudoValue();
1195 if (PSVa
&& ValB
&& !PSVa
->mayAlias(&MFI
))
1197 if (PSVb
&& ValA
&& !PSVb
->mayAlias(&MFI
))
1199 if (PSVa
&& PSVb
&& (PSVa
== PSVb
))
1204 if (!KnownWidthA
|| !KnownWidthB
)
1206 int64_t MaxOffset
= std::max(OffsetA
, OffsetB
);
1207 int64_t LowWidth
= (MinOffset
== OffsetA
) ? WidthA
: WidthB
;
1208 return (MinOffset
+ LowWidth
> MaxOffset
);
1217 assert((OffsetA
>= 0) && "Negative MachineMemOperand offset");
1218 assert((OffsetB
>= 0) && "Negative MachineMemOperand offset");
1220 int64_t OverlapA
= KnownWidthA
? WidthA
+ OffsetA
- MinOffset
1221 : MemoryLocation::UnknownSize
;
1222 int64_t OverlapB
= KnownWidthB
? WidthB
+ OffsetB
- MinOffset
1223 : MemoryLocation::UnknownSize
;
1225 AliasResult AAResult
= AA
->alias(
1226 MemoryLocation(ValA
, OverlapA
,
1227 UseTBAA
? MMOa
->getAAInfo() : AAMDNodes()),
1228 MemoryLocation(ValB
, OverlapB
,
1229 UseTBAA
? MMOb
->getAAInfo() : AAMDNodes()));
1231 return (AAResult
!= NoAlias
);
1234 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1235 /// or volatile memory reference, or if the information describing the memory
1236 /// reference is not available. Return false if it is known to have no ordered
1237 /// memory references.
1238 bool MachineInstr::hasOrderedMemoryRef() const {
1239 // An instruction known never to access memory won't have a volatile access.
1243 !hasUnmodeledSideEffects())
1246 // Otherwise, if the instruction has no memory reference information,
1247 // conservatively assume it wasn't preserved.
1248 if (memoperands_empty())
1251 // Check if any of our memory operands are ordered.
1252 return llvm::any_of(memoperands(), [](const MachineMemOperand
*MMO
) {
1253 return !MMO
->isUnordered();
1257 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1258 /// trap and is loading from a location whose value is invariant across a run of
1260 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis
*AA
) const {
1261 // If the instruction doesn't load at all, it isn't an invariant load.
1265 // If the instruction has lost its memoperands, conservatively assume that
1266 // it may not be an invariant load.
1267 if (memoperands_empty())
1270 const MachineFrameInfo
&MFI
= getParent()->getParent()->getFrameInfo();
1272 for (MachineMemOperand
*MMO
: memoperands()) {
1273 if (MMO
->isVolatile()) return false;
1274 if (MMO
->isStore()) return false;
1275 if (MMO
->isInvariant() && MMO
->isDereferenceable())
1278 // A load from a constant PseudoSourceValue is invariant.
1279 if (const PseudoSourceValue
*PSV
= MMO
->getPseudoValue())
1280 if (PSV
->isConstant(&MFI
))
1283 if (const Value
*V
= MMO
->getValue()) {
1284 // If we have an AliasAnalysis, ask it whether the memory is constant.
1286 AA
->pointsToConstantMemory(
1287 MemoryLocation(V
, MMO
->getSize(), MMO
->getAAInfo())))
1291 // Otherwise assume conservatively.
1295 // Everything checks out.
1299 /// isConstantValuePHI - If the specified instruction is a PHI that always
1300 /// merges together the same virtual register, return the register, otherwise
1302 unsigned MachineInstr::isConstantValuePHI() const {
1305 assert(getNumOperands() >= 3 &&
1306 "It's illegal to have a PHI without source operands");
1308 unsigned Reg
= getOperand(1).getReg();
1309 for (unsigned i
= 3, e
= getNumOperands(); i
< e
; i
+= 2)
1310 if (getOperand(i
).getReg() != Reg
)
1315 bool MachineInstr::hasUnmodeledSideEffects() const {
1316 if (hasProperty(MCID::UnmodeledSideEffects
))
1318 if (isInlineAsm()) {
1319 unsigned ExtraInfo
= getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
1320 if (ExtraInfo
& InlineAsm::Extra_HasSideEffects
)
1327 bool MachineInstr::isLoadFoldBarrier() const {
1328 return mayStore() || isCall() || hasUnmodeledSideEffects();
1331 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1333 bool MachineInstr::allDefsAreDead() const {
1334 for (const MachineOperand
&MO
: operands()) {
1335 if (!MO
.isReg() || MO
.isUse())
1343 /// copyImplicitOps - Copy implicit register operands from specified
1344 /// instruction to this instruction.
1345 void MachineInstr::copyImplicitOps(MachineFunction
&MF
,
1346 const MachineInstr
&MI
) {
1347 for (unsigned i
= MI
.getDesc().getNumOperands(), e
= MI
.getNumOperands();
1349 const MachineOperand
&MO
= MI
.getOperand(i
);
1350 if ((MO
.isReg() && MO
.isImplicit()) || MO
.isRegMask())
1355 bool MachineInstr::hasComplexRegisterTies() const {
1356 const MCInstrDesc
&MCID
= getDesc();
1357 for (unsigned I
= 0, E
= getNumOperands(); I
< E
; ++I
) {
1358 const auto &Operand
= getOperand(I
);
1359 if (!Operand
.isReg() || Operand
.isDef())
1360 // Ignore the defined registers as MCID marks only the uses as tied.
1362 int ExpectedTiedIdx
= MCID
.getOperandConstraint(I
, MCOI::TIED_TO
);
1363 int TiedIdx
= Operand
.isTied() ? int(findTiedOperandIdx(I
)) : -1;
1364 if (ExpectedTiedIdx
!= TiedIdx
)
1370 LLT
MachineInstr::getTypeToPrint(unsigned OpIdx
, SmallBitVector
&PrintedTypes
,
1371 const MachineRegisterInfo
&MRI
) const {
1372 const MachineOperand
&Op
= getOperand(OpIdx
);
1376 if (isVariadic() || OpIdx
>= getNumExplicitOperands())
1377 return MRI
.getType(Op
.getReg());
1379 auto &OpInfo
= getDesc().OpInfo
[OpIdx
];
1380 if (!OpInfo
.isGenericType())
1381 return MRI
.getType(Op
.getReg());
1383 if (PrintedTypes
[OpInfo
.getGenericTypeIndex()])
1386 LLT TypeToPrint
= MRI
.getType(Op
.getReg());
1387 // Don't mark the type index printed if it wasn't actually printed: maybe
1388 // another operand with the same type index has an actual type attached:
1389 if (TypeToPrint
.isValid())
1390 PrintedTypes
.set(OpInfo
.getGenericTypeIndex());
1394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1395 LLVM_DUMP_METHOD
void MachineInstr::dump() const {
1401 void MachineInstr::print(raw_ostream
&OS
, bool IsStandalone
, bool SkipOpers
,
1402 bool SkipDebugLoc
, bool AddNewLine
,
1403 const TargetInstrInfo
*TII
) const {
1404 const Module
*M
= nullptr;
1405 const Function
*F
= nullptr;
1406 if (const MachineFunction
*MF
= getMFIfAvailable(*this)) {
1407 F
= &MF
->getFunction();
1410 TII
= MF
->getSubtarget().getInstrInfo();
1413 ModuleSlotTracker
MST(M
);
1415 MST
.incorporateFunction(*F
);
1416 print(OS
, MST
, IsStandalone
, SkipOpers
, SkipDebugLoc
, TII
);
1419 void MachineInstr::print(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
1420 bool IsStandalone
, bool SkipOpers
, bool SkipDebugLoc
,
1421 bool AddNewLine
, const TargetInstrInfo
*TII
) const {
1422 // We can be a bit tidier if we know the MachineFunction.
1423 const MachineFunction
*MF
= nullptr;
1424 const TargetRegisterInfo
*TRI
= nullptr;
1425 const MachineRegisterInfo
*MRI
= nullptr;
1426 const TargetIntrinsicInfo
*IntrinsicInfo
= nullptr;
1427 tryToGetTargetInfo(*this, TRI
, MRI
, IntrinsicInfo
, TII
);
1429 if (isCFIInstruction())
1430 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
1432 SmallBitVector
PrintedTypes(8);
1433 bool ShouldPrintRegisterTies
= hasComplexRegisterTies();
1434 auto getTiedOperandIdx
= [&](unsigned OpIdx
) {
1435 if (!ShouldPrintRegisterTies
)
1437 const MachineOperand
&MO
= getOperand(OpIdx
);
1438 if (MO
.isReg() && MO
.isTied() && !MO
.isDef())
1439 return findTiedOperandIdx(OpIdx
);
1442 unsigned StartOp
= 0;
1443 unsigned e
= getNumOperands();
1445 // Print explicitly defined operands on the left of an assignment syntax.
1446 while (StartOp
< e
) {
1447 const MachineOperand
&MO
= getOperand(StartOp
);
1448 if (!MO
.isReg() || !MO
.isDef() || MO
.isImplicit())
1454 LLT TypeToPrint
= MRI
? getTypeToPrint(StartOp
, PrintedTypes
, *MRI
) : LLT
{};
1455 unsigned TiedOperandIdx
= getTiedOperandIdx(StartOp
);
1456 MO
.print(OS
, MST
, TypeToPrint
, /*PrintDef=*/false, IsStandalone
,
1457 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
, IntrinsicInfo
);
1464 if (getFlag(MachineInstr::FrameSetup
))
1465 OS
<< "frame-setup ";
1466 if (getFlag(MachineInstr::FrameDestroy
))
1467 OS
<< "frame-destroy ";
1468 if (getFlag(MachineInstr::FmNoNans
))
1470 if (getFlag(MachineInstr::FmNoInfs
))
1472 if (getFlag(MachineInstr::FmNsz
))
1474 if (getFlag(MachineInstr::FmArcp
))
1476 if (getFlag(MachineInstr::FmContract
))
1478 if (getFlag(MachineInstr::FmAfn
))
1480 if (getFlag(MachineInstr::FmReassoc
))
1482 if (getFlag(MachineInstr::NoUWrap
))
1484 if (getFlag(MachineInstr::NoSWrap
))
1486 if (getFlag(MachineInstr::IsExact
))
1489 // Print the opcode name.
1491 OS
<< TII
->getName(getOpcode());
1498 // Print the rest of the operands.
1499 bool FirstOp
= true;
1500 unsigned AsmDescOp
= ~0u;
1501 unsigned AsmOpCount
= 0;
1503 if (isInlineAsm() && e
>= InlineAsm::MIOp_FirstOperand
) {
1504 // Print asm string.
1506 const unsigned OpIdx
= InlineAsm::MIOp_AsmString
;
1507 LLT TypeToPrint
= MRI
? getTypeToPrint(OpIdx
, PrintedTypes
, *MRI
) : LLT
{};
1508 unsigned TiedOperandIdx
= getTiedOperandIdx(OpIdx
);
1509 getOperand(OpIdx
).print(OS
, MST
, TypeToPrint
, /*PrintDef=*/true, IsStandalone
,
1510 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
,
1513 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1514 unsigned ExtraInfo
= getOperand(InlineAsm::MIOp_ExtraInfo
).getImm();
1515 if (ExtraInfo
& InlineAsm::Extra_HasSideEffects
)
1516 OS
<< " [sideeffect]";
1517 if (ExtraInfo
& InlineAsm::Extra_MayLoad
)
1519 if (ExtraInfo
& InlineAsm::Extra_MayStore
)
1520 OS
<< " [maystore]";
1521 if (ExtraInfo
& InlineAsm::Extra_IsConvergent
)
1522 OS
<< " [isconvergent]";
1523 if (ExtraInfo
& InlineAsm::Extra_IsAlignStack
)
1524 OS
<< " [alignstack]";
1525 if (getInlineAsmDialect() == InlineAsm::AD_ATT
)
1526 OS
<< " [attdialect]";
1527 if (getInlineAsmDialect() == InlineAsm::AD_Intel
)
1528 OS
<< " [inteldialect]";
1530 StartOp
= AsmDescOp
= InlineAsm::MIOp_FirstOperand
;
1534 for (unsigned i
= StartOp
, e
= getNumOperands(); i
!= e
; ++i
) {
1535 const MachineOperand
&MO
= getOperand(i
);
1537 if (FirstOp
) FirstOp
= false; else OS
<< ",";
1540 if (isDebugValue() && MO
.isMetadata()) {
1541 // Pretty print DBG_VALUE instructions.
1542 auto *DIV
= dyn_cast
<DILocalVariable
>(MO
.getMetadata());
1543 if (DIV
&& !DIV
->getName().empty())
1544 OS
<< "!\"" << DIV
->getName() << '\"';
1546 LLT TypeToPrint
= MRI
? getTypeToPrint(i
, PrintedTypes
, *MRI
) : LLT
{};
1547 unsigned TiedOperandIdx
= getTiedOperandIdx(i
);
1548 MO
.print(OS
, MST
, TypeToPrint
, /*PrintDef=*/true, IsStandalone
,
1549 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
, IntrinsicInfo
);
1551 } else if (isDebugLabel() && MO
.isMetadata()) {
1552 // Pretty print DBG_LABEL instructions.
1553 auto *DIL
= dyn_cast
<DILabel
>(MO
.getMetadata());
1554 if (DIL
&& !DIL
->getName().empty())
1555 OS
<< "\"" << DIL
->getName() << '\"';
1557 LLT TypeToPrint
= MRI
? getTypeToPrint(i
, PrintedTypes
, *MRI
) : LLT
{};
1558 unsigned TiedOperandIdx
= getTiedOperandIdx(i
);
1559 MO
.print(OS
, MST
, TypeToPrint
, /*PrintDef=*/true, IsStandalone
,
1560 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
, IntrinsicInfo
);
1562 } else if (i
== AsmDescOp
&& MO
.isImm()) {
1563 // Pretty print the inline asm operand descriptor.
1564 OS
<< '$' << AsmOpCount
++;
1565 unsigned Flag
= MO
.getImm();
1566 switch (InlineAsm::getKind(Flag
)) {
1567 case InlineAsm::Kind_RegUse
: OS
<< ":[reguse"; break;
1568 case InlineAsm::Kind_RegDef
: OS
<< ":[regdef"; break;
1569 case InlineAsm::Kind_RegDefEarlyClobber
: OS
<< ":[regdef-ec"; break;
1570 case InlineAsm::Kind_Clobber
: OS
<< ":[clobber"; break;
1571 case InlineAsm::Kind_Imm
: OS
<< ":[imm"; break;
1572 case InlineAsm::Kind_Mem
: OS
<< ":[mem"; break;
1573 default: OS
<< ":[??" << InlineAsm::getKind(Flag
); break;
1577 if (!InlineAsm::isImmKind(Flag
) && !InlineAsm::isMemKind(Flag
) &&
1578 InlineAsm::hasRegClassConstraint(Flag
, RCID
)) {
1580 OS
<< ':' << TRI
->getRegClassName(TRI
->getRegClass(RCID
));
1582 OS
<< ":RC" << RCID
;
1585 if (InlineAsm::isMemKind(Flag
)) {
1586 unsigned MCID
= InlineAsm::getMemoryConstraintID(Flag
);
1588 case InlineAsm::Constraint_es
: OS
<< ":es"; break;
1589 case InlineAsm::Constraint_i
: OS
<< ":i"; break;
1590 case InlineAsm::Constraint_m
: OS
<< ":m"; break;
1591 case InlineAsm::Constraint_o
: OS
<< ":o"; break;
1592 case InlineAsm::Constraint_v
: OS
<< ":v"; break;
1593 case InlineAsm::Constraint_Q
: OS
<< ":Q"; break;
1594 case InlineAsm::Constraint_R
: OS
<< ":R"; break;
1595 case InlineAsm::Constraint_S
: OS
<< ":S"; break;
1596 case InlineAsm::Constraint_T
: OS
<< ":T"; break;
1597 case InlineAsm::Constraint_Um
: OS
<< ":Um"; break;
1598 case InlineAsm::Constraint_Un
: OS
<< ":Un"; break;
1599 case InlineAsm::Constraint_Uq
: OS
<< ":Uq"; break;
1600 case InlineAsm::Constraint_Us
: OS
<< ":Us"; break;
1601 case InlineAsm::Constraint_Ut
: OS
<< ":Ut"; break;
1602 case InlineAsm::Constraint_Uv
: OS
<< ":Uv"; break;
1603 case InlineAsm::Constraint_Uy
: OS
<< ":Uy"; break;
1604 case InlineAsm::Constraint_X
: OS
<< ":X"; break;
1605 case InlineAsm::Constraint_Z
: OS
<< ":Z"; break;
1606 case InlineAsm::Constraint_ZC
: OS
<< ":ZC"; break;
1607 case InlineAsm::Constraint_Zy
: OS
<< ":Zy"; break;
1608 default: OS
<< ":?"; break;
1612 unsigned TiedTo
= 0;
1613 if (InlineAsm::isUseOperandTiedToDef(Flag
, TiedTo
))
1614 OS
<< " tiedto:$" << TiedTo
;
1618 // Compute the index of the next operand descriptor.
1619 AsmDescOp
+= 1 + InlineAsm::getNumOperandRegisters(Flag
);
1621 LLT TypeToPrint
= MRI
? getTypeToPrint(i
, PrintedTypes
, *MRI
) : LLT
{};
1622 unsigned TiedOperandIdx
= getTiedOperandIdx(i
);
1623 if (MO
.isImm() && isOperandSubregIdx(i
))
1624 MachineOperand::printSubRegIdx(OS
, MO
.getImm(), TRI
);
1626 MO
.print(OS
, MST
, TypeToPrint
, /*PrintDef=*/true, IsStandalone
,
1627 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
, IntrinsicInfo
);
1631 // Print any optional symbols attached to this instruction as-if they were
1633 if (MCSymbol
*PreInstrSymbol
= getPreInstrSymbol()) {
1638 OS
<< " pre-instr-symbol ";
1639 MachineOperand::printSymbol(OS
, *PreInstrSymbol
);
1641 if (MCSymbol
*PostInstrSymbol
= getPostInstrSymbol()) {
1646 OS
<< " post-instr-symbol ";
1647 MachineOperand::printSymbol(OS
, *PostInstrSymbol
);
1650 if (!SkipDebugLoc
) {
1651 if (const DebugLoc
&DL
= getDebugLoc()) {
1654 OS
<< " debug-location ";
1655 DL
->printAsOperand(OS
, MST
);
1659 if (!memoperands_empty()) {
1660 SmallVector
<StringRef
, 0> SSNs
;
1661 const LLVMContext
*Context
= nullptr;
1662 std::unique_ptr
<LLVMContext
> CtxPtr
;
1663 const MachineFrameInfo
*MFI
= nullptr;
1664 if (const MachineFunction
*MF
= getMFIfAvailable(*this)) {
1665 MFI
= &MF
->getFrameInfo();
1666 Context
= &MF
->getFunction().getContext();
1668 CtxPtr
= llvm::make_unique
<LLVMContext
>();
1669 Context
= CtxPtr
.get();
1673 bool NeedComma
= false;
1674 for (const MachineMemOperand
*Op
: memoperands()) {
1677 Op
->print(OS
, MST
, SSNs
, *Context
, MFI
, TII
);
1685 bool HaveSemi
= false;
1687 // Print debug location information.
1688 if (const DebugLoc
&DL
= getDebugLoc()) {
1697 // Print extra comments for DEBUG_VALUE.
1698 if (isDebugValue() && getOperand(e
- 2).isMetadata()) {
1703 auto *DV
= cast
<DILocalVariable
>(getOperand(e
- 2).getMetadata());
1704 OS
<< " line no:" << DV
->getLine();
1705 if (auto *InlinedAt
= debugLoc
->getInlinedAt()) {
1706 DebugLoc
InlinedAtDL(InlinedAt
);
1707 if (InlinedAtDL
&& MF
) {
1708 OS
<< " inlined @[ ";
1709 InlinedAtDL
.print(OS
);
1713 if (isIndirectDebugValue())
1722 bool MachineInstr::addRegisterKilled(unsigned IncomingReg
,
1723 const TargetRegisterInfo
*RegInfo
,
1724 bool AddIfNotFound
) {
1725 bool isPhysReg
= TargetRegisterInfo::isPhysicalRegister(IncomingReg
);
1726 bool hasAliases
= isPhysReg
&&
1727 MCRegAliasIterator(IncomingReg
, RegInfo
, false).isValid();
1729 SmallVector
<unsigned,4> DeadOps
;
1730 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
1731 MachineOperand
&MO
= getOperand(i
);
1732 if (!MO
.isReg() || !MO
.isUse() || MO
.isUndef())
1735 // DEBUG_VALUE nodes do not contribute to code generation and should
1736 // always be ignored. Failure to do so may result in trying to modify
1737 // KILL flags on DEBUG_VALUE nodes.
1741 unsigned Reg
= MO
.getReg();
1745 if (Reg
== IncomingReg
) {
1748 // The register is already marked kill.
1750 if (isPhysReg
&& isRegTiedToDefOperand(i
))
1751 // Two-address uses of physregs must not be marked kill.
1756 } else if (hasAliases
&& MO
.isKill() &&
1757 TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1758 // A super-register kill already exists.
1759 if (RegInfo
->isSuperRegister(IncomingReg
, Reg
))
1761 if (RegInfo
->isSubRegister(IncomingReg
, Reg
))
1762 DeadOps
.push_back(i
);
1766 // Trim unneeded kill operands.
1767 while (!DeadOps
.empty()) {
1768 unsigned OpIdx
= DeadOps
.back();
1769 if (getOperand(OpIdx
).isImplicit() &&
1770 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx
) < 0))
1771 RemoveOperand(OpIdx
);
1773 getOperand(OpIdx
).setIsKill(false);
1777 // If not found, this means an alias of one of the operands is killed. Add a
1778 // new implicit operand if required.
1779 if (!Found
&& AddIfNotFound
) {
1780 addOperand(MachineOperand::CreateReg(IncomingReg
,
1789 void MachineInstr::clearRegisterKills(unsigned Reg
,
1790 const TargetRegisterInfo
*RegInfo
) {
1791 if (!TargetRegisterInfo::isPhysicalRegister(Reg
))
1793 for (MachineOperand
&MO
: operands()) {
1794 if (!MO
.isReg() || !MO
.isUse() || !MO
.isKill())
1796 unsigned OpReg
= MO
.getReg();
1797 if ((RegInfo
&& RegInfo
->regsOverlap(Reg
, OpReg
)) || Reg
== OpReg
)
1798 MO
.setIsKill(false);
1802 bool MachineInstr::addRegisterDead(unsigned Reg
,
1803 const TargetRegisterInfo
*RegInfo
,
1804 bool AddIfNotFound
) {
1805 bool isPhysReg
= TargetRegisterInfo::isPhysicalRegister(Reg
);
1806 bool hasAliases
= isPhysReg
&&
1807 MCRegAliasIterator(Reg
, RegInfo
, false).isValid();
1809 SmallVector
<unsigned,4> DeadOps
;
1810 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
1811 MachineOperand
&MO
= getOperand(i
);
1812 if (!MO
.isReg() || !MO
.isDef())
1814 unsigned MOReg
= MO
.getReg();
1821 } else if (hasAliases
&& MO
.isDead() &&
1822 TargetRegisterInfo::isPhysicalRegister(MOReg
)) {
1823 // There exists a super-register that's marked dead.
1824 if (RegInfo
->isSuperRegister(Reg
, MOReg
))
1826 if (RegInfo
->isSubRegister(Reg
, MOReg
))
1827 DeadOps
.push_back(i
);
1831 // Trim unneeded dead operands.
1832 while (!DeadOps
.empty()) {
1833 unsigned OpIdx
= DeadOps
.back();
1834 if (getOperand(OpIdx
).isImplicit() &&
1835 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx
) < 0))
1836 RemoveOperand(OpIdx
);
1838 getOperand(OpIdx
).setIsDead(false);
1842 // If not found, this means an alias of one of the operands is dead. Add a
1843 // new implicit operand if required.
1844 if (Found
|| !AddIfNotFound
)
1847 addOperand(MachineOperand::CreateReg(Reg
,
1855 void MachineInstr::clearRegisterDeads(unsigned Reg
) {
1856 for (MachineOperand
&MO
: operands()) {
1857 if (!MO
.isReg() || !MO
.isDef() || MO
.getReg() != Reg
)
1859 MO
.setIsDead(false);
1863 void MachineInstr::setRegisterDefReadUndef(unsigned Reg
, bool IsUndef
) {
1864 for (MachineOperand
&MO
: operands()) {
1865 if (!MO
.isReg() || !MO
.isDef() || MO
.getReg() != Reg
|| MO
.getSubReg() == 0)
1867 MO
.setIsUndef(IsUndef
);
1871 void MachineInstr::addRegisterDefined(unsigned Reg
,
1872 const TargetRegisterInfo
*RegInfo
) {
1873 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1874 MachineOperand
*MO
= findRegisterDefOperand(Reg
, false, RegInfo
);
1878 for (const MachineOperand
&MO
: operands()) {
1879 if (MO
.isReg() && MO
.getReg() == Reg
&& MO
.isDef() &&
1880 MO
.getSubReg() == 0)
1884 addOperand(MachineOperand::CreateReg(Reg
,
1889 void MachineInstr::setPhysRegsDeadExcept(ArrayRef
<unsigned> UsedRegs
,
1890 const TargetRegisterInfo
&TRI
) {
1891 bool HasRegMask
= false;
1892 for (MachineOperand
&MO
: operands()) {
1893 if (MO
.isRegMask()) {
1897 if (!MO
.isReg() || !MO
.isDef()) continue;
1898 unsigned Reg
= MO
.getReg();
1899 if (!TargetRegisterInfo::isPhysicalRegister(Reg
)) continue;
1900 // If there are no uses, including partial uses, the def is dead.
1901 if (llvm::none_of(UsedRegs
,
1902 [&](unsigned Use
) { return TRI
.regsOverlap(Use
, Reg
); }))
1906 // This is a call with a register mask operand.
1907 // Mask clobbers are always dead, so add defs for the non-dead defines.
1909 for (ArrayRef
<unsigned>::iterator I
= UsedRegs
.begin(), E
= UsedRegs
.end();
1911 addRegisterDefined(*I
, &TRI
);
1915 MachineInstrExpressionTrait::getHashValue(const MachineInstr
* const &MI
) {
1916 // Build up a buffer of hash code components.
1917 SmallVector
<size_t, 8> HashComponents
;
1918 HashComponents
.reserve(MI
->getNumOperands() + 1);
1919 HashComponents
.push_back(MI
->getOpcode());
1920 for (const MachineOperand
&MO
: MI
->operands()) {
1921 if (MO
.isReg() && MO
.isDef() &&
1922 TargetRegisterInfo::isVirtualRegister(MO
.getReg()))
1923 continue; // Skip virtual register defs.
1925 HashComponents
.push_back(hash_value(MO
));
1927 return hash_combine_range(HashComponents
.begin(), HashComponents
.end());
1930 void MachineInstr::emitError(StringRef Msg
) const {
1931 // Find the source location cookie.
1932 unsigned LocCookie
= 0;
1933 const MDNode
*LocMD
= nullptr;
1934 for (unsigned i
= getNumOperands(); i
!= 0; --i
) {
1935 if (getOperand(i
-1).isMetadata() &&
1936 (LocMD
= getOperand(i
-1).getMetadata()) &&
1937 LocMD
->getNumOperands() != 0) {
1938 if (const ConstantInt
*CI
=
1939 mdconst::dyn_extract
<ConstantInt
>(LocMD
->getOperand(0))) {
1940 LocCookie
= CI
->getZExtValue();
1946 if (const MachineBasicBlock
*MBB
= getParent())
1947 if (const MachineFunction
*MF
= MBB
->getParent())
1948 return MF
->getMMI().getModule()->getContext().emitError(LocCookie
, Msg
);
1949 report_fatal_error(Msg
);
1952 MachineInstrBuilder
llvm::BuildMI(MachineFunction
&MF
, const DebugLoc
&DL
,
1953 const MCInstrDesc
&MCID
, bool IsIndirect
,
1954 unsigned Reg
, const MDNode
*Variable
,
1955 const MDNode
*Expr
) {
1956 assert(isa
<DILocalVariable
>(Variable
) && "not a variable");
1957 assert(cast
<DIExpression
>(Expr
)->isValid() && "not an expression");
1958 assert(cast
<DILocalVariable
>(Variable
)->isValidLocationForIntrinsic(DL
) &&
1959 "Expected inlined-at fields to agree");
1960 auto MIB
= BuildMI(MF
, DL
, MCID
).addReg(Reg
, RegState::Debug
);
1964 MIB
.addReg(0U, RegState::Debug
);
1965 return MIB
.addMetadata(Variable
).addMetadata(Expr
);
1968 MachineInstrBuilder
llvm::BuildMI(MachineFunction
&MF
, const DebugLoc
&DL
,
1969 const MCInstrDesc
&MCID
, bool IsIndirect
,
1970 MachineOperand
&MO
, const MDNode
*Variable
,
1971 const MDNode
*Expr
) {
1972 assert(isa
<DILocalVariable
>(Variable
) && "not a variable");
1973 assert(cast
<DIExpression
>(Expr
)->isValid() && "not an expression");
1974 assert(cast
<DILocalVariable
>(Variable
)->isValidLocationForIntrinsic(DL
) &&
1975 "Expected inlined-at fields to agree");
1977 return BuildMI(MF
, DL
, MCID
, IsIndirect
, MO
.getReg(), Variable
, Expr
);
1979 auto MIB
= BuildMI(MF
, DL
, MCID
).add(MO
);
1983 MIB
.addReg(0U, RegState::Debug
);
1984 return MIB
.addMetadata(Variable
).addMetadata(Expr
);
1987 MachineInstrBuilder
llvm::BuildMI(MachineBasicBlock
&BB
,
1988 MachineBasicBlock::iterator I
,
1989 const DebugLoc
&DL
, const MCInstrDesc
&MCID
,
1990 bool IsIndirect
, unsigned Reg
,
1991 const MDNode
*Variable
, const MDNode
*Expr
) {
1992 MachineFunction
&MF
= *BB
.getParent();
1993 MachineInstr
*MI
= BuildMI(MF
, DL
, MCID
, IsIndirect
, Reg
, Variable
, Expr
);
1995 return MachineInstrBuilder(MF
, MI
);
1998 MachineInstrBuilder
llvm::BuildMI(MachineBasicBlock
&BB
,
1999 MachineBasicBlock::iterator I
,
2000 const DebugLoc
&DL
, const MCInstrDesc
&MCID
,
2001 bool IsIndirect
, MachineOperand
&MO
,
2002 const MDNode
*Variable
, const MDNode
*Expr
) {
2003 MachineFunction
&MF
= *BB
.getParent();
2004 MachineInstr
*MI
= BuildMI(MF
, DL
, MCID
, IsIndirect
, MO
, Variable
, Expr
);
2006 return MachineInstrBuilder(MF
, *MI
);
2009 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2010 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2011 static const DIExpression
*computeExprForSpill(const MachineInstr
&MI
) {
2012 assert(MI
.getOperand(0).isReg() && "can't spill non-register");
2013 assert(MI
.getDebugVariable()->isValidLocationForIntrinsic(MI
.getDebugLoc()) &&
2014 "Expected inlined-at fields to agree");
2016 const DIExpression
*Expr
= MI
.getDebugExpression();
2017 if (MI
.isIndirectDebugValue()) {
2018 assert(MI
.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
2019 Expr
= DIExpression::prepend(Expr
, DIExpression::WithDeref
);
2024 MachineInstr
*llvm::buildDbgValueForSpill(MachineBasicBlock
&BB
,
2025 MachineBasicBlock::iterator I
,
2026 const MachineInstr
&Orig
,
2028 const DIExpression
*Expr
= computeExprForSpill(Orig
);
2029 return BuildMI(BB
, I
, Orig
.getDebugLoc(), Orig
.getDesc())
2030 .addFrameIndex(FrameIndex
)
2032 .addMetadata(Orig
.getDebugVariable())
2036 void llvm::updateDbgValueForSpill(MachineInstr
&Orig
, int FrameIndex
) {
2037 const DIExpression
*Expr
= computeExprForSpill(Orig
);
2038 Orig
.getOperand(0).ChangeToFrameIndex(FrameIndex
);
2039 Orig
.getOperand(1).ChangeToImmediate(0U);
2040 Orig
.getOperand(3).setMetadata(Expr
);
2043 void MachineInstr::collectDebugValues(
2044 SmallVectorImpl
<MachineInstr
*> &DbgValues
) {
2045 MachineInstr
&MI
= *this;
2046 if (!MI
.getOperand(0).isReg())
2049 MachineBasicBlock::iterator DI
= MI
; ++DI
;
2050 for (MachineBasicBlock::iterator DE
= MI
.getParent()->end();
2052 if (!DI
->isDebugValue())
2054 if (DI
->getOperand(0).isReg() &&
2055 DI
->getOperand(0).getReg() == MI
.getOperand(0).getReg())
2056 DbgValues
.push_back(&*DI
);