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