]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/MIRPrinter.cpp
Merge ^/head r318658 through r318963.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / MIRPrinter.cpp
1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/MIRPrinter.h"
16
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
20 #include "llvm/CodeGen/MIRYamlMapping.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSlotTracker.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Options.h"
39 #include "llvm/Support/YAMLTraits.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetIntrinsicInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44
45 using namespace llvm;
46
47 static cl::opt<bool> SimplifyMIR("simplify-mir",
48     cl::desc("Leave out unnecessary information when printing MIR"));
49
50 namespace {
51
52 /// This structure describes how to print out stack object references.
53 struct FrameIndexOperand {
54   std::string Name;
55   unsigned ID;
56   bool IsFixed;
57
58   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
59       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
60
61   /// Return an ordinary stack object reference.
62   static FrameIndexOperand create(StringRef Name, unsigned ID) {
63     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
64   }
65
66   /// Return a fixed stack object reference.
67   static FrameIndexOperand createFixed(unsigned ID) {
68     return FrameIndexOperand("", ID, /*IsFixed=*/true);
69   }
70 };
71
72 } // end anonymous namespace
73
74 namespace llvm {
75
76 /// This class prints out the machine functions using the MIR serialization
77 /// format.
78 class MIRPrinter {
79   raw_ostream &OS;
80   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
81   /// Maps from stack object indices to operand indices which will be used when
82   /// printing frame index machine operands.
83   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
84
85 public:
86   MIRPrinter(raw_ostream &OS) : OS(OS) {}
87
88   void print(const MachineFunction &MF);
89
90   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
91                const TargetRegisterInfo *TRI);
92   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
93                const MachineFrameInfo &MFI);
94   void convert(yaml::MachineFunction &MF,
95                const MachineConstantPool &ConstantPool);
96   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
97                const MachineJumpTableInfo &JTI);
98   void convertStackObjects(yaml::MachineFunction &YMF,
99                            const MachineFunction &MF, ModuleSlotTracker &MST);
100
101 private:
102   void initRegisterMaskIds(const MachineFunction &MF);
103 };
104
105 /// This class prints out the machine instructions using the MIR serialization
106 /// format.
107 class MIPrinter {
108   raw_ostream &OS;
109   ModuleSlotTracker &MST;
110   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
111   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
112
113   bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
114   bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
115
116 public:
117   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
118             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
119             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
120       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
121         StackObjectOperandMapping(StackObjectOperandMapping) {}
122
123   void print(const MachineBasicBlock &MBB);
124
125   void print(const MachineInstr &MI);
126   void printMBBReference(const MachineBasicBlock &MBB);
127   void printIRBlockReference(const BasicBlock &BB);
128   void printIRValueReference(const Value &V);
129   void printStackObjectReference(int FrameIndex);
130   void printOffset(int64_t Offset);
131   void printTargetFlags(const MachineOperand &Op);
132   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
133              unsigned I, bool ShouldPrintRegisterTies,
134              LLT TypeToPrint, bool IsDef = false);
135   void print(const MachineMemOperand &Op);
136
137   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
138 };
139
140 } // end namespace llvm
141
142 namespace llvm {
143 namespace yaml {
144
145 /// This struct serializes the LLVM IR module.
146 template <> struct BlockScalarTraits<Module> {
147   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
148     Mod.print(OS, nullptr);
149   }
150   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
151     llvm_unreachable("LLVM Module is supposed to be parsed separately");
152     return "";
153   }
154 };
155
156 } // end namespace yaml
157 } // end namespace llvm
158
159 static void printReg(unsigned Reg, raw_ostream &OS,
160                      const TargetRegisterInfo *TRI) {
161   // TODO: Print Stack Slots.
162   if (!Reg)
163     OS << '_';
164   else if (TargetRegisterInfo::isVirtualRegister(Reg))
165     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
166   else if (Reg < TRI->getNumRegs())
167     OS << '%' << StringRef(TRI->getName(Reg)).lower();
168   else
169     llvm_unreachable("Can't print this kind of register yet");
170 }
171
172 static void printReg(unsigned Reg, yaml::StringValue &Dest,
173                      const TargetRegisterInfo *TRI) {
174   raw_string_ostream OS(Dest.Value);
175   printReg(Reg, OS, TRI);
176 }
177
178 void MIRPrinter::print(const MachineFunction &MF) {
179   initRegisterMaskIds(MF);
180
181   yaml::MachineFunction YamlMF;
182   YamlMF.Name = MF.getName();
183   YamlMF.Alignment = MF.getAlignment();
184   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
185
186   YamlMF.NoVRegs = MF.getProperties().hasProperty(
187       MachineFunctionProperties::Property::NoVRegs);
188   YamlMF.Legalized = MF.getProperties().hasProperty(
189       MachineFunctionProperties::Property::Legalized);
190   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
191       MachineFunctionProperties::Property::RegBankSelected);
192   YamlMF.Selected = MF.getProperties().hasProperty(
193       MachineFunctionProperties::Property::Selected);
194
195   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
196   ModuleSlotTracker MST(MF.getFunction()->getParent());
197   MST.incorporateFunction(*MF.getFunction());
198   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
199   convertStackObjects(YamlMF, MF, MST);
200   if (const auto *ConstantPool = MF.getConstantPool())
201     convert(YamlMF, *ConstantPool);
202   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
203     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
204   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
205   bool IsNewlineNeeded = false;
206   for (const auto &MBB : MF) {
207     if (IsNewlineNeeded)
208       StrOS << "\n";
209     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
210         .print(MBB);
211     IsNewlineNeeded = true;
212   }
213   StrOS.flush();
214   yaml::Output Out(OS);
215   Out << YamlMF;
216 }
217
218 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
219                                const TargetRegisterInfo *TRI) {
220   assert(RegMask && "Can't print an empty register mask");
221   OS << StringRef("CustomRegMask(");
222
223   bool IsRegInRegMaskFound = false;
224   for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
225     // Check whether the register is asserted in regmask.
226     if (RegMask[I / 32] & (1u << (I % 32))) {
227       if (IsRegInRegMaskFound)
228         OS << ',';
229       printReg(I, OS, TRI);
230       IsRegInRegMaskFound = true;
231     }
232   }
233
234   OS << ')';
235 }
236
237 void MIRPrinter::convert(yaml::MachineFunction &MF,
238                          const MachineRegisterInfo &RegInfo,
239                          const TargetRegisterInfo *TRI) {
240   MF.TracksRegLiveness = RegInfo.tracksLiveness();
241
242   // Print the virtual register definitions.
243   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
244     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
245     yaml::VirtualRegisterDefinition VReg;
246     VReg.ID = I;
247     if (RegInfo.getRegClassOrNull(Reg))
248       VReg.Class =
249           StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
250     else if (RegInfo.getRegBankOrNull(Reg))
251       VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
252     else {
253       VReg.Class = std::string("_");
254       assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
255              "Generic registers must have a valid type");
256     }
257     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
258     if (PreferredReg)
259       printReg(PreferredReg, VReg.PreferredRegister, TRI);
260     MF.VirtualRegisters.push_back(VReg);
261   }
262
263   // Print the live ins.
264   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
265     yaml::MachineFunctionLiveIn LiveIn;
266     printReg(I->first, LiveIn.Register, TRI);
267     if (I->second)
268       printReg(I->second, LiveIn.VirtualRegister, TRI);
269     MF.LiveIns.push_back(LiveIn);
270   }
271
272   // Prints the callee saved registers.
273   if (RegInfo.isUpdatedCSRsInitialized()) {
274     const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
275     std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
276     for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
277       yaml::FlowStringValue Reg;
278       printReg(*I, Reg, TRI);
279       CalleeSavedRegisters.push_back(Reg);
280     }
281     MF.CalleeSavedRegisters = CalleeSavedRegisters;
282   }
283 }
284
285 void MIRPrinter::convert(ModuleSlotTracker &MST,
286                          yaml::MachineFrameInfo &YamlMFI,
287                          const MachineFrameInfo &MFI) {
288   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
289   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
290   YamlMFI.HasStackMap = MFI.hasStackMap();
291   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
292   YamlMFI.StackSize = MFI.getStackSize();
293   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
294   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
295   YamlMFI.AdjustsStack = MFI.adjustsStack();
296   YamlMFI.HasCalls = MFI.hasCalls();
297   YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
298     ? MFI.getMaxCallFrameSize() : ~0u;
299   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
300   YamlMFI.HasVAStart = MFI.hasVAStart();
301   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
302   if (MFI.getSavePoint()) {
303     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
304     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
305         .printMBBReference(*MFI.getSavePoint());
306   }
307   if (MFI.getRestorePoint()) {
308     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
309     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
310         .printMBBReference(*MFI.getRestorePoint());
311   }
312 }
313
314 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
315                                      const MachineFunction &MF,
316                                      ModuleSlotTracker &MST) {
317   const MachineFrameInfo &MFI = MF.getFrameInfo();
318   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
319   // Process fixed stack objects.
320   unsigned ID = 0;
321   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
322     if (MFI.isDeadObjectIndex(I))
323       continue;
324
325     yaml::FixedMachineStackObject YamlObject;
326     YamlObject.ID = ID;
327     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
328                           ? yaml::FixedMachineStackObject::SpillSlot
329                           : yaml::FixedMachineStackObject::DefaultType;
330     YamlObject.Offset = MFI.getObjectOffset(I);
331     YamlObject.Size = MFI.getObjectSize(I);
332     YamlObject.Alignment = MFI.getObjectAlignment(I);
333     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
334     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
335     YMF.FixedStackObjects.push_back(YamlObject);
336     StackObjectOperandMapping.insert(
337         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
338   }
339
340   // Process ordinary stack objects.
341   ID = 0;
342   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
343     if (MFI.isDeadObjectIndex(I))
344       continue;
345
346     yaml::MachineStackObject YamlObject;
347     YamlObject.ID = ID;
348     if (const auto *Alloca = MFI.getObjectAllocation(I))
349       YamlObject.Name.Value =
350           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
351     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
352                           ? yaml::MachineStackObject::SpillSlot
353                           : MFI.isVariableSizedObjectIndex(I)
354                                 ? yaml::MachineStackObject::VariableSized
355                                 : yaml::MachineStackObject::DefaultType;
356     YamlObject.Offset = MFI.getObjectOffset(I);
357     YamlObject.Size = MFI.getObjectSize(I);
358     YamlObject.Alignment = MFI.getObjectAlignment(I);
359
360     YMF.StackObjects.push_back(YamlObject);
361     StackObjectOperandMapping.insert(std::make_pair(
362         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
363   }
364
365   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
366     yaml::StringValue Reg;
367     printReg(CSInfo.getReg(), Reg, TRI);
368     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
369     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
370            "Invalid stack object index");
371     const FrameIndexOperand &StackObject = StackObjectInfo->second;
372     if (StackObject.IsFixed)
373       YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
374     else
375       YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
376   }
377   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
378     auto LocalObject = MFI.getLocalFrameObjectMap(I);
379     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
380     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
381            "Invalid stack object index");
382     const FrameIndexOperand &StackObject = StackObjectInfo->second;
383     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
384     YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
385   }
386
387   // Print the stack object references in the frame information class after
388   // converting the stack objects.
389   if (MFI.hasStackProtectorIndex()) {
390     raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
391     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
392         .printStackObjectReference(MFI.getStackProtectorIndex());
393   }
394
395   // Print the debug variable information.
396   for (const MachineFunction::VariableDbgInfo &DebugVar :
397        MF.getVariableDbgInfo()) {
398     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
399     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
400            "Invalid stack object index");
401     const FrameIndexOperand &StackObject = StackObjectInfo->second;
402     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
403     auto &Object = YMF.StackObjects[StackObject.ID];
404     {
405       raw_string_ostream StrOS(Object.DebugVar.Value);
406       DebugVar.Var->printAsOperand(StrOS, MST);
407     }
408     {
409       raw_string_ostream StrOS(Object.DebugExpr.Value);
410       DebugVar.Expr->printAsOperand(StrOS, MST);
411     }
412     {
413       raw_string_ostream StrOS(Object.DebugLoc.Value);
414       DebugVar.Loc->printAsOperand(StrOS, MST);
415     }
416   }
417 }
418
419 void MIRPrinter::convert(yaml::MachineFunction &MF,
420                          const MachineConstantPool &ConstantPool) {
421   unsigned ID = 0;
422   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
423     // TODO: Serialize target specific constant pool entries.
424     if (Constant.isMachineConstantPoolEntry())
425       llvm_unreachable("Can't print target specific constant pool entries yet");
426
427     yaml::MachineConstantPoolValue YamlConstant;
428     std::string Str;
429     raw_string_ostream StrOS(Str);
430     Constant.Val.ConstVal->printAsOperand(StrOS);
431     YamlConstant.ID = ID++;
432     YamlConstant.Value = StrOS.str();
433     YamlConstant.Alignment = Constant.getAlignment();
434     MF.Constants.push_back(YamlConstant);
435   }
436 }
437
438 void MIRPrinter::convert(ModuleSlotTracker &MST,
439                          yaml::MachineJumpTable &YamlJTI,
440                          const MachineJumpTableInfo &JTI) {
441   YamlJTI.Kind = JTI.getEntryKind();
442   unsigned ID = 0;
443   for (const auto &Table : JTI.getJumpTables()) {
444     std::string Str;
445     yaml::MachineJumpTable::Entry Entry;
446     Entry.ID = ID++;
447     for (const auto *MBB : Table.MBBs) {
448       raw_string_ostream StrOS(Str);
449       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
450           .printMBBReference(*MBB);
451       Entry.Blocks.push_back(StrOS.str());
452       Str.clear();
453     }
454     YamlJTI.Entries.push_back(Entry);
455   }
456 }
457
458 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
459   const auto *TRI = MF.getSubtarget().getRegisterInfo();
460   unsigned I = 0;
461   for (const uint32_t *Mask : TRI->getRegMasks())
462     RegisterMaskIds.insert(std::make_pair(Mask, I++));
463 }
464
465 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
466                            SmallVectorImpl<MachineBasicBlock*> &Result,
467                            bool &IsFallthrough) {
468   SmallPtrSet<MachineBasicBlock*,8> Seen;
469
470   for (const MachineInstr &MI : MBB) {
471     if (MI.isPHI())
472       continue;
473     for (const MachineOperand &MO : MI.operands()) {
474       if (!MO.isMBB())
475         continue;
476       MachineBasicBlock *Succ = MO.getMBB();
477       auto RP = Seen.insert(Succ);
478       if (RP.second)
479         Result.push_back(Succ);
480     }
481   }
482   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
483   IsFallthrough = I == MBB.end() || !I->isBarrier();
484 }
485
486 bool
487 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
488   if (MBB.succ_size() <= 1)
489     return true;
490   if (!MBB.hasSuccessorProbabilities())
491     return true;
492
493   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
494                                               MBB.Probs.end());
495   BranchProbability::normalizeProbabilities(Normalized.begin(),
496                                             Normalized.end());
497   SmallVector<BranchProbability,8> Equal(Normalized.size());
498   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
499
500   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
501 }
502
503 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
504   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
505   bool GuessedFallthrough;
506   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
507   if (GuessedFallthrough) {
508     const MachineFunction &MF = *MBB.getParent();
509     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
510     if (NextI != MF.end()) {
511       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
512       if (!is_contained(GuessedSuccs, Next))
513         GuessedSuccs.push_back(Next);
514     }
515   }
516   if (GuessedSuccs.size() != MBB.succ_size())
517     return false;
518   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
519 }
520
521
522 void MIPrinter::print(const MachineBasicBlock &MBB) {
523   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
524   OS << "bb." << MBB.getNumber();
525   bool HasAttributes = false;
526   if (const auto *BB = MBB.getBasicBlock()) {
527     if (BB->hasName()) {
528       OS << "." << BB->getName();
529     } else {
530       HasAttributes = true;
531       OS << " (";
532       int Slot = MST.getLocalSlot(BB);
533       if (Slot == -1)
534         OS << "<ir-block badref>";
535       else
536         OS << (Twine("%ir-block.") + Twine(Slot)).str();
537     }
538   }
539   if (MBB.hasAddressTaken()) {
540     OS << (HasAttributes ? ", " : " (");
541     OS << "address-taken";
542     HasAttributes = true;
543   }
544   if (MBB.isEHPad()) {
545     OS << (HasAttributes ? ", " : " (");
546     OS << "landing-pad";
547     HasAttributes = true;
548   }
549   if (MBB.getAlignment()) {
550     OS << (HasAttributes ? ", " : " (");
551     OS << "align " << MBB.getAlignment();
552     HasAttributes = true;
553   }
554   if (HasAttributes)
555     OS << ")";
556   OS << ":\n";
557
558   bool HasLineAttributes = false;
559   // Print the successors
560   bool canPredictProbs = canPredictBranchProbabilities(MBB);
561   if (!MBB.succ_empty() && (!SimplifyMIR || !canPredictProbs ||
562                             !canPredictSuccessors(MBB))) {
563     OS.indent(2) << "successors: ";
564     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
565       if (I != MBB.succ_begin())
566         OS << ", ";
567       printMBBReference(**I);
568       if (!SimplifyMIR || !canPredictProbs)
569         OS << '('
570            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
571            << ')';
572     }
573     OS << "\n";
574     HasLineAttributes = true;
575   }
576
577   // Print the live in registers.
578   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
579   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
580     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
581     OS.indent(2) << "liveins: ";
582     bool First = true;
583     for (const auto &LI : MBB.liveins()) {
584       if (!First)
585         OS << ", ";
586       First = false;
587       printReg(LI.PhysReg, OS, &TRI);
588       if (!LI.LaneMask.all())
589         OS << ":0x" << PrintLaneMask(LI.LaneMask);
590     }
591     OS << "\n";
592     HasLineAttributes = true;
593   }
594
595   if (HasLineAttributes)
596     OS << "\n";
597   bool IsInBundle = false;
598   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
599     const MachineInstr &MI = *I;
600     if (IsInBundle && !MI.isInsideBundle()) {
601       OS.indent(2) << "}\n";
602       IsInBundle = false;
603     }
604     OS.indent(IsInBundle ? 4 : 2);
605     print(MI);
606     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
607       OS << " {";
608       IsInBundle = true;
609     }
610     OS << "\n";
611   }
612   if (IsInBundle)
613     OS.indent(2) << "}\n";
614 }
615
616 /// Return true when an instruction has tied register that can't be determined
617 /// by the instruction's descriptor.
618 static bool hasComplexRegisterTies(const MachineInstr &MI) {
619   const MCInstrDesc &MCID = MI.getDesc();
620   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
621     const auto &Operand = MI.getOperand(I);
622     if (!Operand.isReg() || Operand.isDef())
623       // Ignore the defined registers as MCID marks only the uses as tied.
624       continue;
625     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
626     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
627     if (ExpectedTiedIdx != TiedIdx)
628       return true;
629   }
630   return false;
631 }
632
633 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
634                           SmallBitVector &PrintedTypes,
635                           const MachineRegisterInfo &MRI) {
636   const MachineOperand &Op = MI.getOperand(OpIdx);
637   if (!Op.isReg())
638     return LLT{};
639
640   if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
641     return MRI.getType(Op.getReg());
642
643   auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
644   if (!OpInfo.isGenericType())
645     return MRI.getType(Op.getReg());
646
647   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
648     return LLT{};
649
650   PrintedTypes.set(OpInfo.getGenericTypeIndex());
651   return MRI.getType(Op.getReg());
652 }
653
654 void MIPrinter::print(const MachineInstr &MI) {
655   const auto *MF = MI.getParent()->getParent();
656   const auto &MRI = MF->getRegInfo();
657   const auto &SubTarget = MF->getSubtarget();
658   const auto *TRI = SubTarget.getRegisterInfo();
659   assert(TRI && "Expected target register info");
660   const auto *TII = SubTarget.getInstrInfo();
661   assert(TII && "Expected target instruction info");
662   if (MI.isCFIInstruction())
663     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
664
665   SmallBitVector PrintedTypes(8);
666   bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
667   unsigned I = 0, E = MI.getNumOperands();
668   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
669          !MI.getOperand(I).isImplicit();
670        ++I) {
671     if (I)
672       OS << ", ";
673     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
674           getTypeToPrint(MI, I, PrintedTypes, MRI),
675           /*IsDef=*/true);
676   }
677
678   if (I)
679     OS << " = ";
680   if (MI.getFlag(MachineInstr::FrameSetup))
681     OS << "frame-setup ";
682   OS << TII->getName(MI.getOpcode());
683   if (I < E)
684     OS << ' ';
685
686   bool NeedComma = false;
687   for (; I < E; ++I) {
688     if (NeedComma)
689       OS << ", ";
690     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
691           getTypeToPrint(MI, I, PrintedTypes, MRI));
692     NeedComma = true;
693   }
694
695   if (MI.getDebugLoc()) {
696     if (NeedComma)
697       OS << ',';
698     OS << " debug-location ";
699     MI.getDebugLoc()->printAsOperand(OS, MST);
700   }
701
702   if (!MI.memoperands_empty()) {
703     OS << " :: ";
704     bool NeedComma = false;
705     for (const auto *Op : MI.memoperands()) {
706       if (NeedComma)
707         OS << ", ";
708       print(*Op);
709       NeedComma = true;
710     }
711   }
712 }
713
714 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
715   OS << "%bb." << MBB.getNumber();
716   if (const auto *BB = MBB.getBasicBlock()) {
717     if (BB->hasName())
718       OS << '.' << BB->getName();
719   }
720 }
721
722 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
723   if (Slot == -1)
724     OS << "<badref>";
725   else
726     OS << Slot;
727 }
728
729 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
730   OS << "%ir-block.";
731   if (BB.hasName()) {
732     printLLVMNameWithoutPrefix(OS, BB.getName());
733     return;
734   }
735   const Function *F = BB.getParent();
736   int Slot;
737   if (F == MST.getCurrentFunction()) {
738     Slot = MST.getLocalSlot(&BB);
739   } else {
740     ModuleSlotTracker CustomMST(F->getParent(),
741                                 /*ShouldInitializeAllMetadata=*/false);
742     CustomMST.incorporateFunction(*F);
743     Slot = CustomMST.getLocalSlot(&BB);
744   }
745   printIRSlotNumber(OS, Slot);
746 }
747
748 void MIPrinter::printIRValueReference(const Value &V) {
749   if (isa<GlobalValue>(V)) {
750     V.printAsOperand(OS, /*PrintType=*/false, MST);
751     return;
752   }
753   if (isa<Constant>(V)) {
754     // Machine memory operands can load/store to/from constant value pointers.
755     OS << '`';
756     V.printAsOperand(OS, /*PrintType=*/true, MST);
757     OS << '`';
758     return;
759   }
760   OS << "%ir.";
761   if (V.hasName()) {
762     printLLVMNameWithoutPrefix(OS, V.getName());
763     return;
764   }
765   printIRSlotNumber(OS, MST.getLocalSlot(&V));
766 }
767
768 void MIPrinter::printStackObjectReference(int FrameIndex) {
769   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
770   assert(ObjectInfo != StackObjectOperandMapping.end() &&
771          "Invalid frame index");
772   const FrameIndexOperand &Operand = ObjectInfo->second;
773   if (Operand.IsFixed) {
774     OS << "%fixed-stack." << Operand.ID;
775     return;
776   }
777   OS << "%stack." << Operand.ID;
778   if (!Operand.Name.empty())
779     OS << '.' << Operand.Name;
780 }
781
782 void MIPrinter::printOffset(int64_t Offset) {
783   if (Offset == 0)
784     return;
785   if (Offset < 0) {
786     OS << " - " << -Offset;
787     return;
788   }
789   OS << " + " << Offset;
790 }
791
792 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
793   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
794   for (const auto &I : Flags) {
795     if (I.first == TF) {
796       return I.second;
797     }
798   }
799   return nullptr;
800 }
801
802 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
803   if (!Op.getTargetFlags())
804     return;
805   const auto *TII =
806       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
807   assert(TII && "expected instruction info");
808   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
809   OS << "target-flags(";
810   const bool HasDirectFlags = Flags.first;
811   const bool HasBitmaskFlags = Flags.second;
812   if (!HasDirectFlags && !HasBitmaskFlags) {
813     OS << "<unknown>) ";
814     return;
815   }
816   if (HasDirectFlags) {
817     if (const auto *Name = getTargetFlagName(TII, Flags.first))
818       OS << Name;
819     else
820       OS << "<unknown target flag>";
821   }
822   if (!HasBitmaskFlags) {
823     OS << ") ";
824     return;
825   }
826   bool IsCommaNeeded = HasDirectFlags;
827   unsigned BitMask = Flags.second;
828   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
829   for (const auto &Mask : BitMasks) {
830     // Check if the flag's bitmask has the bits of the current mask set.
831     if ((BitMask & Mask.first) == Mask.first) {
832       if (IsCommaNeeded)
833         OS << ", ";
834       IsCommaNeeded = true;
835       OS << Mask.second;
836       // Clear the bits which were serialized from the flag's bitmask.
837       BitMask &= ~(Mask.first);
838     }
839   }
840   if (BitMask) {
841     // When the resulting flag's bitmask isn't zero, we know that we didn't
842     // serialize all of the bit flags.
843     if (IsCommaNeeded)
844       OS << ", ";
845     OS << "<unknown bitmask target flag>";
846   }
847   OS << ") ";
848 }
849
850 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
851   const auto *TII = MF.getSubtarget().getInstrInfo();
852   assert(TII && "expected instruction info");
853   auto Indices = TII->getSerializableTargetIndices();
854   for (const auto &I : Indices) {
855     if (I.first == Index) {
856       return I.second;
857     }
858   }
859   return nullptr;
860 }
861
862 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
863                       unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
864                       bool IsDef) {
865   printTargetFlags(Op);
866   switch (Op.getType()) {
867   case MachineOperand::MO_Register:
868     if (Op.isImplicit())
869       OS << (Op.isDef() ? "implicit-def " : "implicit ");
870     else if (!IsDef && Op.isDef())
871       // Print the 'def' flag only when the operand is defined after '='.
872       OS << "def ";
873     if (Op.isInternalRead())
874       OS << "internal ";
875     if (Op.isDead())
876       OS << "dead ";
877     if (Op.isKill())
878       OS << "killed ";
879     if (Op.isUndef())
880       OS << "undef ";
881     if (Op.isEarlyClobber())
882       OS << "early-clobber ";
883     if (Op.isDebug())
884       OS << "debug-use ";
885     printReg(Op.getReg(), OS, TRI);
886     // Print the sub register.
887     if (Op.getSubReg() != 0)
888       OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
889     if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
890       OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
891     if (TypeToPrint.isValid())
892       OS << '(' << TypeToPrint << ')';
893     break;
894   case MachineOperand::MO_Immediate:
895     OS << Op.getImm();
896     break;
897   case MachineOperand::MO_CImmediate:
898     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
899     break;
900   case MachineOperand::MO_FPImmediate:
901     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
902     break;
903   case MachineOperand::MO_MachineBasicBlock:
904     printMBBReference(*Op.getMBB());
905     break;
906   case MachineOperand::MO_FrameIndex:
907     printStackObjectReference(Op.getIndex());
908     break;
909   case MachineOperand::MO_ConstantPoolIndex:
910     OS << "%const." << Op.getIndex();
911     printOffset(Op.getOffset());
912     break;
913   case MachineOperand::MO_TargetIndex: {
914     OS << "target-index(";
915     if (const auto *Name = getTargetIndexName(
916             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
917       OS << Name;
918     else
919       OS << "<unknown>";
920     OS << ')';
921     printOffset(Op.getOffset());
922     break;
923   }
924   case MachineOperand::MO_JumpTableIndex:
925     OS << "%jump-table." << Op.getIndex();
926     break;
927   case MachineOperand::MO_ExternalSymbol:
928     OS << '$';
929     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
930     printOffset(Op.getOffset());
931     break;
932   case MachineOperand::MO_GlobalAddress:
933     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
934     printOffset(Op.getOffset());
935     break;
936   case MachineOperand::MO_BlockAddress:
937     OS << "blockaddress(";
938     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
939                                                         MST);
940     OS << ", ";
941     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
942     OS << ')';
943     printOffset(Op.getOffset());
944     break;
945   case MachineOperand::MO_RegisterMask: {
946     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
947     if (RegMaskInfo != RegisterMaskIds.end())
948       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
949     else
950       printCustomRegMask(Op.getRegMask(), OS, TRI);
951     break;
952   }
953   case MachineOperand::MO_RegisterLiveOut: {
954     const uint32_t *RegMask = Op.getRegLiveOut();
955     OS << "liveout(";
956     bool IsCommaNeeded = false;
957     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
958       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
959         if (IsCommaNeeded)
960           OS << ", ";
961         printReg(Reg, OS, TRI);
962         IsCommaNeeded = true;
963       }
964     }
965     OS << ")";
966     break;
967   }
968   case MachineOperand::MO_Metadata:
969     Op.getMetadata()->printAsOperand(OS, MST);
970     break;
971   case MachineOperand::MO_MCSymbol:
972     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
973     break;
974   case MachineOperand::MO_CFIIndex: {
975     const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
976     print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
977     break;
978   }
979   case MachineOperand::MO_IntrinsicID: {
980     Intrinsic::ID ID = Op.getIntrinsicID();
981     if (ID < Intrinsic::num_intrinsics)
982       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
983     else {
984       const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
985       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
986       OS << "intrinsic(@" << TII->getName(ID) << ')';
987     }
988     break;
989   }
990   case MachineOperand::MO_Predicate: {
991     auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
992     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
993        << CmpInst::getPredicateName(Pred) << ')';
994     break;
995   }
996   }
997 }
998
999 void MIPrinter::print(const MachineMemOperand &Op) {
1000   OS << '(';
1001   // TODO: Print operand's target specific flags.
1002   if (Op.isVolatile())
1003     OS << "volatile ";
1004   if (Op.isNonTemporal())
1005     OS << "non-temporal ";
1006   if (Op.isDereferenceable())
1007     OS << "dereferenceable ";
1008   if (Op.isInvariant())
1009     OS << "invariant ";
1010   if (Op.isLoad())
1011     OS << "load ";
1012   else {
1013     assert(Op.isStore() && "Non load machine operand must be a store");
1014     OS << "store ";
1015   }
1016
1017   if (Op.getSynchScope() == SynchronizationScope::SingleThread)
1018     OS << "singlethread ";
1019
1020   if (Op.getOrdering() != AtomicOrdering::NotAtomic)
1021     OS << toIRString(Op.getOrdering()) << ' ';
1022   if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
1023     OS << toIRString(Op.getFailureOrdering()) << ' ';
1024
1025   OS << Op.getSize();
1026   if (const Value *Val = Op.getValue()) {
1027     OS << (Op.isLoad() ? " from " : " into ");
1028     printIRValueReference(*Val);
1029   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
1030     OS << (Op.isLoad() ? " from " : " into ");
1031     assert(PVal && "Expected a pseudo source value");
1032     switch (PVal->kind()) {
1033     case PseudoSourceValue::Stack:
1034       OS << "stack";
1035       break;
1036     case PseudoSourceValue::GOT:
1037       OS << "got";
1038       break;
1039     case PseudoSourceValue::JumpTable:
1040       OS << "jump-table";
1041       break;
1042     case PseudoSourceValue::ConstantPool:
1043       OS << "constant-pool";
1044       break;
1045     case PseudoSourceValue::FixedStack:
1046       printStackObjectReference(
1047           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
1048       break;
1049     case PseudoSourceValue::GlobalValueCallEntry:
1050       OS << "call-entry ";
1051       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1052           OS, /*PrintType=*/false, MST);
1053       break;
1054     case PseudoSourceValue::ExternalSymbolCallEntry:
1055       OS << "call-entry $";
1056       printLLVMNameWithoutPrefix(
1057           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1058       break;
1059     case PseudoSourceValue::TargetCustom:
1060       llvm_unreachable("TargetCustom pseudo source values are not supported");
1061       break;
1062     }
1063   }
1064   printOffset(Op.getOffset());
1065   if (Op.getBaseAlignment() != Op.getSize())
1066     OS << ", align " << Op.getBaseAlignment();
1067   auto AAInfo = Op.getAAInfo();
1068   if (AAInfo.TBAA) {
1069     OS << ", !tbaa ";
1070     AAInfo.TBAA->printAsOperand(OS, MST);
1071   }
1072   if (AAInfo.Scope) {
1073     OS << ", !alias.scope ";
1074     AAInfo.Scope->printAsOperand(OS, MST);
1075   }
1076   if (AAInfo.NoAlias) {
1077     OS << ", !noalias ";
1078     AAInfo.NoAlias->printAsOperand(OS, MST);
1079   }
1080   if (Op.getRanges()) {
1081     OS << ", !range ";
1082     Op.getRanges()->printAsOperand(OS, MST);
1083   }
1084   OS << ')';
1085 }
1086
1087 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1088                              const TargetRegisterInfo *TRI) {
1089   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1090   if (Reg == -1) {
1091     OS << "<badreg>";
1092     return;
1093   }
1094   printReg(Reg, OS, TRI);
1095 }
1096
1097 void MIPrinter::print(const MCCFIInstruction &CFI,
1098                       const TargetRegisterInfo *TRI) {
1099   switch (CFI.getOperation()) {
1100   case MCCFIInstruction::OpSameValue:
1101     OS << "same_value ";
1102     if (CFI.getLabel())
1103       OS << "<mcsymbol> ";
1104     printCFIRegister(CFI.getRegister(), OS, TRI);
1105     break;
1106   case MCCFIInstruction::OpOffset:
1107     OS << "offset ";
1108     if (CFI.getLabel())
1109       OS << "<mcsymbol> ";
1110     printCFIRegister(CFI.getRegister(), OS, TRI);
1111     OS << ", " << CFI.getOffset();
1112     break;
1113   case MCCFIInstruction::OpDefCfaRegister:
1114     OS << "def_cfa_register ";
1115     if (CFI.getLabel())
1116       OS << "<mcsymbol> ";
1117     printCFIRegister(CFI.getRegister(), OS, TRI);
1118     break;
1119   case MCCFIInstruction::OpDefCfaOffset:
1120     OS << "def_cfa_offset ";
1121     if (CFI.getLabel())
1122       OS << "<mcsymbol> ";
1123     OS << CFI.getOffset();
1124     break;
1125   case MCCFIInstruction::OpDefCfa:
1126     OS << "def_cfa ";
1127     if (CFI.getLabel())
1128       OS << "<mcsymbol> ";
1129     printCFIRegister(CFI.getRegister(), OS, TRI);
1130     OS << ", " << CFI.getOffset();
1131     break;
1132   default:
1133     // TODO: Print the other CFI Operations.
1134     OS << "<unserializable cfi operation>";
1135     break;
1136   }
1137 }
1138
1139 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1140   yaml::Output Out(OS);
1141   Out << const_cast<Module &>(M);
1142 }
1143
1144 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1145   MIRPrinter Printer(OS);
1146   Printer.print(MF);
1147 }