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