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