1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that prints out the LLVM IR and machine
10 // functions using the MIR serialization format.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MIRPrinter.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/MIRYamlMapping.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/PseudoSourceValue.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/CodeGen/TargetFrameLowering.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/IRPrintingPasses.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/ModuleSlotTracker.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/MC/LaneBitmask.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCSymbol.h"
56 #include "llvm/Support/AtomicOrdering.h"
57 #include "llvm/Support/BranchProbability.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/Format.h"
62 #include "llvm/Support/LowLevelTypeImpl.h"
63 #include "llvm/Support/YAMLTraits.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetIntrinsicInfo.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cinttypes>
70 #include <cstdint>
71 #include <iterator>
72 #include <string>
73 #include <utility>
74 #include <vector>
75 
76 using namespace llvm;
77 
78 static cl::opt<bool> SimplifyMIR(
79     "simplify-mir", cl::Hidden,
80     cl::desc("Leave out unnecessary information when printing MIR"));
81 
82 namespace {
83 
84 /// This structure describes how to print out stack object references.
85 struct FrameIndexOperand {
86   std::string Name;
87   unsigned ID;
88   bool IsFixed;
89 
90   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
91       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
92 
93   /// Return an ordinary stack object reference.
94   static FrameIndexOperand create(StringRef Name, unsigned ID) {
95     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
96   }
97 
98   /// Return a fixed stack object reference.
99   static FrameIndexOperand createFixed(unsigned ID) {
100     return FrameIndexOperand("", ID, /*IsFixed=*/true);
101   }
102 };
103 
104 } // end anonymous namespace
105 
106 namespace llvm {
107 
108 /// This class prints out the machine functions using the MIR serialization
109 /// format.
110 class MIRPrinter {
111   raw_ostream &OS;
112   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
113   /// Maps from stack object indices to operand indices which will be used when
114   /// printing frame index machine operands.
115   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
116 
117 public:
118   MIRPrinter(raw_ostream &OS) : OS(OS) {}
119 
120   void print(const MachineFunction &MF);
121 
122   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
123                const TargetRegisterInfo *TRI);
124   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
125                const MachineFrameInfo &MFI);
126   void convert(yaml::MachineFunction &MF,
127                const MachineConstantPool &ConstantPool);
128   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
129                const MachineJumpTableInfo &JTI);
130   void convertStackObjects(yaml::MachineFunction &YMF,
131                            const MachineFunction &MF, ModuleSlotTracker &MST);
132   void convertCallSiteObjects(yaml::MachineFunction &YMF,
133                               const MachineFunction &MF,
134                               ModuleSlotTracker &MST);
135 
136 private:
137   void initRegisterMaskIds(const MachineFunction &MF);
138 };
139 
140 /// This class prints out the machine instructions using the MIR serialization
141 /// format.
142 class MIPrinter {
143   raw_ostream &OS;
144   ModuleSlotTracker &MST;
145   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
146   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
147   /// Synchronization scope names registered with LLVMContext.
148   SmallVector<StringRef, 8> SSNs;
149 
150   bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
151   bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
152 
153 public:
154   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
155             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
156             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
157       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
158         StackObjectOperandMapping(StackObjectOperandMapping) {}
159 
160   void print(const MachineBasicBlock &MBB);
161 
162   void print(const MachineInstr &MI);
163   void printStackObjectReference(int FrameIndex);
164   void print(const MachineInstr &MI, unsigned OpIdx,
165              const TargetRegisterInfo *TRI, const TargetInstrInfo *TII,
166              bool ShouldPrintRegisterTies, LLT TypeToPrint,
167              bool PrintDef = true);
168 };
169 
170 } // end namespace llvm
171 
172 namespace llvm {
173 namespace yaml {
174 
175 /// This struct serializes the LLVM IR module.
176 template <> struct BlockScalarTraits<Module> {
177   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
178     Mod.print(OS, nullptr);
179   }
180 
181   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
182     llvm_unreachable("LLVM Module is supposed to be parsed separately");
183     return "";
184   }
185 };
186 
187 } // end namespace yaml
188 } // end namespace llvm
189 
190 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
191                         const TargetRegisterInfo *TRI) {
192   raw_string_ostream OS(Dest.Value);
193   OS << printReg(Reg, TRI);
194 }
195 
196 void MIRPrinter::print(const MachineFunction &MF) {
197   initRegisterMaskIds(MF);
198 
199   yaml::MachineFunction YamlMF;
200   YamlMF.Name = MF.getName();
201   YamlMF.Alignment = MF.getAlignment().value();
202   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
203   YamlMF.HasWinCFI = MF.hasWinCFI();
204 
205   YamlMF.Legalized = MF.getProperties().hasProperty(
206       MachineFunctionProperties::Property::Legalized);
207   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
208       MachineFunctionProperties::Property::RegBankSelected);
209   YamlMF.Selected = MF.getProperties().hasProperty(
210       MachineFunctionProperties::Property::Selected);
211   YamlMF.FailedISel = MF.getProperties().hasProperty(
212       MachineFunctionProperties::Property::FailedISel);
213 
214   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
215   ModuleSlotTracker MST(MF.getFunction().getParent());
216   MST.incorporateFunction(MF.getFunction());
217   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
218   convertStackObjects(YamlMF, MF, MST);
219   convertCallSiteObjects(YamlMF, MF, MST);
220   if (const auto *ConstantPool = MF.getConstantPool())
221     convert(YamlMF, *ConstantPool);
222   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
223     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
224 
225   const TargetMachine &TM = MF.getTarget();
226   YamlMF.MachineFuncInfo =
227       std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
228 
229   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
230   bool IsNewlineNeeded = false;
231   for (const auto &MBB : MF) {
232     if (IsNewlineNeeded)
233       StrOS << "\n";
234     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
235         .print(MBB);
236     IsNewlineNeeded = true;
237   }
238   StrOS.flush();
239   yaml::Output Out(OS);
240   if (!SimplifyMIR)
241       Out.setWriteDefaultValues(true);
242   Out << YamlMF;
243 }
244 
245 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
246                                const TargetRegisterInfo *TRI) {
247   assert(RegMask && "Can't print an empty register mask");
248   OS << StringRef("CustomRegMask(");
249 
250   bool IsRegInRegMaskFound = false;
251   for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
252     // Check whether the register is asserted in regmask.
253     if (RegMask[I / 32] & (1u << (I % 32))) {
254       if (IsRegInRegMaskFound)
255         OS << ',';
256       OS << printReg(I, TRI);
257       IsRegInRegMaskFound = true;
258     }
259   }
260 
261   OS << ')';
262 }
263 
264 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
265                                 const MachineRegisterInfo &RegInfo,
266                                 const TargetRegisterInfo *TRI) {
267   raw_string_ostream OS(Dest.Value);
268   OS << printRegClassOrBank(Reg, RegInfo, TRI);
269 }
270 
271 template <typename T>
272 static void
273 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
274                         T &Object, ModuleSlotTracker &MST) {
275   std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
276                                         &Object.DebugExpr.Value,
277                                         &Object.DebugLoc.Value}};
278   std::array<const Metadata *, 3> Metas{{DebugVar.Var,
279                                         DebugVar.Expr,
280                                         DebugVar.Loc}};
281   for (unsigned i = 0; i < 3; ++i) {
282     raw_string_ostream StrOS(*Outputs[i]);
283     Metas[i]->printAsOperand(StrOS, MST);
284   }
285 }
286 
287 void MIRPrinter::convert(yaml::MachineFunction &MF,
288                          const MachineRegisterInfo &RegInfo,
289                          const TargetRegisterInfo *TRI) {
290   MF.TracksRegLiveness = RegInfo.tracksLiveness();
291 
292   // Print the virtual register definitions.
293   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
294     unsigned Reg = Register::index2VirtReg(I);
295     yaml::VirtualRegisterDefinition VReg;
296     VReg.ID = I;
297     if (RegInfo.getVRegName(Reg) != "")
298       continue;
299     ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
300     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
301     if (PreferredReg)
302       printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
303     MF.VirtualRegisters.push_back(VReg);
304   }
305 
306   // Print the live ins.
307   for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
308     yaml::MachineFunctionLiveIn LiveIn;
309     printRegMIR(LI.first, LiveIn.Register, TRI);
310     if (LI.second)
311       printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
312     MF.LiveIns.push_back(LiveIn);
313   }
314 
315   // Prints the callee saved registers.
316   if (RegInfo.isUpdatedCSRsInitialized()) {
317     const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
318     std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
319     for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
320       yaml::FlowStringValue Reg;
321       printRegMIR(*I, Reg, TRI);
322       CalleeSavedRegisters.push_back(Reg);
323     }
324     MF.CalleeSavedRegisters = CalleeSavedRegisters;
325   }
326 }
327 
328 void MIRPrinter::convert(ModuleSlotTracker &MST,
329                          yaml::MachineFrameInfo &YamlMFI,
330                          const MachineFrameInfo &MFI) {
331   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
332   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
333   YamlMFI.HasStackMap = MFI.hasStackMap();
334   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
335   YamlMFI.StackSize = MFI.getStackSize();
336   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
337   YamlMFI.MaxAlignment = MFI.getMaxAlign().value();
338   YamlMFI.AdjustsStack = MFI.adjustsStack();
339   YamlMFI.HasCalls = MFI.hasCalls();
340   YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
341     ? MFI.getMaxCallFrameSize() : ~0u;
342   YamlMFI.CVBytesOfCalleeSavedRegisters =
343       MFI.getCVBytesOfCalleeSavedRegisters();
344   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
345   YamlMFI.HasVAStart = MFI.hasVAStart();
346   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
347   YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
348   if (MFI.getSavePoint()) {
349     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
350     StrOS << printMBBReference(*MFI.getSavePoint());
351   }
352   if (MFI.getRestorePoint()) {
353     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
354     StrOS << printMBBReference(*MFI.getRestorePoint());
355   }
356 }
357 
358 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
359                                      const MachineFunction &MF,
360                                      ModuleSlotTracker &MST) {
361   const MachineFrameInfo &MFI = MF.getFrameInfo();
362   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
363   // Process fixed stack objects.
364   unsigned ID = 0;
365   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I, ++ID) {
366     if (MFI.isDeadObjectIndex(I))
367       continue;
368 
369     yaml::FixedMachineStackObject YamlObject;
370     YamlObject.ID = ID;
371     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
372                           ? yaml::FixedMachineStackObject::SpillSlot
373                           : yaml::FixedMachineStackObject::DefaultType;
374     YamlObject.Offset = MFI.getObjectOffset(I);
375     YamlObject.Size = MFI.getObjectSize(I);
376     YamlObject.Alignment = MFI.getObjectAlignment(I);
377     YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
378     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
379     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
380     YMF.FixedStackObjects.push_back(YamlObject);
381     StackObjectOperandMapping.insert(
382         std::make_pair(I, FrameIndexOperand::createFixed(ID)));
383   }
384 
385   // Process ordinary stack objects.
386   ID = 0;
387   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I, ++ID) {
388     if (MFI.isDeadObjectIndex(I))
389       continue;
390 
391     yaml::MachineStackObject YamlObject;
392     YamlObject.ID = ID;
393     if (const auto *Alloca = MFI.getObjectAllocation(I))
394       YamlObject.Name.Value = std::string(
395           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>");
396     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
397                           ? yaml::MachineStackObject::SpillSlot
398                           : MFI.isVariableSizedObjectIndex(I)
399                                 ? yaml::MachineStackObject::VariableSized
400                                 : yaml::MachineStackObject::DefaultType;
401     YamlObject.Offset = MFI.getObjectOffset(I);
402     YamlObject.Size = MFI.getObjectSize(I);
403     YamlObject.Alignment = MFI.getObjectAlignment(I);
404     YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
405 
406     YMF.StackObjects.push_back(YamlObject);
407     StackObjectOperandMapping.insert(std::make_pair(
408         I, FrameIndexOperand::create(YamlObject.Name.Value, ID)));
409   }
410 
411   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
412     if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(CSInfo.getFrameIdx()))
413       continue;
414 
415     yaml::StringValue Reg;
416     printRegMIR(CSInfo.getReg(), Reg, TRI);
417     if (!CSInfo.isSpilledToReg()) {
418       auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
419       assert(StackObjectInfo != StackObjectOperandMapping.end() &&
420              "Invalid stack object index");
421       const FrameIndexOperand &StackObject = StackObjectInfo->second;
422       if (StackObject.IsFixed) {
423         YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
424         YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
425           CSInfo.isRestored();
426       } else {
427         YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
428         YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
429           CSInfo.isRestored();
430       }
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     if (StackObject.IsFixed) {
459       auto &Object = YMF.FixedStackObjects[StackObject.ID];
460       printStackObjectDbgInfo(DebugVar, Object, MST);
461     } else {
462       auto &Object = YMF.StackObjects[StackObject.ID];
463       printStackObjectDbgInfo(DebugVar, Object, MST);
464     }
465   }
466 }
467 
468 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF,
469                                         const MachineFunction &MF,
470                                         ModuleSlotTracker &MST) {
471   const auto *TRI = MF.getSubtarget().getRegisterInfo();
472   for (auto CSInfo : MF.getCallSitesInfo()) {
473     yaml::CallSiteInfo YmlCS;
474     yaml::CallSiteInfo::MachineInstrLoc CallLocation;
475 
476     // Prepare instruction position.
477     MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator();
478     CallLocation.BlockNum = CallI->getParent()->getNumber();
479     // Get call instruction offset from the beginning of block.
480     CallLocation.Offset =
481         std::distance(CallI->getParent()->instr_begin(), CallI);
482     YmlCS.CallLocation = CallLocation;
483     // Construct call arguments and theirs forwarding register info.
484     for (auto ArgReg : CSInfo.second) {
485       yaml::CallSiteInfo::ArgRegPair YmlArgReg;
486       YmlArgReg.ArgNo = ArgReg.ArgNo;
487       printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI);
488       YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg);
489     }
490     YMF.CallSitesInfo.push_back(YmlCS);
491   }
492 
493   // Sort call info by position of call instructions.
494   llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(),
495              [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) {
496                if (A.CallLocation.BlockNum == B.CallLocation.BlockNum)
497                  return A.CallLocation.Offset < B.CallLocation.Offset;
498                return A.CallLocation.BlockNum < B.CallLocation.BlockNum;
499              });
500 }
501 
502 void MIRPrinter::convert(yaml::MachineFunction &MF,
503                          const MachineConstantPool &ConstantPool) {
504   unsigned ID = 0;
505   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
506     std::string Str;
507     raw_string_ostream StrOS(Str);
508     if (Constant.isMachineConstantPoolEntry()) {
509       Constant.Val.MachineCPVal->print(StrOS);
510     } else {
511       Constant.Val.ConstVal->printAsOperand(StrOS);
512     }
513 
514     yaml::MachineConstantPoolValue YamlConstant;
515     YamlConstant.ID = ID++;
516     YamlConstant.Value = StrOS.str();
517     YamlConstant.Alignment = Constant.getAlignment();
518     YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
519 
520     MF.Constants.push_back(YamlConstant);
521   }
522 }
523 
524 void MIRPrinter::convert(ModuleSlotTracker &MST,
525                          yaml::MachineJumpTable &YamlJTI,
526                          const MachineJumpTableInfo &JTI) {
527   YamlJTI.Kind = JTI.getEntryKind();
528   unsigned ID = 0;
529   for (const auto &Table : JTI.getJumpTables()) {
530     std::string Str;
531     yaml::MachineJumpTable::Entry Entry;
532     Entry.ID = ID++;
533     for (const auto *MBB : Table.MBBs) {
534       raw_string_ostream StrOS(Str);
535       StrOS << printMBBReference(*MBB);
536       Entry.Blocks.push_back(StrOS.str());
537       Str.clear();
538     }
539     YamlJTI.Entries.push_back(Entry);
540   }
541 }
542 
543 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
544   const auto *TRI = MF.getSubtarget().getRegisterInfo();
545   unsigned I = 0;
546   for (const uint32_t *Mask : TRI->getRegMasks())
547     RegisterMaskIds.insert(std::make_pair(Mask, I++));
548 }
549 
550 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
551                            SmallVectorImpl<MachineBasicBlock*> &Result,
552                            bool &IsFallthrough) {
553   SmallPtrSet<MachineBasicBlock*,8> Seen;
554 
555   for (const MachineInstr &MI : MBB) {
556     if (MI.isPHI())
557       continue;
558     for (const MachineOperand &MO : MI.operands()) {
559       if (!MO.isMBB())
560         continue;
561       MachineBasicBlock *Succ = MO.getMBB();
562       auto RP = Seen.insert(Succ);
563       if (RP.second)
564         Result.push_back(Succ);
565     }
566   }
567   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
568   IsFallthrough = I == MBB.end() || !I->isBarrier();
569 }
570 
571 bool
572 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
573   if (MBB.succ_size() <= 1)
574     return true;
575   if (!MBB.hasSuccessorProbabilities())
576     return true;
577 
578   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
579                                               MBB.Probs.end());
580   BranchProbability::normalizeProbabilities(Normalized.begin(),
581                                             Normalized.end());
582   SmallVector<BranchProbability,8> Equal(Normalized.size());
583   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
584 
585   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
586 }
587 
588 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
589   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
590   bool GuessedFallthrough;
591   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
592   if (GuessedFallthrough) {
593     const MachineFunction &MF = *MBB.getParent();
594     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
595     if (NextI != MF.end()) {
596       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
597       if (!is_contained(GuessedSuccs, Next))
598         GuessedSuccs.push_back(Next);
599     }
600   }
601   if (GuessedSuccs.size() != MBB.succ_size())
602     return false;
603   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
604 }
605 
606 void MIPrinter::print(const MachineBasicBlock &MBB) {
607   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
608   OS << "bb." << MBB.getNumber();
609   bool HasAttributes = false;
610   if (const auto *BB = MBB.getBasicBlock()) {
611     if (BB->hasName()) {
612       OS << "." << BB->getName();
613     } else {
614       HasAttributes = true;
615       OS << " (";
616       int Slot = MST.getLocalSlot(BB);
617       if (Slot == -1)
618         OS << "<ir-block badref>";
619       else
620         OS << (Twine("%ir-block.") + Twine(Slot)).str();
621     }
622   }
623   if (MBB.hasAddressTaken()) {
624     OS << (HasAttributes ? ", " : " (");
625     OS << "address-taken";
626     HasAttributes = true;
627   }
628   if (MBB.isEHPad()) {
629     OS << (HasAttributes ? ", " : " (");
630     OS << "landing-pad";
631     HasAttributes = true;
632   }
633   if (MBB.isEHFuncletEntry()) {
634     OS << (HasAttributes ? ", " : " (");
635     OS << "ehfunclet-entry";
636     HasAttributes = true;
637   }
638   if (MBB.getAlignment() != Align(1)) {
639     OS << (HasAttributes ? ", " : " (");
640     OS << "align " << MBB.getAlignment().value();
641     HasAttributes = true;
642   }
643   if (MBB.getSectionType() != MBBS_None) {
644     OS << (HasAttributes ? ", " : " (");
645     OS << "bbsections ";
646     switch (MBB.getSectionType()) {
647     case MBBS_Entry:
648       OS << "Entry";
649       break;
650     case MBBS_Exception:
651       OS << "Exception";
652       break;
653     case MBBS_Cold:
654       OS << "Cold";
655       break;
656     case MBBS_Unique:
657       OS << "Unique";
658       break;
659     default:
660       llvm_unreachable("No such section type");
661     }
662     HasAttributes = true;
663   }
664   if (HasAttributes)
665     OS << ")";
666   OS << ":\n";
667 
668   bool HasLineAttributes = false;
669   // Print the successors
670   bool canPredictProbs = canPredictBranchProbabilities(MBB);
671   // Even if the list of successors is empty, if we cannot guess it,
672   // we need to print it to tell the parser that the list is empty.
673   // This is needed, because MI model unreachable as empty blocks
674   // with an empty successor list. If the parser would see that
675   // without the successor list, it would guess the code would
676   // fallthrough.
677   if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
678       !canPredictSuccessors(MBB)) {
679     OS.indent(2) << "successors: ";
680     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
681       if (I != MBB.succ_begin())
682         OS << ", ";
683       OS << printMBBReference(**I);
684       if (!SimplifyMIR || !canPredictProbs)
685         OS << '('
686            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
687            << ')';
688     }
689     OS << "\n";
690     HasLineAttributes = true;
691   }
692 
693   // Print the live in registers.
694   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
695   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
696     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
697     OS.indent(2) << "liveins: ";
698     bool First = true;
699     for (const auto &LI : MBB.liveins()) {
700       if (!First)
701         OS << ", ";
702       First = false;
703       OS << printReg(LI.PhysReg, &TRI);
704       if (!LI.LaneMask.all())
705         OS << ":0x" << PrintLaneMask(LI.LaneMask);
706     }
707     OS << "\n";
708     HasLineAttributes = true;
709   }
710 
711   if (HasLineAttributes)
712     OS << "\n";
713   bool IsInBundle = false;
714   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
715     const MachineInstr &MI = *I;
716     if (IsInBundle && !MI.isInsideBundle()) {
717       OS.indent(2) << "}\n";
718       IsInBundle = false;
719     }
720     OS.indent(IsInBundle ? 4 : 2);
721     print(MI);
722     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
723       OS << " {";
724       IsInBundle = true;
725     }
726     OS << "\n";
727   }
728   if (IsInBundle)
729     OS.indent(2) << "}\n";
730 }
731 
732 void MIPrinter::print(const MachineInstr &MI) {
733   const auto *MF = MI.getMF();
734   const auto &MRI = MF->getRegInfo();
735   const auto &SubTarget = MF->getSubtarget();
736   const auto *TRI = SubTarget.getRegisterInfo();
737   assert(TRI && "Expected target register info");
738   const auto *TII = SubTarget.getInstrInfo();
739   assert(TII && "Expected target instruction info");
740   if (MI.isCFIInstruction())
741     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
742 
743   SmallBitVector PrintedTypes(8);
744   bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
745   unsigned I = 0, E = MI.getNumOperands();
746   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
747          !MI.getOperand(I).isImplicit();
748        ++I) {
749     if (I)
750       OS << ", ";
751     print(MI, I, TRI, TII, ShouldPrintRegisterTies,
752           MI.getTypeToPrint(I, PrintedTypes, MRI),
753           /*PrintDef=*/false);
754   }
755 
756   if (I)
757     OS << " = ";
758   if (MI.getFlag(MachineInstr::FrameSetup))
759     OS << "frame-setup ";
760   if (MI.getFlag(MachineInstr::FrameDestroy))
761     OS << "frame-destroy ";
762   if (MI.getFlag(MachineInstr::FmNoNans))
763     OS << "nnan ";
764   if (MI.getFlag(MachineInstr::FmNoInfs))
765     OS << "ninf ";
766   if (MI.getFlag(MachineInstr::FmNsz))
767     OS << "nsz ";
768   if (MI.getFlag(MachineInstr::FmArcp))
769     OS << "arcp ";
770   if (MI.getFlag(MachineInstr::FmContract))
771     OS << "contract ";
772   if (MI.getFlag(MachineInstr::FmAfn))
773     OS << "afn ";
774   if (MI.getFlag(MachineInstr::FmReassoc))
775     OS << "reassoc ";
776   if (MI.getFlag(MachineInstr::NoUWrap))
777     OS << "nuw ";
778   if (MI.getFlag(MachineInstr::NoSWrap))
779     OS << "nsw ";
780   if (MI.getFlag(MachineInstr::IsExact))
781     OS << "exact ";
782   if (MI.getFlag(MachineInstr::NoFPExcept))
783     OS << "nofpexcept ";
784 
785   OS << TII->getName(MI.getOpcode());
786   if (I < E)
787     OS << ' ';
788 
789   bool NeedComma = false;
790   for (; I < E; ++I) {
791     if (NeedComma)
792       OS << ", ";
793     print(MI, I, TRI, TII, ShouldPrintRegisterTies,
794           MI.getTypeToPrint(I, PrintedTypes, MRI));
795     NeedComma = true;
796   }
797 
798   // Print any optional symbols attached to this instruction as-if they were
799   // operands.
800   if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
801     if (NeedComma)
802       OS << ',';
803     OS << " pre-instr-symbol ";
804     MachineOperand::printSymbol(OS, *PreInstrSymbol);
805     NeedComma = true;
806   }
807   if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
808     if (NeedComma)
809       OS << ',';
810     OS << " post-instr-symbol ";
811     MachineOperand::printSymbol(OS, *PostInstrSymbol);
812     NeedComma = true;
813   }
814   if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) {
815     if (NeedComma)
816       OS << ',';
817     OS << " heap-alloc-marker ";
818     HeapAllocMarker->printAsOperand(OS, MST);
819     NeedComma = true;
820   }
821 
822   if (const DebugLoc &DL = MI.getDebugLoc()) {
823     if (NeedComma)
824       OS << ',';
825     OS << " debug-location ";
826     DL->printAsOperand(OS, MST);
827   }
828 
829   if (!MI.memoperands_empty()) {
830     OS << " :: ";
831     const LLVMContext &Context = MF->getFunction().getContext();
832     const MachineFrameInfo &MFI = MF->getFrameInfo();
833     bool NeedComma = false;
834     for (const auto *Op : MI.memoperands()) {
835       if (NeedComma)
836         OS << ", ";
837       Op->print(OS, MST, SSNs, Context, &MFI, TII);
838       NeedComma = true;
839     }
840   }
841 }
842 
843 void MIPrinter::printStackObjectReference(int FrameIndex) {
844   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
845   assert(ObjectInfo != StackObjectOperandMapping.end() &&
846          "Invalid frame index");
847   const FrameIndexOperand &Operand = ObjectInfo->second;
848   MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
849                                             Operand.Name);
850 }
851 
852 static std::string formatOperandComment(std::string Comment) {
853   if (Comment.empty())
854     return Comment;
855   return std::string(" /* " + Comment + " */");
856 }
857 
858 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
859                       const TargetRegisterInfo *TRI,
860                       const TargetInstrInfo *TII,
861                       bool ShouldPrintRegisterTies, LLT TypeToPrint,
862                       bool PrintDef) {
863   const MachineOperand &Op = MI.getOperand(OpIdx);
864   std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx);
865 
866   switch (Op.getType()) {
867   case MachineOperand::MO_Immediate:
868     if (MI.isOperandSubregIdx(OpIdx)) {
869       MachineOperand::printTargetFlags(OS, Op);
870       MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
871       break;
872     }
873     LLVM_FALLTHROUGH;
874   case MachineOperand::MO_Register:
875   case MachineOperand::MO_CImmediate:
876   case MachineOperand::MO_FPImmediate:
877   case MachineOperand::MO_MachineBasicBlock:
878   case MachineOperand::MO_ConstantPoolIndex:
879   case MachineOperand::MO_TargetIndex:
880   case MachineOperand::MO_JumpTableIndex:
881   case MachineOperand::MO_ExternalSymbol:
882   case MachineOperand::MO_GlobalAddress:
883   case MachineOperand::MO_RegisterLiveOut:
884   case MachineOperand::MO_Metadata:
885   case MachineOperand::MO_MCSymbol:
886   case MachineOperand::MO_CFIIndex:
887   case MachineOperand::MO_IntrinsicID:
888   case MachineOperand::MO_Predicate:
889   case MachineOperand::MO_BlockAddress:
890   case MachineOperand::MO_ShuffleMask: {
891     unsigned TiedOperandIdx = 0;
892     if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
893       TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
894     const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
895     Op.print(OS, MST, TypeToPrint, OpIdx, PrintDef, /*IsStandalone=*/false,
896              ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
897       OS << formatOperandComment(MOComment);
898     break;
899   }
900   case MachineOperand::MO_FrameIndex:
901     printStackObjectReference(Op.getIndex());
902     break;
903   case MachineOperand::MO_RegisterMask: {
904     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
905     if (RegMaskInfo != RegisterMaskIds.end())
906       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
907     else
908       printCustomRegMask(Op.getRegMask(), OS, TRI);
909     break;
910   }
911   }
912 }
913 
914 void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V,
915                                 ModuleSlotTracker &MST) {
916   if (isa<GlobalValue>(V)) {
917     V.printAsOperand(OS, /*PrintType=*/false, MST);
918     return;
919   }
920   if (isa<Constant>(V)) {
921     // Machine memory operands can load/store to/from constant value pointers.
922     OS << '`';
923     V.printAsOperand(OS, /*PrintType=*/true, MST);
924     OS << '`';
925     return;
926   }
927   OS << "%ir.";
928   if (V.hasName()) {
929     printLLVMNameWithoutPrefix(OS, V.getName());
930     return;
931   }
932   int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1;
933   MachineOperand::printIRSlotNumber(OS, Slot);
934 }
935 
936 void llvm::printMIR(raw_ostream &OS, const Module &M) {
937   yaml::Output Out(OS);
938   Out << const_cast<Module &>(M);
939 }
940 
941 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
942   MIRPrinter Printer(OS);
943   Printer.print(MF);
944 }
945