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