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     else
413       YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
414   }
415   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
416     auto LocalObject = MFI.getLocalFrameObjectMap(I);
417     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
418     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
419            "Invalid stack object index");
420     const FrameIndexOperand &StackObject = StackObjectInfo->second;
421     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
422     YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
423   }
424 
425   // Print the stack object references in the frame information class after
426   // converting the stack objects.
427   if (MFI.hasStackProtectorIndex()) {
428     raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
429     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
430         .printStackObjectReference(MFI.getStackProtectorIndex());
431   }
432 
433   // Print the debug variable information.
434   for (const MachineFunction::VariableDbgInfo &DebugVar :
435        MF.getVariableDbgInfo()) {
436     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
437     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
438            "Invalid stack object index");
439     const FrameIndexOperand &StackObject = StackObjectInfo->second;
440     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
441     auto &Object = YMF.StackObjects[StackObject.ID];
442     {
443       raw_string_ostream StrOS(Object.DebugVar.Value);
444       DebugVar.Var->printAsOperand(StrOS, MST);
445     }
446     {
447       raw_string_ostream StrOS(Object.DebugExpr.Value);
448       DebugVar.Expr->printAsOperand(StrOS, MST);
449     }
450     {
451       raw_string_ostream StrOS(Object.DebugLoc.Value);
452       DebugVar.Loc->printAsOperand(StrOS, MST);
453     }
454   }
455 }
456 
457 void MIRPrinter::convert(yaml::MachineFunction &MF,
458                          const MachineConstantPool &ConstantPool) {
459   unsigned ID = 0;
460   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
461     // TODO: Serialize target specific constant pool entries.
462     if (Constant.isMachineConstantPoolEntry())
463       llvm_unreachable("Can't print target specific constant pool entries yet");
464 
465     yaml::MachineConstantPoolValue YamlConstant;
466     std::string Str;
467     raw_string_ostream StrOS(Str);
468     Constant.Val.ConstVal->printAsOperand(StrOS);
469     YamlConstant.ID = ID++;
470     YamlConstant.Value = StrOS.str();
471     YamlConstant.Alignment = Constant.getAlignment();
472     MF.Constants.push_back(YamlConstant);
473   }
474 }
475 
476 void MIRPrinter::convert(ModuleSlotTracker &MST,
477                          yaml::MachineJumpTable &YamlJTI,
478                          const MachineJumpTableInfo &JTI) {
479   YamlJTI.Kind = JTI.getEntryKind();
480   unsigned ID = 0;
481   for (const auto &Table : JTI.getJumpTables()) {
482     std::string Str;
483     yaml::MachineJumpTable::Entry Entry;
484     Entry.ID = ID++;
485     for (const auto *MBB : Table.MBBs) {
486       raw_string_ostream StrOS(Str);
487       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
488           .printMBBReference(*MBB);
489       Entry.Blocks.push_back(StrOS.str());
490       Str.clear();
491     }
492     YamlJTI.Entries.push_back(Entry);
493   }
494 }
495 
496 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
497   const auto *TRI = MF.getSubtarget().getRegisterInfo();
498   unsigned I = 0;
499   for (const uint32_t *Mask : TRI->getRegMasks())
500     RegisterMaskIds.insert(std::make_pair(Mask, I++));
501 }
502 
503 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
504                            SmallVectorImpl<MachineBasicBlock*> &Result,
505                            bool &IsFallthrough) {
506   SmallPtrSet<MachineBasicBlock*,8> Seen;
507 
508   for (const MachineInstr &MI : MBB) {
509     if (MI.isPHI())
510       continue;
511     for (const MachineOperand &MO : MI.operands()) {
512       if (!MO.isMBB())
513         continue;
514       MachineBasicBlock *Succ = MO.getMBB();
515       auto RP = Seen.insert(Succ);
516       if (RP.second)
517         Result.push_back(Succ);
518     }
519   }
520   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
521   IsFallthrough = I == MBB.end() || !I->isBarrier();
522 }
523 
524 bool
525 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
526   if (MBB.succ_size() <= 1)
527     return true;
528   if (!MBB.hasSuccessorProbabilities())
529     return true;
530 
531   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
532                                               MBB.Probs.end());
533   BranchProbability::normalizeProbabilities(Normalized.begin(),
534                                             Normalized.end());
535   SmallVector<BranchProbability,8> Equal(Normalized.size());
536   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
537 
538   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
539 }
540 
541 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
542   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
543   bool GuessedFallthrough;
544   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
545   if (GuessedFallthrough) {
546     const MachineFunction &MF = *MBB.getParent();
547     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
548     if (NextI != MF.end()) {
549       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
550       if (!is_contained(GuessedSuccs, Next))
551         GuessedSuccs.push_back(Next);
552     }
553   }
554   if (GuessedSuccs.size() != MBB.succ_size())
555     return false;
556   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
557 }
558 
559 void MIPrinter::print(const MachineBasicBlock &MBB) {
560   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
561   OS << "bb." << MBB.getNumber();
562   bool HasAttributes = false;
563   if (const auto *BB = MBB.getBasicBlock()) {
564     if (BB->hasName()) {
565       OS << "." << BB->getName();
566     } else {
567       HasAttributes = true;
568       OS << " (";
569       int Slot = MST.getLocalSlot(BB);
570       if (Slot == -1)
571         OS << "<ir-block badref>";
572       else
573         OS << (Twine("%ir-block.") + Twine(Slot)).str();
574     }
575   }
576   if (MBB.hasAddressTaken()) {
577     OS << (HasAttributes ? ", " : " (");
578     OS << "address-taken";
579     HasAttributes = true;
580   }
581   if (MBB.isEHPad()) {
582     OS << (HasAttributes ? ", " : " (");
583     OS << "landing-pad";
584     HasAttributes = true;
585   }
586   if (MBB.getAlignment()) {
587     OS << (HasAttributes ? ", " : " (");
588     OS << "align " << MBB.getAlignment();
589     HasAttributes = true;
590   }
591   if (HasAttributes)
592     OS << ")";
593   OS << ":\n";
594 
595   bool HasLineAttributes = false;
596   // Print the successors
597   bool canPredictProbs = canPredictBranchProbabilities(MBB);
598   if (!MBB.succ_empty() && (!SimplifyMIR || !canPredictProbs ||
599                             !canPredictSuccessors(MBB))) {
600     OS.indent(2) << "successors: ";
601     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
602       if (I != MBB.succ_begin())
603         OS << ", ";
604       printMBBReference(**I);
605       if (!SimplifyMIR || !canPredictProbs)
606         OS << '('
607            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
608            << ')';
609     }
610     OS << "\n";
611     HasLineAttributes = true;
612   }
613 
614   // Print the live in registers.
615   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
616   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
617     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
618     OS.indent(2) << "liveins: ";
619     bool First = true;
620     for (const auto &LI : MBB.liveins()) {
621       if (!First)
622         OS << ", ";
623       First = false;
624       printReg(LI.PhysReg, OS, &TRI);
625       if (!LI.LaneMask.all())
626         OS << ":0x" << PrintLaneMask(LI.LaneMask);
627     }
628     OS << "\n";
629     HasLineAttributes = true;
630   }
631 
632   if (HasLineAttributes)
633     OS << "\n";
634   bool IsInBundle = false;
635   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
636     const MachineInstr &MI = *I;
637     if (IsInBundle && !MI.isInsideBundle()) {
638       OS.indent(2) << "}\n";
639       IsInBundle = false;
640     }
641     OS.indent(IsInBundle ? 4 : 2);
642     print(MI);
643     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
644       OS << " {";
645       IsInBundle = true;
646     }
647     OS << "\n";
648   }
649   if (IsInBundle)
650     OS.indent(2) << "}\n";
651 }
652 
653 /// Return true when an instruction has tied register that can't be determined
654 /// by the instruction's descriptor.
655 static bool hasComplexRegisterTies(const MachineInstr &MI) {
656   const MCInstrDesc &MCID = MI.getDesc();
657   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
658     const auto &Operand = MI.getOperand(I);
659     if (!Operand.isReg() || Operand.isDef())
660       // Ignore the defined registers as MCID marks only the uses as tied.
661       continue;
662     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
663     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
664     if (ExpectedTiedIdx != TiedIdx)
665       return true;
666   }
667   return false;
668 }
669 
670 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
671                           SmallBitVector &PrintedTypes,
672                           const MachineRegisterInfo &MRI) {
673   const MachineOperand &Op = MI.getOperand(OpIdx);
674   if (!Op.isReg())
675     return LLT{};
676 
677   if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
678     return MRI.getType(Op.getReg());
679 
680   auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
681   if (!OpInfo.isGenericType())
682     return MRI.getType(Op.getReg());
683 
684   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
685     return LLT{};
686 
687   PrintedTypes.set(OpInfo.getGenericTypeIndex());
688   return MRI.getType(Op.getReg());
689 }
690 
691 void MIPrinter::print(const MachineInstr &MI) {
692   const auto *MF = MI.getParent()->getParent();
693   const auto &MRI = MF->getRegInfo();
694   const auto &SubTarget = MF->getSubtarget();
695   const auto *TRI = SubTarget.getRegisterInfo();
696   assert(TRI && "Expected target register info");
697   const auto *TII = SubTarget.getInstrInfo();
698   assert(TII && "Expected target instruction info");
699   if (MI.isCFIInstruction())
700     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
701 
702   SmallBitVector PrintedTypes(8);
703   bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
704   unsigned I = 0, E = MI.getNumOperands();
705   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
706          !MI.getOperand(I).isImplicit();
707        ++I) {
708     if (I)
709       OS << ", ";
710     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
711           getTypeToPrint(MI, I, PrintedTypes, MRI),
712           /*IsDef=*/true);
713   }
714 
715   if (I)
716     OS << " = ";
717   if (MI.getFlag(MachineInstr::FrameSetup))
718     OS << "frame-setup ";
719   OS << TII->getName(MI.getOpcode());
720   if (I < E)
721     OS << ' ';
722 
723   bool NeedComma = false;
724   for (; I < E; ++I) {
725     if (NeedComma)
726       OS << ", ";
727     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
728           getTypeToPrint(MI, I, PrintedTypes, MRI));
729     NeedComma = true;
730   }
731 
732   if (MI.getDebugLoc()) {
733     if (NeedComma)
734       OS << ',';
735     OS << " debug-location ";
736     MI.getDebugLoc()->printAsOperand(OS, MST);
737   }
738 
739   if (!MI.memoperands_empty()) {
740     OS << " :: ";
741     const LLVMContext &Context = MF->getFunction()->getContext();
742     bool NeedComma = false;
743     for (const auto *Op : MI.memoperands()) {
744       if (NeedComma)
745         OS << ", ";
746       print(Context, *TII, *Op);
747       NeedComma = true;
748     }
749   }
750 }
751 
752 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
753   OS << "%bb." << MBB.getNumber();
754   if (const auto *BB = MBB.getBasicBlock()) {
755     if (BB->hasName())
756       OS << '.' << BB->getName();
757   }
758 }
759 
760 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
761   if (Slot == -1)
762     OS << "<badref>";
763   else
764     OS << Slot;
765 }
766 
767 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
768   OS << "%ir-block.";
769   if (BB.hasName()) {
770     printLLVMNameWithoutPrefix(OS, BB.getName());
771     return;
772   }
773   const Function *F = BB.getParent();
774   int Slot;
775   if (F == MST.getCurrentFunction()) {
776     Slot = MST.getLocalSlot(&BB);
777   } else {
778     ModuleSlotTracker CustomMST(F->getParent(),
779                                 /*ShouldInitializeAllMetadata=*/false);
780     CustomMST.incorporateFunction(*F);
781     Slot = CustomMST.getLocalSlot(&BB);
782   }
783   printIRSlotNumber(OS, Slot);
784 }
785 
786 void MIPrinter::printIRValueReference(const Value &V) {
787   if (isa<GlobalValue>(V)) {
788     V.printAsOperand(OS, /*PrintType=*/false, MST);
789     return;
790   }
791   if (isa<Constant>(V)) {
792     // Machine memory operands can load/store to/from constant value pointers.
793     OS << '`';
794     V.printAsOperand(OS, /*PrintType=*/true, MST);
795     OS << '`';
796     return;
797   }
798   OS << "%ir.";
799   if (V.hasName()) {
800     printLLVMNameWithoutPrefix(OS, V.getName());
801     return;
802   }
803   printIRSlotNumber(OS, MST.getLocalSlot(&V));
804 }
805 
806 void MIPrinter::printStackObjectReference(int FrameIndex) {
807   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
808   assert(ObjectInfo != StackObjectOperandMapping.end() &&
809          "Invalid frame index");
810   const FrameIndexOperand &Operand = ObjectInfo->second;
811   if (Operand.IsFixed) {
812     OS << "%fixed-stack." << Operand.ID;
813     return;
814   }
815   OS << "%stack." << Operand.ID;
816   if (!Operand.Name.empty())
817     OS << '.' << Operand.Name;
818 }
819 
820 void MIPrinter::printOffset(int64_t Offset) {
821   if (Offset == 0)
822     return;
823   if (Offset < 0) {
824     OS << " - " << -Offset;
825     return;
826   }
827   OS << " + " << Offset;
828 }
829 
830 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
831   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
832   for (const auto &I : Flags) {
833     if (I.first == TF) {
834       return I.second;
835     }
836   }
837   return nullptr;
838 }
839 
840 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
841   if (!Op.getTargetFlags())
842     return;
843   const auto *TII =
844       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
845   assert(TII && "expected instruction info");
846   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
847   OS << "target-flags(";
848   const bool HasDirectFlags = Flags.first;
849   const bool HasBitmaskFlags = Flags.second;
850   if (!HasDirectFlags && !HasBitmaskFlags) {
851     OS << "<unknown>) ";
852     return;
853   }
854   if (HasDirectFlags) {
855     if (const auto *Name = getTargetFlagName(TII, Flags.first))
856       OS << Name;
857     else
858       OS << "<unknown target flag>";
859   }
860   if (!HasBitmaskFlags) {
861     OS << ") ";
862     return;
863   }
864   bool IsCommaNeeded = HasDirectFlags;
865   unsigned BitMask = Flags.second;
866   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
867   for (const auto &Mask : BitMasks) {
868     // Check if the flag's bitmask has the bits of the current mask set.
869     if ((BitMask & Mask.first) == Mask.first) {
870       if (IsCommaNeeded)
871         OS << ", ";
872       IsCommaNeeded = true;
873       OS << Mask.second;
874       // Clear the bits which were serialized from the flag's bitmask.
875       BitMask &= ~(Mask.first);
876     }
877   }
878   if (BitMask) {
879     // When the resulting flag's bitmask isn't zero, we know that we didn't
880     // serialize all of the bit flags.
881     if (IsCommaNeeded)
882       OS << ", ";
883     OS << "<unknown bitmask target flag>";
884   }
885   OS << ") ";
886 }
887 
888 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
889   const auto *TII = MF.getSubtarget().getInstrInfo();
890   assert(TII && "expected instruction info");
891   auto Indices = TII->getSerializableTargetIndices();
892   for (const auto &I : Indices) {
893     if (I.first == Index) {
894       return I.second;
895     }
896   }
897   return nullptr;
898 }
899 
900 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
901                       unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
902                       bool IsDef) {
903   printTargetFlags(Op);
904   switch (Op.getType()) {
905   case MachineOperand::MO_Register:
906     if (Op.isImplicit())
907       OS << (Op.isDef() ? "implicit-def " : "implicit ");
908     else if (!IsDef && Op.isDef())
909       // Print the 'def' flag only when the operand is defined after '='.
910       OS << "def ";
911     if (Op.isInternalRead())
912       OS << "internal ";
913     if (Op.isDead())
914       OS << "dead ";
915     if (Op.isKill())
916       OS << "killed ";
917     if (Op.isUndef())
918       OS << "undef ";
919     if (Op.isEarlyClobber())
920       OS << "early-clobber ";
921     if (Op.isDebug())
922       OS << "debug-use ";
923     printReg(Op.getReg(), OS, TRI);
924     // Print the sub register.
925     if (Op.getSubReg() != 0)
926       OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
927     if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
928       OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
929     if (TypeToPrint.isValid())
930       OS << '(' << TypeToPrint << ')';
931     break;
932   case MachineOperand::MO_Immediate:
933     OS << Op.getImm();
934     break;
935   case MachineOperand::MO_CImmediate:
936     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
937     break;
938   case MachineOperand::MO_FPImmediate:
939     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
940     break;
941   case MachineOperand::MO_MachineBasicBlock:
942     printMBBReference(*Op.getMBB());
943     break;
944   case MachineOperand::MO_FrameIndex:
945     printStackObjectReference(Op.getIndex());
946     break;
947   case MachineOperand::MO_ConstantPoolIndex:
948     OS << "%const." << Op.getIndex();
949     printOffset(Op.getOffset());
950     break;
951   case MachineOperand::MO_TargetIndex:
952     OS << "target-index(";
953     if (const auto *Name = getTargetIndexName(
954             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
955       OS << Name;
956     else
957       OS << "<unknown>";
958     OS << ')';
959     printOffset(Op.getOffset());
960     break;
961   case MachineOperand::MO_JumpTableIndex:
962     OS << "%jump-table." << Op.getIndex();
963     break;
964   case MachineOperand::MO_ExternalSymbol: {
965     StringRef Name = Op.getSymbolName();
966     OS << '$';
967     if (Name.empty()) {
968       OS << "\"\"";
969     } else {
970       printLLVMNameWithoutPrefix(OS, Name);
971     }
972     printOffset(Op.getOffset());
973     break;
974   }
975   case MachineOperand::MO_GlobalAddress:
976     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
977     printOffset(Op.getOffset());
978     break;
979   case MachineOperand::MO_BlockAddress:
980     OS << "blockaddress(";
981     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
982                                                         MST);
983     OS << ", ";
984     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
985     OS << ')';
986     printOffset(Op.getOffset());
987     break;
988   case MachineOperand::MO_RegisterMask: {
989     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
990     if (RegMaskInfo != RegisterMaskIds.end())
991       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
992     else
993       printCustomRegMask(Op.getRegMask(), OS, TRI);
994     break;
995   }
996   case MachineOperand::MO_RegisterLiveOut: {
997     const uint32_t *RegMask = Op.getRegLiveOut();
998     OS << "liveout(";
999     bool IsCommaNeeded = false;
1000     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
1001       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
1002         if (IsCommaNeeded)
1003           OS << ", ";
1004         printReg(Reg, OS, TRI);
1005         IsCommaNeeded = true;
1006       }
1007     }
1008     OS << ")";
1009     break;
1010   }
1011   case MachineOperand::MO_Metadata:
1012     Op.getMetadata()->printAsOperand(OS, MST);
1013     break;
1014   case MachineOperand::MO_MCSymbol:
1015     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
1016     break;
1017   case MachineOperand::MO_CFIIndex: {
1018     const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
1019     print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
1020     break;
1021   }
1022   case MachineOperand::MO_IntrinsicID: {
1023     Intrinsic::ID ID = Op.getIntrinsicID();
1024     if (ID < Intrinsic::num_intrinsics)
1025       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
1026     else {
1027       const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
1028       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
1029       OS << "intrinsic(@" << TII->getName(ID) << ')';
1030     }
1031     break;
1032   }
1033   case MachineOperand::MO_Predicate: {
1034     auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
1035     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
1036        << CmpInst::getPredicateName(Pred) << ')';
1037     break;
1038   }
1039   }
1040 }
1041 
1042 static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
1043                                         unsigned TMMOFlag) {
1044   auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
1045   for (const auto &I : Flags) {
1046     if (I.first == TMMOFlag) {
1047       return I.second;
1048     }
1049   }
1050   return nullptr;
1051 }
1052 
1053 void MIPrinter::print(const LLVMContext &Context, const TargetInstrInfo &TII,
1054                       const MachineMemOperand &Op) {
1055   OS << '(';
1056   if (Op.isVolatile())
1057     OS << "volatile ";
1058   if (Op.isNonTemporal())
1059     OS << "non-temporal ";
1060   if (Op.isDereferenceable())
1061     OS << "dereferenceable ";
1062   if (Op.isInvariant())
1063     OS << "invariant ";
1064   if (Op.getFlags() & MachineMemOperand::MOTargetFlag1)
1065     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag1)
1066        << "\" ";
1067   if (Op.getFlags() & MachineMemOperand::MOTargetFlag2)
1068     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag2)
1069        << "\" ";
1070   if (Op.getFlags() & MachineMemOperand::MOTargetFlag3)
1071     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag3)
1072        << "\" ";
1073   if (Op.isLoad())
1074     OS << "load ";
1075   else {
1076     assert(Op.isStore() && "Non load machine operand must be a store");
1077     OS << "store ";
1078   }
1079 
1080   printSyncScope(Context, Op.getSyncScopeID());
1081 
1082   if (Op.getOrdering() != AtomicOrdering::NotAtomic)
1083     OS << toIRString(Op.getOrdering()) << ' ';
1084   if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
1085     OS << toIRString(Op.getFailureOrdering()) << ' ';
1086 
1087   OS << Op.getSize();
1088   if (const Value *Val = Op.getValue()) {
1089     OS << (Op.isLoad() ? " from " : " into ");
1090     printIRValueReference(*Val);
1091   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
1092     OS << (Op.isLoad() ? " from " : " into ");
1093     assert(PVal && "Expected a pseudo source value");
1094     switch (PVal->kind()) {
1095     case PseudoSourceValue::Stack:
1096       OS << "stack";
1097       break;
1098     case PseudoSourceValue::GOT:
1099       OS << "got";
1100       break;
1101     case PseudoSourceValue::JumpTable:
1102       OS << "jump-table";
1103       break;
1104     case PseudoSourceValue::ConstantPool:
1105       OS << "constant-pool";
1106       break;
1107     case PseudoSourceValue::FixedStack:
1108       printStackObjectReference(
1109           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
1110       break;
1111     case PseudoSourceValue::GlobalValueCallEntry:
1112       OS << "call-entry ";
1113       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1114           OS, /*PrintType=*/false, MST);
1115       break;
1116     case PseudoSourceValue::ExternalSymbolCallEntry:
1117       OS << "call-entry $";
1118       printLLVMNameWithoutPrefix(
1119           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1120       break;
1121     case PseudoSourceValue::TargetCustom:
1122       llvm_unreachable("TargetCustom pseudo source values are not supported");
1123       break;
1124     }
1125   }
1126   printOffset(Op.getOffset());
1127   if (Op.getBaseAlignment() != Op.getSize())
1128     OS << ", align " << Op.getBaseAlignment();
1129   auto AAInfo = Op.getAAInfo();
1130   if (AAInfo.TBAA) {
1131     OS << ", !tbaa ";
1132     AAInfo.TBAA->printAsOperand(OS, MST);
1133   }
1134   if (AAInfo.Scope) {
1135     OS << ", !alias.scope ";
1136     AAInfo.Scope->printAsOperand(OS, MST);
1137   }
1138   if (AAInfo.NoAlias) {
1139     OS << ", !noalias ";
1140     AAInfo.NoAlias->printAsOperand(OS, MST);
1141   }
1142   if (Op.getRanges()) {
1143     OS << ", !range ";
1144     Op.getRanges()->printAsOperand(OS, MST);
1145   }
1146   OS << ')';
1147 }
1148 
1149 void MIPrinter::printSyncScope(const LLVMContext &Context, SyncScope::ID SSID) {
1150   switch (SSID) {
1151   case SyncScope::System: {
1152     break;
1153   }
1154   default: {
1155     if (SSNs.empty())
1156       Context.getSyncScopeNames(SSNs);
1157 
1158     OS << "syncscope(\"";
1159     PrintEscapedString(SSNs[SSID], OS);
1160     OS << "\") ";
1161     break;
1162   }
1163   }
1164 }
1165 
1166 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1167                              const TargetRegisterInfo *TRI) {
1168   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1169   if (Reg == -1) {
1170     OS << "<badreg>";
1171     return;
1172   }
1173   printReg(Reg, OS, TRI);
1174 }
1175 
1176 void MIPrinter::print(const MCCFIInstruction &CFI,
1177                       const TargetRegisterInfo *TRI) {
1178   switch (CFI.getOperation()) {
1179   case MCCFIInstruction::OpSameValue:
1180     OS << "same_value ";
1181     if (CFI.getLabel())
1182       OS << "<mcsymbol> ";
1183     printCFIRegister(CFI.getRegister(), OS, TRI);
1184     break;
1185   case MCCFIInstruction::OpOffset:
1186     OS << "offset ";
1187     if (CFI.getLabel())
1188       OS << "<mcsymbol> ";
1189     printCFIRegister(CFI.getRegister(), OS, TRI);
1190     OS << ", " << CFI.getOffset();
1191     break;
1192   case MCCFIInstruction::OpDefCfaRegister:
1193     OS << "def_cfa_register ";
1194     if (CFI.getLabel())
1195       OS << "<mcsymbol> ";
1196     printCFIRegister(CFI.getRegister(), OS, TRI);
1197     break;
1198   case MCCFIInstruction::OpDefCfaOffset:
1199     OS << "def_cfa_offset ";
1200     if (CFI.getLabel())
1201       OS << "<mcsymbol> ";
1202     OS << CFI.getOffset();
1203     break;
1204   case MCCFIInstruction::OpDefCfa:
1205     OS << "def_cfa ";
1206     if (CFI.getLabel())
1207       OS << "<mcsymbol> ";
1208     printCFIRegister(CFI.getRegister(), OS, TRI);
1209     OS << ", " << CFI.getOffset();
1210     break;
1211   default:
1212     // TODO: Print the other CFI Operations.
1213     OS << "<unserializable cfi operation>";
1214     break;
1215   }
1216 }
1217 
1218 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1219   yaml::Output Out(OS);
1220   Out << const_cast<Module &>(M);
1221 }
1222 
1223 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1224   MIRPrinter Printer(OS);
1225   Printer.print(MF);
1226 }
1227