xref: /llvm-project/llvm/lib/CodeGen/MachineOperand.cpp (revision 7615c0b2eb52b8c5d8e6dfc7f265a87a7a9f3ef5)
1 //===- lib/CodeGen/MachineOperand.cpp -------------------------------------===//
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 /// \file Methods common to all machine operands.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineOperand.h"
14 #include "llvm/ADT/StableHashing.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/CodeGen/MIRFormatter.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/PseudoSourceValueManager.h"
22 #include "llvm/CodeGen/TargetInstrInfo.h"
23 #include "llvm/CodeGen/TargetRegisterInfo.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/ModuleSlotTracker.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Target/TargetIntrinsicInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include <optional>
33 
34 using namespace llvm;
35 
36 static cl::opt<int>
37     PrintRegMaskNumRegs("print-regmask-num-regs",
38                         cl::desc("Number of registers to limit to when "
39                                  "printing regmask operands in IR dumps. "
40                                  "unlimited = -1"),
41                         cl::init(32), cl::Hidden);
42 
43 static const MachineFunction *getMFIfAvailable(const MachineOperand &MO) {
44   if (const MachineInstr *MI = MO.getParent())
45     if (const MachineBasicBlock *MBB = MI->getParent())
46       if (const MachineFunction *MF = MBB->getParent())
47         return MF;
48   return nullptr;
49 }
50 
51 static MachineFunction *getMFIfAvailable(MachineOperand &MO) {
52   return const_cast<MachineFunction *>(
53       getMFIfAvailable(const_cast<const MachineOperand &>(MO)));
54 }
55 
56 unsigned MachineOperand::getOperandNo() const {
57   assert(getParent() && "Operand does not belong to any instruction!");
58   return getParent()->getOperandNo(this);
59 }
60 
61 void MachineOperand::setReg(Register Reg) {
62   if (getReg() == Reg)
63     return; // No change.
64 
65   // Clear the IsRenamable bit to keep it conservatively correct.
66   IsRenamable = false;
67 
68   // Otherwise, we have to change the register.  If this operand is embedded
69   // into a machine function, we need to update the old and new register's
70   // use/def lists.
71   if (MachineFunction *MF = getMFIfAvailable(*this)) {
72     MachineRegisterInfo &MRI = MF->getRegInfo();
73     MRI.removeRegOperandFromUseList(this);
74     SmallContents.RegNo = Reg;
75     MRI.addRegOperandToUseList(this);
76     return;
77   }
78 
79   // Otherwise, just change the register, no problem.  :)
80   SmallContents.RegNo = Reg;
81 }
82 
83 void MachineOperand::substVirtReg(Register Reg, unsigned SubIdx,
84                                   const TargetRegisterInfo &TRI) {
85   assert(Reg.isVirtual());
86   if (SubIdx && getSubReg())
87     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
88   setReg(Reg);
89   if (SubIdx)
90     setSubReg(SubIdx);
91 }
92 
93 void MachineOperand::substPhysReg(MCRegister Reg, const TargetRegisterInfo &TRI) {
94   assert(Register::isPhysicalRegister(Reg));
95   if (getSubReg()) {
96     Reg = TRI.getSubReg(Reg, getSubReg());
97     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
98     // That won't happen in legal code.
99     setSubReg(0);
100     if (isDef())
101       setIsUndef(false);
102   }
103   setReg(Reg);
104 }
105 
106 /// Change a def to a use, or a use to a def.
107 void MachineOperand::setIsDef(bool Val) {
108   assert(isReg() && "Wrong MachineOperand accessor");
109   assert((!Val || !isDebug()) && "Marking a debug operation as def");
110   if (IsDef == Val)
111     return;
112   assert(!IsDeadOrKill && "Changing def/use with dead/kill set not supported");
113   // MRI may keep uses and defs in different list positions.
114   if (MachineFunction *MF = getMFIfAvailable(*this)) {
115     MachineRegisterInfo &MRI = MF->getRegInfo();
116     MRI.removeRegOperandFromUseList(this);
117     IsDef = Val;
118     MRI.addRegOperandToUseList(this);
119     return;
120   }
121   IsDef = Val;
122 }
123 
124 bool MachineOperand::isRenamable() const {
125   assert(isReg() && "Wrong MachineOperand accessor");
126   assert(getReg().isPhysical() &&
127          "isRenamable should only be checked on physical registers");
128   if (!IsRenamable)
129     return false;
130 
131   const MachineInstr *MI = getParent();
132   if (!MI)
133     return true;
134 
135   if (isDef())
136     return !MI->hasExtraDefRegAllocReq(MachineInstr::IgnoreBundle);
137 
138   assert(isUse() && "Reg is not def or use");
139   return !MI->hasExtraSrcRegAllocReq(MachineInstr::IgnoreBundle);
140 }
141 
142 void MachineOperand::setIsRenamable(bool Val) {
143   assert(isReg() && "Wrong MachineOperand accessor");
144   assert(getReg().isPhysical() &&
145          "setIsRenamable should only be called on physical registers");
146   IsRenamable = Val;
147 }
148 
149 // If this operand is currently a register operand, and if this is in a
150 // function, deregister the operand from the register's use/def list.
151 void MachineOperand::removeRegFromUses() {
152   if (!isReg() || !isOnRegUseList())
153     return;
154 
155   if (MachineFunction *MF = getMFIfAvailable(*this))
156     MF->getRegInfo().removeRegOperandFromUseList(this);
157 }
158 
159 /// ChangeToImmediate - Replace this operand with a new immediate operand of
160 /// the specified value.  If an operand is known to be an immediate already,
161 /// the setImm method should be used.
162 void MachineOperand::ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags) {
163   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
164 
165   removeRegFromUses();
166 
167   OpKind = MO_Immediate;
168   Contents.ImmVal = ImmVal;
169   setTargetFlags(TargetFlags);
170 }
171 
172 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm,
173                                          unsigned TargetFlags) {
174   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
175 
176   removeRegFromUses();
177 
178   OpKind = MO_FPImmediate;
179   Contents.CFP = FPImm;
180   setTargetFlags(TargetFlags);
181 }
182 
183 void MachineOperand::ChangeToES(const char *SymName,
184                                 unsigned TargetFlags) {
185   assert((!isReg() || !isTied()) &&
186          "Cannot change a tied operand into an external symbol");
187 
188   removeRegFromUses();
189 
190   OpKind = MO_ExternalSymbol;
191   Contents.OffsetedInfo.Val.SymbolName = SymName;
192   setOffset(0); // Offset is always 0.
193   setTargetFlags(TargetFlags);
194 }
195 
196 void MachineOperand::ChangeToGA(const GlobalValue *GV, int64_t Offset,
197                                 unsigned TargetFlags) {
198   assert((!isReg() || !isTied()) &&
199          "Cannot change a tied operand into a global address");
200 
201   removeRegFromUses();
202 
203   OpKind = MO_GlobalAddress;
204   Contents.OffsetedInfo.Val.GV = GV;
205   setOffset(Offset);
206   setTargetFlags(TargetFlags);
207 }
208 
209 void MachineOperand::ChangeToBA(const BlockAddress *BA, int64_t Offset,
210                                 unsigned TargetFlags) {
211   assert((!isReg() || !isTied()) &&
212          "Cannot change a tied operand into a block address");
213 
214   removeRegFromUses();
215 
216   OpKind = MO_BlockAddress;
217   Contents.OffsetedInfo.Val.BA = BA;
218   setOffset(Offset);
219   setTargetFlags(TargetFlags);
220 }
221 
222 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags) {
223   assert((!isReg() || !isTied()) &&
224          "Cannot change a tied operand into an MCSymbol");
225 
226   removeRegFromUses();
227 
228   OpKind = MO_MCSymbol;
229   Contents.Sym = Sym;
230   setTargetFlags(TargetFlags);
231 }
232 
233 void MachineOperand::ChangeToFrameIndex(int Idx, unsigned TargetFlags) {
234   assert((!isReg() || !isTied()) &&
235          "Cannot change a tied operand into a FrameIndex");
236 
237   removeRegFromUses();
238 
239   OpKind = MO_FrameIndex;
240   setIndex(Idx);
241   setTargetFlags(TargetFlags);
242 }
243 
244 void MachineOperand::ChangeToTargetIndex(unsigned Idx, int64_t Offset,
245                                          unsigned TargetFlags) {
246   assert((!isReg() || !isTied()) &&
247          "Cannot change a tied operand into a FrameIndex");
248 
249   removeRegFromUses();
250 
251   OpKind = MO_TargetIndex;
252   setIndex(Idx);
253   setOffset(Offset);
254   setTargetFlags(TargetFlags);
255 }
256 
257 void MachineOperand::ChangeToDbgInstrRef(unsigned InstrIdx, unsigned OpIdx,
258                                          unsigned TargetFlags) {
259   assert((!isReg() || !isTied()) &&
260          "Cannot change a tied operand into a DbgInstrRef");
261 
262   removeRegFromUses();
263 
264   OpKind = MO_DbgInstrRef;
265   setInstrRefInstrIndex(InstrIdx);
266   setInstrRefOpIndex(OpIdx);
267   setTargetFlags(TargetFlags);
268 }
269 
270 /// ChangeToRegister - Replace this operand with a new register operand of
271 /// the specified value.  If an operand is known to be an register already,
272 /// the setReg method should be used.
273 void MachineOperand::ChangeToRegister(Register Reg, bool isDef, bool isImp,
274                                       bool isKill, bool isDead, bool isUndef,
275                                       bool isDebug) {
276   MachineRegisterInfo *RegInfo = nullptr;
277   if (MachineFunction *MF = getMFIfAvailable(*this))
278     RegInfo = &MF->getRegInfo();
279   // If this operand is already a register operand, remove it from the
280   // register's use/def lists.
281   bool WasReg = isReg();
282   if (RegInfo && WasReg)
283     RegInfo->removeRegOperandFromUseList(this);
284 
285   // Ensure debug instructions set debug flag on register uses.
286   const MachineInstr *MI = getParent();
287   if (!isDef && MI && MI->isDebugInstr())
288     isDebug = true;
289 
290   // Change this to a register and set the reg#.
291   assert(!(isDead && !isDef) && "Dead flag on non-def");
292   assert(!(isKill && isDef) && "Kill flag on def");
293   OpKind = MO_Register;
294   SmallContents.RegNo = Reg;
295   SubReg_TargetFlags = 0;
296   IsDef = isDef;
297   IsImp = isImp;
298   IsDeadOrKill = isKill | isDead;
299   IsRenamable = false;
300   IsUndef = isUndef;
301   IsInternalRead = false;
302   IsEarlyClobber = false;
303   IsDebug = isDebug;
304   // Ensure isOnRegUseList() returns false.
305   Contents.Reg.Prev = nullptr;
306   // Preserve the tie when the operand was already a register.
307   if (!WasReg)
308     TiedTo = 0;
309 
310   // If this operand is embedded in a function, add the operand to the
311   // register's use/def list.
312   if (RegInfo)
313     RegInfo->addRegOperandToUseList(this);
314 }
315 
316 /// isIdenticalTo - Return true if this operand is identical to the specified
317 /// operand. Note that this should stay in sync with the hash_value overload
318 /// below.
319 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
320   if (getType() != Other.getType() ||
321       getTargetFlags() != Other.getTargetFlags())
322     return false;
323 
324   switch (getType()) {
325   case MachineOperand::MO_Register:
326     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
327            getSubReg() == Other.getSubReg();
328   case MachineOperand::MO_Immediate:
329     return getImm() == Other.getImm();
330   case MachineOperand::MO_CImmediate:
331     return getCImm() == Other.getCImm();
332   case MachineOperand::MO_FPImmediate:
333     return getFPImm() == Other.getFPImm();
334   case MachineOperand::MO_MachineBasicBlock:
335     return getMBB() == Other.getMBB();
336   case MachineOperand::MO_FrameIndex:
337     return getIndex() == Other.getIndex();
338   case MachineOperand::MO_ConstantPoolIndex:
339   case MachineOperand::MO_TargetIndex:
340     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
341   case MachineOperand::MO_JumpTableIndex:
342     return getIndex() == Other.getIndex();
343   case MachineOperand::MO_GlobalAddress:
344     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
345   case MachineOperand::MO_ExternalSymbol:
346     return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
347            getOffset() == Other.getOffset();
348   case MachineOperand::MO_BlockAddress:
349     return getBlockAddress() == Other.getBlockAddress() &&
350            getOffset() == Other.getOffset();
351   case MachineOperand::MO_RegisterMask:
352   case MachineOperand::MO_RegisterLiveOut: {
353     // Shallow compare of the two RegMasks
354     const uint32_t *RegMask = getRegMask();
355     const uint32_t *OtherRegMask = Other.getRegMask();
356     if (RegMask == OtherRegMask)
357       return true;
358 
359     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
360       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
361       unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
362       // Deep compare of the two RegMasks
363       return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
364     }
365     // We don't know the size of the RegMask, so we can't deep compare the two
366     // reg masks.
367     return false;
368   }
369   case MachineOperand::MO_MCSymbol:
370     return getMCSymbol() == Other.getMCSymbol();
371   case MachineOperand::MO_DbgInstrRef:
372     return getInstrRefInstrIndex() == Other.getInstrRefInstrIndex() &&
373            getInstrRefOpIndex() == Other.getInstrRefOpIndex();
374   case MachineOperand::MO_CFIIndex:
375     return getCFIIndex() == Other.getCFIIndex();
376   case MachineOperand::MO_Metadata:
377     return getMetadata() == Other.getMetadata();
378   case MachineOperand::MO_IntrinsicID:
379     return getIntrinsicID() == Other.getIntrinsicID();
380   case MachineOperand::MO_Predicate:
381     return getPredicate() == Other.getPredicate();
382   case MachineOperand::MO_ShuffleMask:
383     return getShuffleMask() == Other.getShuffleMask();
384   }
385   llvm_unreachable("Invalid machine operand type");
386 }
387 
388 // Note: this must stay exactly in sync with isIdenticalTo above.
389 hash_code llvm::hash_value(const MachineOperand &MO) {
390   switch (MO.getType()) {
391   case MachineOperand::MO_Register:
392     // Register operands don't have target flags.
393     return hash_combine(MO.getType(), (unsigned)MO.getReg(), MO.getSubReg(), MO.isDef());
394   case MachineOperand::MO_Immediate:
395     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
396   case MachineOperand::MO_CImmediate:
397     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
398   case MachineOperand::MO_FPImmediate:
399     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
400   case MachineOperand::MO_MachineBasicBlock:
401     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
402   case MachineOperand::MO_FrameIndex:
403     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
404   case MachineOperand::MO_ConstantPoolIndex:
405   case MachineOperand::MO_TargetIndex:
406     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
407                         MO.getOffset());
408   case MachineOperand::MO_JumpTableIndex:
409     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
410   case MachineOperand::MO_ExternalSymbol:
411     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
412                         StringRef(MO.getSymbolName()));
413   case MachineOperand::MO_GlobalAddress:
414     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
415                         MO.getOffset());
416   case MachineOperand::MO_BlockAddress:
417     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getBlockAddress(),
418                         MO.getOffset());
419   case MachineOperand::MO_RegisterMask:
420   case MachineOperand::MO_RegisterLiveOut: {
421     if (const MachineFunction *MF = getMFIfAvailable(MO)) {
422       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
423       unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
424       const uint32_t *RegMask = MO.getRegMask();
425       std::vector<stable_hash> RegMaskHashes(RegMask, RegMask + RegMaskSize);
426       return hash_combine(MO.getType(), MO.getTargetFlags(),
427                           stable_hash_combine(RegMaskHashes));
428     }
429 
430     assert(0 && "MachineOperand not associated with any MachineFunction");
431     return hash_combine(MO.getType(), MO.getTargetFlags());
432   }
433   case MachineOperand::MO_Metadata:
434     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
435   case MachineOperand::MO_MCSymbol:
436     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
437   case MachineOperand::MO_DbgInstrRef:
438     return hash_combine(MO.getType(), MO.getTargetFlags(),
439                         MO.getInstrRefInstrIndex(), MO.getInstrRefOpIndex());
440   case MachineOperand::MO_CFIIndex:
441     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
442   case MachineOperand::MO_IntrinsicID:
443     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
444   case MachineOperand::MO_Predicate:
445     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
446   case MachineOperand::MO_ShuffleMask:
447     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getShuffleMask());
448   }
449   llvm_unreachable("Invalid machine operand type");
450 }
451 
452 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
453 // it.
454 static void tryToGetTargetInfo(const MachineOperand &MO,
455                                const TargetRegisterInfo *&TRI,
456                                const TargetIntrinsicInfo *&IntrinsicInfo) {
457   if (const MachineFunction *MF = getMFIfAvailable(MO)) {
458     TRI = MF->getSubtarget().getRegisterInfo();
459     IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
460   }
461 }
462 
463 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
464   const auto *TII = MF.getSubtarget().getInstrInfo();
465   assert(TII && "expected instruction info");
466   auto Indices = TII->getSerializableTargetIndices();
467   auto Found = find_if(Indices, [&](const std::pair<int, const char *> &I) {
468     return I.first == Index;
469   });
470   if (Found != Indices.end())
471     return Found->second;
472   return nullptr;
473 }
474 
475 const char *MachineOperand::getTargetIndexName() const {
476   const MachineFunction *MF = getMFIfAvailable(*this);
477   return MF ? ::getTargetIndexName(*MF, this->getIndex()) : nullptr;
478 }
479 
480 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
481   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
482   for (const auto &I : Flags) {
483     if (I.first == TF) {
484       return I.second;
485     }
486   }
487   return nullptr;
488 }
489 
490 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
491                              const TargetRegisterInfo *TRI) {
492   if (!TRI) {
493     OS << "%dwarfreg." << DwarfReg;
494     return;
495   }
496 
497   if (std::optional<unsigned> Reg = TRI->getLLVMRegNum(DwarfReg, true))
498     OS << printReg(*Reg, TRI);
499   else
500     OS << "<badreg>";
501 }
502 
503 static void printIRBlockReference(raw_ostream &OS, const BasicBlock &BB,
504                                   ModuleSlotTracker &MST) {
505   OS << "%ir-block.";
506   if (BB.hasName()) {
507     printLLVMNameWithoutPrefix(OS, BB.getName());
508     return;
509   }
510   std::optional<int> Slot;
511   if (const Function *F = BB.getParent()) {
512     if (F == MST.getCurrentFunction()) {
513       Slot = MST.getLocalSlot(&BB);
514     } else if (const Module *M = F->getParent()) {
515       ModuleSlotTracker CustomMST(M, /*ShouldInitializeAllMetadata=*/false);
516       CustomMST.incorporateFunction(*F);
517       Slot = CustomMST.getLocalSlot(&BB);
518     }
519   }
520   if (Slot)
521     MachineOperand::printIRSlotNumber(OS, *Slot);
522   else
523     OS << "<unknown>";
524 }
525 
526 static void printSyncScope(raw_ostream &OS, const LLVMContext &Context,
527                            SyncScope::ID SSID,
528                            SmallVectorImpl<StringRef> &SSNs) {
529   switch (SSID) {
530   case SyncScope::System:
531     break;
532   default:
533     if (SSNs.empty())
534       Context.getSyncScopeNames(SSNs);
535 
536     OS << "syncscope(\"";
537     printEscapedString(SSNs[SSID], OS);
538     OS << "\") ";
539     break;
540   }
541 }
542 
543 static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
544                                         unsigned TMMOFlag) {
545   auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
546   for (const auto &I : Flags) {
547     if (I.first == TMMOFlag) {
548       return I.second;
549     }
550   }
551   return nullptr;
552 }
553 
554 static void printFrameIndex(raw_ostream& OS, int FrameIndex, bool IsFixed,
555                             const MachineFrameInfo *MFI) {
556   StringRef Name;
557   if (MFI) {
558     IsFixed = MFI->isFixedObjectIndex(FrameIndex);
559     if (const AllocaInst *Alloca = MFI->getObjectAllocation(FrameIndex))
560       if (Alloca->hasName())
561         Name = Alloca->getName();
562     if (IsFixed)
563       FrameIndex -= MFI->getObjectIndexBegin();
564   }
565   MachineOperand::printStackObjectReference(OS, FrameIndex, IsFixed, Name);
566 }
567 
568 void MachineOperand::printSubRegIdx(raw_ostream &OS, uint64_t Index,
569                                     const TargetRegisterInfo *TRI) {
570   OS << "%subreg.";
571   if (TRI && Index != 0 && Index < TRI->getNumSubRegIndices())
572     OS << TRI->getSubRegIndexName(Index);
573   else
574     OS << Index;
575 }
576 
577 void MachineOperand::printTargetFlags(raw_ostream &OS,
578                                       const MachineOperand &Op) {
579   if (!Op.getTargetFlags())
580     return;
581   const MachineFunction *MF = getMFIfAvailable(Op);
582   if (!MF)
583     return;
584 
585   const auto *TII = MF->getSubtarget().getInstrInfo();
586   assert(TII && "expected instruction info");
587   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
588   OS << "target-flags(";
589   const bool HasDirectFlags = Flags.first;
590   const bool HasBitmaskFlags = Flags.second;
591   if (!HasDirectFlags && !HasBitmaskFlags) {
592     OS << "<unknown>) ";
593     return;
594   }
595   if (HasDirectFlags) {
596     if (const auto *Name = getTargetFlagName(TII, Flags.first))
597       OS << Name;
598     else
599       OS << "<unknown target flag>";
600   }
601   if (!HasBitmaskFlags) {
602     OS << ") ";
603     return;
604   }
605   bool IsCommaNeeded = HasDirectFlags;
606   unsigned BitMask = Flags.second;
607   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
608   for (const auto &Mask : BitMasks) {
609     // Check if the flag's bitmask has the bits of the current mask set.
610     if ((BitMask & Mask.first) == Mask.first) {
611       if (IsCommaNeeded)
612         OS << ", ";
613       IsCommaNeeded = true;
614       OS << Mask.second;
615       // Clear the bits which were serialized from the flag's bitmask.
616       BitMask &= ~(Mask.first);
617     }
618   }
619   if (BitMask) {
620     // When the resulting flag's bitmask isn't zero, we know that we didn't
621     // serialize all of the bit flags.
622     if (IsCommaNeeded)
623       OS << ", ";
624     OS << "<unknown bitmask target flag>";
625   }
626   OS << ") ";
627 }
628 
629 void MachineOperand::printSymbol(raw_ostream &OS, MCSymbol &Sym) {
630   OS << "<mcsymbol " << Sym << ">";
631 }
632 
633 void MachineOperand::printStackObjectReference(raw_ostream &OS,
634                                                unsigned FrameIndex,
635                                                bool IsFixed, StringRef Name) {
636   if (IsFixed) {
637     OS << "%fixed-stack." << FrameIndex;
638     return;
639   }
640 
641   OS << "%stack." << FrameIndex;
642   if (!Name.empty())
643     OS << '.' << Name;
644 }
645 
646 void MachineOperand::printOperandOffset(raw_ostream &OS, int64_t Offset) {
647   if (Offset == 0)
648     return;
649   if (Offset < 0) {
650     OS << " - " << -Offset;
651     return;
652   }
653   OS << " + " << Offset;
654 }
655 
656 void MachineOperand::printIRSlotNumber(raw_ostream &OS, int Slot) {
657   if (Slot == -1)
658     OS << "<badref>";
659   else
660     OS << Slot;
661 }
662 
663 static void printCFI(raw_ostream &OS, const MCCFIInstruction &CFI,
664                      const TargetRegisterInfo *TRI) {
665   switch (CFI.getOperation()) {
666   case MCCFIInstruction::OpSameValue:
667     OS << "same_value ";
668     if (MCSymbol *Label = CFI.getLabel())
669       MachineOperand::printSymbol(OS, *Label);
670     printCFIRegister(CFI.getRegister(), OS, TRI);
671     break;
672   case MCCFIInstruction::OpRememberState:
673     OS << "remember_state ";
674     if (MCSymbol *Label = CFI.getLabel())
675       MachineOperand::printSymbol(OS, *Label);
676     break;
677   case MCCFIInstruction::OpRestoreState:
678     OS << "restore_state ";
679     if (MCSymbol *Label = CFI.getLabel())
680       MachineOperand::printSymbol(OS, *Label);
681     break;
682   case MCCFIInstruction::OpOffset:
683     OS << "offset ";
684     if (MCSymbol *Label = CFI.getLabel())
685       MachineOperand::printSymbol(OS, *Label);
686     printCFIRegister(CFI.getRegister(), OS, TRI);
687     OS << ", " << CFI.getOffset();
688     break;
689   case MCCFIInstruction::OpDefCfaRegister:
690     OS << "def_cfa_register ";
691     if (MCSymbol *Label = CFI.getLabel())
692       MachineOperand::printSymbol(OS, *Label);
693     printCFIRegister(CFI.getRegister(), OS, TRI);
694     break;
695   case MCCFIInstruction::OpDefCfaOffset:
696     OS << "def_cfa_offset ";
697     if (MCSymbol *Label = CFI.getLabel())
698       MachineOperand::printSymbol(OS, *Label);
699     OS << CFI.getOffset();
700     break;
701   case MCCFIInstruction::OpDefCfa:
702     OS << "def_cfa ";
703     if (MCSymbol *Label = CFI.getLabel())
704       MachineOperand::printSymbol(OS, *Label);
705     printCFIRegister(CFI.getRegister(), OS, TRI);
706     OS << ", " << CFI.getOffset();
707     break;
708   case MCCFIInstruction::OpLLVMDefAspaceCfa:
709     OS << "llvm_def_aspace_cfa ";
710     if (MCSymbol *Label = CFI.getLabel())
711       MachineOperand::printSymbol(OS, *Label);
712     printCFIRegister(CFI.getRegister(), OS, TRI);
713     OS << ", " << CFI.getOffset();
714     OS << ", " << CFI.getAddressSpace();
715     break;
716   case MCCFIInstruction::OpRelOffset:
717     OS << "rel_offset ";
718     if (MCSymbol *Label = CFI.getLabel())
719       MachineOperand::printSymbol(OS, *Label);
720     printCFIRegister(CFI.getRegister(), OS, TRI);
721     OS << ", " << CFI.getOffset();
722     break;
723   case MCCFIInstruction::OpAdjustCfaOffset:
724     OS << "adjust_cfa_offset ";
725     if (MCSymbol *Label = CFI.getLabel())
726       MachineOperand::printSymbol(OS, *Label);
727     OS << CFI.getOffset();
728     break;
729   case MCCFIInstruction::OpRestore:
730     OS << "restore ";
731     if (MCSymbol *Label = CFI.getLabel())
732       MachineOperand::printSymbol(OS, *Label);
733     printCFIRegister(CFI.getRegister(), OS, TRI);
734     break;
735   case MCCFIInstruction::OpEscape: {
736     OS << "escape ";
737     if (MCSymbol *Label = CFI.getLabel())
738       MachineOperand::printSymbol(OS, *Label);
739     if (!CFI.getValues().empty()) {
740       size_t e = CFI.getValues().size() - 1;
741       for (size_t i = 0; i < e; ++i)
742         OS << format("0x%02x", uint8_t(CFI.getValues()[i])) << ", ";
743       OS << format("0x%02x", uint8_t(CFI.getValues()[e]));
744     }
745     break;
746   }
747   case MCCFIInstruction::OpUndefined:
748     OS << "undefined ";
749     if (MCSymbol *Label = CFI.getLabel())
750       MachineOperand::printSymbol(OS, *Label);
751     printCFIRegister(CFI.getRegister(), OS, TRI);
752     break;
753   case MCCFIInstruction::OpRegister:
754     OS << "register ";
755     if (MCSymbol *Label = CFI.getLabel())
756       MachineOperand::printSymbol(OS, *Label);
757     printCFIRegister(CFI.getRegister(), OS, TRI);
758     OS << ", ";
759     printCFIRegister(CFI.getRegister2(), OS, TRI);
760     break;
761   case MCCFIInstruction::OpWindowSave:
762     OS << "window_save ";
763     if (MCSymbol *Label = CFI.getLabel())
764       MachineOperand::printSymbol(OS, *Label);
765     break;
766   case MCCFIInstruction::OpNegateRAState:
767     OS << "negate_ra_sign_state ";
768     if (MCSymbol *Label = CFI.getLabel())
769       MachineOperand::printSymbol(OS, *Label);
770     break;
771   default:
772     // TODO: Print the other CFI Operations.
773     OS << "<unserializable cfi directive>";
774     break;
775   }
776 }
777 
778 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
779                            const TargetIntrinsicInfo *IntrinsicInfo) const {
780   print(OS, LLT{}, TRI, IntrinsicInfo);
781 }
782 
783 void MachineOperand::print(raw_ostream &OS, LLT TypeToPrint,
784                            const TargetRegisterInfo *TRI,
785                            const TargetIntrinsicInfo *IntrinsicInfo) const {
786   tryToGetTargetInfo(*this, TRI, IntrinsicInfo);
787   ModuleSlotTracker DummyMST(nullptr);
788   print(OS, DummyMST, TypeToPrint, std::nullopt, /*PrintDef=*/false,
789         /*IsStandalone=*/true,
790         /*ShouldPrintRegisterTies=*/true,
791         /*TiedOperandIdx=*/0, TRI, IntrinsicInfo);
792 }
793 
794 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
795                            LLT TypeToPrint, std::optional<unsigned> OpIdx,
796                            bool PrintDef, bool IsStandalone,
797                            bool ShouldPrintRegisterTies,
798                            unsigned TiedOperandIdx,
799                            const TargetRegisterInfo *TRI,
800                            const TargetIntrinsicInfo *IntrinsicInfo) const {
801   printTargetFlags(OS, *this);
802   switch (getType()) {
803   case MachineOperand::MO_Register: {
804     Register Reg = getReg();
805     if (isImplicit())
806       OS << (isDef() ? "implicit-def " : "implicit ");
807     else if (PrintDef && isDef())
808       // Print the 'def' flag only when the operand is defined after '='.
809       OS << "def ";
810     if (isInternalRead())
811       OS << "internal ";
812     if (isDead())
813       OS << "dead ";
814     if (isKill())
815       OS << "killed ";
816     if (isUndef())
817       OS << "undef ";
818     if (isEarlyClobber())
819       OS << "early-clobber ";
820     if (getReg().isPhysical() && isRenamable())
821       OS << "renamable ";
822     // isDebug() is exactly true for register operands of a DBG_VALUE. So we
823     // simply infer it when parsing and do not need to print it.
824 
825     const MachineRegisterInfo *MRI = nullptr;
826     if (Reg.isVirtual()) {
827       if (const MachineFunction *MF = getMFIfAvailable(*this)) {
828         MRI = &MF->getRegInfo();
829       }
830     }
831 
832     OS << printReg(Reg, TRI, 0, MRI);
833     // Print the sub register.
834     if (unsigned SubReg = getSubReg()) {
835       if (TRI)
836         OS << '.' << TRI->getSubRegIndexName(SubReg);
837       else
838         OS << ".subreg" << SubReg;
839     }
840     // Print the register class / bank.
841     if (Reg.isVirtual()) {
842       if (const MachineFunction *MF = getMFIfAvailable(*this)) {
843         const MachineRegisterInfo &MRI = MF->getRegInfo();
844         if (IsStandalone || !PrintDef || MRI.def_empty(Reg)) {
845           OS << ':';
846           OS << printRegClassOrBank(Reg, MRI, TRI);
847         }
848       }
849     }
850     // Print ties.
851     if (ShouldPrintRegisterTies && isTied() && !isDef())
852       OS << "(tied-def " << TiedOperandIdx << ")";
853     // Print types.
854     if (TypeToPrint.isValid())
855       OS << '(' << TypeToPrint << ')';
856     break;
857   }
858   case MachineOperand::MO_Immediate: {
859     const MIRFormatter *Formatter = nullptr;
860     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
861       const auto *TII = MF->getSubtarget().getInstrInfo();
862       assert(TII && "expected instruction info");
863       Formatter = TII->getMIRFormatter();
864     }
865     if (Formatter)
866       Formatter->printImm(OS, *getParent(), OpIdx, getImm());
867     else
868       OS << getImm();
869     break;
870   }
871   case MachineOperand::MO_CImmediate:
872     getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
873     break;
874   case MachineOperand::MO_FPImmediate:
875     getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
876     break;
877   case MachineOperand::MO_MachineBasicBlock:
878     OS << printMBBReference(*getMBB());
879     break;
880   case MachineOperand::MO_FrameIndex: {
881     int FrameIndex = getIndex();
882     bool IsFixed = false;
883     const MachineFrameInfo *MFI = nullptr;
884     if (const MachineFunction *MF = getMFIfAvailable(*this))
885       MFI = &MF->getFrameInfo();
886     printFrameIndex(OS, FrameIndex, IsFixed, MFI);
887     break;
888   }
889   case MachineOperand::MO_ConstantPoolIndex:
890     OS << "%const." << getIndex();
891     printOperandOffset(OS, getOffset());
892     break;
893   case MachineOperand::MO_TargetIndex: {
894     OS << "target-index(";
895     const char *Name = "<unknown>";
896     if (const MachineFunction *MF = getMFIfAvailable(*this))
897       if (const auto *TargetIndexName = ::getTargetIndexName(*MF, getIndex()))
898         Name = TargetIndexName;
899     OS << Name << ')';
900     printOperandOffset(OS, getOffset());
901     break;
902   }
903   case MachineOperand::MO_JumpTableIndex:
904     OS << printJumpTableEntryReference(getIndex());
905     break;
906   case MachineOperand::MO_GlobalAddress:
907     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
908     printOperandOffset(OS, getOffset());
909     break;
910   case MachineOperand::MO_ExternalSymbol: {
911     StringRef Name = getSymbolName();
912     OS << '&';
913     if (Name.empty()) {
914       OS << "\"\"";
915     } else {
916       printLLVMNameWithoutPrefix(OS, Name);
917     }
918     printOperandOffset(OS, getOffset());
919     break;
920   }
921   case MachineOperand::MO_BlockAddress: {
922     OS << "blockaddress(";
923     getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
924                                                      MST);
925     OS << ", ";
926     printIRBlockReference(OS, *getBlockAddress()->getBasicBlock(), MST);
927     OS << ')';
928     MachineOperand::printOperandOffset(OS, getOffset());
929     break;
930   }
931   case MachineOperand::MO_RegisterMask: {
932     OS << "<regmask";
933     if (TRI) {
934       unsigned NumRegsInMask = 0;
935       unsigned NumRegsEmitted = 0;
936       for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
937         unsigned MaskWord = i / 32;
938         unsigned MaskBit = i % 32;
939         if (getRegMask()[MaskWord] & (1 << MaskBit)) {
940           if (PrintRegMaskNumRegs < 0 ||
941               NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
942             OS << " " << printReg(i, TRI);
943             NumRegsEmitted++;
944           }
945           NumRegsInMask++;
946         }
947       }
948       if (NumRegsEmitted != NumRegsInMask)
949         OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
950     } else {
951       OS << " ...";
952     }
953     OS << ">";
954     break;
955   }
956   case MachineOperand::MO_RegisterLiveOut: {
957     const uint32_t *RegMask = getRegLiveOut();
958     OS << "liveout(";
959     if (!TRI) {
960       OS << "<unknown>";
961     } else {
962       bool IsCommaNeeded = false;
963       for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
964         if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
965           if (IsCommaNeeded)
966             OS << ", ";
967           OS << printReg(Reg, TRI);
968           IsCommaNeeded = true;
969         }
970       }
971     }
972     OS << ")";
973     break;
974   }
975   case MachineOperand::MO_Metadata:
976     getMetadata()->printAsOperand(OS, MST);
977     break;
978   case MachineOperand::MO_MCSymbol:
979     printSymbol(OS, *getMCSymbol());
980     break;
981   case MachineOperand::MO_DbgInstrRef: {
982     OS << "dbg-instr-ref(" << getInstrRefInstrIndex() << ", "
983        << getInstrRefOpIndex() << ')';
984     break;
985   }
986   case MachineOperand::MO_CFIIndex: {
987     if (const MachineFunction *MF = getMFIfAvailable(*this))
988       printCFI(OS, MF->getFrameInstructions()[getCFIIndex()], TRI);
989     else
990       OS << "<cfi directive>";
991     break;
992   }
993   case MachineOperand::MO_IntrinsicID: {
994     Intrinsic::ID ID = getIntrinsicID();
995     if (ID < Intrinsic::num_intrinsics)
996       OS << "intrinsic(@" << Intrinsic::getBaseName(ID) << ')';
997     else if (IntrinsicInfo)
998       OS << "intrinsic(@" << IntrinsicInfo->getName(ID) << ')';
999     else
1000       OS << "intrinsic(" << ID << ')';
1001     break;
1002   }
1003   case MachineOperand::MO_Predicate: {
1004     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
1005     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
1006        << Pred << ')';
1007     break;
1008   }
1009   case MachineOperand::MO_ShuffleMask:
1010     OS << "shufflemask(";
1011     ArrayRef<int> Mask = getShuffleMask();
1012     StringRef Separator;
1013     for (int Elt : Mask) {
1014       if (Elt == -1)
1015         OS << Separator << "undef";
1016       else
1017         OS << Separator << Elt;
1018       Separator = ", ";
1019     }
1020 
1021     OS << ')';
1022     break;
1023   }
1024 }
1025 
1026 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1027 LLVM_DUMP_METHOD void MachineOperand::dump() const { dbgs() << *this << '\n'; }
1028 #endif
1029 
1030 //===----------------------------------------------------------------------===//
1031 // MachineMemOperand Implementation
1032 //===----------------------------------------------------------------------===//
1033 
1034 /// getAddrSpace - Return the LLVM IR address space number that this pointer
1035 /// points into.
1036 unsigned MachinePointerInfo::getAddrSpace() const { return AddrSpace; }
1037 
1038 /// isDereferenceable - Return true if V is always dereferenceable for
1039 /// Offset + Size byte.
1040 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
1041                                            const DataLayout &DL) const {
1042   if (!isa<const Value *>(V))
1043     return false;
1044 
1045   const Value *BasePtr = cast<const Value *>(V);
1046   if (BasePtr == nullptr)
1047     return false;
1048 
1049   return isDereferenceableAndAlignedPointer(
1050       BasePtr, Align(1), APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
1051 }
1052 
1053 /// getConstantPool - Return a MachinePointerInfo record that refers to the
1054 /// constant pool.
1055 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
1056   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
1057 }
1058 
1059 /// getFixedStack - Return a MachinePointerInfo record that refers to the
1060 /// the specified FrameIndex.
1061 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
1062                                                      int FI, int64_t Offset) {
1063   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
1064 }
1065 
1066 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
1067   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
1068 }
1069 
1070 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
1071   return MachinePointerInfo(MF.getPSVManager().getGOT());
1072 }
1073 
1074 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
1075                                                 int64_t Offset, uint8_t ID) {
1076   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset, ID);
1077 }
1078 
1079 MachinePointerInfo MachinePointerInfo::getUnknownStack(MachineFunction &MF) {
1080   return MachinePointerInfo(MF.getDataLayout().getAllocaAddrSpace());
1081 }
1082 
1083 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
1084                                      LLT type, Align a, const AAMDNodes &AAInfo,
1085                                      const MDNode *Ranges, SyncScope::ID SSID,
1086                                      AtomicOrdering Ordering,
1087                                      AtomicOrdering FailureOrdering)
1088     : PtrInfo(ptrinfo), MemoryType(type), FlagVals(f), BaseAlign(a),
1089       AAInfo(AAInfo), Ranges(Ranges) {
1090   assert((PtrInfo.V.isNull() || isa<const PseudoSourceValue *>(PtrInfo.V) ||
1091           isa<PointerType>(cast<const Value *>(PtrInfo.V)->getType())) &&
1092          "invalid pointer value");
1093   assert((isLoad() || isStore()) && "Not a load/store!");
1094 
1095   AtomicInfo.SSID = static_cast<unsigned>(SSID);
1096   assert(getSyncScopeID() == SSID && "Value truncated");
1097   AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
1098   assert(getSuccessOrdering() == Ordering && "Value truncated");
1099   AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
1100   assert(getFailureOrdering() == FailureOrdering && "Value truncated");
1101 }
1102 
1103 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags F,
1104                                      LocationSize TS, Align BaseAlignment,
1105                                      const AAMDNodes &AAInfo,
1106                                      const MDNode *Ranges, SyncScope::ID SSID,
1107                                      AtomicOrdering Ordering,
1108                                      AtomicOrdering FailureOrdering)
1109     : MachineMemOperand(
1110           ptrinfo, F,
1111           !TS.hasValue() ? LLT()
1112           : TS.isScalable()
1113               ? LLT::scalable_vector(1, 8 * TS.getValue().getKnownMinValue())
1114               : LLT::scalar(8 * TS.getValue().getKnownMinValue()),
1115           BaseAlignment, AAInfo, Ranges, SSID, Ordering, FailureOrdering) {}
1116 
1117 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
1118   // The Value and Offset may differ due to CSE. But the flags and size
1119   // should be the same.
1120   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
1121   assert((!MMO->getSize().hasValue() || !getSize().hasValue() ||
1122           MMO->getSize() == getSize()) &&
1123          "Size mismatch!");
1124   if (MMO->getBaseAlign() >= getBaseAlign()) {
1125     // Update the alignment value.
1126     BaseAlign = MMO->getBaseAlign();
1127     // Also update the base and offset, because the new alignment may
1128     // not be applicable with the old ones.
1129     PtrInfo = MMO->PtrInfo;
1130   }
1131 }
1132 
1133 /// getAlign - Return the minimum known alignment in bytes of the
1134 /// actual memory reference.
1135 Align MachineMemOperand::getAlign() const {
1136   return commonAlignment(getBaseAlign(), getOffset());
1137 }
1138 
1139 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
1140                               SmallVectorImpl<StringRef> &SSNs,
1141                               const LLVMContext &Context,
1142                               const MachineFrameInfo *MFI,
1143                               const TargetInstrInfo *TII) const {
1144   OS << '(';
1145   if (isVolatile())
1146     OS << "volatile ";
1147   if (isNonTemporal())
1148     OS << "non-temporal ";
1149   if (isDereferenceable())
1150     OS << "dereferenceable ";
1151   if (isInvariant())
1152     OS << "invariant ";
1153   if (TII) {
1154     if (getFlags() & MachineMemOperand::MOTargetFlag1)
1155       OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag1)
1156          << "\" ";
1157     if (getFlags() & MachineMemOperand::MOTargetFlag2)
1158       OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag2)
1159          << "\" ";
1160     if (getFlags() & MachineMemOperand::MOTargetFlag3)
1161       OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag3)
1162          << "\" ";
1163   } else {
1164     if (getFlags() & MachineMemOperand::MOTargetFlag1)
1165       OS << "\"MOTargetFlag1\" ";
1166     if (getFlags() & MachineMemOperand::MOTargetFlag2)
1167       OS << "\"MOTargetFlag2\" ";
1168     if (getFlags() & MachineMemOperand::MOTargetFlag3)
1169       OS << "\"MOTargetFlag3\" ";
1170   }
1171 
1172   assert((isLoad() || isStore()) &&
1173          "machine memory operand must be a load or store (or both)");
1174   if (isLoad())
1175     OS << "load ";
1176   if (isStore())
1177     OS << "store ";
1178 
1179   printSyncScope(OS, Context, getSyncScopeID(), SSNs);
1180 
1181   if (getSuccessOrdering() != AtomicOrdering::NotAtomic)
1182     OS << toIRString(getSuccessOrdering()) << ' ';
1183   if (getFailureOrdering() != AtomicOrdering::NotAtomic)
1184     OS << toIRString(getFailureOrdering()) << ' ';
1185 
1186   if (getMemoryType().isValid())
1187     OS << '(' << getMemoryType() << ')';
1188   else
1189     OS << "unknown-size";
1190 
1191   if (const Value *Val = getValue()) {
1192     OS << ((isLoad() && isStore()) ? " on " : isLoad() ? " from " : " into ");
1193     MIRFormatter::printIRValue(OS, *Val, MST);
1194   } else if (const PseudoSourceValue *PVal = getPseudoValue()) {
1195     OS << ((isLoad() && isStore()) ? " on " : isLoad() ? " from " : " into ");
1196     assert(PVal && "Expected a pseudo source value");
1197     switch (PVal->kind()) {
1198     case PseudoSourceValue::Stack:
1199       OS << "stack";
1200       break;
1201     case PseudoSourceValue::GOT:
1202       OS << "got";
1203       break;
1204     case PseudoSourceValue::JumpTable:
1205       OS << "jump-table";
1206       break;
1207     case PseudoSourceValue::ConstantPool:
1208       OS << "constant-pool";
1209       break;
1210     case PseudoSourceValue::FixedStack: {
1211       int FrameIndex = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1212       bool IsFixed = true;
1213       printFrameIndex(OS, FrameIndex, IsFixed, MFI);
1214       break;
1215     }
1216     case PseudoSourceValue::GlobalValueCallEntry:
1217       OS << "call-entry ";
1218       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1219           OS, /*PrintType=*/false, MST);
1220       break;
1221     case PseudoSourceValue::ExternalSymbolCallEntry:
1222       OS << "call-entry &";
1223       printLLVMNameWithoutPrefix(
1224           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1225       break;
1226     default: {
1227       const MIRFormatter *Formatter = TII->getMIRFormatter();
1228       // FIXME: This is not necessarily the correct MIR serialization format for
1229       // a custom pseudo source value, but at least it allows
1230       // MIR printing to work on a target with custom pseudo source
1231       // values.
1232       OS << "custom \"";
1233       Formatter->printCustomPseudoSourceValue(OS, MST, *PVal);
1234       OS << '\"';
1235       break;
1236     }
1237     }
1238   } else if (getOpaqueValue() == nullptr && getOffset() != 0) {
1239     OS << ((isLoad() && isStore()) ? " on "
1240            : isLoad()              ? " from "
1241                                    : " into ")
1242        << "unknown-address";
1243   }
1244   MachineOperand::printOperandOffset(OS, getOffset());
1245   if (!getSize().hasValue() ||
1246       getAlign() != getSize().getValue().getKnownMinValue())
1247     OS << ", align " << getAlign().value();
1248   if (getAlign() != getBaseAlign())
1249     OS << ", basealign " << getBaseAlign().value();
1250   auto AAInfo = getAAInfo();
1251   if (AAInfo.TBAA) {
1252     OS << ", !tbaa ";
1253     AAInfo.TBAA->printAsOperand(OS, MST);
1254   }
1255   if (AAInfo.Scope) {
1256     OS << ", !alias.scope ";
1257     AAInfo.Scope->printAsOperand(OS, MST);
1258   }
1259   if (AAInfo.NoAlias) {
1260     OS << ", !noalias ";
1261     AAInfo.NoAlias->printAsOperand(OS, MST);
1262   }
1263   if (getRanges()) {
1264     OS << ", !range ";
1265     getRanges()->printAsOperand(OS, MST);
1266   }
1267   // FIXME: Implement addrspace printing/parsing in MIR.
1268   // For now, print this even though parsing it is not available in MIR.
1269   if (unsigned AS = getAddrSpace())
1270     OS << ", addrspace " << AS;
1271 
1272   OS << ')';
1273 }
1274