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