1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
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 // This file contains the declaration of the MachineInstr class, which is the
11 // basic representation for all target dependent machine instructions used by
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
17 #define LLVM_CODEGEN_MACHINEINSTR_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/Support/ArrayRecycler.h"
33 #include "llvm/Target/TargetOpcodes.h"
37 template <typename T> class SmallVectorImpl;
38 class TargetInstrInfo;
39 class TargetRegisterClass;
40 class TargetRegisterInfo;
41 class MachineFunction;
42 class MachineMemOperand;
44 //===----------------------------------------------------------------------===//
45 /// Representation of each machine instruction.
47 /// This class isn't a POD type, but it must have a trivial destructor. When a
48 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
49 /// without having their destructor called.
51 class MachineInstr : public ilist_node<MachineInstr> {
53 typedef MachineMemOperand **mmo_iterator;
55 /// Flags to specify different kinds of comments to output in
56 /// assembly code. These flags carry semantic information not
57 /// otherwise easily derivable from the IR text.
65 FrameSetup = 1 << 0, // Instruction is used as a part of
66 // function frame setup code.
67 FrameDestroy = 1 << 1, // Instruction is used as a part of
68 // function frame destruction code.
69 BundledPred = 1 << 2, // Instruction has bundled predecessors.
70 BundledSucc = 1 << 3 // Instruction has bundled successors.
73 const MCInstrDesc *MCID; // Instruction descriptor.
74 MachineBasicBlock *Parent; // Pointer to the owning basic block.
76 // Operands are allocated by an ArrayRecycler.
77 MachineOperand *Operands; // Pointer to the first operand.
78 unsigned NumOperands; // Number of operands on instruction.
79 typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
80 OperandCapacity CapOperands; // Capacity of the Operands array.
82 uint8_t Flags; // Various bits of additional
83 // information about machine
86 uint8_t AsmPrinterFlags; // Various bits of information used by
87 // the AsmPrinter to emit helpful
88 // comments. This is *not* semantic
89 // information. Do not use this for
90 // anything other than to convey comment
91 // information to AsmPrinter.
93 uint8_t NumMemRefs; // Information on memory references.
96 DebugLoc debugLoc; // Source line information.
98 MachineInstr(const MachineInstr&) = delete;
99 void operator=(const MachineInstr&) = delete;
100 // Use MachineFunction::DeleteMachineInstr() instead.
101 ~MachineInstr() = delete;
103 // Intrusive list support
104 friend struct ilist_traits<MachineInstr>;
105 friend struct ilist_traits<MachineBasicBlock>;
106 void setParent(MachineBasicBlock *P) { Parent = P; }
108 /// This constructor creates a copy of the given
109 /// MachineInstr in the given MachineFunction.
110 MachineInstr(MachineFunction &, const MachineInstr &);
112 /// This constructor create a MachineInstr and add the implicit operands.
113 /// It reserves space for number of operands specified by
114 /// MCInstrDesc. An explicit DebugLoc is supplied.
115 MachineInstr(MachineFunction &, const MCInstrDesc &MCID, DebugLoc dl,
118 // MachineInstrs are pool-allocated and owned by MachineFunction.
119 friend class MachineFunction;
122 const MachineBasicBlock* getParent() const { return Parent; }
123 MachineBasicBlock* getParent() { return Parent; }
125 /// Return the asm printer flags bitvector.
126 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
128 /// Clear the AsmPrinter bitvector.
129 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
131 /// Return whether an AsmPrinter flag is set.
132 bool getAsmPrinterFlag(CommentFlag Flag) const {
133 return AsmPrinterFlags & Flag;
136 /// Set a flag for the AsmPrinter.
137 void setAsmPrinterFlag(CommentFlag Flag) {
138 AsmPrinterFlags |= (uint8_t)Flag;
141 /// Clear specific AsmPrinter flags.
142 void clearAsmPrinterFlag(CommentFlag Flag) {
143 AsmPrinterFlags &= ~Flag;
146 /// Return the MI flags bitvector.
147 uint8_t getFlags() const {
151 /// Return whether an MI flag is set.
152 bool getFlag(MIFlag Flag) const {
157 void setFlag(MIFlag Flag) {
158 Flags |= (uint8_t)Flag;
161 void setFlags(unsigned flags) {
162 // Filter out the automatically maintained flags.
163 unsigned Mask = BundledPred | BundledSucc;
164 Flags = (Flags & Mask) | (flags & ~Mask);
167 /// clearFlag - Clear a MI flag.
168 void clearFlag(MIFlag Flag) {
169 Flags &= ~((uint8_t)Flag);
172 /// Return true if MI is in a bundle (but not the first MI in a bundle).
174 /// A bundle looks like this before it's finalized:
186 /// In this case, the first MI starts a bundle but is not inside a bundle, the
187 /// next 2 MIs are considered "inside" the bundle.
189 /// After a bundle is finalized, it looks like this:
205 /// The first instruction has the special opcode "BUNDLE". It's not "inside"
206 /// a bundle, but the next three MIs are.
207 bool isInsideBundle() const {
208 return getFlag(BundledPred);
211 /// Return true if this instruction part of a bundle. This is true
212 /// if either itself or its following instruction is marked "InsideBundle".
213 bool isBundled() const {
214 return isBundledWithPred() || isBundledWithSucc();
217 /// Return true if this instruction is part of a bundle, and it is not the
218 /// first instruction in the bundle.
219 bool isBundledWithPred() const { return getFlag(BundledPred); }
221 /// Return true if this instruction is part of a bundle, and it is not the
222 /// last instruction in the bundle.
223 bool isBundledWithSucc() const { return getFlag(BundledSucc); }
225 /// Bundle this instruction with its predecessor. This can be an unbundled
226 /// instruction, or it can be the first instruction in a bundle.
227 void bundleWithPred();
229 /// Bundle this instruction with its successor. This can be an unbundled
230 /// instruction, or it can be the last instruction in a bundle.
231 void bundleWithSucc();
233 /// Break bundle above this instruction.
234 void unbundleFromPred();
236 /// Break bundle below this instruction.
237 void unbundleFromSucc();
239 /// Returns the debug location id of this MachineInstr.
240 const DebugLoc &getDebugLoc() const { return debugLoc; }
242 /// Return the debug variable referenced by
243 /// this DBG_VALUE instruction.
244 const DILocalVariable *getDebugVariable() const {
245 assert(isDebugValue() && "not a DBG_VALUE");
246 return cast<DILocalVariable>(getOperand(2).getMetadata());
249 /// Return the complex address expression referenced by
250 /// this DBG_VALUE instruction.
251 const DIExpression *getDebugExpression() const {
252 assert(isDebugValue() && "not a DBG_VALUE");
253 return cast<DIExpression>(getOperand(3).getMetadata());
256 /// Emit an error referring to the source location of this instruction.
257 /// This should only be used for inline assembly that is somehow
258 /// impossible to compile. Other errors should have been handled much
261 /// If this method returns, the caller should try to recover from the error.
263 void emitError(StringRef Msg) const;
265 /// Returns the target instruction descriptor of this MachineInstr.
266 const MCInstrDesc &getDesc() const { return *MCID; }
268 /// Returns the opcode of this MachineInstr.
269 unsigned getOpcode() const { return MCID->Opcode; }
271 /// Access to explicit operands of the instruction.
273 unsigned getNumOperands() const { return NumOperands; }
275 const MachineOperand& getOperand(unsigned i) const {
276 assert(i < getNumOperands() && "getOperand() out of range!");
279 MachineOperand& getOperand(unsigned i) {
280 assert(i < getNumOperands() && "getOperand() out of range!");
284 /// Returns the number of non-implicit operands.
285 unsigned getNumExplicitOperands() const;
287 /// iterator/begin/end - Iterate over all operands of a machine instruction.
288 typedef MachineOperand *mop_iterator;
289 typedef const MachineOperand *const_mop_iterator;
291 mop_iterator operands_begin() { return Operands; }
292 mop_iterator operands_end() { return Operands + NumOperands; }
294 const_mop_iterator operands_begin() const { return Operands; }
295 const_mop_iterator operands_end() const { return Operands + NumOperands; }
297 iterator_range<mop_iterator> operands() {
298 return iterator_range<mop_iterator>(operands_begin(), operands_end());
300 iterator_range<const_mop_iterator> operands() const {
301 return iterator_range<const_mop_iterator>(operands_begin(), operands_end());
303 iterator_range<mop_iterator> explicit_operands() {
304 return iterator_range<mop_iterator>(
305 operands_begin(), operands_begin() + getNumExplicitOperands());
307 iterator_range<const_mop_iterator> explicit_operands() const {
308 return iterator_range<const_mop_iterator>(
309 operands_begin(), operands_begin() + getNumExplicitOperands());
311 iterator_range<mop_iterator> implicit_operands() {
312 return iterator_range<mop_iterator>(explicit_operands().end(),
315 iterator_range<const_mop_iterator> implicit_operands() const {
316 return iterator_range<const_mop_iterator>(explicit_operands().end(),
319 /// Returns a range over all explicit operands that are register definitions.
320 /// Implicit definition are not included!
321 iterator_range<mop_iterator> defs() {
322 return iterator_range<mop_iterator>(
323 operands_begin(), operands_begin() + getDesc().getNumDefs());
326 iterator_range<const_mop_iterator> defs() const {
327 return iterator_range<const_mop_iterator>(
328 operands_begin(), operands_begin() + getDesc().getNumDefs());
330 /// Returns a range that includes all operands that are register uses.
331 /// This may include unrelated operands which are not register uses.
332 iterator_range<mop_iterator> uses() {
333 return iterator_range<mop_iterator>(
334 operands_begin() + getDesc().getNumDefs(), operands_end());
337 iterator_range<const_mop_iterator> uses() const {
338 return iterator_range<const_mop_iterator>(
339 operands_begin() + getDesc().getNumDefs(), operands_end());
342 /// Returns the number of the operand iterator \p I points to.
343 unsigned getOperandNo(const_mop_iterator I) const {
344 return I - operands_begin();
347 /// Access to memory operands of the instruction
348 mmo_iterator memoperands_begin() const { return MemRefs; }
349 mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
350 bool memoperands_empty() const { return NumMemRefs == 0; }
352 iterator_range<mmo_iterator> memoperands() {
353 return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
355 iterator_range<mmo_iterator> memoperands() const {
356 return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
359 /// Return true if this instruction has exactly one MachineMemOperand.
360 bool hasOneMemOperand() const {
361 return NumMemRefs == 1;
364 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
365 /// queries but they are bundle aware.
368 IgnoreBundle, // Ignore bundles
369 AnyInBundle, // Return true if any instruction in bundle has property
370 AllInBundle // Return true if all instructions in bundle have property
373 /// Return true if the instruction (or in the case of a bundle,
374 /// the instructions inside the bundle) has the specified property.
375 /// The first argument is the property being queried.
376 /// The second argument indicates whether the query should look inside
377 /// instruction bundles.
378 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
379 // Inline the fast path for unbundled or bundle-internal instructions.
380 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
381 return getDesc().getFlags() & (1 << MCFlag);
383 // If this is the first instruction in a bundle, take the slow path.
384 return hasPropertyInBundle(1 << MCFlag, Type);
387 /// Return true if this instruction can have a variable number of operands.
388 /// In this case, the variable operands will be after the normal
389 /// operands but before the implicit definitions and uses (if any are
391 bool isVariadic(QueryType Type = IgnoreBundle) const {
392 return hasProperty(MCID::Variadic, Type);
395 /// Set if this instruction has an optional definition, e.g.
396 /// ARM instructions which can set condition code if 's' bit is set.
397 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
398 return hasProperty(MCID::HasOptionalDef, Type);
401 /// Return true if this is a pseudo instruction that doesn't
402 /// correspond to a real machine instruction.
403 bool isPseudo(QueryType Type = IgnoreBundle) const {
404 return hasProperty(MCID::Pseudo, Type);
407 bool isReturn(QueryType Type = AnyInBundle) const {
408 return hasProperty(MCID::Return, Type);
411 bool isCall(QueryType Type = AnyInBundle) const {
412 return hasProperty(MCID::Call, Type);
415 /// Returns true if the specified instruction stops control flow
416 /// from executing the instruction immediately following it. Examples include
417 /// unconditional branches and return instructions.
418 bool isBarrier(QueryType Type = AnyInBundle) const {
419 return hasProperty(MCID::Barrier, Type);
422 /// Returns true if this instruction part of the terminator for a basic block.
423 /// Typically this is things like return and branch instructions.
425 /// Various passes use this to insert code into the bottom of a basic block,
426 /// but before control flow occurs.
427 bool isTerminator(QueryType Type = AnyInBundle) const {
428 return hasProperty(MCID::Terminator, Type);
431 /// Returns true if this is a conditional, unconditional, or indirect branch.
432 /// Predicates below can be used to discriminate between
433 /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
434 /// get more information.
435 bool isBranch(QueryType Type = AnyInBundle) const {
436 return hasProperty(MCID::Branch, Type);
439 /// Return true if this is an indirect branch, such as a
440 /// branch through a register.
441 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
442 return hasProperty(MCID::IndirectBranch, Type);
445 /// Return true if this is a branch which may fall
446 /// through to the next instruction or may transfer control flow to some other
447 /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
448 /// information about this branch.
449 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
450 return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
453 /// Return true if this is a branch which always
454 /// transfers control flow to some other block. The
455 /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
456 /// about this branch.
457 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
458 return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
461 /// Return true if this instruction has a predicate operand that
462 /// controls execution. It may be set to 'always', or may be set to other
463 /// values. There are various methods in TargetInstrInfo that can be used to
464 /// control and modify the predicate in this instruction.
465 bool isPredicable(QueryType Type = AllInBundle) const {
466 // If it's a bundle than all bundled instructions must be predicable for this
468 return hasProperty(MCID::Predicable, Type);
471 /// Return true if this instruction is a comparison.
472 bool isCompare(QueryType Type = IgnoreBundle) const {
473 return hasProperty(MCID::Compare, Type);
476 /// Return true if this instruction is a move immediate
477 /// (including conditional moves) instruction.
478 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
479 return hasProperty(MCID::MoveImm, Type);
482 /// Return true if this instruction is a bitcast instruction.
483 bool isBitcast(QueryType Type = IgnoreBundle) const {
484 return hasProperty(MCID::Bitcast, Type);
487 /// Return true if this instruction is a select instruction.
488 bool isSelect(QueryType Type = IgnoreBundle) const {
489 return hasProperty(MCID::Select, Type);
492 /// Return true if this instruction cannot be safely duplicated.
493 /// For example, if the instruction has a unique labels attached
494 /// to it, duplicating it would cause multiple definition errors.
495 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
496 return hasProperty(MCID::NotDuplicable, Type);
499 /// Return true if this instruction is convergent.
500 /// Convergent instructions can not be made control-dependent on any
501 /// additional values.
502 bool isConvergent(QueryType Type = AnyInBundle) const {
503 return hasProperty(MCID::Convergent, Type);
506 /// Returns true if the specified instruction has a delay slot
507 /// which must be filled by the code generator.
508 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
509 return hasProperty(MCID::DelaySlot, Type);
512 /// Return true for instructions that can be folded as
513 /// memory operands in other instructions. The most common use for this
514 /// is instructions that are simple loads from memory that don't modify
515 /// the loaded value in any way, but it can also be used for instructions
516 /// that can be expressed as constant-pool loads, such as V_SETALLONES
517 /// on x86, to allow them to be folded when it is beneficial.
518 /// This should only be set on instructions that return a value in their
519 /// only virtual register definition.
520 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
521 return hasProperty(MCID::FoldableAsLoad, Type);
524 /// \brief Return true if this instruction behaves
525 /// the same way as the generic REG_SEQUENCE instructions.
527 /// dX VMOVDRR rY, rZ
529 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
531 /// Note that for the optimizers to be able to take advantage of
532 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
533 /// override accordingly.
534 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
535 return hasProperty(MCID::RegSequence, Type);
538 /// \brief Return true if this instruction behaves
539 /// the same way as the generic EXTRACT_SUBREG instructions.
541 /// rX, rY VMOVRRD dZ
542 /// is equivalent to two EXTRACT_SUBREG:
543 /// rX = EXTRACT_SUBREG dZ, ssub_0
544 /// rY = EXTRACT_SUBREG dZ, ssub_1
546 /// Note that for the optimizers to be able to take advantage of
547 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
548 /// override accordingly.
549 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
550 return hasProperty(MCID::ExtractSubreg, Type);
553 /// \brief Return true if this instruction behaves
554 /// the same way as the generic INSERT_SUBREG instructions.
556 /// dX = VSETLNi32 dY, rZ, Imm
557 /// is equivalent to a INSERT_SUBREG:
558 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
560 /// Note that for the optimizers to be able to take advantage of
561 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
562 /// override accordingly.
563 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
564 return hasProperty(MCID::InsertSubreg, Type);
567 //===--------------------------------------------------------------------===//
568 // Side Effect Analysis
569 //===--------------------------------------------------------------------===//
571 /// Return true if this instruction could possibly read memory.
572 /// Instructions with this flag set are not necessarily simple load
573 /// instructions, they may load a value and modify it, for example.
574 bool mayLoad(QueryType Type = AnyInBundle) const {
576 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
577 if (ExtraInfo & InlineAsm::Extra_MayLoad)
580 return hasProperty(MCID::MayLoad, Type);
583 /// Return true if this instruction could possibly modify memory.
584 /// Instructions with this flag set are not necessarily simple store
585 /// instructions, they may store a modified value based on their operands, or
586 /// may not actually modify anything, for example.
587 bool mayStore(QueryType Type = AnyInBundle) const {
589 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
590 if (ExtraInfo & InlineAsm::Extra_MayStore)
593 return hasProperty(MCID::MayStore, Type);
596 /// Return true if this instruction could possibly read or modify memory.
597 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
598 return mayLoad(Type) || mayStore(Type);
601 //===--------------------------------------------------------------------===//
602 // Flags that indicate whether an instruction can be modified by a method.
603 //===--------------------------------------------------------------------===//
605 /// Return true if this may be a 2- or 3-address
606 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
607 /// result if Y and Z are exchanged. If this flag is set, then the
608 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
611 /// Note that this flag may be set on instructions that are only commutable
612 /// sometimes. In these cases, the call to commuteInstruction will fail.
613 /// Also note that some instructions require non-trivial modification to
615 bool isCommutable(QueryType Type = IgnoreBundle) const {
616 return hasProperty(MCID::Commutable, Type);
619 /// Return true if this is a 2-address instruction
620 /// which can be changed into a 3-address instruction if needed. Doing this
621 /// transformation can be profitable in the register allocator, because it
622 /// means that the instruction can use a 2-address form if possible, but
623 /// degrade into a less efficient form if the source and dest register cannot
624 /// be assigned to the same register. For example, this allows the x86
625 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
626 /// is the same speed as the shift but has bigger code size.
628 /// If this returns true, then the target must implement the
629 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
630 /// is allowed to fail if the transformation isn't valid for this specific
631 /// instruction (e.g. shl reg, 4 on x86).
633 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
634 return hasProperty(MCID::ConvertibleTo3Addr, Type);
637 /// Return true if this instruction requires
638 /// custom insertion support when the DAG scheduler is inserting it into a
639 /// machine basic block. If this is true for the instruction, it basically
640 /// means that it is a pseudo instruction used at SelectionDAG time that is
641 /// expanded out into magic code by the target when MachineInstrs are formed.
643 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
644 /// is used to insert this into the MachineBasicBlock.
645 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
646 return hasProperty(MCID::UsesCustomInserter, Type);
649 /// Return true if this instruction requires *adjustment*
650 /// after instruction selection by calling a target hook. For example, this
651 /// can be used to fill in ARM 's' optional operand depending on whether
652 /// the conditional flag register is used.
653 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
654 return hasProperty(MCID::HasPostISelHook, Type);
657 /// Returns true if this instruction is a candidate for remat.
658 /// This flag is deprecated, please don't use it anymore. If this
659 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
660 /// verify the instruction is really rematable.
661 bool isRematerializable(QueryType Type = AllInBundle) const {
662 // It's only possible to re-mat a bundle if all bundled instructions are
663 // re-materializable.
664 return hasProperty(MCID::Rematerializable, Type);
667 /// Returns true if this instruction has the same cost (or less) than a move
668 /// instruction. This is useful during certain types of optimizations
669 /// (e.g., remat during two-address conversion or machine licm)
670 /// where we would like to remat or hoist the instruction, but not if it costs
671 /// more than moving the instruction into the appropriate register. Note, we
672 /// are not marking copies from and to the same register class with this flag.
673 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
674 // Only returns true for a bundle if all bundled instructions are cheap.
675 return hasProperty(MCID::CheapAsAMove, Type);
678 /// Returns true if this instruction source operands
679 /// have special register allocation requirements that are not captured by the
680 /// operand register classes. e.g. ARM::STRD's two source registers must be an
681 /// even / odd pair, ARM::STM registers have to be in ascending order.
682 /// Post-register allocation passes should not attempt to change allocations
683 /// for sources of instructions with this flag.
684 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
685 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
688 /// Returns true if this instruction def operands
689 /// have special register allocation requirements that are not captured by the
690 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
691 /// even / odd pair, ARM::LDM registers have to be in ascending order.
692 /// Post-register allocation passes should not attempt to change allocations
693 /// for definitions of instructions with this flag.
694 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
695 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
700 CheckDefs, // Check all operands for equality
701 CheckKillDead, // Check all operands including kill / dead markers
702 IgnoreDefs, // Ignore all definitions
703 IgnoreVRegDefs // Ignore virtual register definitions
706 /// Return true if this instruction is identical to (same
707 /// opcode and same operands as) the specified instruction.
708 bool isIdenticalTo(const MachineInstr *Other,
709 MICheckType Check = CheckDefs) const;
711 /// Unlink 'this' from the containing basic block, and return it without
714 /// This function can not be used on bundled instructions, use
715 /// removeFromBundle() to remove individual instructions from a bundle.
716 MachineInstr *removeFromParent();
718 /// Unlink this instruction from its basic block and return it without
721 /// If the instruction is part of a bundle, the other instructions in the
722 /// bundle remain bundled.
723 MachineInstr *removeFromBundle();
725 /// Unlink 'this' from the containing basic block and delete it.
727 /// If this instruction is the header of a bundle, the whole bundle is erased.
728 /// This function can not be used for instructions inside a bundle, use
729 /// eraseFromBundle() to erase individual bundled instructions.
730 void eraseFromParent();
732 /// Unlink 'this' from the containing basic block and delete it.
734 /// For all definitions mark their uses in DBG_VALUE nodes
735 /// as undefined. Otherwise like eraseFromParent().
736 void eraseFromParentAndMarkDBGValuesForRemoval();
738 /// Unlink 'this' form its basic block and delete it.
740 /// If the instruction is part of a bundle, the other instructions in the
741 /// bundle remain bundled.
742 void eraseFromBundle();
744 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
745 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
747 /// Returns true if the MachineInstr represents a label.
748 bool isLabel() const { return isEHLabel() || isGCLabel(); }
749 bool isCFIInstruction() const {
750 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
753 // True if the instruction represents a position in the function.
754 bool isPosition() const { return isLabel() || isCFIInstruction(); }
756 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
757 /// A DBG_VALUE is indirect iff the first operand is a register and
758 /// the second operand is an immediate.
759 bool isIndirectDebugValue() const {
760 return isDebugValue()
761 && getOperand(0).isReg()
762 && getOperand(1).isImm();
765 bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
766 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
767 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
768 bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
769 bool isMSInlineAsm() const {
770 return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
772 bool isStackAligningInlineAsm() const;
773 InlineAsm::AsmDialect getInlineAsmDialect() const;
774 bool isInsertSubreg() const {
775 return getOpcode() == TargetOpcode::INSERT_SUBREG;
777 bool isSubregToReg() const {
778 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
780 bool isRegSequence() const {
781 return getOpcode() == TargetOpcode::REG_SEQUENCE;
783 bool isBundle() const {
784 return getOpcode() == TargetOpcode::BUNDLE;
786 bool isCopy() const {
787 return getOpcode() == TargetOpcode::COPY;
789 bool isFullCopy() const {
790 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
792 bool isExtractSubreg() const {
793 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
796 /// Return true if the instruction behaves like a copy.
797 /// This does not include native copy instructions.
798 bool isCopyLike() const {
799 return isCopy() || isSubregToReg();
802 /// Return true is the instruction is an identity copy.
803 bool isIdentityCopy() const {
804 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
805 getOperand(0).getSubReg() == getOperand(1).getSubReg();
808 /// Return true if this is a transient instruction that is
809 /// either very likely to be eliminated during register allocation (such as
810 /// copy-like instructions), or if this instruction doesn't have an
811 /// execution-time cost.
812 bool isTransient() const {
813 switch(getOpcode()) {
814 default: return false;
815 // Copy-like instructions are usually eliminated during register allocation.
816 case TargetOpcode::PHI:
817 case TargetOpcode::COPY:
818 case TargetOpcode::INSERT_SUBREG:
819 case TargetOpcode::SUBREG_TO_REG:
820 case TargetOpcode::REG_SEQUENCE:
821 // Pseudo-instructions that don't produce any real output.
822 case TargetOpcode::IMPLICIT_DEF:
823 case TargetOpcode::KILL:
824 case TargetOpcode::CFI_INSTRUCTION:
825 case TargetOpcode::EH_LABEL:
826 case TargetOpcode::GC_LABEL:
827 case TargetOpcode::DBG_VALUE:
832 /// Return the number of instructions inside the MI bundle, excluding the
835 /// This is the number of instructions that MachineBasicBlock::iterator
836 /// skips, 0 for unbundled instructions.
837 unsigned getBundleSize() const;
839 /// Return true if the MachineInstr reads the specified register.
840 /// If TargetRegisterInfo is passed, then it also checks if there
841 /// is a read of a super-register.
842 /// This does not count partial redefines of virtual registers as reads:
844 bool readsRegister(unsigned Reg,
845 const TargetRegisterInfo *TRI = nullptr) const {
846 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
849 /// Return true if the MachineInstr reads the specified virtual register.
850 /// Take into account that a partial define is a
851 /// read-modify-write operation.
852 bool readsVirtualRegister(unsigned Reg) const {
853 return readsWritesVirtualRegister(Reg).first;
856 /// Return a pair of bools (reads, writes) indicating if this instruction
857 /// reads or writes Reg. This also considers partial defines.
858 /// If Ops is not null, all operand indices for Reg are added.
859 std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
860 SmallVectorImpl<unsigned> *Ops = nullptr) const;
862 /// Return true if the MachineInstr kills the specified register.
863 /// If TargetRegisterInfo is passed, then it also checks if there is
864 /// a kill of a super-register.
865 bool killsRegister(unsigned Reg,
866 const TargetRegisterInfo *TRI = nullptr) const {
867 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
870 /// Return true if the MachineInstr fully defines the specified register.
871 /// If TargetRegisterInfo is passed, then it also checks
872 /// if there is a def of a super-register.
873 /// NOTE: It's ignoring subreg indices on virtual registers.
874 bool definesRegister(unsigned Reg,
875 const TargetRegisterInfo *TRI = nullptr) const {
876 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
879 /// Return true if the MachineInstr modifies (fully define or partially
880 /// define) the specified register.
881 /// NOTE: It's ignoring subreg indices on virtual registers.
882 bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
883 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
886 /// Returns true if the register is dead in this machine instruction.
887 /// If TargetRegisterInfo is passed, then it also checks
888 /// if there is a dead def of a super-register.
889 bool registerDefIsDead(unsigned Reg,
890 const TargetRegisterInfo *TRI = nullptr) const {
891 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
894 /// Returns the operand index that is a use of the specific register or -1
895 /// if it is not found. It further tightens the search criteria to a use
896 /// that kills the register if isKill is true.
897 int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
898 const TargetRegisterInfo *TRI = nullptr) const;
900 /// Wrapper for findRegisterUseOperandIdx, it returns
901 /// a pointer to the MachineOperand rather than an index.
902 MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
903 const TargetRegisterInfo *TRI = nullptr) {
904 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
905 return (Idx == -1) ? nullptr : &getOperand(Idx);
908 const MachineOperand *findRegisterUseOperand(
909 unsigned Reg, bool isKill = false,
910 const TargetRegisterInfo *TRI = nullptr) const {
911 return const_cast<MachineInstr *>(this)->
912 findRegisterUseOperand(Reg, isKill, TRI);
915 /// Returns the operand index that is a def of the specified register or
916 /// -1 if it is not found. If isDead is true, defs that are not dead are
917 /// skipped. If Overlap is true, then it also looks for defs that merely
918 /// overlap the specified register. If TargetRegisterInfo is non-null,
919 /// then it also checks if there is a def of a super-register.
920 /// This may also return a register mask operand when Overlap is true.
921 int findRegisterDefOperandIdx(unsigned Reg,
922 bool isDead = false, bool Overlap = false,
923 const TargetRegisterInfo *TRI = nullptr) const;
925 /// Wrapper for findRegisterDefOperandIdx, it returns
926 /// a pointer to the MachineOperand rather than an index.
927 MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
928 const TargetRegisterInfo *TRI = nullptr) {
929 int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
930 return (Idx == -1) ? nullptr : &getOperand(Idx);
933 /// Find the index of the first operand in the
934 /// operand list that is used to represent the predicate. It returns -1 if
936 int findFirstPredOperandIdx() const;
938 /// Find the index of the flag word operand that
939 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
940 /// getOperand(OpIdx) does not belong to an inline asm operand group.
942 /// If GroupNo is not NULL, it will receive the number of the operand group
943 /// containing OpIdx.
945 /// The flag operand is an immediate that can be decoded with methods like
946 /// InlineAsm::hasRegClassConstraint().
948 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
950 /// Compute the static register class constraint for operand OpIdx.
951 /// For normal instructions, this is derived from the MCInstrDesc.
952 /// For inline assembly it is derived from the flag words.
954 /// Returns NULL if the static register class constraint cannot be
957 const TargetRegisterClass*
958 getRegClassConstraint(unsigned OpIdx,
959 const TargetInstrInfo *TII,
960 const TargetRegisterInfo *TRI) const;
962 /// \brief Applies the constraints (def/use) implied by this MI on \p Reg to
963 /// the given \p CurRC.
964 /// If \p ExploreBundle is set and MI is part of a bundle, all the
965 /// instructions inside the bundle will be taken into account. In other words,
966 /// this method accumulates all the constraints of the operand of this MI and
967 /// the related bundle if MI is a bundle or inside a bundle.
969 /// Returns the register class that satisfies both \p CurRC and the
970 /// constraints set by MI. Returns NULL if such a register class does not
973 /// \pre CurRC must not be NULL.
974 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
975 unsigned Reg, const TargetRegisterClass *CurRC,
976 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
977 bool ExploreBundle = false) const;
979 /// \brief Applies the constraints (def/use) implied by the \p OpIdx operand
980 /// to the given \p CurRC.
982 /// Returns the register class that satisfies both \p CurRC and the
983 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
986 /// \pre CurRC must not be NULL.
987 /// \pre The operand at \p OpIdx must be a register.
988 const TargetRegisterClass *
989 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
990 const TargetInstrInfo *TII,
991 const TargetRegisterInfo *TRI) const;
993 /// Add a tie between the register operands at DefIdx and UseIdx.
994 /// The tie will cause the register allocator to ensure that the two
995 /// operands are assigned the same physical register.
997 /// Tied operands are managed automatically for explicit operands in the
998 /// MCInstrDesc. This method is for exceptional cases like inline asm.
999 void tieOperands(unsigned DefIdx, unsigned UseIdx);
1001 /// Given the index of a tied register operand, find the
1002 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1003 /// index of the tied operand which must exist.
1004 unsigned findTiedOperandIdx(unsigned OpIdx) const;
1006 /// Given the index of a register def operand,
1007 /// check if the register def is tied to a source operand, due to either
1008 /// two-address elimination or inline assembly constraints. Returns the
1009 /// first tied use operand index by reference if UseOpIdx is not null.
1010 bool isRegTiedToUseOperand(unsigned DefOpIdx,
1011 unsigned *UseOpIdx = nullptr) const {
1012 const MachineOperand &MO = getOperand(DefOpIdx);
1013 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1016 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1020 /// Return true if the use operand of the specified index is tied to a def
1021 /// operand. It also returns the def operand index by reference if DefOpIdx
1023 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1024 unsigned *DefOpIdx = nullptr) const {
1025 const MachineOperand &MO = getOperand(UseOpIdx);
1026 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1029 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1033 /// Clears kill flags on all operands.
1034 void clearKillInfo();
1036 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1037 /// properly composing subreg indices where necessary.
1038 void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1039 const TargetRegisterInfo &RegInfo);
1041 /// We have determined MI kills a register. Look for the
1042 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1043 /// add a implicit operand if it's not found. Returns true if the operand
1044 /// exists / is added.
1045 bool addRegisterKilled(unsigned IncomingReg,
1046 const TargetRegisterInfo *RegInfo,
1047 bool AddIfNotFound = false);
1049 /// Clear all kill flags affecting Reg. If RegInfo is
1050 /// provided, this includes super-register kills.
1051 void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1053 /// We have determined MI defined a register without a use.
1054 /// Look for the operand that defines it and mark it as IsDead. If
1055 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1056 /// true if the operand exists / is added.
1057 bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1058 bool AddIfNotFound = false);
1060 /// Clear all dead flags on operands defining register @p Reg.
1061 void clearRegisterDeads(unsigned Reg);
1063 /// Mark all subregister defs of register @p Reg with the undef flag.
1064 /// This function is used when we determined to have a subregister def in an
1065 /// otherwise undefined super register.
1066 void addRegisterDefReadUndef(unsigned Reg);
1068 /// We have determined MI defines a register. Make sure there is an operand
1070 void addRegisterDefined(unsigned Reg,
1071 const TargetRegisterInfo *RegInfo = nullptr);
1073 /// Mark every physreg used by this instruction as
1074 /// dead except those in the UsedRegs list.
1076 /// On instructions with register mask operands, also add implicit-def
1077 /// operands for all registers in UsedRegs.
1078 void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1079 const TargetRegisterInfo &TRI);
1081 /// Return true if it is safe to move this instruction. If
1082 /// SawStore is set to true, it means that there is a store (or call) between
1083 /// the instruction's location and its intended destination.
1084 bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const;
1086 /// Return true if this instruction may have an ordered
1087 /// or volatile memory reference, or if the information describing the memory
1088 /// reference is not available. Return false if it is known to have no
1089 /// ordered or volatile memory references.
1090 bool hasOrderedMemoryRef() const;
1092 /// Return true if this instruction is loading from a
1093 /// location whose value is invariant across the function. For example,
1094 /// loading a value from the constant pool or from the argument area of
1095 /// a function if it does not change. This should only return true of *all*
1096 /// loads the instruction does are invariant (if it does multiple loads).
1097 bool isInvariantLoad(AliasAnalysis *AA) const;
1099 /// If the specified instruction is a PHI that always merges together the
1100 /// same virtual register, return the register, otherwise return 0.
1101 unsigned isConstantValuePHI() const;
1103 /// Return true if this instruction has side effects that are not modeled
1104 /// by mayLoad / mayStore, etc.
1105 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1106 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1107 /// INLINEASM instruction, in which case the side effect property is encoded
1108 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1110 bool hasUnmodeledSideEffects() const;
1112 /// Returns true if it is illegal to fold a load across this instruction.
1113 bool isLoadFoldBarrier() const;
1115 /// Return true if all the defs of this instruction are dead.
1116 bool allDefsAreDead() const;
1118 /// Copy implicit register operands from specified
1119 /// instruction to this instruction.
1120 void copyImplicitOps(MachineFunction &MF, const MachineInstr *MI);
1123 // Debugging support
1125 void print(raw_ostream &OS, bool SkipOpers = false) const;
1126 void print(raw_ostream &OS, ModuleSlotTracker &MST,
1127 bool SkipOpers = false) const;
1130 //===--------------------------------------------------------------------===//
1131 // Accessors used to build up machine instructions.
1133 /// Add the specified operand to the instruction. If it is an implicit
1134 /// operand, it is added to the end of the operand list. If it is an
1135 /// explicit operand it is added at the end of the explicit operand list
1136 /// (before the first implicit operand).
1138 /// MF must be the machine function that was used to allocate this
1141 /// MachineInstrBuilder provides a more convenient interface for creating
1142 /// instructions and adding operands.
1143 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1145 /// Add an operand without providing an MF reference. This only works for
1146 /// instructions that are inserted in a basic block.
1148 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1150 void addOperand(const MachineOperand &Op);
1152 /// Replace the instruction descriptor (thus opcode) of
1153 /// the current instruction with a new one.
1154 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1156 /// Replace current source information with new such.
1157 /// Avoid using this, the constructor argument is preferable.
1158 void setDebugLoc(DebugLoc dl) {
1159 debugLoc = std::move(dl);
1160 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1163 /// Erase an operand from an instruction, leaving it with one
1164 /// fewer operand than it started with.
1165 void RemoveOperand(unsigned i);
1167 /// Add a MachineMemOperand to the machine instruction.
1168 /// This function should be used only occasionally. The setMemRefs function
1169 /// is the primary method for setting up a MachineInstr's MemRefs list.
1170 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1172 /// Assign this MachineInstr's memory reference descriptor list.
1173 /// This does not transfer ownership.
1174 void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1175 MemRefs = NewMemRefs;
1176 NumMemRefs = uint8_t(NewMemRefsEnd - NewMemRefs);
1177 assert(NumMemRefs == NewMemRefsEnd - NewMemRefs && "Too many memrefs");
1180 /// Clear this MachineInstr's memory reference descriptor list.
1181 void clearMemRefs() {
1186 /// Break any tie involving OpIdx.
1187 void untieRegOperand(unsigned OpIdx) {
1188 MachineOperand &MO = getOperand(OpIdx);
1189 if (MO.isReg() && MO.isTied()) {
1190 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1195 /// Add all implicit def and use operands to this instruction.
1196 void addImplicitDefUseOperands(MachineFunction &MF);
1199 /// If this instruction is embedded into a MachineFunction, return the
1200 /// MachineRegisterInfo object for the current function, otherwise
1202 MachineRegisterInfo *getRegInfo();
1204 /// Unlink all of the register operands in this instruction from their
1205 /// respective use lists. This requires that the operands already be on their
1207 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1209 /// Add all of the register operands in this instruction from their
1210 /// respective use lists. This requires that the operands not be on their
1212 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1214 /// Slow path for hasProperty when we're dealing with a bundle.
1215 bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1217 /// \brief Implements the logic of getRegClassConstraintEffectForVReg for the
1218 /// this MI and the given operand index \p OpIdx.
1219 /// If the related operand does not constrained Reg, this returns CurRC.
1220 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1221 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1222 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1225 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1226 /// instruction rather than by pointer value.
1227 /// The hashing and equality testing functions ignore definitions so this is
1228 /// useful for CSE, etc.
1229 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1230 static inline MachineInstr *getEmptyKey() {
1234 static inline MachineInstr *getTombstoneKey() {
1235 return reinterpret_cast<MachineInstr*>(-1);
1238 static unsigned getHashValue(const MachineInstr* const &MI);
1240 static bool isEqual(const MachineInstr* const &LHS,
1241 const MachineInstr* const &RHS) {
1242 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1243 LHS == getEmptyKey() || LHS == getTombstoneKey())
1245 return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
1249 //===----------------------------------------------------------------------===//
1250 // Debugging Support
1252 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1257 } // End llvm namespace