67fd5c226a59e24106a31512dafabbc6d7a42345
[oota-llvm.git] / 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 "MIRPrinter.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MIRYamlMapping.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/YAMLTraits.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35
36 using namespace llvm;
37
38 namespace {
39
40 /// This structure describes how to print out stack object references.
41 struct FrameIndexOperand {
42   std::string Name;
43   unsigned ID;
44   bool IsFixed;
45
46   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
47       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
48
49   /// Return an ordinary stack object reference.
50   static FrameIndexOperand create(StringRef Name, unsigned ID) {
51     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
52   }
53
54   /// Return a fixed stack object reference.
55   static FrameIndexOperand createFixed(unsigned ID) {
56     return FrameIndexOperand("", ID, /*IsFixed=*/true);
57   }
58 };
59
60 } // end anonymous namespace
61
62 namespace llvm {
63
64 /// This class prints out the machine functions using the MIR serialization
65 /// format.
66 class MIRPrinter {
67   raw_ostream &OS;
68   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
69   /// Maps from stack object indices to operand indices which will be used when
70   /// printing frame index machine operands.
71   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
72
73 public:
74   MIRPrinter(raw_ostream &OS) : OS(OS) {}
75
76   void print(const MachineFunction &MF);
77
78   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
79                const TargetRegisterInfo *TRI);
80   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
81                const MachineFrameInfo &MFI);
82   void convert(yaml::MachineFunction &MF,
83                const MachineConstantPool &ConstantPool);
84   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
85                const MachineJumpTableInfo &JTI);
86   void convertStackObjects(yaml::MachineFunction &MF,
87                            const MachineFrameInfo &MFI, ModuleSlotTracker &MST,
88                            const TargetRegisterInfo *TRI);
89
90 private:
91   void initRegisterMaskIds(const MachineFunction &MF);
92 };
93
94 /// This class prints out the machine instructions using the MIR serialization
95 /// format.
96 class MIPrinter {
97   raw_ostream &OS;
98   ModuleSlotTracker &MST;
99   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
100   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
101
102 public:
103   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
104             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
105             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
106       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
107         StackObjectOperandMapping(StackObjectOperandMapping) {}
108
109   void print(const MachineBasicBlock &MBB);
110
111   void print(const MachineInstr &MI);
112   void printMBBReference(const MachineBasicBlock &MBB);
113   void printIRBlockReference(const BasicBlock &BB);
114   void printIRValueReference(const Value &V);
115   void printStackObjectReference(int FrameIndex);
116   void printOffset(int64_t Offset);
117   void printTargetFlags(const MachineOperand &Op);
118   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
119   void print(const MachineMemOperand &Op);
120
121   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
122 };
123
124 } // end namespace llvm
125
126 namespace llvm {
127 namespace yaml {
128
129 /// This struct serializes the LLVM IR module.
130 template <> struct BlockScalarTraits<Module> {
131   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
132     Mod.print(OS, nullptr);
133   }
134   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
135     llvm_unreachable("LLVM Module is supposed to be parsed separately");
136     return "";
137   }
138 };
139
140 } // end namespace yaml
141 } // end namespace llvm
142
143 static void printReg(unsigned Reg, raw_ostream &OS,
144                      const TargetRegisterInfo *TRI) {
145   // TODO: Print Stack Slots.
146   if (!Reg)
147     OS << '_';
148   else if (TargetRegisterInfo::isVirtualRegister(Reg))
149     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
150   else if (Reg < TRI->getNumRegs())
151     OS << '%' << StringRef(TRI->getName(Reg)).lower();
152   else
153     llvm_unreachable("Can't print this kind of register yet");
154 }
155
156 static void printReg(unsigned Reg, yaml::StringValue &Dest,
157                      const TargetRegisterInfo *TRI) {
158   raw_string_ostream OS(Dest.Value);
159   printReg(Reg, OS, TRI);
160 }
161
162 void MIRPrinter::print(const MachineFunction &MF) {
163   initRegisterMaskIds(MF);
164
165   yaml::MachineFunction YamlMF;
166   YamlMF.Name = MF.getName();
167   YamlMF.Alignment = MF.getAlignment();
168   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
169   YamlMF.HasInlineAsm = MF.hasInlineAsm();
170   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
171   ModuleSlotTracker MST(MF.getFunction()->getParent());
172   MST.incorporateFunction(*MF.getFunction());
173   convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
174   convertStackObjects(YamlMF, *MF.getFrameInfo(), MST,
175                       MF.getSubtarget().getRegisterInfo());
176   if (const auto *ConstantPool = MF.getConstantPool())
177     convert(YamlMF, *ConstantPool);
178   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
179     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
180   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
181   bool IsNewlineNeeded = false;
182   for (const auto &MBB : MF) {
183     if (IsNewlineNeeded)
184       StrOS << "\n";
185     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
186         .print(MBB);
187     IsNewlineNeeded = true;
188   }
189   StrOS.flush();
190   yaml::Output Out(OS);
191   Out << YamlMF;
192 }
193
194 void MIRPrinter::convert(yaml::MachineFunction &MF,
195                          const MachineRegisterInfo &RegInfo,
196                          const TargetRegisterInfo *TRI) {
197   MF.IsSSA = RegInfo.isSSA();
198   MF.TracksRegLiveness = RegInfo.tracksLiveness();
199   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
200
201   // Print the virtual register definitions.
202   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
203     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
204     yaml::VirtualRegisterDefinition VReg;
205     VReg.ID = I;
206     VReg.Class =
207         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
208     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
209     if (PreferredReg)
210       printReg(PreferredReg, VReg.PreferredRegister, TRI);
211     MF.VirtualRegisters.push_back(VReg);
212   }
213
214   // Print the live ins.
215   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
216     yaml::MachineFunctionLiveIn LiveIn;
217     printReg(I->first, LiveIn.Register, TRI);
218     if (I->second)
219       printReg(I->second, LiveIn.VirtualRegister, TRI);
220     MF.LiveIns.push_back(LiveIn);
221   }
222   // The used physical register mask is printed as an inverted callee saved
223   // register mask.
224   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
225   if (UsedPhysRegMask.none())
226     return;
227   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
228   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
229     if (!UsedPhysRegMask[I]) {
230       yaml::FlowStringValue Reg;
231       printReg(I, Reg, TRI);
232       CalleeSavedRegisters.push_back(Reg);
233     }
234   }
235   MF.CalleeSavedRegisters = CalleeSavedRegisters;
236 }
237
238 void MIRPrinter::convert(ModuleSlotTracker &MST,
239                          yaml::MachineFrameInfo &YamlMFI,
240                          const MachineFrameInfo &MFI) {
241   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
242   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
243   YamlMFI.HasStackMap = MFI.hasStackMap();
244   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
245   YamlMFI.StackSize = MFI.getStackSize();
246   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
247   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
248   YamlMFI.AdjustsStack = MFI.adjustsStack();
249   YamlMFI.HasCalls = MFI.hasCalls();
250   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
251   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
252   YamlMFI.HasVAStart = MFI.hasVAStart();
253   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
254   if (MFI.getSavePoint()) {
255     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
256     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
257         .printMBBReference(*MFI.getSavePoint());
258   }
259   if (MFI.getRestorePoint()) {
260     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
261     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
262         .printMBBReference(*MFI.getRestorePoint());
263   }
264 }
265
266 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
267                                      const MachineFrameInfo &MFI,
268                                      ModuleSlotTracker &MST,
269                                      const TargetRegisterInfo *TRI) {
270   // Process fixed stack objects.
271   unsigned ID = 0;
272   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
273     if (MFI.isDeadObjectIndex(I))
274       continue;
275
276     yaml::FixedMachineStackObject YamlObject;
277     YamlObject.ID = ID;
278     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
279                           ? yaml::FixedMachineStackObject::SpillSlot
280                           : yaml::FixedMachineStackObject::DefaultType;
281     YamlObject.Offset = MFI.getObjectOffset(I);
282     YamlObject.Size = MFI.getObjectSize(I);
283     YamlObject.Alignment = MFI.getObjectAlignment(I);
284     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
285     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
286     MF.FixedStackObjects.push_back(YamlObject);
287     StackObjectOperandMapping.insert(
288         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
289   }
290
291   // Process ordinary stack objects.
292   ID = 0;
293   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
294     if (MFI.isDeadObjectIndex(I))
295       continue;
296
297     yaml::MachineStackObject YamlObject;
298     YamlObject.ID = ID;
299     if (const auto *Alloca = MFI.getObjectAllocation(I))
300       YamlObject.Name.Value =
301           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
302     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
303                           ? yaml::MachineStackObject::SpillSlot
304                           : MFI.isVariableSizedObjectIndex(I)
305                                 ? yaml::MachineStackObject::VariableSized
306                                 : yaml::MachineStackObject::DefaultType;
307     YamlObject.Offset = MFI.getObjectOffset(I);
308     YamlObject.Size = MFI.getObjectSize(I);
309     YamlObject.Alignment = MFI.getObjectAlignment(I);
310
311     MF.StackObjects.push_back(YamlObject);
312     StackObjectOperandMapping.insert(std::make_pair(
313         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
314   }
315
316   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
317     yaml::StringValue Reg;
318     printReg(CSInfo.getReg(), Reg, TRI);
319     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
320     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
321            "Invalid stack object index");
322     const FrameIndexOperand &StackObject = StackObjectInfo->second;
323     if (StackObject.IsFixed)
324       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
325     else
326       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
327   }
328   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
329     auto LocalObject = MFI.getLocalFrameObjectMap(I);
330     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
331     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
332            "Invalid stack object index");
333     const FrameIndexOperand &StackObject = StackObjectInfo->second;
334     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
335     MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
336   }
337
338   // Print the stack object references in the frame information class after
339   // converting the stack objects.
340   if (MFI.hasStackProtectorIndex()) {
341     raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
342     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
343         .printStackObjectReference(MFI.getStackProtectorIndex());
344   }
345 }
346
347 void MIRPrinter::convert(yaml::MachineFunction &MF,
348                          const MachineConstantPool &ConstantPool) {
349   unsigned ID = 0;
350   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
351     // TODO: Serialize target specific constant pool entries.
352     if (Constant.isMachineConstantPoolEntry())
353       llvm_unreachable("Can't print target specific constant pool entries yet");
354
355     yaml::MachineConstantPoolValue YamlConstant;
356     std::string Str;
357     raw_string_ostream StrOS(Str);
358     Constant.Val.ConstVal->printAsOperand(StrOS);
359     YamlConstant.ID = ID++;
360     YamlConstant.Value = StrOS.str();
361     YamlConstant.Alignment = Constant.getAlignment();
362     MF.Constants.push_back(YamlConstant);
363   }
364 }
365
366 void MIRPrinter::convert(ModuleSlotTracker &MST,
367                          yaml::MachineJumpTable &YamlJTI,
368                          const MachineJumpTableInfo &JTI) {
369   YamlJTI.Kind = JTI.getEntryKind();
370   unsigned ID = 0;
371   for (const auto &Table : JTI.getJumpTables()) {
372     std::string Str;
373     yaml::MachineJumpTable::Entry Entry;
374     Entry.ID = ID++;
375     for (const auto *MBB : Table.MBBs) {
376       raw_string_ostream StrOS(Str);
377       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
378           .printMBBReference(*MBB);
379       Entry.Blocks.push_back(StrOS.str());
380       Str.clear();
381     }
382     YamlJTI.Entries.push_back(Entry);
383   }
384 }
385
386 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
387   const auto *TRI = MF.getSubtarget().getRegisterInfo();
388   unsigned I = 0;
389   for (const uint32_t *Mask : TRI->getRegMasks())
390     RegisterMaskIds.insert(std::make_pair(Mask, I++));
391 }
392
393 void MIPrinter::print(const MachineBasicBlock &MBB) {
394   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
395   OS << "bb." << MBB.getNumber();
396   bool HasAttributes = false;
397   if (const auto *BB = MBB.getBasicBlock()) {
398     if (BB->hasName()) {
399       OS << "." << BB->getName();
400     } else {
401       HasAttributes = true;
402       OS << " (";
403       int Slot = MST.getLocalSlot(BB);
404       if (Slot == -1)
405         OS << "<ir-block badref>";
406       else
407         OS << (Twine("%ir-block.") + Twine(Slot)).str();
408     }
409   }
410   if (MBB.hasAddressTaken()) {
411     OS << (HasAttributes ? ", " : " (");
412     OS << "address-taken";
413     HasAttributes = true;
414   }
415   if (MBB.isLandingPad()) {
416     OS << (HasAttributes ? ", " : " (");
417     OS << "landing-pad";
418     HasAttributes = true;
419   }
420   if (MBB.getAlignment()) {
421     OS << (HasAttributes ? ", " : " (");
422     OS << "align " << MBB.getAlignment();
423     HasAttributes = true;
424   }
425   if (HasAttributes)
426     OS << ")";
427   OS << ":\n";
428
429   bool HasLineAttributes = false;
430   // Print the successors
431   if (!MBB.succ_empty()) {
432     OS.indent(2) << "successors: ";
433     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
434       if (I != MBB.succ_begin())
435         OS << ", ";
436       printMBBReference(**I);
437       if (MBB.hasSuccessorWeights())
438         OS << '(' << MBB.getSuccWeight(I) << ')';
439     }
440     OS << "\n";
441     HasLineAttributes = true;
442   }
443
444   // Print the live in registers.
445   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
446   assert(TRI && "Expected target register info");
447   if (!MBB.livein_empty()) {
448     OS.indent(2) << "liveins: ";
449     for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
450       if (I != MBB.livein_begin())
451         OS << ", ";
452       printReg(*I, OS, TRI);
453     }
454     OS << "\n";
455     HasLineAttributes = true;
456   }
457
458   if (HasLineAttributes)
459     OS << "\n";
460   bool IsInBundle = false;
461   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
462     const MachineInstr &MI = *I;
463     if (IsInBundle && !MI.isInsideBundle()) {
464       OS.indent(2) << "}\n";
465       IsInBundle = false;
466     }
467     OS.indent(IsInBundle ? 4 : 2);
468     print(MI);
469     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
470       OS << " {";
471       IsInBundle = true;
472     }
473     OS << "\n";
474   }
475   if (IsInBundle)
476     OS.indent(2) << "}\n";
477 }
478
479 void MIPrinter::print(const MachineInstr &MI) {
480   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
481   const auto *TRI = SubTarget.getRegisterInfo();
482   assert(TRI && "Expected target register info");
483   const auto *TII = SubTarget.getInstrInfo();
484   assert(TII && "Expected target instruction info");
485   if (MI.isCFIInstruction())
486     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
487
488   unsigned I = 0, E = MI.getNumOperands();
489   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
490          !MI.getOperand(I).isImplicit();
491        ++I) {
492     if (I)
493       OS << ", ";
494     print(MI.getOperand(I), TRI);
495   }
496
497   if (I)
498     OS << " = ";
499   if (MI.getFlag(MachineInstr::FrameSetup))
500     OS << "frame-setup ";
501   OS << TII->getName(MI.getOpcode());
502   if (I < E)
503     OS << ' ';
504
505   bool NeedComma = false;
506   for (; I < E; ++I) {
507     if (NeedComma)
508       OS << ", ";
509     print(MI.getOperand(I), TRI);
510     NeedComma = true;
511   }
512
513   if (MI.getDebugLoc()) {
514     if (NeedComma)
515       OS << ',';
516     OS << " debug-location ";
517     MI.getDebugLoc()->printAsOperand(OS, MST);
518   }
519
520   if (!MI.memoperands_empty()) {
521     OS << " :: ";
522     bool NeedComma = false;
523     for (const auto *Op : MI.memoperands()) {
524       if (NeedComma)
525         OS << ", ";
526       print(*Op);
527       NeedComma = true;
528     }
529   }
530 }
531
532 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
533   OS << "%bb." << MBB.getNumber();
534   if (const auto *BB = MBB.getBasicBlock()) {
535     if (BB->hasName())
536       OS << '.' << BB->getName();
537   }
538 }
539
540 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
541   OS << "%ir-block.";
542   if (BB.hasName()) {
543     printLLVMNameWithoutPrefix(OS, BB.getName());
544     return;
545   }
546   const Function *F = BB.getParent();
547   int Slot;
548   if (F == MST.getCurrentFunction()) {
549     Slot = MST.getLocalSlot(&BB);
550   } else {
551     ModuleSlotTracker CustomMST(F->getParent(),
552                                 /*ShouldInitializeAllMetadata=*/false);
553     CustomMST.incorporateFunction(*F);
554     Slot = CustomMST.getLocalSlot(&BB);
555   }
556   if (Slot == -1)
557     OS << "<badref>";
558   else
559     OS << Slot;
560 }
561
562 void MIPrinter::printIRValueReference(const Value &V) {
563   OS << "%ir.";
564   if (V.hasName()) {
565     printLLVMNameWithoutPrefix(OS, V.getName());
566     return;
567   }
568   // TODO: Serialize the unnamed IR value references.
569   OS << "<unserializable ir value>";
570 }
571
572 void MIPrinter::printStackObjectReference(int FrameIndex) {
573   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
574   assert(ObjectInfo != StackObjectOperandMapping.end() &&
575          "Invalid frame index");
576   const FrameIndexOperand &Operand = ObjectInfo->second;
577   if (Operand.IsFixed) {
578     OS << "%fixed-stack." << Operand.ID;
579     return;
580   }
581   OS << "%stack." << Operand.ID;
582   if (!Operand.Name.empty())
583     OS << '.' << Operand.Name;
584 }
585
586 void MIPrinter::printOffset(int64_t Offset) {
587   if (Offset == 0)
588     return;
589   if (Offset < 0) {
590     OS << " - " << -Offset;
591     return;
592   }
593   OS << " + " << Offset;
594 }
595
596 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
597   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
598   for (const auto &I : Flags) {
599     if (I.first == TF) {
600       return I.second;
601     }
602   }
603   return nullptr;
604 }
605
606 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
607   if (!Op.getTargetFlags())
608     return;
609   const auto *TII =
610       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
611   assert(TII && "expected instruction info");
612   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
613   OS << "target-flags(";
614   const bool HasDirectFlags = Flags.first;
615   const bool HasBitmaskFlags = Flags.second;
616   if (!HasDirectFlags && !HasBitmaskFlags) {
617     OS << "<unknown>) ";
618     return;
619   }
620   if (HasDirectFlags) {
621     if (const auto *Name = getTargetFlagName(TII, Flags.first))
622       OS << Name;
623     else
624       OS << "<unknown target flag>";
625   }
626   if (!HasBitmaskFlags) {
627     OS << ") ";
628     return;
629   }
630   bool IsCommaNeeded = HasDirectFlags;
631   unsigned BitMask = Flags.second;
632   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
633   for (const auto &Mask : BitMasks) {
634     // Check if the flag's bitmask has the bits of the current mask set.
635     if ((BitMask & Mask.first) == Mask.first) {
636       if (IsCommaNeeded)
637         OS << ", ";
638       IsCommaNeeded = true;
639       OS << Mask.second;
640       // Clear the bits which were serialized from the flag's bitmask.
641       BitMask &= ~(Mask.first);
642     }
643   }
644   if (BitMask) {
645     // When the resulting flag's bitmask isn't zero, we know that we didn't
646     // serialize all of the bit flags.
647     if (IsCommaNeeded)
648       OS << ", ";
649     OS << "<unknown bitmask target flag>";
650   }
651   OS << ") ";
652 }
653
654 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
655   const auto *TII = MF.getSubtarget().getInstrInfo();
656   assert(TII && "expected instruction info");
657   auto Indices = TII->getSerializableTargetIndices();
658   for (const auto &I : Indices) {
659     if (I.first == Index) {
660       return I.second;
661     }
662   }
663   return nullptr;
664 }
665
666 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
667   printTargetFlags(Op);
668   switch (Op.getType()) {
669   case MachineOperand::MO_Register:
670     // FIXME: Serialize the tied register.
671     if (Op.isImplicit())
672       OS << (Op.isDef() ? "implicit-def " : "implicit ");
673     if (Op.isInternalRead())
674       OS << "internal ";
675     if (Op.isDead())
676       OS << "dead ";
677     if (Op.isKill())
678       OS << "killed ";
679     if (Op.isUndef())
680       OS << "undef ";
681     if (Op.isEarlyClobber())
682       OS << "early-clobber ";
683     if (Op.isDebug())
684       OS << "debug-use ";
685     printReg(Op.getReg(), OS, TRI);
686     // Print the sub register.
687     if (Op.getSubReg() != 0)
688       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
689     break;
690   case MachineOperand::MO_Immediate:
691     OS << Op.getImm();
692     break;
693   case MachineOperand::MO_CImmediate:
694     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
695     break;
696   case MachineOperand::MO_FPImmediate:
697     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
698     break;
699   case MachineOperand::MO_MachineBasicBlock:
700     printMBBReference(*Op.getMBB());
701     break;
702   case MachineOperand::MO_FrameIndex:
703     printStackObjectReference(Op.getIndex());
704     break;
705   case MachineOperand::MO_ConstantPoolIndex:
706     OS << "%const." << Op.getIndex();
707     printOffset(Op.getOffset());
708     break;
709   case MachineOperand::MO_TargetIndex: {
710     OS << "target-index(";
711     if (const auto *Name = getTargetIndexName(
712             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
713       OS << Name;
714     else
715       OS << "<unknown>";
716     OS << ')';
717     printOffset(Op.getOffset());
718     break;
719   }
720   case MachineOperand::MO_JumpTableIndex:
721     OS << "%jump-table." << Op.getIndex();
722     break;
723   case MachineOperand::MO_ExternalSymbol:
724     OS << '$';
725     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
726     printOffset(Op.getOffset());
727     break;
728   case MachineOperand::MO_GlobalAddress:
729     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
730     printOffset(Op.getOffset());
731     break;
732   case MachineOperand::MO_BlockAddress:
733     OS << "blockaddress(";
734     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
735                                                         MST);
736     OS << ", ";
737     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
738     OS << ')';
739     printOffset(Op.getOffset());
740     break;
741   case MachineOperand::MO_RegisterMask: {
742     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
743     if (RegMaskInfo != RegisterMaskIds.end())
744       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
745     else
746       llvm_unreachable("Can't print this machine register mask yet.");
747     break;
748   }
749   case MachineOperand::MO_RegisterLiveOut: {
750     const uint32_t *RegMask = Op.getRegLiveOut();
751     OS << "liveout(";
752     bool IsCommaNeeded = false;
753     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
754       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
755         if (IsCommaNeeded)
756           OS << ", ";
757         printReg(Reg, OS, TRI);
758         IsCommaNeeded = true;
759       }
760     }
761     OS << ")";
762     break;
763   }
764   case MachineOperand::MO_Metadata:
765     Op.getMetadata()->printAsOperand(OS, MST);
766     break;
767   case MachineOperand::MO_CFIIndex: {
768     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
769     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
770     break;
771   }
772   default:
773     // TODO: Print the other machine operands.
774     llvm_unreachable("Can't print this machine operand at the moment");
775   }
776 }
777
778 void MIPrinter::print(const MachineMemOperand &Op) {
779   OS << '(';
780   // TODO: Print operand's target specific flags.
781   if (Op.isVolatile())
782     OS << "volatile ";
783   if (Op.isNonTemporal())
784     OS << "non-temporal ";
785   if (Op.isInvariant())
786     OS << "invariant ";
787   if (Op.isLoad())
788     OS << "load ";
789   else {
790     assert(Op.isStore() && "Non load machine operand must be a store");
791     OS << "store ";
792   }
793   OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
794   if (const Value *Val = Op.getValue()) {
795     printIRValueReference(*Val);
796   } else {
797     const PseudoSourceValue *PVal = Op.getPseudoValue();
798     assert(PVal && "Expected a pseudo source value");
799     switch (PVal->kind()) {
800     case PseudoSourceValue::Stack:
801       OS << "stack";
802       break;
803     case PseudoSourceValue::GOT:
804       OS << "got";
805       break;
806     case PseudoSourceValue::JumpTable:
807       OS << "jump-table";
808       break;
809     case PseudoSourceValue::ConstantPool:
810       OS << "constant-pool";
811       break;
812     case PseudoSourceValue::FixedStack:
813       printStackObjectReference(
814           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
815       break;
816     case PseudoSourceValue::GlobalValueCallEntry:
817       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
818           OS, /*PrintType=*/false, MST);
819       break;
820     case PseudoSourceValue::ExternalSymbolCallEntry:
821       OS << '$';
822       printLLVMNameWithoutPrefix(
823           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
824       break;
825     }
826   }
827   printOffset(Op.getOffset());
828   if (Op.getBaseAlignment() != Op.getSize())
829     OS << ", align " << Op.getBaseAlignment();
830   auto AAInfo = Op.getAAInfo();
831   if (AAInfo.TBAA) {
832     OS << ", !tbaa ";
833     AAInfo.TBAA->printAsOperand(OS, MST);
834   }
835   if (AAInfo.Scope) {
836     OS << ", !alias.scope ";
837     AAInfo.Scope->printAsOperand(OS, MST);
838   }
839   if (AAInfo.NoAlias) {
840     OS << ", !noalias ";
841     AAInfo.NoAlias->printAsOperand(OS, MST);
842   }
843   if (Op.getRanges()) {
844     OS << ", !range ";
845     Op.getRanges()->printAsOperand(OS, MST);
846   }
847   OS << ')';
848 }
849
850 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
851                              const TargetRegisterInfo *TRI) {
852   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
853   if (Reg == -1) {
854     OS << "<badreg>";
855     return;
856   }
857   printReg(Reg, OS, TRI);
858 }
859
860 void MIPrinter::print(const MCCFIInstruction &CFI,
861                       const TargetRegisterInfo *TRI) {
862   switch (CFI.getOperation()) {
863   case MCCFIInstruction::OpSameValue:
864     OS << ".cfi_same_value ";
865     if (CFI.getLabel())
866       OS << "<mcsymbol> ";
867     printCFIRegister(CFI.getRegister(), OS, TRI);
868     break;
869   case MCCFIInstruction::OpOffset:
870     OS << ".cfi_offset ";
871     if (CFI.getLabel())
872       OS << "<mcsymbol> ";
873     printCFIRegister(CFI.getRegister(), OS, TRI);
874     OS << ", " << CFI.getOffset();
875     break;
876   case MCCFIInstruction::OpDefCfaRegister:
877     OS << ".cfi_def_cfa_register ";
878     if (CFI.getLabel())
879       OS << "<mcsymbol> ";
880     printCFIRegister(CFI.getRegister(), OS, TRI);
881     break;
882   case MCCFIInstruction::OpDefCfaOffset:
883     OS << ".cfi_def_cfa_offset ";
884     if (CFI.getLabel())
885       OS << "<mcsymbol> ";
886     OS << CFI.getOffset();
887     break;
888   case MCCFIInstruction::OpDefCfa:
889     OS << ".cfi_def_cfa ";
890     if (CFI.getLabel())
891       OS << "<mcsymbol> ";
892     printCFIRegister(CFI.getRegister(), OS, TRI);
893     OS << ", " << CFI.getOffset();
894     break;
895   default:
896     // TODO: Print the other CFI Operations.
897     OS << "<unserializable cfi operation>";
898     break;
899   }
900 }
901
902 void llvm::printMIR(raw_ostream &OS, const Module &M) {
903   yaml::Output Out(OS);
904   Out << const_cast<Module &>(M);
905 }
906
907 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
908   MIRPrinter Printer(OS);
909   Printer.print(MF);
910 }