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