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