xref: /llvm-project/llvm/lib/CodeGen/MachineOperand.cpp (revision 8122660226be6e5cf7782f4d5ad1d632787a942a)
1 //===- lib/CodeGen/MachineOperand.cpp -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file Methods common to all machine operands.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MachineOperand.h"
15 #include "llvm/Analysis/Loads.h"
16 #include "llvm/CodeGen/MIRPrinter.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/IRPrintingPasses.h"
24 #include "llvm/IR/ModuleSlotTracker.h"
25 #include "llvm/Target/TargetIntrinsicInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 
28 using namespace llvm;
29 
30 static cl::opt<int>
31     PrintRegMaskNumRegs("print-regmask-num-regs",
32                         cl::desc("Number of registers to limit to when "
33                                  "printing regmask operands in IR dumps. "
34                                  "unlimited = -1"),
35                         cl::init(32), cl::Hidden);
36 
37 static const MachineFunction *getMFIfAvailable(const MachineOperand &MO) {
38   if (const MachineInstr *MI = MO.getParent())
39     if (const MachineBasicBlock *MBB = MI->getParent())
40       if (const MachineFunction *MF = MBB->getParent())
41         return MF;
42   return nullptr;
43 }
44 static MachineFunction *getMFIfAvailable(MachineOperand &MO) {
45   return const_cast<MachineFunction *>(
46       getMFIfAvailable(const_cast<const MachineOperand &>(MO)));
47 }
48 
49 void MachineOperand::setReg(unsigned Reg) {
50   if (getReg() == Reg)
51     return; // No change.
52 
53   // Otherwise, we have to change the register.  If this operand is embedded
54   // into a machine function, we need to update the old and new register's
55   // use/def lists.
56   if (MachineFunction *MF = getMFIfAvailable(*this)) {
57     MachineRegisterInfo &MRI = MF->getRegInfo();
58     MRI.removeRegOperandFromUseList(this);
59     SmallContents.RegNo = Reg;
60     MRI.addRegOperandToUseList(this);
61     return;
62   }
63 
64   // Otherwise, just change the register, no problem.  :)
65   SmallContents.RegNo = Reg;
66 }
67 
68 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
69                                   const TargetRegisterInfo &TRI) {
70   assert(TargetRegisterInfo::isVirtualRegister(Reg));
71   if (SubIdx && getSubReg())
72     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
73   setReg(Reg);
74   if (SubIdx)
75     setSubReg(SubIdx);
76 }
77 
78 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
79   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
80   if (getSubReg()) {
81     Reg = TRI.getSubReg(Reg, getSubReg());
82     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
83     // That won't happen in legal code.
84     setSubReg(0);
85     if (isDef())
86       setIsUndef(false);
87   }
88   setReg(Reg);
89 }
90 
91 /// Change a def to a use, or a use to a def.
92 void MachineOperand::setIsDef(bool Val) {
93   assert(isReg() && "Wrong MachineOperand accessor");
94   assert((!Val || !isDebug()) && "Marking a debug operation as def");
95   if (IsDef == Val)
96     return;
97   assert(!IsDeadOrKill && "Changing def/use with dead/kill set not supported");
98   // MRI may keep uses and defs in different list positions.
99   if (MachineFunction *MF = getMFIfAvailable(*this)) {
100     MachineRegisterInfo &MRI = MF->getRegInfo();
101     MRI.removeRegOperandFromUseList(this);
102     IsDef = Val;
103     MRI.addRegOperandToUseList(this);
104     return;
105   }
106   IsDef = Val;
107 }
108 
109 bool MachineOperand::isRenamable() const {
110   assert(isReg() && "Wrong MachineOperand accessor");
111   assert(TargetRegisterInfo::isPhysicalRegister(getReg()) &&
112          "isRenamable should only be checked on physical registers");
113   return IsRenamable;
114 }
115 
116 void MachineOperand::setIsRenamable(bool Val) {
117   assert(isReg() && "Wrong MachineOperand accessor");
118   assert(TargetRegisterInfo::isPhysicalRegister(getReg()) &&
119          "setIsRenamable should only be called on physical registers");
120   if (const MachineInstr *MI = getParent())
121     if ((isDef() && MI->hasExtraDefRegAllocReq()) ||
122         (isUse() && MI->hasExtraSrcRegAllocReq()))
123       assert(!Val && "isRenamable should be false for "
124                      "hasExtraDefRegAllocReq/hasExtraSrcRegAllocReq opcodes");
125   IsRenamable = Val;
126 }
127 
128 void MachineOperand::setIsRenamableIfNoExtraRegAllocReq() {
129   if (const MachineInstr *MI = getParent())
130     if ((isDef() && MI->hasExtraDefRegAllocReq()) ||
131         (isUse() && MI->hasExtraSrcRegAllocReq()))
132       return;
133 
134   setIsRenamable(true);
135 }
136 
137 // If this operand is currently a register operand, and if this is in a
138 // function, deregister the operand from the register's use/def list.
139 void MachineOperand::removeRegFromUses() {
140   if (!isReg() || !isOnRegUseList())
141     return;
142 
143   if (MachineFunction *MF = getMFIfAvailable(*this))
144     MF->getRegInfo().removeRegOperandFromUseList(this);
145 }
146 
147 /// ChangeToImmediate - Replace this operand with a new immediate operand of
148 /// the specified value.  If an operand is known to be an immediate already,
149 /// the setImm method should be used.
150 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
151   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
152 
153   removeRegFromUses();
154 
155   OpKind = MO_Immediate;
156   Contents.ImmVal = ImmVal;
157 }
158 
159 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
160   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
161 
162   removeRegFromUses();
163 
164   OpKind = MO_FPImmediate;
165   Contents.CFP = FPImm;
166 }
167 
168 void MachineOperand::ChangeToES(const char *SymName,
169                                 unsigned char TargetFlags) {
170   assert((!isReg() || !isTied()) &&
171          "Cannot change a tied operand into an external symbol");
172 
173   removeRegFromUses();
174 
175   OpKind = MO_ExternalSymbol;
176   Contents.OffsetedInfo.Val.SymbolName = SymName;
177   setOffset(0); // Offset is always 0.
178   setTargetFlags(TargetFlags);
179 }
180 
181 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
182   assert((!isReg() || !isTied()) &&
183          "Cannot change a tied operand into an MCSymbol");
184 
185   removeRegFromUses();
186 
187   OpKind = MO_MCSymbol;
188   Contents.Sym = Sym;
189 }
190 
191 void MachineOperand::ChangeToFrameIndex(int Idx) {
192   assert((!isReg() || !isTied()) &&
193          "Cannot change a tied operand into a FrameIndex");
194 
195   removeRegFromUses();
196 
197   OpKind = MO_FrameIndex;
198   setIndex(Idx);
199 }
200 
201 void MachineOperand::ChangeToTargetIndex(unsigned Idx, int64_t Offset,
202                                          unsigned char TargetFlags) {
203   assert((!isReg() || !isTied()) &&
204          "Cannot change a tied operand into a FrameIndex");
205 
206   removeRegFromUses();
207 
208   OpKind = MO_TargetIndex;
209   setIndex(Idx);
210   setOffset(Offset);
211   setTargetFlags(TargetFlags);
212 }
213 
214 /// ChangeToRegister - Replace this operand with a new register operand of
215 /// the specified value.  If an operand is known to be an register already,
216 /// the setReg method should be used.
217 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
218                                       bool isKill, bool isDead, bool isUndef,
219                                       bool isDebug) {
220   MachineRegisterInfo *RegInfo = nullptr;
221   if (MachineFunction *MF = getMFIfAvailable(*this))
222     RegInfo = &MF->getRegInfo();
223   // If this operand is already a register operand, remove it from the
224   // register's use/def lists.
225   bool WasReg = isReg();
226   if (RegInfo && WasReg)
227     RegInfo->removeRegOperandFromUseList(this);
228 
229   // Change this to a register and set the reg#.
230   assert(!(isDead && !isDef) && "Dead flag on non-def");
231   assert(!(isKill && isDef) && "Kill flag on def");
232   OpKind = MO_Register;
233   SmallContents.RegNo = Reg;
234   SubReg_TargetFlags = 0;
235   IsDef = isDef;
236   IsImp = isImp;
237   IsDeadOrKill = isKill | isDead;
238   IsRenamable = false;
239   IsUndef = isUndef;
240   IsInternalRead = false;
241   IsEarlyClobber = false;
242   IsDebug = isDebug;
243   // Ensure isOnRegUseList() returns false.
244   Contents.Reg.Prev = nullptr;
245   // Preserve the tie when the operand was already a register.
246   if (!WasReg)
247     TiedTo = 0;
248 
249   // If this operand is embedded in a function, add the operand to the
250   // register's use/def list.
251   if (RegInfo)
252     RegInfo->addRegOperandToUseList(this);
253 }
254 
255 /// isIdenticalTo - Return true if this operand is identical to the specified
256 /// operand. Note that this should stay in sync with the hash_value overload
257 /// below.
258 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
259   if (getType() != Other.getType() ||
260       getTargetFlags() != Other.getTargetFlags())
261     return false;
262 
263   switch (getType()) {
264   case MachineOperand::MO_Register:
265     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
266            getSubReg() == Other.getSubReg();
267   case MachineOperand::MO_Immediate:
268     return getImm() == Other.getImm();
269   case MachineOperand::MO_CImmediate:
270     return getCImm() == Other.getCImm();
271   case MachineOperand::MO_FPImmediate:
272     return getFPImm() == Other.getFPImm();
273   case MachineOperand::MO_MachineBasicBlock:
274     return getMBB() == Other.getMBB();
275   case MachineOperand::MO_FrameIndex:
276     return getIndex() == Other.getIndex();
277   case MachineOperand::MO_ConstantPoolIndex:
278   case MachineOperand::MO_TargetIndex:
279     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
280   case MachineOperand::MO_JumpTableIndex:
281     return getIndex() == Other.getIndex();
282   case MachineOperand::MO_GlobalAddress:
283     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
284   case MachineOperand::MO_ExternalSymbol:
285     return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
286            getOffset() == Other.getOffset();
287   case MachineOperand::MO_BlockAddress:
288     return getBlockAddress() == Other.getBlockAddress() &&
289            getOffset() == Other.getOffset();
290   case MachineOperand::MO_RegisterMask:
291   case MachineOperand::MO_RegisterLiveOut: {
292     // Shallow compare of the two RegMasks
293     const uint32_t *RegMask = getRegMask();
294     const uint32_t *OtherRegMask = Other.getRegMask();
295     if (RegMask == OtherRegMask)
296       return true;
297 
298     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
299       // Calculate the size of the RegMask
300       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
301       unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
302 
303       // Deep compare of the two RegMasks
304       return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
305     }
306     // We don't know the size of the RegMask, so we can't deep compare the two
307     // reg masks.
308     return false;
309   }
310   case MachineOperand::MO_MCSymbol:
311     return getMCSymbol() == Other.getMCSymbol();
312   case MachineOperand::MO_CFIIndex:
313     return getCFIIndex() == Other.getCFIIndex();
314   case MachineOperand::MO_Metadata:
315     return getMetadata() == Other.getMetadata();
316   case MachineOperand::MO_IntrinsicID:
317     return getIntrinsicID() == Other.getIntrinsicID();
318   case MachineOperand::MO_Predicate:
319     return getPredicate() == Other.getPredicate();
320   }
321   llvm_unreachable("Invalid machine operand type");
322 }
323 
324 // Note: this must stay exactly in sync with isIdenticalTo above.
325 hash_code llvm::hash_value(const MachineOperand &MO) {
326   switch (MO.getType()) {
327   case MachineOperand::MO_Register:
328     // Register operands don't have target flags.
329     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
330   case MachineOperand::MO_Immediate:
331     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
332   case MachineOperand::MO_CImmediate:
333     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
334   case MachineOperand::MO_FPImmediate:
335     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
336   case MachineOperand::MO_MachineBasicBlock:
337     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
338   case MachineOperand::MO_FrameIndex:
339     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
340   case MachineOperand::MO_ConstantPoolIndex:
341   case MachineOperand::MO_TargetIndex:
342     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
343                         MO.getOffset());
344   case MachineOperand::MO_JumpTableIndex:
345     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
346   case MachineOperand::MO_ExternalSymbol:
347     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
348                         MO.getSymbolName());
349   case MachineOperand::MO_GlobalAddress:
350     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
351                         MO.getOffset());
352   case MachineOperand::MO_BlockAddress:
353     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getBlockAddress(),
354                         MO.getOffset());
355   case MachineOperand::MO_RegisterMask:
356   case MachineOperand::MO_RegisterLiveOut:
357     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
358   case MachineOperand::MO_Metadata:
359     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
360   case MachineOperand::MO_MCSymbol:
361     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
362   case MachineOperand::MO_CFIIndex:
363     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
364   case MachineOperand::MO_IntrinsicID:
365     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
366   case MachineOperand::MO_Predicate:
367     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
368   }
369   llvm_unreachable("Invalid machine operand type");
370 }
371 
372 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
373 // it.
374 static void tryToGetTargetInfo(const MachineOperand &MO,
375                                const TargetRegisterInfo *&TRI,
376                                const TargetIntrinsicInfo *&IntrinsicInfo) {
377   if (const MachineFunction *MF = getMFIfAvailable(MO)) {
378     TRI = MF->getSubtarget().getRegisterInfo();
379     IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
380   }
381 }
382 
383 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
384   const auto *TII = MF.getSubtarget().getInstrInfo();
385   assert(TII && "expected instruction info");
386   auto Indices = TII->getSerializableTargetIndices();
387   auto Found = find_if(Indices, [&](const std::pair<int, const char *> &I) {
388     return I.first == Index;
389   });
390   if (Found != Indices.end())
391     return Found->second;
392   return nullptr;
393 }
394 
395 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
396   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
397   for (const auto &I : Flags) {
398     if (I.first == TF) {
399       return I.second;
400     }
401   }
402   return nullptr;
403 }
404 
405 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
406                              const TargetRegisterInfo *TRI) {
407   if (!TRI) {
408     OS << "%dwarfreg." << DwarfReg;
409     return;
410   }
411 
412   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
413   if (Reg == -1) {
414     OS << "<badreg>";
415     return;
416   }
417   OS << printReg(Reg, TRI);
418 }
419 
420 void MachineOperand::printSubregIdx(raw_ostream &OS, uint64_t Index,
421                                     const TargetRegisterInfo *TRI) {
422   OS << "%subreg.";
423   if (TRI)
424     OS << TRI->getSubRegIndexName(Index);
425   else
426     OS << Index;
427 }
428 
429 void MachineOperand::printTargetFlags(raw_ostream &OS,
430                                       const MachineOperand &Op) {
431   if (!Op.getTargetFlags())
432     return;
433   const MachineFunction *MF = getMFIfAvailable(Op);
434   if (!MF)
435     return;
436 
437   const auto *TII = MF->getSubtarget().getInstrInfo();
438   assert(TII && "expected instruction info");
439   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
440   OS << "target-flags(";
441   const bool HasDirectFlags = Flags.first;
442   const bool HasBitmaskFlags = Flags.second;
443   if (!HasDirectFlags && !HasBitmaskFlags) {
444     OS << "<unknown>) ";
445     return;
446   }
447   if (HasDirectFlags) {
448     if (const auto *Name = getTargetFlagName(TII, Flags.first))
449       OS << Name;
450     else
451       OS << "<unknown target flag>";
452   }
453   if (!HasBitmaskFlags) {
454     OS << ") ";
455     return;
456   }
457   bool IsCommaNeeded = HasDirectFlags;
458   unsigned BitMask = Flags.second;
459   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
460   for (const auto &Mask : BitMasks) {
461     // Check if the flag's bitmask has the bits of the current mask set.
462     if ((BitMask & Mask.first) == Mask.first) {
463       if (IsCommaNeeded)
464         OS << ", ";
465       IsCommaNeeded = true;
466       OS << Mask.second;
467       // Clear the bits which were serialized from the flag's bitmask.
468       BitMask &= ~(Mask.first);
469     }
470   }
471   if (BitMask) {
472     // When the resulting flag's bitmask isn't zero, we know that we didn't
473     // serialize all of the bit flags.
474     if (IsCommaNeeded)
475       OS << ", ";
476     OS << "<unknown bitmask target flag>";
477   }
478   OS << ") ";
479 }
480 
481 void MachineOperand::printSymbol(raw_ostream &OS, MCSymbol &Sym) {
482   OS << "<mcsymbol " << Sym << ">";
483 }
484 
485 void MachineOperand::printStackObjectReference(raw_ostream &OS,
486                                                unsigned FrameIndex,
487                                                bool IsFixed, StringRef Name) {
488   if (IsFixed) {
489     OS << "%fixed-stack." << FrameIndex;
490     return;
491   }
492 
493   OS << "%stack." << FrameIndex;
494   if (!Name.empty())
495     OS << '.' << Name;
496 }
497 
498 void MachineOperand::printOperandOffset(raw_ostream &OS, int64_t Offset) {
499   if (Offset == 0)
500     return;
501   if (Offset < 0) {
502     OS << " - " << -Offset;
503     return;
504   }
505   OS << " + " << Offset;
506 }
507 
508 static void printCFI(raw_ostream &OS, const MCCFIInstruction &CFI,
509                      const TargetRegisterInfo *TRI) {
510   switch (CFI.getOperation()) {
511   case MCCFIInstruction::OpSameValue:
512     OS << "same_value ";
513     if (MCSymbol *Label = CFI.getLabel())
514       MachineOperand::printSymbol(OS, *Label);
515     printCFIRegister(CFI.getRegister(), OS, TRI);
516     break;
517   case MCCFIInstruction::OpRememberState:
518     OS << "remember_state ";
519     if (MCSymbol *Label = CFI.getLabel())
520       MachineOperand::printSymbol(OS, *Label);
521     break;
522   case MCCFIInstruction::OpRestoreState:
523     OS << "restore_state ";
524     if (MCSymbol *Label = CFI.getLabel())
525       MachineOperand::printSymbol(OS, *Label);
526     break;
527   case MCCFIInstruction::OpOffset:
528     OS << "offset ";
529     if (MCSymbol *Label = CFI.getLabel())
530       MachineOperand::printSymbol(OS, *Label);
531     printCFIRegister(CFI.getRegister(), OS, TRI);
532     OS << ", " << CFI.getOffset();
533     break;
534   case MCCFIInstruction::OpDefCfaRegister:
535     OS << "def_cfa_register ";
536     if (MCSymbol *Label = CFI.getLabel())
537       MachineOperand::printSymbol(OS, *Label);
538     printCFIRegister(CFI.getRegister(), OS, TRI);
539     break;
540   case MCCFIInstruction::OpDefCfaOffset:
541     OS << "def_cfa_offset ";
542     if (MCSymbol *Label = CFI.getLabel())
543       MachineOperand::printSymbol(OS, *Label);
544     OS << CFI.getOffset();
545     break;
546   case MCCFIInstruction::OpDefCfa:
547     OS << "def_cfa ";
548     if (MCSymbol *Label = CFI.getLabel())
549       MachineOperand::printSymbol(OS, *Label);
550     printCFIRegister(CFI.getRegister(), OS, TRI);
551     OS << ", " << CFI.getOffset();
552     break;
553   case MCCFIInstruction::OpRelOffset:
554     OS << "rel_offset ";
555     if (MCSymbol *Label = CFI.getLabel())
556       MachineOperand::printSymbol(OS, *Label);
557     printCFIRegister(CFI.getRegister(), OS, TRI);
558     OS << ", " << CFI.getOffset();
559     break;
560   case MCCFIInstruction::OpAdjustCfaOffset:
561     OS << "adjust_cfa_offset ";
562     if (MCSymbol *Label = CFI.getLabel())
563       MachineOperand::printSymbol(OS, *Label);
564     OS << CFI.getOffset();
565     break;
566   case MCCFIInstruction::OpRestore:
567     OS << "restore ";
568     if (MCSymbol *Label = CFI.getLabel())
569       MachineOperand::printSymbol(OS, *Label);
570     printCFIRegister(CFI.getRegister(), OS, TRI);
571     break;
572   case MCCFIInstruction::OpEscape: {
573     OS << "escape ";
574     if (MCSymbol *Label = CFI.getLabel())
575       MachineOperand::printSymbol(OS, *Label);
576     if (!CFI.getValues().empty()) {
577       size_t e = CFI.getValues().size() - 1;
578       for (size_t i = 0; i < e; ++i)
579         OS << format("0x%02x", uint8_t(CFI.getValues()[i])) << ", ";
580       OS << format("0x%02x", uint8_t(CFI.getValues()[e])) << ", ";
581     }
582     break;
583   }
584   case MCCFIInstruction::OpUndefined:
585     OS << "undefined ";
586     if (MCSymbol *Label = CFI.getLabel())
587       MachineOperand::printSymbol(OS, *Label);
588     printCFIRegister(CFI.getRegister(), OS, TRI);
589     break;
590   case MCCFIInstruction::OpRegister:
591     OS << "register ";
592     if (MCSymbol *Label = CFI.getLabel())
593       MachineOperand::printSymbol(OS, *Label);
594     printCFIRegister(CFI.getRegister(), OS, TRI);
595     OS << ", ";
596     printCFIRegister(CFI.getRegister2(), OS, TRI);
597     break;
598   case MCCFIInstruction::OpWindowSave:
599     OS << "window_save ";
600     if (MCSymbol *Label = CFI.getLabel())
601       MachineOperand::printSymbol(OS, *Label);
602     break;
603   default:
604     // TODO: Print the other CFI Operations.
605     OS << "<unserializable cfi directive>";
606     break;
607   }
608 }
609 
610 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
611                            const TargetIntrinsicInfo *IntrinsicInfo) const {
612   tryToGetTargetInfo(*this, TRI, IntrinsicInfo);
613   ModuleSlotTracker DummyMST(nullptr);
614   print(OS, DummyMST, LLT{}, /*PrintDef=*/false,
615         /*ShouldPrintRegisterTies=*/true,
616         /*TiedOperandIdx=*/0, TRI, IntrinsicInfo);
617 }
618 
619 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
620                            LLT TypeToPrint, bool PrintDef,
621                            bool ShouldPrintRegisterTies,
622                            unsigned TiedOperandIdx,
623                            const TargetRegisterInfo *TRI,
624                            const TargetIntrinsicInfo *IntrinsicInfo) const {
625   printTargetFlags(OS, *this);
626   switch (getType()) {
627   case MachineOperand::MO_Register: {
628     unsigned Reg = getReg();
629     if (isImplicit())
630       OS << (isDef() ? "implicit-def " : "implicit ");
631     else if (PrintDef && isDef())
632       // Print the 'def' flag only when the operand is defined after '='.
633       OS << "def ";
634     if (isInternalRead())
635       OS << "internal ";
636     if (isDead())
637       OS << "dead ";
638     if (isKill())
639       OS << "killed ";
640     if (isUndef())
641       OS << "undef ";
642     if (isEarlyClobber())
643       OS << "early-clobber ";
644     if (isDebug())
645       OS << "debug-use ";
646     if (TargetRegisterInfo::isPhysicalRegister(getReg()) && isRenamable())
647       OS << "renamable ";
648     OS << printReg(Reg, TRI);
649     // Print the sub register.
650     if (unsigned SubReg = getSubReg()) {
651       if (TRI)
652         OS << '.' << TRI->getSubRegIndexName(SubReg);
653       else
654         OS << ".subreg" << SubReg;
655     }
656     // Print the register class / bank.
657     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
658       if (const MachineFunction *MF = getMFIfAvailable(*this)) {
659         const MachineRegisterInfo &MRI = MF->getRegInfo();
660         if (!PrintDef || MRI.def_empty(Reg)) {
661           OS << ':';
662           OS << printRegClassOrBank(Reg, MRI, TRI);
663         }
664       }
665     }
666     // Print ties.
667     if (ShouldPrintRegisterTies && isTied() && !isDef())
668       OS << "(tied-def " << TiedOperandIdx << ")";
669     // Print types.
670     if (TypeToPrint.isValid())
671       OS << '(' << TypeToPrint << ')';
672     break;
673   }
674   case MachineOperand::MO_Immediate:
675     OS << getImm();
676     break;
677   case MachineOperand::MO_CImmediate:
678     getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
679     break;
680   case MachineOperand::MO_FPImmediate:
681     if (getFPImm()->getType()->isFloatTy()) {
682       OS << getFPImm()->getValueAPF().convertToFloat();
683     } else if (getFPImm()->getType()->isHalfTy()) {
684       APFloat APF = getFPImm()->getValueAPF();
685       bool Unused;
686       APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
687       OS << "half " << APF.convertToFloat();
688     } else if (getFPImm()->getType()->isFP128Ty()) {
689       APFloat APF = getFPImm()->getValueAPF();
690       SmallString<16> Str;
691       getFPImm()->getValueAPF().toString(Str);
692       OS << "quad " << Str;
693     } else if (getFPImm()->getType()->isX86_FP80Ty()) {
694       APFloat APF = getFPImm()->getValueAPF();
695       OS << "x86_fp80 0xK";
696       APInt API = APF.bitcastToAPInt();
697       OS << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
698                                  /*Upper=*/true);
699       OS << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
700                                  /*Upper=*/true);
701     } else {
702       OS << getFPImm()->getValueAPF().convertToDouble();
703     }
704     break;
705   case MachineOperand::MO_MachineBasicBlock:
706     OS << printMBBReference(*getMBB());
707     break;
708   case MachineOperand::MO_FrameIndex: {
709     int FrameIndex = getIndex();
710     bool IsFixed = false;
711     StringRef Name;
712     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
713       const MachineFrameInfo &MFI = MF->getFrameInfo();
714       IsFixed = MFI.isFixedObjectIndex(FrameIndex);
715       if (const AllocaInst *Alloca = MFI.getObjectAllocation(FrameIndex))
716         if (Alloca->hasName())
717           Name = Alloca->getName();
718       if (IsFixed)
719         FrameIndex -= MFI.getObjectIndexBegin();
720     }
721     printStackObjectReference(OS, FrameIndex, IsFixed, Name);
722     break;
723   }
724   case MachineOperand::MO_ConstantPoolIndex:
725     OS << "%const." << getIndex();
726     printOperandOffset(OS, getOffset());
727     break;
728   case MachineOperand::MO_TargetIndex: {
729     OS << "target-index(";
730     const char *Name = "<unknown>";
731     if (const MachineFunction *MF = getMFIfAvailable(*this))
732       if (const auto *TargetIndexName = getTargetIndexName(*MF, getIndex()))
733         Name = TargetIndexName;
734     OS << Name << ')';
735     printOperandOffset(OS, getOffset());
736     break;
737   }
738   case MachineOperand::MO_JumpTableIndex:
739     OS << printJumpTableEntryReference(getIndex());
740     break;
741   case MachineOperand::MO_GlobalAddress:
742     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
743     printOperandOffset(OS, getOffset());
744     break;
745   case MachineOperand::MO_ExternalSymbol: {
746     StringRef Name = getSymbolName();
747     OS << '$';
748     if (Name.empty()) {
749       OS << "\"\"";
750     } else {
751       printLLVMNameWithoutPrefix(OS, Name);
752     }
753     printOperandOffset(OS, getOffset());
754     break;
755   }
756   case MachineOperand::MO_BlockAddress:
757     OS << '<';
758     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
759     if (getOffset())
760       OS << "+" << getOffset();
761     OS << '>';
762     break;
763   case MachineOperand::MO_RegisterMask: {
764     OS << "<regmask";
765     if (TRI) {
766       unsigned NumRegsInMask = 0;
767       unsigned NumRegsEmitted = 0;
768       for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
769         unsigned MaskWord = i / 32;
770         unsigned MaskBit = i % 32;
771         if (getRegMask()[MaskWord] & (1 << MaskBit)) {
772           if (PrintRegMaskNumRegs < 0 ||
773               NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
774             OS << " " << printReg(i, TRI);
775             NumRegsEmitted++;
776           }
777           NumRegsInMask++;
778         }
779       }
780       if (NumRegsEmitted != NumRegsInMask)
781         OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
782     } else {
783       OS << " ...";
784     }
785     OS << ">";
786     break;
787   }
788   case MachineOperand::MO_RegisterLiveOut: {
789     const uint32_t *RegMask = getRegLiveOut();
790     OS << "liveout(";
791     if (!TRI) {
792       OS << "<unknown>";
793     } else {
794       bool IsCommaNeeded = false;
795       for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
796         if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
797           if (IsCommaNeeded)
798             OS << ", ";
799           OS << printReg(Reg, TRI);
800           IsCommaNeeded = true;
801         }
802       }
803     }
804     OS << ")";
805     break;
806   }
807   case MachineOperand::MO_Metadata:
808     getMetadata()->printAsOperand(OS, MST);
809     break;
810   case MachineOperand::MO_MCSymbol:
811     printSymbol(OS, *getMCSymbol());
812     break;
813   case MachineOperand::MO_CFIIndex: {
814     if (const MachineFunction *MF = getMFIfAvailable(*this))
815       printCFI(OS, MF->getFrameInstructions()[getCFIIndex()], TRI);
816     else
817       OS << "<cfi directive>";
818     break;
819   }
820   case MachineOperand::MO_IntrinsicID: {
821     Intrinsic::ID ID = getIntrinsicID();
822     if (ID < Intrinsic::num_intrinsics)
823       OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
824     else if (IntrinsicInfo)
825       OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
826     else
827       OS << "<intrinsic:" << ID << '>';
828     break;
829   }
830   case MachineOperand::MO_Predicate: {
831     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
832     OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
833        << CmpInst::getPredicateName(Pred) << '>';
834     break;
835   }
836   }
837 }
838 
839 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
840 LLVM_DUMP_METHOD void MachineOperand::dump() const { dbgs() << *this << '\n'; }
841 #endif
842 
843 //===----------------------------------------------------------------------===//
844 // MachineMemOperand Implementation
845 //===----------------------------------------------------------------------===//
846 
847 /// getAddrSpace - Return the LLVM IR address space number that this pointer
848 /// points into.
849 unsigned MachinePointerInfo::getAddrSpace() const { return AddrSpace; }
850 
851 /// isDereferenceable - Return true if V is always dereferenceable for
852 /// Offset + Size byte.
853 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
854                                            const DataLayout &DL) const {
855   if (!V.is<const Value *>())
856     return false;
857 
858   const Value *BasePtr = V.get<const Value *>();
859   if (BasePtr == nullptr)
860     return false;
861 
862   return isDereferenceableAndAlignedPointer(
863       BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
864 }
865 
866 /// getConstantPool - Return a MachinePointerInfo record that refers to the
867 /// constant pool.
868 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
869   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
870 }
871 
872 /// getFixedStack - Return a MachinePointerInfo record that refers to the
873 /// the specified FrameIndex.
874 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
875                                                      int FI, int64_t Offset) {
876   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
877 }
878 
879 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
880   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
881 }
882 
883 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
884   return MachinePointerInfo(MF.getPSVManager().getGOT());
885 }
886 
887 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
888                                                 int64_t Offset, uint8_t ID) {
889   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset, ID);
890 }
891 
892 MachinePointerInfo MachinePointerInfo::getUnknownStack(MachineFunction &MF) {
893   return MachinePointerInfo(MF.getDataLayout().getAllocaAddrSpace());
894 }
895 
896 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
897                                      uint64_t s, unsigned int a,
898                                      const AAMDNodes &AAInfo,
899                                      const MDNode *Ranges, SyncScope::ID SSID,
900                                      AtomicOrdering Ordering,
901                                      AtomicOrdering FailureOrdering)
902     : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
903       AAInfo(AAInfo), Ranges(Ranges) {
904   assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue *>() ||
905           isa<PointerType>(PtrInfo.V.get<const Value *>()->getType())) &&
906          "invalid pointer value");
907   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
908   assert((isLoad() || isStore()) && "Not a load/store!");
909 
910   AtomicInfo.SSID = static_cast<unsigned>(SSID);
911   assert(getSyncScopeID() == SSID && "Value truncated");
912   AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
913   assert(getOrdering() == Ordering && "Value truncated");
914   AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
915   assert(getFailureOrdering() == FailureOrdering && "Value truncated");
916 }
917 
918 /// Profile - Gather unique data for the object.
919 ///
920 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
921   ID.AddInteger(getOffset());
922   ID.AddInteger(Size);
923   ID.AddPointer(getOpaqueValue());
924   ID.AddInteger(getFlags());
925   ID.AddInteger(getBaseAlignment());
926 }
927 
928 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
929   // The Value and Offset may differ due to CSE. But the flags and size
930   // should be the same.
931   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
932   assert(MMO->getSize() == getSize() && "Size mismatch!");
933 
934   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
935     // Update the alignment value.
936     BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
937     // Also update the base and offset, because the new alignment may
938     // not be applicable with the old ones.
939     PtrInfo = MMO->PtrInfo;
940   }
941 }
942 
943 /// getAlignment - Return the minimum known alignment in bytes of the
944 /// actual memory reference.
945 uint64_t MachineMemOperand::getAlignment() const {
946   return MinAlign(getBaseAlignment(), getOffset());
947 }
948 
949 void MachineMemOperand::print(raw_ostream &OS) const {
950   ModuleSlotTracker DummyMST(nullptr);
951   print(OS, DummyMST);
952 }
953 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
954   assert((isLoad() || isStore()) && "SV has to be a load, store or both.");
955 
956   if (isVolatile())
957     OS << "Volatile ";
958 
959   if (isLoad())
960     OS << "LD";
961   if (isStore())
962     OS << "ST";
963   OS << getSize();
964 
965   // Print the address information.
966   OS << "[";
967   if (const Value *V = getValue())
968     V->printAsOperand(OS, /*PrintType=*/false, MST);
969   else if (const PseudoSourceValue *PSV = getPseudoValue())
970     PSV->printCustom(OS);
971   else
972     OS << "<unknown>";
973 
974   unsigned AS = getAddrSpace();
975   if (AS != 0)
976     OS << "(addrspace=" << AS << ')';
977 
978   // If the alignment of the memory reference itself differs from the alignment
979   // of the base pointer, print the base alignment explicitly, next to the base
980   // pointer.
981   if (getBaseAlignment() != getAlignment())
982     OS << "(align=" << getBaseAlignment() << ")";
983 
984   if (getOffset() != 0)
985     OS << "+" << getOffset();
986   OS << "]";
987 
988   // Print the alignment of the reference.
989   if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
990     OS << "(align=" << getAlignment() << ")";
991 
992   // Print TBAA info.
993   if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
994     OS << "(tbaa=";
995     if (TBAAInfo->getNumOperands() > 0)
996       TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
997     else
998       OS << "<unknown>";
999     OS << ")";
1000   }
1001 
1002   // Print AA scope info.
1003   if (const MDNode *ScopeInfo = getAAInfo().Scope) {
1004     OS << "(alias.scope=";
1005     if (ScopeInfo->getNumOperands() > 0)
1006       for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
1007         ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
1008         if (i != ie - 1)
1009           OS << ",";
1010       }
1011     else
1012       OS << "<unknown>";
1013     OS << ")";
1014   }
1015 
1016   // Print AA noalias scope info.
1017   if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
1018     OS << "(noalias=";
1019     if (NoAliasInfo->getNumOperands() > 0)
1020       for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
1021         NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
1022         if (i != ie - 1)
1023           OS << ",";
1024       }
1025     else
1026       OS << "<unknown>";
1027     OS << ")";
1028   }
1029 
1030   if (const MDNode *Ranges = getRanges()) {
1031     unsigned NumRanges = Ranges->getNumOperands();
1032     if (NumRanges != 0) {
1033       OS << "(ranges=";
1034 
1035       for (unsigned I = 0; I != NumRanges; ++I) {
1036         Ranges->getOperand(I)->printAsOperand(OS, MST);
1037         if (I != NumRanges - 1)
1038           OS << ',';
1039       }
1040 
1041       OS << ')';
1042     }
1043   }
1044 
1045   if (isNonTemporal())
1046     OS << "(nontemporal)";
1047   if (isDereferenceable())
1048     OS << "(dereferenceable)";
1049   if (isInvariant())
1050     OS << "(invariant)";
1051   if (getFlags() & MOTargetFlag1)
1052     OS << "(flag1)";
1053   if (getFlags() & MOTargetFlag2)
1054     OS << "(flag2)";
1055   if (getFlags() & MOTargetFlag3)
1056     OS << "(flag3)";
1057 }
1058