1 //===-- llvm/CodeGen/MachineOperand.h - MachineOperand class ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the MachineOperand class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEOPERAND_H
14 #define LLVM_CODEGEN_MACHINEOPERAND_H
15 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/CodeGen/Register.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/Support/LowLevelTypeImpl.h"
21 #include <cassert>
22 
23 namespace llvm {
24 
25 class BlockAddress;
26 class Constant;
27 class ConstantFP;
28 class ConstantInt;
29 class GlobalValue;
30 class MachineBasicBlock;
31 class MachineInstr;
32 class MachineRegisterInfo;
33 class MCCFIInstruction;
34 class MDNode;
35 class ModuleSlotTracker;
36 class TargetIntrinsicInfo;
37 class TargetRegisterInfo;
38 class hash_code;
39 class raw_ostream;
40 class MCSymbol;
41 
42 /// MachineOperand class - Representation of each machine instruction operand.
43 ///
44 /// This class isn't a POD type because it has a private constructor, but its
45 /// destructor must be trivial. Functions like MachineInstr::addOperand(),
46 /// MachineRegisterInfo::moveOperands(), and MF::DeleteMachineInstr() depend on
47 /// not having to call the MachineOperand destructor.
48 ///
49 class MachineOperand {
50 public:
51   enum MachineOperandType : unsigned char {
52     MO_Register,          ///< Register operand.
53     MO_Immediate,         ///< Immediate operand
54     MO_CImmediate,        ///< Immediate >64bit operand
55     MO_FPImmediate,       ///< Floating-point immediate operand
56     MO_MachineBasicBlock, ///< MachineBasicBlock reference
57     MO_FrameIndex,        ///< Abstract Stack Frame Index
58     MO_ConstantPoolIndex, ///< Address of indexed Constant in Constant Pool
59     MO_TargetIndex,       ///< Target-dependent index+offset operand.
60     MO_JumpTableIndex,    ///< Address of indexed Jump Table for switch
61     MO_ExternalSymbol,    ///< Name of external global symbol
62     MO_GlobalAddress,     ///< Address of a global value
63     MO_BlockAddress,      ///< Address of a basic block
64     MO_RegisterMask,      ///< Mask of preserved registers.
65     MO_RegisterLiveOut,   ///< Mask of live-out registers.
66     MO_Metadata,          ///< Metadata reference (for debug info)
67     MO_MCSymbol,          ///< MCSymbol reference (for debug/eh info)
68     MO_CFIIndex,          ///< MCCFIInstruction index.
69     MO_IntrinsicID,       ///< Intrinsic ID for ISel
70     MO_Predicate,         ///< Generic predicate for ISel
71     MO_ShuffleMask,       ///< Other IR Constant for ISel (shuffle masks)
72     MO_Last = MO_ShuffleMask
73   };
74 
75 private:
76   /// OpKind - Specify what kind of operand this is.  This discriminates the
77   /// union.
78   unsigned OpKind : 8;
79 
80   /// Subregister number for MO_Register.  A value of 0 indicates the
81   /// MO_Register has no subReg.
82   ///
83   /// For all other kinds of operands, this field holds target-specific flags.
84   unsigned SubReg_TargetFlags : 12;
85 
86   /// TiedTo - Non-zero when this register operand is tied to another register
87   /// operand. The encoding of this field is described in the block comment
88   /// before MachineInstr::tieOperands().
89   unsigned TiedTo : 4;
90 
91   /// IsDef - True if this is a def, false if this is a use of the register.
92   /// This is only valid on register operands.
93   ///
94   unsigned IsDef : 1;
95 
96   /// IsImp - True if this is an implicit def or use, false if it is explicit.
97   /// This is only valid on register opderands.
98   ///
99   unsigned IsImp : 1;
100 
101   /// IsDeadOrKill
102   /// For uses: IsKill - Conservatively indicates the last use of a register
103   /// on this path through the function. A register operand with true value of
104   /// this flag must be the last use of the register, a register operand with
105   /// false value may or may not be the last use of the register. After regalloc
106   /// we can use recomputeLivenessFlags to get precise kill flags.
107   /// For defs: IsDead - True if this register is never used by a subsequent
108   /// instruction.
109   /// This is only valid on register operands.
110   unsigned IsDeadOrKill : 1;
111 
112   /// See isRenamable().
113   unsigned IsRenamable : 1;
114 
115   /// IsUndef - True if this register operand reads an "undef" value, i.e. the
116   /// read value doesn't matter.  This flag can be set on both use and def
117   /// operands.  On a sub-register def operand, it refers to the part of the
118   /// register that isn't written.  On a full-register def operand, it is a
119   /// noop.  See readsReg().
120   ///
121   /// This is only valid on registers.
122   ///
123   /// Note that an instruction may have multiple <undef> operands referring to
124   /// the same register.  In that case, the instruction may depend on those
125   /// operands reading the same dont-care value.  For example:
126   ///
127   ///   %1 = XOR undef %2, undef %2
128   ///
129   /// Any register can be used for %2, and its value doesn't matter, but
130   /// the two operands must be the same register.
131   ///
132   unsigned IsUndef : 1;
133 
134   /// IsInternalRead - True if this operand reads a value that was defined
135   /// inside the same instruction or bundle.  This flag can be set on both use
136   /// and def operands.  On a sub-register def operand, it refers to the part
137   /// of the register that isn't written.  On a full-register def operand, it
138   /// is a noop.
139   ///
140   /// When this flag is set, the instruction bundle must contain at least one
141   /// other def of the register.  If multiple instructions in the bundle define
142   /// the register, the meaning is target-defined.
143   unsigned IsInternalRead : 1;
144 
145   /// IsEarlyClobber - True if this MO_Register 'def' operand is written to
146   /// by the MachineInstr before all input registers are read.  This is used to
147   /// model the GCC inline asm '&' constraint modifier.
148   unsigned IsEarlyClobber : 1;
149 
150   /// IsDebug - True if this MO_Register 'use' operand is in a debug pseudo,
151   /// not a real instruction.  Such uses should be ignored during codegen.
152   unsigned IsDebug : 1;
153 
154   /// SmallContents - This really should be part of the Contents union, but
155   /// lives out here so we can get a better packed struct.
156   /// MO_Register: Register number.
157   /// OffsetedInfo: Low bits of offset.
158   union {
159     unsigned RegNo;           // For MO_Register.
160     unsigned OffsetLo;        // Matches Contents.OffsetedInfo.OffsetHi.
161   } SmallContents;
162 
163   /// ParentMI - This is the instruction that this operand is embedded into.
164   /// This is valid for all operand types, when the operand is in an instr.
165   MachineInstr *ParentMI;
166 
167   /// Contents union - This contains the payload for the various operand types.
168   union ContentsUnion {
ContentsUnion()169     ContentsUnion() {}
170     MachineBasicBlock *MBB;  // For MO_MachineBasicBlock.
171     const ConstantFP *CFP;   // For MO_FPImmediate.
172     const ConstantInt *CI;   // For MO_CImmediate. Integers > 64bit.
173     int64_t ImmVal;          // For MO_Immediate.
174     const uint32_t *RegMask; // For MO_RegisterMask and MO_RegisterLiveOut.
175     const MDNode *MD;        // For MO_Metadata.
176     MCSymbol *Sym;           // For MO_MCSymbol.
177     unsigned CFIIndex;       // For MO_CFI.
178     Intrinsic::ID IntrinsicID; // For MO_IntrinsicID.
179     unsigned Pred;           // For MO_Predicate
180     ArrayRef<int> ShuffleMask; // For MO_ShuffleMask
181 
182     struct {                  // For MO_Register.
183       // Register number is in SmallContents.RegNo.
184       MachineOperand *Prev;   // Access list for register. See MRI.
185       MachineOperand *Next;
186     } Reg;
187 
188     /// OffsetedInfo - This struct contains the offset and an object identifier.
189     /// this represent the object as with an optional offset from it.
190     struct {
191       union {
192         int Index;                // For MO_*Index - The index itself.
193         const char *SymbolName;   // For MO_ExternalSymbol.
194         const GlobalValue *GV;    // For MO_GlobalAddress.
195         const BlockAddress *BA;   // For MO_BlockAddress.
196       } Val;
197       // Low bits of offset are in SmallContents.OffsetLo.
198       int OffsetHi;               // An offset from the object, high 32 bits.
199     } OffsetedInfo;
200   } Contents;
201 
MachineOperand(MachineOperandType K)202   explicit MachineOperand(MachineOperandType K)
203     : OpKind(K), SubReg_TargetFlags(0), ParentMI(nullptr) {
204     // Assert that the layout is what we expect. It's easy to grow this object.
205     static_assert(alignof(MachineOperand) <= alignof(int64_t),
206                   "MachineOperand shouldn't be more than 8 byte aligned");
207     static_assert(sizeof(Contents) <= 2 * sizeof(void *),
208                   "Contents should be at most two pointers");
209     static_assert(sizeof(MachineOperand) <=
210                       alignTo<alignof(int64_t)>(2 * sizeof(unsigned) +
211                                                 3 * sizeof(void *)),
212                   "MachineOperand too big. Should be Kind, SmallContents, "
213                   "ParentMI, and Contents");
214   }
215 
216 public:
217   /// getType - Returns the MachineOperandType for this operand.
218   ///
getType()219   MachineOperandType getType() const { return (MachineOperandType)OpKind; }
220 
getTargetFlags()221   unsigned getTargetFlags() const {
222     return isReg() ? 0 : SubReg_TargetFlags;
223   }
setTargetFlags(unsigned F)224   void setTargetFlags(unsigned F) {
225     assert(!isReg() && "Register operands can't have target flags");
226     SubReg_TargetFlags = F;
227     assert(SubReg_TargetFlags == F && "Target flags out of range");
228   }
addTargetFlag(unsigned F)229   void addTargetFlag(unsigned F) {
230     assert(!isReg() && "Register operands can't have target flags");
231     SubReg_TargetFlags |= F;
232     assert((SubReg_TargetFlags & F) && "Target flags out of range");
233   }
234 
235 
236   /// getParent - Return the instruction that this operand belongs to.
237   ///
getParent()238   MachineInstr *getParent() { return ParentMI; }
getParent()239   const MachineInstr *getParent() const { return ParentMI; }
240 
241   /// clearParent - Reset the parent pointer.
242   ///
243   /// The MachineOperand copy constructor also copies ParentMI, expecting the
244   /// original to be deleted. If a MachineOperand is ever stored outside a
245   /// MachineInstr, the parent pointer must be cleared.
246   ///
247   /// Never call clearParent() on an operand in a MachineInstr.
248   ///
clearParent()249   void clearParent() { ParentMI = nullptr; }
250 
251   /// Print a subreg index operand.
252   /// MO_Immediate operands can also be subreg idices. If it's the case, the
253   /// subreg index name will be printed. MachineInstr::isOperandSubregIdx can be
254   /// called to check this.
255   static void printSubRegIdx(raw_ostream &OS, uint64_t Index,
256                              const TargetRegisterInfo *TRI);
257 
258   /// Print operand target flags.
259   static void printTargetFlags(raw_ostream& OS, const MachineOperand &Op);
260 
261   /// Print a MCSymbol as an operand.
262   static void printSymbol(raw_ostream &OS, MCSymbol &Sym);
263 
264   /// Print a stack object reference.
265   static void printStackObjectReference(raw_ostream &OS, unsigned FrameIndex,
266                                         bool IsFixed, StringRef Name);
267 
268   /// Print the offset with explicit +/- signs.
269   static void printOperandOffset(raw_ostream &OS, int64_t Offset);
270 
271   /// Print an IRSlotNumber.
272   static void printIRSlotNumber(raw_ostream &OS, int Slot);
273 
274   /// Print the MachineOperand to \p os.
275   /// Providing a valid \p TRI and \p IntrinsicInfo results in a more
276   /// target-specific printing. If \p TRI and \p IntrinsicInfo are null, the
277   /// function will try to pick it up from the parent.
278   void print(raw_ostream &os, const TargetRegisterInfo *TRI = nullptr,
279              const TargetIntrinsicInfo *IntrinsicInfo = nullptr) const;
280 
281   /// More complex way of printing a MachineOperand.
282   /// \param TypeToPrint specifies the generic type to be printed on uses and
283   /// defs. It can be determined using MachineInstr::getTypeToPrint.
284   /// \param OpIdx - specifies the index of the operand in machine instruction.
285   /// This will be used by target dependent MIR formatter. Could be None if the
286   /// index is unknown, e.g. called by dump().
287   /// \param PrintDef - whether we want to print `def` on an operand which
288   /// isDef. Sometimes, if the operand is printed before '=', we don't print
289   /// `def`.
290   /// \param IsStandalone - whether we want a verbose output of the MO. This
291   /// prints extra information that can be easily inferred when printing the
292   /// whole function, but not when printing only a fragment of it.
293   /// \param ShouldPrintRegisterTies - whether we want to print register ties.
294   /// Sometimes they are easily determined by the instruction's descriptor
295   /// (MachineInstr::hasComplexRegiterTies can determine if it's needed).
296   /// \param TiedOperandIdx - if we need to print register ties this needs to
297   /// provide the index of the tied register. If not, it will be ignored.
298   /// \param TRI - provide more target-specific information to the printer.
299   /// Unlike the previous function, this one will not try and get the
300   /// information from it's parent.
301   /// \param IntrinsicInfo - same as \p TRI.
302   void print(raw_ostream &os, ModuleSlotTracker &MST, LLT TypeToPrint,
303              Optional<unsigned> OpIdx, bool PrintDef, bool IsStandalone,
304              bool ShouldPrintRegisterTies, unsigned TiedOperandIdx,
305              const TargetRegisterInfo *TRI,
306              const TargetIntrinsicInfo *IntrinsicInfo) const;
307 
308   /// Same as print(os, TRI, IntrinsicInfo), but allows to specify the low-level
309   /// type to be printed the same way the full version of print(...) does it.
310   void print(raw_ostream &os, LLT TypeToPrint,
311              const TargetRegisterInfo *TRI = nullptr,
312              const TargetIntrinsicInfo *IntrinsicInfo = nullptr) const;
313 
314   void dump() const;
315 
316   //===--------------------------------------------------------------------===//
317   // Accessors that tell you what kind of MachineOperand you're looking at.
318   //===--------------------------------------------------------------------===//
319 
320   /// isReg - Tests if this is a MO_Register operand.
isReg()321   bool isReg() const { return OpKind == MO_Register; }
322   /// isImm - Tests if this is a MO_Immediate operand.
isImm()323   bool isImm() const { return OpKind == MO_Immediate; }
324   /// isCImm - Test if this is a MO_CImmediate operand.
isCImm()325   bool isCImm() const { return OpKind == MO_CImmediate; }
326   /// isFPImm - Tests if this is a MO_FPImmediate operand.
isFPImm()327   bool isFPImm() const { return OpKind == MO_FPImmediate; }
328   /// isMBB - Tests if this is a MO_MachineBasicBlock operand.
isMBB()329   bool isMBB() const { return OpKind == MO_MachineBasicBlock; }
330   /// isFI - Tests if this is a MO_FrameIndex operand.
isFI()331   bool isFI() const { return OpKind == MO_FrameIndex; }
332   /// isCPI - Tests if this is a MO_ConstantPoolIndex operand.
isCPI()333   bool isCPI() const { return OpKind == MO_ConstantPoolIndex; }
334   /// isTargetIndex - Tests if this is a MO_TargetIndex operand.
isTargetIndex()335   bool isTargetIndex() const { return OpKind == MO_TargetIndex; }
336   /// isJTI - Tests if this is a MO_JumpTableIndex operand.
isJTI()337   bool isJTI() const { return OpKind == MO_JumpTableIndex; }
338   /// isGlobal - Tests if this is a MO_GlobalAddress operand.
isGlobal()339   bool isGlobal() const { return OpKind == MO_GlobalAddress; }
340   /// isSymbol - Tests if this is a MO_ExternalSymbol operand.
isSymbol()341   bool isSymbol() const { return OpKind == MO_ExternalSymbol; }
342   /// isBlockAddress - Tests if this is a MO_BlockAddress operand.
isBlockAddress()343   bool isBlockAddress() const { return OpKind == MO_BlockAddress; }
344   /// isRegMask - Tests if this is a MO_RegisterMask operand.
isRegMask()345   bool isRegMask() const { return OpKind == MO_RegisterMask; }
346   /// isRegLiveOut - Tests if this is a MO_RegisterLiveOut operand.
isRegLiveOut()347   bool isRegLiveOut() const { return OpKind == MO_RegisterLiveOut; }
348   /// isMetadata - Tests if this is a MO_Metadata operand.
isMetadata()349   bool isMetadata() const { return OpKind == MO_Metadata; }
isMCSymbol()350   bool isMCSymbol() const { return OpKind == MO_MCSymbol; }
isCFIIndex()351   bool isCFIIndex() const { return OpKind == MO_CFIIndex; }
isIntrinsicID()352   bool isIntrinsicID() const { return OpKind == MO_IntrinsicID; }
isPredicate()353   bool isPredicate() const { return OpKind == MO_Predicate; }
isShuffleMask()354   bool isShuffleMask() const { return OpKind == MO_ShuffleMask; }
355   //===--------------------------------------------------------------------===//
356   // Accessors for Register Operands
357   //===--------------------------------------------------------------------===//
358 
359   /// getReg - Returns the register number.
getReg()360   Register getReg() const {
361     assert(isReg() && "This is not a register operand!");
362     return Register(SmallContents.RegNo);
363   }
364 
getSubReg()365   unsigned getSubReg() const {
366     assert(isReg() && "Wrong MachineOperand accessor");
367     return SubReg_TargetFlags;
368   }
369 
isUse()370   bool isUse() const {
371     assert(isReg() && "Wrong MachineOperand accessor");
372     return !IsDef;
373   }
374 
isDef()375   bool isDef() const {
376     assert(isReg() && "Wrong MachineOperand accessor");
377     return IsDef;
378   }
379 
isImplicit()380   bool isImplicit() const {
381     assert(isReg() && "Wrong MachineOperand accessor");
382     return IsImp;
383   }
384 
isDead()385   bool isDead() const {
386     assert(isReg() && "Wrong MachineOperand accessor");
387     return IsDeadOrKill & IsDef;
388   }
389 
isKill()390   bool isKill() const {
391     assert(isReg() && "Wrong MachineOperand accessor");
392     return IsDeadOrKill & !IsDef;
393   }
394 
isUndef()395   bool isUndef() const {
396     assert(isReg() && "Wrong MachineOperand accessor");
397     return IsUndef;
398   }
399 
400   /// isRenamable - Returns true if this register may be renamed, i.e. it does
401   /// not generate a value that is somehow read in a way that is not represented
402   /// by the Machine IR (e.g. to meet an ABI or ISA requirement).  This is only
403   /// valid on physical register operands.  Virtual registers are assumed to
404   /// always be renamable regardless of the value of this field.
405   ///
406   /// Operands that are renamable can freely be changed to any other register
407   /// that is a member of the register class returned by
408   /// MI->getRegClassConstraint().
409   ///
410   /// isRenamable can return false for several different reasons:
411   ///
412   /// - ABI constraints (since liveness is not always precisely modeled).  We
413   ///   conservatively handle these cases by setting all physical register
414   ///   operands that didn’t start out as virtual regs to not be renamable.
415   ///   Also any physical register operands created after register allocation or
416   ///   whose register is changed after register allocation will not be
417   ///   renamable.  This state is tracked in the MachineOperand::IsRenamable
418   ///   bit.
419   ///
420   /// - Opcode/target constraints: for opcodes that have complex register class
421   ///   requirements (e.g. that depend on other operands/instructions), we set
422   ///   hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq in the machine opcode
423   ///   description.  Operands belonging to instructions with opcodes that are
424   ///   marked hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq return false from
425   ///   isRenamable().  Additionally, the AllowRegisterRenaming target property
426   ///   prevents any operands from being marked renamable for targets that don't
427   ///   have detailed opcode hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq
428   ///   values.
429   bool isRenamable() const;
430 
isInternalRead()431   bool isInternalRead() const {
432     assert(isReg() && "Wrong MachineOperand accessor");
433     return IsInternalRead;
434   }
435 
isEarlyClobber()436   bool isEarlyClobber() const {
437     assert(isReg() && "Wrong MachineOperand accessor");
438     return IsEarlyClobber;
439   }
440 
isTied()441   bool isTied() const {
442     assert(isReg() && "Wrong MachineOperand accessor");
443     return TiedTo;
444   }
445 
isDebug()446   bool isDebug() const {
447     assert(isReg() && "Wrong MachineOperand accessor");
448     return IsDebug;
449   }
450 
451   /// readsReg - Returns true if this operand reads the previous value of its
452   /// register.  A use operand with the <undef> flag set doesn't read its
453   /// register.  A sub-register def implicitly reads the other parts of the
454   /// register being redefined unless the <undef> flag is set.
455   ///
456   /// This refers to reading the register value from before the current
457   /// instruction or bundle. Internal bundle reads are not included.
readsReg()458   bool readsReg() const {
459     assert(isReg() && "Wrong MachineOperand accessor");
460     return !isUndef() && !isInternalRead() && (isUse() || getSubReg());
461   }
462 
463   //===--------------------------------------------------------------------===//
464   // Mutators for Register Operands
465   //===--------------------------------------------------------------------===//
466 
467   /// Change the register this operand corresponds to.
468   ///
469   void setReg(Register Reg);
470 
setSubReg(unsigned subReg)471   void setSubReg(unsigned subReg) {
472     assert(isReg() && "Wrong MachineOperand mutator");
473     SubReg_TargetFlags = subReg;
474     assert(SubReg_TargetFlags == subReg && "SubReg out of range");
475   }
476 
477   /// substVirtReg - Substitute the current register with the virtual
478   /// subregister Reg:SubReg. Take any existing SubReg index into account,
479   /// using TargetRegisterInfo to compose the subreg indices if necessary.
480   /// Reg must be a virtual register, SubIdx can be 0.
481   ///
482   void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo&);
483 
484   /// substPhysReg - Substitute the current register with the physical register
485   /// Reg, taking any existing SubReg into account. For instance,
486   /// substPhysReg(%eax) will change %reg1024:sub_8bit to %al.
487   ///
488   void substPhysReg(MCRegister Reg, const TargetRegisterInfo&);
489 
490   void setIsUse(bool Val = true) { setIsDef(!Val); }
491 
492   /// Change a def to a use, or a use to a def.
493   void setIsDef(bool Val = true);
494 
495   void setImplicit(bool Val = true) {
496     assert(isReg() && "Wrong MachineOperand mutator");
497     IsImp = Val;
498   }
499 
500   void setIsKill(bool Val = true) {
501     assert(isReg() && !IsDef && "Wrong MachineOperand mutator");
502     assert((!Val || !isDebug()) && "Marking a debug operation as kill");
503     IsDeadOrKill = Val;
504   }
505 
506   void setIsDead(bool Val = true) {
507     assert(isReg() && IsDef && "Wrong MachineOperand mutator");
508     IsDeadOrKill = Val;
509   }
510 
511   void setIsUndef(bool Val = true) {
512     assert(isReg() && "Wrong MachineOperand mutator");
513     IsUndef = Val;
514   }
515 
516   void setIsRenamable(bool Val = true);
517 
518   void setIsInternalRead(bool Val = true) {
519     assert(isReg() && "Wrong MachineOperand mutator");
520     IsInternalRead = Val;
521   }
522 
523   void setIsEarlyClobber(bool Val = true) {
524     assert(isReg() && IsDef && "Wrong MachineOperand mutator");
525     IsEarlyClobber = Val;
526   }
527 
528   void setIsDebug(bool Val = true) {
529     assert(isReg() && !IsDef && "Wrong MachineOperand mutator");
530     IsDebug = Val;
531   }
532 
533   //===--------------------------------------------------------------------===//
534   // Accessors for various operand types.
535   //===--------------------------------------------------------------------===//
536 
getImm()537   int64_t getImm() const {
538     assert(isImm() && "Wrong MachineOperand accessor");
539     return Contents.ImmVal;
540   }
541 
getCImm()542   const ConstantInt *getCImm() const {
543     assert(isCImm() && "Wrong MachineOperand accessor");
544     return Contents.CI;
545   }
546 
getFPImm()547   const ConstantFP *getFPImm() const {
548     assert(isFPImm() && "Wrong MachineOperand accessor");
549     return Contents.CFP;
550   }
551 
getMBB()552   MachineBasicBlock *getMBB() const {
553     assert(isMBB() && "Wrong MachineOperand accessor");
554     return Contents.MBB;
555   }
556 
getIndex()557   int getIndex() const {
558     assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
559            "Wrong MachineOperand accessor");
560     return Contents.OffsetedInfo.Val.Index;
561   }
562 
getGlobal()563   const GlobalValue *getGlobal() const {
564     assert(isGlobal() && "Wrong MachineOperand accessor");
565     return Contents.OffsetedInfo.Val.GV;
566   }
567 
getBlockAddress()568   const BlockAddress *getBlockAddress() const {
569     assert(isBlockAddress() && "Wrong MachineOperand accessor");
570     return Contents.OffsetedInfo.Val.BA;
571   }
572 
getMCSymbol()573   MCSymbol *getMCSymbol() const {
574     assert(isMCSymbol() && "Wrong MachineOperand accessor");
575     return Contents.Sym;
576   }
577 
getCFIIndex()578   unsigned getCFIIndex() const {
579     assert(isCFIIndex() && "Wrong MachineOperand accessor");
580     return Contents.CFIIndex;
581   }
582 
getIntrinsicID()583   Intrinsic::ID getIntrinsicID() const {
584     assert(isIntrinsicID() && "Wrong MachineOperand accessor");
585     return Contents.IntrinsicID;
586   }
587 
getPredicate()588   unsigned getPredicate() const {
589     assert(isPredicate() && "Wrong MachineOperand accessor");
590     return Contents.Pred;
591   }
592 
getShuffleMask()593   ArrayRef<int> getShuffleMask() const {
594     assert(isShuffleMask() && "Wrong MachineOperand accessor");
595     return Contents.ShuffleMask;
596   }
597 
598   /// Return the offset from the symbol in this operand. This always returns 0
599   /// for ExternalSymbol operands.
getOffset()600   int64_t getOffset() const {
601     assert((isGlobal() || isSymbol() || isMCSymbol() || isCPI() ||
602             isTargetIndex() || isBlockAddress()) &&
603            "Wrong MachineOperand accessor");
604     return int64_t(uint64_t(Contents.OffsetedInfo.OffsetHi) << 32) |
605            SmallContents.OffsetLo;
606   }
607 
getSymbolName()608   const char *getSymbolName() const {
609     assert(isSymbol() && "Wrong MachineOperand accessor");
610     return Contents.OffsetedInfo.Val.SymbolName;
611   }
612 
613   /// clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
614   /// It is sometimes necessary to detach the register mask pointer from its
615   /// machine operand. This static method can be used for such detached bit
616   /// mask pointers.
clobbersPhysReg(const uint32_t * RegMask,MCRegister PhysReg)617   static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg) {
618     // See TargetRegisterInfo.h.
619     assert(PhysReg < (1u << 30) && "Not a physical register");
620     return !(RegMask[PhysReg / 32] & (1u << PhysReg % 32));
621   }
622 
623   /// clobbersPhysReg - Returns true if this RegMask operand clobbers PhysReg.
clobbersPhysReg(MCRegister PhysReg)624   bool clobbersPhysReg(MCRegister PhysReg) const {
625      return clobbersPhysReg(getRegMask(), PhysReg);
626   }
627 
628   /// getRegMask - Returns a bit mask of registers preserved by this RegMask
629   /// operand.
getRegMask()630   const uint32_t *getRegMask() const {
631     assert(isRegMask() && "Wrong MachineOperand accessor");
632     return Contents.RegMask;
633   }
634 
635   /// Returns number of elements needed for a regmask array.
getRegMaskSize(unsigned NumRegs)636   static unsigned getRegMaskSize(unsigned NumRegs) {
637     return (NumRegs + 31) / 32;
638   }
639 
640   /// getRegLiveOut - Returns a bit mask of live-out registers.
getRegLiveOut()641   const uint32_t *getRegLiveOut() const {
642     assert(isRegLiveOut() && "Wrong MachineOperand accessor");
643     return Contents.RegMask;
644   }
645 
getMetadata()646   const MDNode *getMetadata() const {
647     assert(isMetadata() && "Wrong MachineOperand accessor");
648     return Contents.MD;
649   }
650 
651   //===--------------------------------------------------------------------===//
652   // Mutators for various operand types.
653   //===--------------------------------------------------------------------===//
654 
setImm(int64_t immVal)655   void setImm(int64_t immVal) {
656     assert(isImm() && "Wrong MachineOperand mutator");
657     Contents.ImmVal = immVal;
658   }
659 
setCImm(const ConstantInt * CI)660   void setCImm(const ConstantInt *CI) {
661     assert(isCImm() && "Wrong MachineOperand mutator");
662     Contents.CI = CI;
663   }
664 
setFPImm(const ConstantFP * CFP)665   void setFPImm(const ConstantFP *CFP) {
666     assert(isFPImm() && "Wrong MachineOperand mutator");
667     Contents.CFP = CFP;
668   }
669 
setOffset(int64_t Offset)670   void setOffset(int64_t Offset) {
671     assert((isGlobal() || isSymbol() || isMCSymbol() || isCPI() ||
672             isTargetIndex() || isBlockAddress()) &&
673            "Wrong MachineOperand mutator");
674     SmallContents.OffsetLo = unsigned(Offset);
675     Contents.OffsetedInfo.OffsetHi = int(Offset >> 32);
676   }
677 
setIndex(int Idx)678   void setIndex(int Idx) {
679     assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
680            "Wrong MachineOperand mutator");
681     Contents.OffsetedInfo.Val.Index = Idx;
682   }
683 
setMetadata(const MDNode * MD)684   void setMetadata(const MDNode *MD) {
685     assert(isMetadata() && "Wrong MachineOperand mutator");
686     Contents.MD = MD;
687   }
688 
setMBB(MachineBasicBlock * MBB)689   void setMBB(MachineBasicBlock *MBB) {
690     assert(isMBB() && "Wrong MachineOperand mutator");
691     Contents.MBB = MBB;
692   }
693 
694   /// Sets value of register mask operand referencing Mask.  The
695   /// operand does not take ownership of the memory referenced by Mask, it must
696   /// remain valid for the lifetime of the operand. See CreateRegMask().
697   /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
setRegMask(const uint32_t * RegMaskPtr)698   void setRegMask(const uint32_t *RegMaskPtr) {
699     assert(isRegMask() && "Wrong MachineOperand mutator");
700     Contents.RegMask = RegMaskPtr;
701   }
702 
setIntrinsicID(Intrinsic::ID IID)703   void setIntrinsicID(Intrinsic::ID IID) {
704     assert(isIntrinsicID() && "Wrong MachineOperand mutator");
705     Contents.IntrinsicID = IID;
706   }
707 
setPredicate(unsigned Predicate)708   void setPredicate(unsigned Predicate) {
709     assert(isPredicate() && "Wrong MachineOperand mutator");
710     Contents.Pred = Predicate;
711   }
712 
713   //===--------------------------------------------------------------------===//
714   // Other methods.
715   //===--------------------------------------------------------------------===//
716 
717   /// Returns true if this operand is identical to the specified operand except
718   /// for liveness related flags (isKill, isUndef and isDead). Note that this
719   /// should stay in sync with the hash_value overload below.
720   bool isIdenticalTo(const MachineOperand &Other) const;
721 
722   /// MachineOperand hash_value overload.
723   ///
724   /// Note that this includes the same information in the hash that
725   /// isIdenticalTo uses for comparison. It is thus suited for use in hash
726   /// tables which use that function for equality comparisons only. This must
727   /// stay exactly in sync with isIdenticalTo above.
728   friend hash_code hash_value(const MachineOperand &MO);
729 
730   /// ChangeToImmediate - Replace this operand with a new immediate operand of
731   /// the specified value.  If an operand is known to be an immediate already,
732   /// the setImm method should be used.
733   void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags = 0);
734 
735   /// ChangeToFPImmediate - Replace this operand with a new FP immediate operand
736   /// of the specified value.  If an operand is known to be an FP immediate
737   /// already, the setFPImm method should be used.
738   void ChangeToFPImmediate(const ConstantFP *FPImm, unsigned TargetFlags = 0);
739 
740   /// ChangeToES - Replace this operand with a new external symbol operand.
741   void ChangeToES(const char *SymName, unsigned TargetFlags = 0);
742 
743   /// ChangeToGA - Replace this operand with a new global address operand.
744   void ChangeToGA(const GlobalValue *GV, int64_t Offset,
745                   unsigned TargetFlags = 0);
746 
747   /// ChangeToMCSymbol - Replace this operand with a new MC symbol operand.
748   void ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags = 0);
749 
750   /// Replace this operand with a frame index.
751   void ChangeToFrameIndex(int Idx, unsigned TargetFlags = 0);
752 
753   /// Replace this operand with a target index.
754   void ChangeToTargetIndex(unsigned Idx, int64_t Offset,
755                            unsigned TargetFlags = 0);
756 
757   /// ChangeToRegister - Replace this operand with a new register operand of
758   /// the specified value.  If an operand is known to be an register already,
759   /// the setReg method should be used.
760   void ChangeToRegister(Register Reg, bool isDef, bool isImp = false,
761                         bool isKill = false, bool isDead = false,
762                         bool isUndef = false, bool isDebug = false);
763 
764   /// getTargetIndexName - If this MachineOperand is a TargetIndex that has a
765   /// name, attempt to get the name. Returns nullptr if the TargetIndex does not
766   /// have a name. Asserts if MO is not a TargetIndex.
767   const char *getTargetIndexName() const;
768 
769   //===--------------------------------------------------------------------===//
770   // Construction methods.
771   //===--------------------------------------------------------------------===//
772 
CreateImm(int64_t Val)773   static MachineOperand CreateImm(int64_t Val) {
774     MachineOperand Op(MachineOperand::MO_Immediate);
775     Op.setImm(Val);
776     return Op;
777   }
778 
CreateCImm(const ConstantInt * CI)779   static MachineOperand CreateCImm(const ConstantInt *CI) {
780     MachineOperand Op(MachineOperand::MO_CImmediate);
781     Op.Contents.CI = CI;
782     return Op;
783   }
784 
CreateFPImm(const ConstantFP * CFP)785   static MachineOperand CreateFPImm(const ConstantFP *CFP) {
786     MachineOperand Op(MachineOperand::MO_FPImmediate);
787     Op.Contents.CFP = CFP;
788     return Op;
789   }
790 
791   static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp = false,
792                                   bool isKill = false, bool isDead = false,
793                                   bool isUndef = false,
794                                   bool isEarlyClobber = false,
795                                   unsigned SubReg = 0, bool isDebug = false,
796                                   bool isInternalRead = false,
797                                   bool isRenamable = false) {
798     assert(!(isDead && !isDef) && "Dead flag on non-def");
799     assert(!(isKill && isDef) && "Kill flag on def");
800     MachineOperand Op(MachineOperand::MO_Register);
801     Op.IsDef = isDef;
802     Op.IsImp = isImp;
803     Op.IsDeadOrKill = isKill | isDead;
804     Op.IsRenamable = isRenamable;
805     Op.IsUndef = isUndef;
806     Op.IsInternalRead = isInternalRead;
807     Op.IsEarlyClobber = isEarlyClobber;
808     Op.TiedTo = 0;
809     Op.IsDebug = isDebug;
810     Op.SmallContents.RegNo = Reg;
811     Op.Contents.Reg.Prev = nullptr;
812     Op.Contents.Reg.Next = nullptr;
813     Op.setSubReg(SubReg);
814     return Op;
815   }
816   static MachineOperand CreateMBB(MachineBasicBlock *MBB,
817                                   unsigned TargetFlags = 0) {
818     MachineOperand Op(MachineOperand::MO_MachineBasicBlock);
819     Op.setMBB(MBB);
820     Op.setTargetFlags(TargetFlags);
821     return Op;
822   }
CreateFI(int Idx)823   static MachineOperand CreateFI(int Idx) {
824     MachineOperand Op(MachineOperand::MO_FrameIndex);
825     Op.setIndex(Idx);
826     return Op;
827   }
828   static MachineOperand CreateCPI(unsigned Idx, int Offset,
829                                   unsigned TargetFlags = 0) {
830     MachineOperand Op(MachineOperand::MO_ConstantPoolIndex);
831     Op.setIndex(Idx);
832     Op.setOffset(Offset);
833     Op.setTargetFlags(TargetFlags);
834     return Op;
835   }
836   static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset,
837                                           unsigned TargetFlags = 0) {
838     MachineOperand Op(MachineOperand::MO_TargetIndex);
839     Op.setIndex(Idx);
840     Op.setOffset(Offset);
841     Op.setTargetFlags(TargetFlags);
842     return Op;
843   }
844   static MachineOperand CreateJTI(unsigned Idx, unsigned TargetFlags = 0) {
845     MachineOperand Op(MachineOperand::MO_JumpTableIndex);
846     Op.setIndex(Idx);
847     Op.setTargetFlags(TargetFlags);
848     return Op;
849   }
850   static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset,
851                                  unsigned TargetFlags = 0) {
852     MachineOperand Op(MachineOperand::MO_GlobalAddress);
853     Op.Contents.OffsetedInfo.Val.GV = GV;
854     Op.setOffset(Offset);
855     Op.setTargetFlags(TargetFlags);
856     return Op;
857   }
858   static MachineOperand CreateES(const char *SymName,
859                                  unsigned TargetFlags = 0) {
860     MachineOperand Op(MachineOperand::MO_ExternalSymbol);
861     Op.Contents.OffsetedInfo.Val.SymbolName = SymName;
862     Op.setOffset(0); // Offset is always 0.
863     Op.setTargetFlags(TargetFlags);
864     return Op;
865   }
866   static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset,
867                                  unsigned TargetFlags = 0) {
868     MachineOperand Op(MachineOperand::MO_BlockAddress);
869     Op.Contents.OffsetedInfo.Val.BA = BA;
870     Op.setOffset(Offset);
871     Op.setTargetFlags(TargetFlags);
872     return Op;
873   }
874   /// CreateRegMask - Creates a register mask operand referencing Mask.  The
875   /// operand does not take ownership of the memory referenced by Mask, it
876   /// must remain valid for the lifetime of the operand.
877   ///
878   /// A RegMask operand represents a set of non-clobbered physical registers
879   /// on an instruction that clobbers many registers, typically a call.  The
880   /// bit mask has a bit set for each physreg that is preserved by this
881   /// instruction, as described in the documentation for
882   /// TargetRegisterInfo::getCallPreservedMask().
883   ///
884   /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
885   ///
CreateRegMask(const uint32_t * Mask)886   static MachineOperand CreateRegMask(const uint32_t *Mask) {
887     assert(Mask && "Missing register mask");
888     MachineOperand Op(MachineOperand::MO_RegisterMask);
889     Op.Contents.RegMask = Mask;
890     return Op;
891   }
CreateRegLiveOut(const uint32_t * Mask)892   static MachineOperand CreateRegLiveOut(const uint32_t *Mask) {
893     assert(Mask && "Missing live-out register mask");
894     MachineOperand Op(MachineOperand::MO_RegisterLiveOut);
895     Op.Contents.RegMask = Mask;
896     return Op;
897   }
CreateMetadata(const MDNode * Meta)898   static MachineOperand CreateMetadata(const MDNode *Meta) {
899     MachineOperand Op(MachineOperand::MO_Metadata);
900     Op.Contents.MD = Meta;
901     return Op;
902   }
903 
904   static MachineOperand CreateMCSymbol(MCSymbol *Sym,
905                                        unsigned TargetFlags = 0) {
906     MachineOperand Op(MachineOperand::MO_MCSymbol);
907     Op.Contents.Sym = Sym;
908     Op.setOffset(0);
909     Op.setTargetFlags(TargetFlags);
910     return Op;
911   }
912 
CreateCFIIndex(unsigned CFIIndex)913   static MachineOperand CreateCFIIndex(unsigned CFIIndex) {
914     MachineOperand Op(MachineOperand::MO_CFIIndex);
915     Op.Contents.CFIIndex = CFIIndex;
916     return Op;
917   }
918 
CreateIntrinsicID(Intrinsic::ID ID)919   static MachineOperand CreateIntrinsicID(Intrinsic::ID ID) {
920     MachineOperand Op(MachineOperand::MO_IntrinsicID);
921     Op.Contents.IntrinsicID = ID;
922     return Op;
923   }
924 
CreatePredicate(unsigned Pred)925   static MachineOperand CreatePredicate(unsigned Pred) {
926     MachineOperand Op(MachineOperand::MO_Predicate);
927     Op.Contents.Pred = Pred;
928     return Op;
929   }
930 
CreateShuffleMask(ArrayRef<int> Mask)931   static MachineOperand CreateShuffleMask(ArrayRef<int> Mask) {
932     MachineOperand Op(MachineOperand::MO_ShuffleMask);
933     Op.Contents.ShuffleMask = Mask;
934     return Op;
935   }
936 
937   friend class MachineInstr;
938   friend class MachineRegisterInfo;
939 
940 private:
941   // If this operand is currently a register operand, and if this is in a
942   // function, deregister the operand from the register's use/def list.
943   void removeRegFromUses();
944 
945   /// Artificial kinds for DenseMap usage.
946   enum : unsigned char {
947     MO_Empty = MO_Last + 1,
948     MO_Tombstone,
949   };
950 
951   friend struct DenseMapInfo<MachineOperand>;
952 
953   //===--------------------------------------------------------------------===//
954   // Methods for handling register use/def lists.
955   //===--------------------------------------------------------------------===//
956 
957   /// isOnRegUseList - Return true if this operand is on a register use/def
958   /// list or false if not.  This can only be called for register operands
959   /// that are part of a machine instruction.
960   bool isOnRegUseList() const {
961     assert(isReg() && "Can only add reg operand to use lists");
962     return Contents.Reg.Prev != nullptr;
963   }
964 };
965 
966 template <> struct DenseMapInfo<MachineOperand> {
967   static MachineOperand getEmptyKey() {
968     return MachineOperand(static_cast<MachineOperand::MachineOperandType>(
969         MachineOperand::MO_Empty));
970   }
971   static MachineOperand getTombstoneKey() {
972     return MachineOperand(static_cast<MachineOperand::MachineOperandType>(
973         MachineOperand::MO_Tombstone));
974   }
975   static unsigned getHashValue(const MachineOperand &MO) {
976     return hash_value(MO);
977   }
978   static bool isEqual(const MachineOperand &LHS, const MachineOperand &RHS) {
979     if (LHS.getType() == static_cast<MachineOperand::MachineOperandType>(
980                              MachineOperand::MO_Empty) ||
981         LHS.getType() == static_cast<MachineOperand::MachineOperandType>(
982                              MachineOperand::MO_Tombstone))
983       return LHS.getType() == RHS.getType();
984     return LHS.isIdenticalTo(RHS);
985   }
986 };
987 
988 inline raw_ostream &operator<<(raw_ostream &OS, const MachineOperand &MO) {
989   MO.print(OS);
990   return OS;
991 }
992 
993 // See friend declaration above. This additional declaration is required in
994 // order to compile LLVM with IBM xlC compiler.
995 hash_code hash_value(const MachineOperand &MO);
996 } // namespace llvm
997 
998 #endif
999