1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
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 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "MIRPrinter.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
19 #include "llvm/CodeGen/MIRYamlMapping.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/IRPrintingPasses.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/YAMLTraits.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetIntrinsicInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 
42 using namespace llvm;
43 
44 namespace {
45 
46 /// This structure describes how to print out stack object references.
47 struct FrameIndexOperand {
48   std::string Name;
49   unsigned ID;
50   bool IsFixed;
51 
52   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
53       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
54 
55   /// Return an ordinary stack object reference.
56   static FrameIndexOperand create(StringRef Name, unsigned ID) {
57     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
58   }
59 
60   /// Return a fixed stack object reference.
61   static FrameIndexOperand createFixed(unsigned ID) {
62     return FrameIndexOperand("", ID, /*IsFixed=*/true);
63   }
64 };
65 
66 } // end anonymous namespace
67 
68 namespace llvm {
69 
70 /// This class prints out the machine functions using the MIR serialization
71 /// format.
72 class MIRPrinter {
73   raw_ostream &OS;
74   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
75   /// Maps from stack object indices to operand indices which will be used when
76   /// printing frame index machine operands.
77   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
78 
79 public:
80   MIRPrinter(raw_ostream &OS) : OS(OS) {}
81 
82   void print(const MachineFunction &MF);
83 
84   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
85                const TargetRegisterInfo *TRI);
86   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
87                const MachineFrameInfo &MFI);
88   void convert(yaml::MachineFunction &MF,
89                const MachineConstantPool &ConstantPool);
90   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
91                const MachineJumpTableInfo &JTI);
92   void convertStackObjects(yaml::MachineFunction &MF,
93                            const MachineFrameInfo &MFI, MachineModuleInfo &MMI,
94                            ModuleSlotTracker &MST,
95                            const TargetRegisterInfo *TRI);
96 
97 private:
98   void initRegisterMaskIds(const MachineFunction &MF);
99 };
100 
101 /// This class prints out the machine instructions using the MIR serialization
102 /// format.
103 class MIPrinter {
104   raw_ostream &OS;
105   ModuleSlotTracker &MST;
106   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
107   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
108 
109 public:
110   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
111             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
112             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
113       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
114         StackObjectOperandMapping(StackObjectOperandMapping) {}
115 
116   void print(const MachineBasicBlock &MBB);
117 
118   void print(const MachineInstr &MI);
119   void printMBBReference(const MachineBasicBlock &MBB);
120   void printIRBlockReference(const BasicBlock &BB);
121   void printIRValueReference(const Value &V);
122   void printStackObjectReference(int FrameIndex);
123   void printOffset(int64_t Offset);
124   void printTargetFlags(const MachineOperand &Op);
125   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
126              unsigned I, bool ShouldPrintRegisterTies,
127              LLT TypeToPrint, bool IsDef = false);
128   void print(const MachineMemOperand &Op);
129 
130   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
131 };
132 
133 } // end namespace llvm
134 
135 namespace llvm {
136 namespace yaml {
137 
138 /// This struct serializes the LLVM IR module.
139 template <> struct BlockScalarTraits<Module> {
140   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
141     Mod.print(OS, nullptr);
142   }
143   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
144     llvm_unreachable("LLVM Module is supposed to be parsed separately");
145     return "";
146   }
147 };
148 
149 } // end namespace yaml
150 } // end namespace llvm
151 
152 static void printReg(unsigned Reg, raw_ostream &OS,
153                      const TargetRegisterInfo *TRI) {
154   // TODO: Print Stack Slots.
155   if (!Reg)
156     OS << '_';
157   else if (TargetRegisterInfo::isVirtualRegister(Reg))
158     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
159   else if (Reg < TRI->getNumRegs())
160     OS << '%' << StringRef(TRI->getName(Reg)).lower();
161   else
162     llvm_unreachable("Can't print this kind of register yet");
163 }
164 
165 static void printReg(unsigned Reg, yaml::StringValue &Dest,
166                      const TargetRegisterInfo *TRI) {
167   raw_string_ostream OS(Dest.Value);
168   printReg(Reg, OS, TRI);
169 }
170 
171 void MIRPrinter::print(const MachineFunction &MF) {
172   initRegisterMaskIds(MF);
173 
174   yaml::MachineFunction YamlMF;
175   YamlMF.Name = MF.getName();
176   YamlMF.Alignment = MF.getAlignment();
177   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
178 
179   YamlMF.Legalized = MF.getProperties().hasProperty(
180       MachineFunctionProperties::Property::Legalized);
181   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
182       MachineFunctionProperties::Property::RegBankSelected);
183   YamlMF.Selected = MF.getProperties().hasProperty(
184       MachineFunctionProperties::Property::Selected);
185 
186   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
187   ModuleSlotTracker MST(MF.getFunction()->getParent());
188   MST.incorporateFunction(*MF.getFunction());
189   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
190   convertStackObjects(YamlMF, MF.getFrameInfo(), MF.getMMI(), MST,
191                       MF.getSubtarget().getRegisterInfo());
192   if (const auto *ConstantPool = MF.getConstantPool())
193     convert(YamlMF, *ConstantPool);
194   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
195     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
196   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
197   bool IsNewlineNeeded = false;
198   for (const auto &MBB : MF) {
199     if (IsNewlineNeeded)
200       StrOS << "\n";
201     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
202         .print(MBB);
203     IsNewlineNeeded = true;
204   }
205   StrOS.flush();
206   yaml::Output Out(OS);
207   Out << YamlMF;
208 }
209 
210 void MIRPrinter::convert(yaml::MachineFunction &MF,
211                          const MachineRegisterInfo &RegInfo,
212                          const TargetRegisterInfo *TRI) {
213   MF.TracksRegLiveness = RegInfo.tracksLiveness();
214 
215   // Print the virtual register definitions.
216   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
217     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
218     yaml::VirtualRegisterDefinition VReg;
219     VReg.ID = I;
220     if (RegInfo.getRegClassOrNull(Reg))
221       VReg.Class =
222           StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
223     else if (RegInfo.getRegBankOrNull(Reg))
224       VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
225     else {
226       VReg.Class = std::string("_");
227       assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
228              "Generic registers must have a valid type");
229     }
230     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
231     if (PreferredReg)
232       printReg(PreferredReg, VReg.PreferredRegister, TRI);
233     MF.VirtualRegisters.push_back(VReg);
234   }
235 
236   // Print the live ins.
237   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
238     yaml::MachineFunctionLiveIn LiveIn;
239     printReg(I->first, LiveIn.Register, TRI);
240     if (I->second)
241       printReg(I->second, LiveIn.VirtualRegister, TRI);
242     MF.LiveIns.push_back(LiveIn);
243   }
244   // The used physical register mask is printed as an inverted callee saved
245   // register mask.
246   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
247   if (UsedPhysRegMask.none())
248     return;
249   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
250   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
251     if (!UsedPhysRegMask[I]) {
252       yaml::FlowStringValue Reg;
253       printReg(I, Reg, TRI);
254       CalleeSavedRegisters.push_back(Reg);
255     }
256   }
257   MF.CalleeSavedRegisters = CalleeSavedRegisters;
258 }
259 
260 void MIRPrinter::convert(ModuleSlotTracker &MST,
261                          yaml::MachineFrameInfo &YamlMFI,
262                          const MachineFrameInfo &MFI) {
263   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
264   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
265   YamlMFI.HasStackMap = MFI.hasStackMap();
266   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
267   YamlMFI.StackSize = MFI.getStackSize();
268   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
269   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
270   YamlMFI.AdjustsStack = MFI.adjustsStack();
271   YamlMFI.HasCalls = MFI.hasCalls();
272   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
273   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
274   YamlMFI.HasVAStart = MFI.hasVAStart();
275   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
276   if (MFI.getSavePoint()) {
277     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
278     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
279         .printMBBReference(*MFI.getSavePoint());
280   }
281   if (MFI.getRestorePoint()) {
282     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
283     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
284         .printMBBReference(*MFI.getRestorePoint());
285   }
286 }
287 
288 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
289                                      const MachineFrameInfo &MFI,
290                                      MachineModuleInfo &MMI,
291                                      ModuleSlotTracker &MST,
292                                      const TargetRegisterInfo *TRI) {
293   // Process fixed stack objects.
294   unsigned ID = 0;
295   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
296     if (MFI.isDeadObjectIndex(I))
297       continue;
298 
299     yaml::FixedMachineStackObject YamlObject;
300     YamlObject.ID = ID;
301     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
302                           ? yaml::FixedMachineStackObject::SpillSlot
303                           : yaml::FixedMachineStackObject::DefaultType;
304     YamlObject.Offset = MFI.getObjectOffset(I);
305     YamlObject.Size = MFI.getObjectSize(I);
306     YamlObject.Alignment = MFI.getObjectAlignment(I);
307     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
308     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
309     MF.FixedStackObjects.push_back(YamlObject);
310     StackObjectOperandMapping.insert(
311         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
312   }
313 
314   // Process ordinary stack objects.
315   ID = 0;
316   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
317     if (MFI.isDeadObjectIndex(I))
318       continue;
319 
320     yaml::MachineStackObject YamlObject;
321     YamlObject.ID = ID;
322     if (const auto *Alloca = MFI.getObjectAllocation(I))
323       YamlObject.Name.Value =
324           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
325     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
326                           ? yaml::MachineStackObject::SpillSlot
327                           : MFI.isVariableSizedObjectIndex(I)
328                                 ? yaml::MachineStackObject::VariableSized
329                                 : yaml::MachineStackObject::DefaultType;
330     YamlObject.Offset = MFI.getObjectOffset(I);
331     YamlObject.Size = MFI.getObjectSize(I);
332     YamlObject.Alignment = MFI.getObjectAlignment(I);
333 
334     MF.StackObjects.push_back(YamlObject);
335     StackObjectOperandMapping.insert(std::make_pair(
336         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
337   }
338 
339   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
340     yaml::StringValue Reg;
341     printReg(CSInfo.getReg(), Reg, TRI);
342     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
343     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
344            "Invalid stack object index");
345     const FrameIndexOperand &StackObject = StackObjectInfo->second;
346     if (StackObject.IsFixed)
347       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
348     else
349       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
350   }
351   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
352     auto LocalObject = MFI.getLocalFrameObjectMap(I);
353     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
354     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
355            "Invalid stack object index");
356     const FrameIndexOperand &StackObject = StackObjectInfo->second;
357     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
358     MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
359   }
360 
361   // Print the stack object references in the frame information class after
362   // converting the stack objects.
363   if (MFI.hasStackProtectorIndex()) {
364     raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
365     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
366         .printStackObjectReference(MFI.getStackProtectorIndex());
367   }
368 
369   // Print the debug variable information.
370   for (MachineModuleInfo::VariableDbgInfo &DebugVar :
371        MMI.getVariableDbgInfo()) {
372     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
373     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
374            "Invalid stack object index");
375     const FrameIndexOperand &StackObject = StackObjectInfo->second;
376     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
377     auto &Object = MF.StackObjects[StackObject.ID];
378     {
379       raw_string_ostream StrOS(Object.DebugVar.Value);
380       DebugVar.Var->printAsOperand(StrOS, MST);
381     }
382     {
383       raw_string_ostream StrOS(Object.DebugExpr.Value);
384       DebugVar.Expr->printAsOperand(StrOS, MST);
385     }
386     {
387       raw_string_ostream StrOS(Object.DebugLoc.Value);
388       DebugVar.Loc->printAsOperand(StrOS, MST);
389     }
390   }
391 }
392 
393 void MIRPrinter::convert(yaml::MachineFunction &MF,
394                          const MachineConstantPool &ConstantPool) {
395   unsigned ID = 0;
396   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
397     // TODO: Serialize target specific constant pool entries.
398     if (Constant.isMachineConstantPoolEntry())
399       llvm_unreachable("Can't print target specific constant pool entries yet");
400 
401     yaml::MachineConstantPoolValue YamlConstant;
402     std::string Str;
403     raw_string_ostream StrOS(Str);
404     Constant.Val.ConstVal->printAsOperand(StrOS);
405     YamlConstant.ID = ID++;
406     YamlConstant.Value = StrOS.str();
407     YamlConstant.Alignment = Constant.getAlignment();
408     MF.Constants.push_back(YamlConstant);
409   }
410 }
411 
412 void MIRPrinter::convert(ModuleSlotTracker &MST,
413                          yaml::MachineJumpTable &YamlJTI,
414                          const MachineJumpTableInfo &JTI) {
415   YamlJTI.Kind = JTI.getEntryKind();
416   unsigned ID = 0;
417   for (const auto &Table : JTI.getJumpTables()) {
418     std::string Str;
419     yaml::MachineJumpTable::Entry Entry;
420     Entry.ID = ID++;
421     for (const auto *MBB : Table.MBBs) {
422       raw_string_ostream StrOS(Str);
423       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
424           .printMBBReference(*MBB);
425       Entry.Blocks.push_back(StrOS.str());
426       Str.clear();
427     }
428     YamlJTI.Entries.push_back(Entry);
429   }
430 }
431 
432 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
433   const auto *TRI = MF.getSubtarget().getRegisterInfo();
434   unsigned I = 0;
435   for (const uint32_t *Mask : TRI->getRegMasks())
436     RegisterMaskIds.insert(std::make_pair(Mask, I++));
437 }
438 
439 void MIPrinter::print(const MachineBasicBlock &MBB) {
440   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
441   OS << "bb." << MBB.getNumber();
442   bool HasAttributes = false;
443   if (const auto *BB = MBB.getBasicBlock()) {
444     if (BB->hasName()) {
445       OS << "." << BB->getName();
446     } else {
447       HasAttributes = true;
448       OS << " (";
449       int Slot = MST.getLocalSlot(BB);
450       if (Slot == -1)
451         OS << "<ir-block badref>";
452       else
453         OS << (Twine("%ir-block.") + Twine(Slot)).str();
454     }
455   }
456   if (MBB.hasAddressTaken()) {
457     OS << (HasAttributes ? ", " : " (");
458     OS << "address-taken";
459     HasAttributes = true;
460   }
461   if (MBB.isEHPad()) {
462     OS << (HasAttributes ? ", " : " (");
463     OS << "landing-pad";
464     HasAttributes = true;
465   }
466   if (MBB.getAlignment()) {
467     OS << (HasAttributes ? ", " : " (");
468     OS << "align " << MBB.getAlignment();
469     HasAttributes = true;
470   }
471   if (HasAttributes)
472     OS << ")";
473   OS << ":\n";
474 
475   bool HasLineAttributes = false;
476   // Print the successors
477   if (!MBB.succ_empty()) {
478     OS.indent(2) << "successors: ";
479     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
480       if (I != MBB.succ_begin())
481         OS << ", ";
482       printMBBReference(**I);
483       if (MBB.hasSuccessorProbabilities())
484         OS << '(' << MBB.getSuccProbability(I) << ')';
485     }
486     OS << "\n";
487     HasLineAttributes = true;
488   }
489 
490   // Print the live in registers.
491   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
492   assert(TRI && "Expected target register info");
493   if (!MBB.livein_empty()) {
494     OS.indent(2) << "liveins: ";
495     bool First = true;
496     for (const auto &LI : MBB.liveins()) {
497       if (!First)
498         OS << ", ";
499       First = false;
500       printReg(LI.PhysReg, OS, TRI);
501       if (LI.LaneMask != ~0u)
502         OS << ":0x" << PrintLaneMask(LI.LaneMask);
503     }
504     OS << "\n";
505     HasLineAttributes = true;
506   }
507 
508   if (HasLineAttributes)
509     OS << "\n";
510   bool IsInBundle = false;
511   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
512     const MachineInstr &MI = *I;
513     if (IsInBundle && !MI.isInsideBundle()) {
514       OS.indent(2) << "}\n";
515       IsInBundle = false;
516     }
517     OS.indent(IsInBundle ? 4 : 2);
518     print(MI);
519     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
520       OS << " {";
521       IsInBundle = true;
522     }
523     OS << "\n";
524   }
525   if (IsInBundle)
526     OS.indent(2) << "}\n";
527 }
528 
529 /// Return true when an instruction has tied register that can't be determined
530 /// by the instruction's descriptor.
531 static bool hasComplexRegisterTies(const MachineInstr &MI) {
532   const MCInstrDesc &MCID = MI.getDesc();
533   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
534     const auto &Operand = MI.getOperand(I);
535     if (!Operand.isReg() || Operand.isDef())
536       // Ignore the defined registers as MCID marks only the uses as tied.
537       continue;
538     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
539     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
540     if (ExpectedTiedIdx != TiedIdx)
541       return true;
542   }
543   return false;
544 }
545 
546 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
547                           SmallBitVector &PrintedTypes,
548                           const MachineRegisterInfo &MRI) {
549   const MachineOperand &Op = MI.getOperand(OpIdx);
550   if (!Op.isReg())
551     return LLT{};
552 
553   if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
554     return MRI.getType(Op.getReg());
555 
556   auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
557   if (!OpInfo.isGenericType())
558     return MRI.getType(Op.getReg());
559 
560   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
561     return LLT{};
562 
563   PrintedTypes.set(OpInfo.getGenericTypeIndex());
564   return MRI.getType(Op.getReg());
565 }
566 
567 void MIPrinter::print(const MachineInstr &MI) {
568   const auto *MF = MI.getParent()->getParent();
569   const auto &MRI = MF->getRegInfo();
570   const auto &SubTarget = MF->getSubtarget();
571   const auto *TRI = SubTarget.getRegisterInfo();
572   assert(TRI && "Expected target register info");
573   const auto *TII = SubTarget.getInstrInfo();
574   assert(TII && "Expected target instruction info");
575   if (MI.isCFIInstruction())
576     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
577 
578   SmallBitVector PrintedTypes(8);
579   bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
580   unsigned I = 0, E = MI.getNumOperands();
581   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
582          !MI.getOperand(I).isImplicit();
583        ++I) {
584     if (I)
585       OS << ", ";
586     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
587           getTypeToPrint(MI, I, PrintedTypes, MRI),
588           /*IsDef=*/true);
589   }
590 
591   if (I)
592     OS << " = ";
593   if (MI.getFlag(MachineInstr::FrameSetup))
594     OS << "frame-setup ";
595   OS << TII->getName(MI.getOpcode());
596   if (I < E)
597     OS << ' ';
598 
599   bool NeedComma = false;
600   for (; I < E; ++I) {
601     if (NeedComma)
602       OS << ", ";
603     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
604           getTypeToPrint(MI, I, PrintedTypes, MRI));
605     NeedComma = true;
606   }
607 
608   if (MI.getDebugLoc()) {
609     if (NeedComma)
610       OS << ',';
611     OS << " debug-location ";
612     MI.getDebugLoc()->printAsOperand(OS, MST);
613   }
614 
615   if (!MI.memoperands_empty()) {
616     OS << " :: ";
617     bool NeedComma = false;
618     for (const auto *Op : MI.memoperands()) {
619       if (NeedComma)
620         OS << ", ";
621       print(*Op);
622       NeedComma = true;
623     }
624   }
625 }
626 
627 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
628   OS << "%bb." << MBB.getNumber();
629   if (const auto *BB = MBB.getBasicBlock()) {
630     if (BB->hasName())
631       OS << '.' << BB->getName();
632   }
633 }
634 
635 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
636   if (Slot == -1)
637     OS << "<badref>";
638   else
639     OS << Slot;
640 }
641 
642 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
643   OS << "%ir-block.";
644   if (BB.hasName()) {
645     printLLVMNameWithoutPrefix(OS, BB.getName());
646     return;
647   }
648   const Function *F = BB.getParent();
649   int Slot;
650   if (F == MST.getCurrentFunction()) {
651     Slot = MST.getLocalSlot(&BB);
652   } else {
653     ModuleSlotTracker CustomMST(F->getParent(),
654                                 /*ShouldInitializeAllMetadata=*/false);
655     CustomMST.incorporateFunction(*F);
656     Slot = CustomMST.getLocalSlot(&BB);
657   }
658   printIRSlotNumber(OS, Slot);
659 }
660 
661 void MIPrinter::printIRValueReference(const Value &V) {
662   if (isa<GlobalValue>(V)) {
663     V.printAsOperand(OS, /*PrintType=*/false, MST);
664     return;
665   }
666   if (isa<Constant>(V)) {
667     // Machine memory operands can load/store to/from constant value pointers.
668     OS << '`';
669     V.printAsOperand(OS, /*PrintType=*/true, MST);
670     OS << '`';
671     return;
672   }
673   OS << "%ir.";
674   if (V.hasName()) {
675     printLLVMNameWithoutPrefix(OS, V.getName());
676     return;
677   }
678   printIRSlotNumber(OS, MST.getLocalSlot(&V));
679 }
680 
681 void MIPrinter::printStackObjectReference(int FrameIndex) {
682   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
683   assert(ObjectInfo != StackObjectOperandMapping.end() &&
684          "Invalid frame index");
685   const FrameIndexOperand &Operand = ObjectInfo->second;
686   if (Operand.IsFixed) {
687     OS << "%fixed-stack." << Operand.ID;
688     return;
689   }
690   OS << "%stack." << Operand.ID;
691   if (!Operand.Name.empty())
692     OS << '.' << Operand.Name;
693 }
694 
695 void MIPrinter::printOffset(int64_t Offset) {
696   if (Offset == 0)
697     return;
698   if (Offset < 0) {
699     OS << " - " << -Offset;
700     return;
701   }
702   OS << " + " << Offset;
703 }
704 
705 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
706   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
707   for (const auto &I : Flags) {
708     if (I.first == TF) {
709       return I.second;
710     }
711   }
712   return nullptr;
713 }
714 
715 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
716   if (!Op.getTargetFlags())
717     return;
718   const auto *TII =
719       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
720   assert(TII && "expected instruction info");
721   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
722   OS << "target-flags(";
723   const bool HasDirectFlags = Flags.first;
724   const bool HasBitmaskFlags = Flags.second;
725   if (!HasDirectFlags && !HasBitmaskFlags) {
726     OS << "<unknown>) ";
727     return;
728   }
729   if (HasDirectFlags) {
730     if (const auto *Name = getTargetFlagName(TII, Flags.first))
731       OS << Name;
732     else
733       OS << "<unknown target flag>";
734   }
735   if (!HasBitmaskFlags) {
736     OS << ") ";
737     return;
738   }
739   bool IsCommaNeeded = HasDirectFlags;
740   unsigned BitMask = Flags.second;
741   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
742   for (const auto &Mask : BitMasks) {
743     // Check if the flag's bitmask has the bits of the current mask set.
744     if ((BitMask & Mask.first) == Mask.first) {
745       if (IsCommaNeeded)
746         OS << ", ";
747       IsCommaNeeded = true;
748       OS << Mask.second;
749       // Clear the bits which were serialized from the flag's bitmask.
750       BitMask &= ~(Mask.first);
751     }
752   }
753   if (BitMask) {
754     // When the resulting flag's bitmask isn't zero, we know that we didn't
755     // serialize all of the bit flags.
756     if (IsCommaNeeded)
757       OS << ", ";
758     OS << "<unknown bitmask target flag>";
759   }
760   OS << ") ";
761 }
762 
763 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
764   const auto *TII = MF.getSubtarget().getInstrInfo();
765   assert(TII && "expected instruction info");
766   auto Indices = TII->getSerializableTargetIndices();
767   for (const auto &I : Indices) {
768     if (I.first == Index) {
769       return I.second;
770     }
771   }
772   return nullptr;
773 }
774 
775 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
776                       unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
777                       bool IsDef) {
778   printTargetFlags(Op);
779   switch (Op.getType()) {
780   case MachineOperand::MO_Register:
781     if (Op.isImplicit())
782       OS << (Op.isDef() ? "implicit-def " : "implicit ");
783     else if (!IsDef && Op.isDef())
784       // Print the 'def' flag only when the operand is defined after '='.
785       OS << "def ";
786     if (Op.isInternalRead())
787       OS << "internal ";
788     if (Op.isDead())
789       OS << "dead ";
790     if (Op.isKill())
791       OS << "killed ";
792     if (Op.isUndef())
793       OS << "undef ";
794     if (Op.isEarlyClobber())
795       OS << "early-clobber ";
796     if (Op.isDebug())
797       OS << "debug-use ";
798     printReg(Op.getReg(), OS, TRI);
799     // Print the sub register.
800     if (Op.getSubReg() != 0)
801       OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
802     if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
803       OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
804     if (TypeToPrint.isValid())
805       OS << '(' << TypeToPrint << ')';
806     break;
807   case MachineOperand::MO_Immediate:
808     OS << Op.getImm();
809     break;
810   case MachineOperand::MO_CImmediate:
811     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
812     break;
813   case MachineOperand::MO_FPImmediate:
814     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
815     break;
816   case MachineOperand::MO_MachineBasicBlock:
817     printMBBReference(*Op.getMBB());
818     break;
819   case MachineOperand::MO_FrameIndex:
820     printStackObjectReference(Op.getIndex());
821     break;
822   case MachineOperand::MO_ConstantPoolIndex:
823     OS << "%const." << Op.getIndex();
824     printOffset(Op.getOffset());
825     break;
826   case MachineOperand::MO_TargetIndex: {
827     OS << "target-index(";
828     if (const auto *Name = getTargetIndexName(
829             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
830       OS << Name;
831     else
832       OS << "<unknown>";
833     OS << ')';
834     printOffset(Op.getOffset());
835     break;
836   }
837   case MachineOperand::MO_JumpTableIndex:
838     OS << "%jump-table." << Op.getIndex();
839     break;
840   case MachineOperand::MO_ExternalSymbol:
841     OS << '$';
842     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
843     printOffset(Op.getOffset());
844     break;
845   case MachineOperand::MO_GlobalAddress:
846     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
847     printOffset(Op.getOffset());
848     break;
849   case MachineOperand::MO_BlockAddress:
850     OS << "blockaddress(";
851     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
852                                                         MST);
853     OS << ", ";
854     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
855     OS << ')';
856     printOffset(Op.getOffset());
857     break;
858   case MachineOperand::MO_RegisterMask: {
859     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
860     if (RegMaskInfo != RegisterMaskIds.end())
861       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
862     else
863       llvm_unreachable("Can't print this machine register mask yet.");
864     break;
865   }
866   case MachineOperand::MO_RegisterLiveOut: {
867     const uint32_t *RegMask = Op.getRegLiveOut();
868     OS << "liveout(";
869     bool IsCommaNeeded = false;
870     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
871       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
872         if (IsCommaNeeded)
873           OS << ", ";
874         printReg(Reg, OS, TRI);
875         IsCommaNeeded = true;
876       }
877     }
878     OS << ")";
879     break;
880   }
881   case MachineOperand::MO_Metadata:
882     Op.getMetadata()->printAsOperand(OS, MST);
883     break;
884   case MachineOperand::MO_MCSymbol:
885     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
886     break;
887   case MachineOperand::MO_CFIIndex: {
888     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
889     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
890     break;
891   }
892   case MachineOperand::MO_IntrinsicID: {
893     Intrinsic::ID ID = Op.getIntrinsicID();
894     if (ID < Intrinsic::num_intrinsics)
895       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
896     else {
897       const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
898       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
899       OS << "intrinsic(@" << TII->getName(ID) << ')';
900     }
901     break;
902   }
903   case MachineOperand::MO_Predicate: {
904     auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
905     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
906        << CmpInst::getPredicateName(Pred) << ')';
907     break;
908   }
909   }
910 }
911 
912 void MIPrinter::print(const MachineMemOperand &Op) {
913   OS << '(';
914   // TODO: Print operand's target specific flags.
915   if (Op.isVolatile())
916     OS << "volatile ";
917   if (Op.isNonTemporal())
918     OS << "non-temporal ";
919   if (Op.isDereferenceable())
920     OS << "dereferenceable ";
921   if (Op.isInvariant())
922     OS << "invariant ";
923   if (Op.isLoad())
924     OS << "load ";
925   else {
926     assert(Op.isStore() && "Non load machine operand must be a store");
927     OS << "store ";
928   }
929   OS << Op.getSize();
930   if (const Value *Val = Op.getValue()) {
931     OS << (Op.isLoad() ? " from " : " into ");
932     printIRValueReference(*Val);
933   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
934     OS << (Op.isLoad() ? " from " : " into ");
935     assert(PVal && "Expected a pseudo source value");
936     switch (PVal->kind()) {
937     case PseudoSourceValue::Stack:
938       OS << "stack";
939       break;
940     case PseudoSourceValue::GOT:
941       OS << "got";
942       break;
943     case PseudoSourceValue::JumpTable:
944       OS << "jump-table";
945       break;
946     case PseudoSourceValue::ConstantPool:
947       OS << "constant-pool";
948       break;
949     case PseudoSourceValue::FixedStack:
950       printStackObjectReference(
951           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
952       break;
953     case PseudoSourceValue::GlobalValueCallEntry:
954       OS << "call-entry ";
955       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
956           OS, /*PrintType=*/false, MST);
957       break;
958     case PseudoSourceValue::ExternalSymbolCallEntry:
959       OS << "call-entry $";
960       printLLVMNameWithoutPrefix(
961           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
962       break;
963     }
964   }
965   printOffset(Op.getOffset());
966   if (Op.getBaseAlignment() != Op.getSize())
967     OS << ", align " << Op.getBaseAlignment();
968   auto AAInfo = Op.getAAInfo();
969   if (AAInfo.TBAA) {
970     OS << ", !tbaa ";
971     AAInfo.TBAA->printAsOperand(OS, MST);
972   }
973   if (AAInfo.Scope) {
974     OS << ", !alias.scope ";
975     AAInfo.Scope->printAsOperand(OS, MST);
976   }
977   if (AAInfo.NoAlias) {
978     OS << ", !noalias ";
979     AAInfo.NoAlias->printAsOperand(OS, MST);
980   }
981   if (Op.getRanges()) {
982     OS << ", !range ";
983     Op.getRanges()->printAsOperand(OS, MST);
984   }
985   OS << ')';
986 }
987 
988 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
989                              const TargetRegisterInfo *TRI) {
990   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
991   if (Reg == -1) {
992     OS << "<badreg>";
993     return;
994   }
995   printReg(Reg, OS, TRI);
996 }
997 
998 void MIPrinter::print(const MCCFIInstruction &CFI,
999                       const TargetRegisterInfo *TRI) {
1000   switch (CFI.getOperation()) {
1001   case MCCFIInstruction::OpSameValue:
1002     OS << "same_value ";
1003     if (CFI.getLabel())
1004       OS << "<mcsymbol> ";
1005     printCFIRegister(CFI.getRegister(), OS, TRI);
1006     break;
1007   case MCCFIInstruction::OpOffset:
1008     OS << "offset ";
1009     if (CFI.getLabel())
1010       OS << "<mcsymbol> ";
1011     printCFIRegister(CFI.getRegister(), OS, TRI);
1012     OS << ", " << CFI.getOffset();
1013     break;
1014   case MCCFIInstruction::OpDefCfaRegister:
1015     OS << "def_cfa_register ";
1016     if (CFI.getLabel())
1017       OS << "<mcsymbol> ";
1018     printCFIRegister(CFI.getRegister(), OS, TRI);
1019     break;
1020   case MCCFIInstruction::OpDefCfaOffset:
1021     OS << "def_cfa_offset ";
1022     if (CFI.getLabel())
1023       OS << "<mcsymbol> ";
1024     OS << CFI.getOffset();
1025     break;
1026   case MCCFIInstruction::OpDefCfa:
1027     OS << "def_cfa ";
1028     if (CFI.getLabel())
1029       OS << "<mcsymbol> ";
1030     printCFIRegister(CFI.getRegister(), OS, TRI);
1031     OS << ", " << CFI.getOffset();
1032     break;
1033   default:
1034     // TODO: Print the other CFI Operations.
1035     OS << "<unserializable cfi operation>";
1036     break;
1037   }
1038 }
1039 
1040 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1041   yaml::Output Out(OS);
1042   Out << const_cast<Module &>(M);
1043 }
1044 
1045 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1046   MIRPrinter Printer(OS);
1047   Printer.print(MF);
1048 }
1049