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