MIR Serialization: Serialize the machine operand's offset.
[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 convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
87                const MachineBasicBlock &MBB);
88   void convertStackObjects(yaml::MachineFunction &MF,
89                            const MachineFrameInfo &MFI,
90                            const TargetRegisterInfo *TRI);
91
92 private:
93   void initRegisterMaskIds(const MachineFunction &MF);
94 };
95
96 } // end namespace llvm
97
98 namespace {
99
100 /// This class prints out the machine instructions using the MIR serialization
101 /// format.
102 class MIPrinter {
103   raw_ostream &OS;
104   ModuleSlotTracker &MST;
105   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
106   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
107
108 public:
109   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
110             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
111             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
112       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
113         StackObjectOperandMapping(StackObjectOperandMapping) {}
114
115   void print(const MachineInstr &MI);
116   void printMBBReference(const MachineBasicBlock &MBB);
117   void printIRBlockReference(const BasicBlock &BB);
118   void printIRValueReference(const Value &V);
119   void printStackObjectReference(int FrameIndex);
120   void printOffset(int64_t Offset);
121   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
122   void print(const MachineMemOperand &Op);
123
124   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
125 };
126
127 } // end anonymous namespace
128
129 namespace llvm {
130 namespace yaml {
131
132 /// This struct serializes the LLVM IR module.
133 template <> struct BlockScalarTraits<Module> {
134   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
135     Mod.print(OS, nullptr);
136   }
137   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
138     llvm_unreachable("LLVM Module is supposed to be parsed separately");
139     return "";
140   }
141 };
142
143 } // end namespace yaml
144 } // end namespace llvm
145
146 static void printReg(unsigned Reg, raw_ostream &OS,
147                      const TargetRegisterInfo *TRI) {
148   // TODO: Print Stack Slots.
149   if (!Reg)
150     OS << '_';
151   else if (TargetRegisterInfo::isVirtualRegister(Reg))
152     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
153   else if (Reg < TRI->getNumRegs())
154     OS << '%' << StringRef(TRI->getName(Reg)).lower();
155   else
156     llvm_unreachable("Can't print this kind of register yet");
157 }
158
159 static void printReg(unsigned Reg, yaml::StringValue &Dest,
160                      const TargetRegisterInfo *TRI) {
161   raw_string_ostream OS(Dest.Value);
162   printReg(Reg, OS, TRI);
163 }
164
165 void MIRPrinter::print(const MachineFunction &MF) {
166   initRegisterMaskIds(MF);
167
168   yaml::MachineFunction YamlMF;
169   YamlMF.Name = MF.getName();
170   YamlMF.Alignment = MF.getAlignment();
171   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
172   YamlMF.HasInlineAsm = MF.hasInlineAsm();
173   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
174   ModuleSlotTracker MST(MF.getFunction()->getParent());
175   MST.incorporateFunction(*MF.getFunction());
176   convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
177   convertStackObjects(YamlMF, *MF.getFrameInfo(),
178                       MF.getSubtarget().getRegisterInfo());
179   if (const auto *ConstantPool = MF.getConstantPool())
180     convert(YamlMF, *ConstantPool);
181   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
182     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
183   for (const auto &MBB : MF) {
184     yaml::MachineBasicBlock YamlMBB;
185     convert(MST, YamlMBB, MBB);
186     YamlMF.BasicBlocks.push_back(YamlMBB);
187   }
188   yaml::Output Out(OS);
189   Out << YamlMF;
190 }
191
192 void MIRPrinter::convert(yaml::MachineFunction &MF,
193                          const MachineRegisterInfo &RegInfo,
194                          const TargetRegisterInfo *TRI) {
195   MF.IsSSA = RegInfo.isSSA();
196   MF.TracksRegLiveness = RegInfo.tracksLiveness();
197   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
198
199   // Print the virtual register definitions.
200   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
201     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
202     yaml::VirtualRegisterDefinition VReg;
203     VReg.ID = I;
204     VReg.Class =
205         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
206     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
207     if (PreferredReg)
208       printReg(PreferredReg, VReg.PreferredRegister, TRI);
209     MF.VirtualRegisters.push_back(VReg);
210   }
211
212   // Print the live ins.
213   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
214     yaml::MachineFunctionLiveIn LiveIn;
215     printReg(I->first, LiveIn.Register, TRI);
216     if (I->second)
217       printReg(I->second, LiveIn.VirtualRegister, TRI);
218     MF.LiveIns.push_back(LiveIn);
219   }
220 }
221
222 void MIRPrinter::convert(ModuleSlotTracker &MST,
223                          yaml::MachineFrameInfo &YamlMFI,
224                          const MachineFrameInfo &MFI) {
225   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
226   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
227   YamlMFI.HasStackMap = MFI.hasStackMap();
228   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
229   YamlMFI.StackSize = MFI.getStackSize();
230   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
231   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
232   YamlMFI.AdjustsStack = MFI.adjustsStack();
233   YamlMFI.HasCalls = MFI.hasCalls();
234   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
235   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
236   YamlMFI.HasVAStart = MFI.hasVAStart();
237   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
238   if (MFI.getSavePoint()) {
239     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
240     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
241         .printMBBReference(*MFI.getSavePoint());
242   }
243   if (MFI.getRestorePoint()) {
244     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
245     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
246         .printMBBReference(*MFI.getRestorePoint());
247   }
248 }
249
250 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
251                                      const MachineFrameInfo &MFI,
252                                      const TargetRegisterInfo *TRI) {
253   // Process fixed stack objects.
254   unsigned ID = 0;
255   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
256     if (MFI.isDeadObjectIndex(I))
257       continue;
258
259     yaml::FixedMachineStackObject YamlObject;
260     YamlObject.ID = ID;
261     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
262                           ? yaml::FixedMachineStackObject::SpillSlot
263                           : yaml::FixedMachineStackObject::DefaultType;
264     YamlObject.Offset = MFI.getObjectOffset(I);
265     YamlObject.Size = MFI.getObjectSize(I);
266     YamlObject.Alignment = MFI.getObjectAlignment(I);
267     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
268     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
269     MF.FixedStackObjects.push_back(YamlObject);
270     StackObjectOperandMapping.insert(
271         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
272   }
273
274   // Process ordinary stack objects.
275   ID = 0;
276   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
277     if (MFI.isDeadObjectIndex(I))
278       continue;
279
280     yaml::MachineStackObject YamlObject;
281     YamlObject.ID = ID;
282     if (const auto *Alloca = MFI.getObjectAllocation(I))
283       YamlObject.Name.Value =
284           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
285     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
286                           ? yaml::MachineStackObject::SpillSlot
287                           : MFI.isVariableSizedObjectIndex(I)
288                                 ? yaml::MachineStackObject::VariableSized
289                                 : yaml::MachineStackObject::DefaultType;
290     YamlObject.Offset = MFI.getObjectOffset(I);
291     YamlObject.Size = MFI.getObjectSize(I);
292     YamlObject.Alignment = MFI.getObjectAlignment(I);
293
294     MF.StackObjects.push_back(YamlObject);
295     StackObjectOperandMapping.insert(std::make_pair(
296         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
297   }
298
299   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
300     yaml::StringValue Reg;
301     printReg(CSInfo.getReg(), Reg, TRI);
302     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
303     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
304            "Invalid stack object index");
305     const FrameIndexOperand &StackObject = StackObjectInfo->second;
306     if (StackObject.IsFixed)
307       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
308     else
309       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
310   }
311 }
312
313 void MIRPrinter::convert(yaml::MachineFunction &MF,
314                          const MachineConstantPool &ConstantPool) {
315   unsigned ID = 0;
316   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
317     // TODO: Serialize target specific constant pool entries.
318     if (Constant.isMachineConstantPoolEntry())
319       llvm_unreachable("Can't print target specific constant pool entries yet");
320
321     yaml::MachineConstantPoolValue YamlConstant;
322     std::string Str;
323     raw_string_ostream StrOS(Str);
324     Constant.Val.ConstVal->printAsOperand(StrOS);
325     YamlConstant.ID = ID++;
326     YamlConstant.Value = StrOS.str();
327     YamlConstant.Alignment = Constant.getAlignment();
328     MF.Constants.push_back(YamlConstant);
329   }
330 }
331
332 void MIRPrinter::convert(ModuleSlotTracker &MST,
333                          yaml::MachineJumpTable &YamlJTI,
334                          const MachineJumpTableInfo &JTI) {
335   YamlJTI.Kind = JTI.getEntryKind();
336   unsigned ID = 0;
337   for (const auto &Table : JTI.getJumpTables()) {
338     std::string Str;
339     yaml::MachineJumpTable::Entry Entry;
340     Entry.ID = ID++;
341     for (const auto *MBB : Table.MBBs) {
342       raw_string_ostream StrOS(Str);
343       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
344           .printMBBReference(*MBB);
345       Entry.Blocks.push_back(StrOS.str());
346       Str.clear();
347     }
348     YamlJTI.Entries.push_back(Entry);
349   }
350 }
351
352 void MIRPrinter::convert(ModuleSlotTracker &MST,
353                          yaml::MachineBasicBlock &YamlMBB,
354                          const MachineBasicBlock &MBB) {
355   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
356   YamlMBB.ID = (unsigned)MBB.getNumber();
357   if (const auto *BB = MBB.getBasicBlock()) {
358     if (BB->hasName()) {
359       YamlMBB.Name.Value = BB->getName();
360     } else {
361       int Slot = MST.getLocalSlot(BB);
362       if (Slot == -1)
363         YamlMBB.IRBlock.Value = "<badref>";
364       else
365         YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
366     }
367   }
368   YamlMBB.Alignment = MBB.getAlignment();
369   YamlMBB.AddressTaken = MBB.hasAddressTaken();
370   YamlMBB.IsLandingPad = MBB.isLandingPad();
371   for (const auto *SuccMBB : MBB.successors()) {
372     std::string Str;
373     raw_string_ostream StrOS(Str);
374     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
375         .printMBBReference(*SuccMBB);
376     YamlMBB.Successors.push_back(StrOS.str());
377   }
378   if (MBB.hasSuccessorWeights()) {
379     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I)
380       YamlMBB.SuccessorWeights.push_back(
381           yaml::UnsignedValue(MBB.getSuccWeight(I)));
382   }
383   // Print the live in registers.
384   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
385   assert(TRI && "Expected target register info");
386   for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
387     std::string Str;
388     raw_string_ostream StrOS(Str);
389     printReg(*I, StrOS, TRI);
390     YamlMBB.LiveIns.push_back(StrOS.str());
391   }
392   // Print the machine instructions.
393   YamlMBB.Instructions.reserve(MBB.size());
394   std::string Str;
395   for (const auto &MI : MBB) {
396     raw_string_ostream StrOS(Str);
397     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
398     YamlMBB.Instructions.push_back(StrOS.str());
399     Str.clear();
400   }
401 }
402
403 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
404   const auto *TRI = MF.getSubtarget().getRegisterInfo();
405   unsigned I = 0;
406   for (const uint32_t *Mask : TRI->getRegMasks())
407     RegisterMaskIds.insert(std::make_pair(Mask, I++));
408 }
409
410 void MIPrinter::print(const MachineInstr &MI) {
411   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
412   const auto *TRI = SubTarget.getRegisterInfo();
413   assert(TRI && "Expected target register info");
414   const auto *TII = SubTarget.getInstrInfo();
415   assert(TII && "Expected target instruction info");
416   if (MI.isCFIInstruction())
417     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
418
419   unsigned I = 0, E = MI.getNumOperands();
420   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
421          !MI.getOperand(I).isImplicit();
422        ++I) {
423     if (I)
424       OS << ", ";
425     print(MI.getOperand(I), TRI);
426   }
427
428   if (I)
429     OS << " = ";
430   if (MI.getFlag(MachineInstr::FrameSetup))
431     OS << "frame-setup ";
432   OS << TII->getName(MI.getOpcode());
433   // TODO: Print the bundling instruction flags.
434   if (I < E)
435     OS << ' ';
436
437   bool NeedComma = false;
438   for (; I < E; ++I) {
439     if (NeedComma)
440       OS << ", ";
441     print(MI.getOperand(I), TRI);
442     NeedComma = true;
443   }
444
445   if (MI.getDebugLoc()) {
446     if (NeedComma)
447       OS << ',';
448     OS << " debug-location ";
449     MI.getDebugLoc()->printAsOperand(OS, MST);
450   }
451
452   if (!MI.memoperands_empty()) {
453     OS << " :: ";
454     bool NeedComma = false;
455     for (const auto *Op : MI.memoperands()) {
456       if (NeedComma)
457         OS << ", ";
458       print(*Op);
459       NeedComma = true;
460     }
461   }
462 }
463
464 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
465   OS << "%bb." << MBB.getNumber();
466   if (const auto *BB = MBB.getBasicBlock()) {
467     if (BB->hasName())
468       OS << '.' << BB->getName();
469   }
470 }
471
472 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
473   OS << "%ir-block.";
474   if (BB.hasName()) {
475     printLLVMNameWithoutPrefix(OS, BB.getName());
476     return;
477   }
478   int Slot = MST.getLocalSlot(&BB);
479   if (Slot == -1)
480     OS << "<badref>";
481   else
482     OS << Slot;
483 }
484
485 void MIPrinter::printIRValueReference(const Value &V) {
486   OS << "%ir.";
487   if (V.hasName()) {
488     printLLVMNameWithoutPrefix(OS, V.getName());
489     return;
490   }
491   // TODO: Serialize the unnamed IR value references.
492   OS << "<unserializable ir value>";
493 }
494
495 void MIPrinter::printStackObjectReference(int FrameIndex) {
496   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
497   assert(ObjectInfo != StackObjectOperandMapping.end() &&
498          "Invalid frame index");
499   const FrameIndexOperand &Operand = ObjectInfo->second;
500   if (Operand.IsFixed) {
501     OS << "%fixed-stack." << Operand.ID;
502     return;
503   }
504   OS << "%stack." << Operand.ID;
505   if (!Operand.Name.empty())
506     OS << '.' << Operand.Name;
507 }
508
509 void MIPrinter::printOffset(int64_t Offset) {
510   if (Offset == 0)
511     return;
512   if (Offset < 0) {
513     OS << " - " << -Offset;
514     return;
515   }
516   OS << " + " << Offset;
517 }
518
519 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
520   const auto *TII = MF.getSubtarget().getInstrInfo();
521   assert(TII && "expected instruction info");
522   auto Indices = TII->getSerializableTargetIndices();
523   for (const auto &I : Indices) {
524     if (I.first == Index) {
525       return I.second;
526     }
527   }
528   return nullptr;
529 }
530
531 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
532   switch (Op.getType()) {
533   case MachineOperand::MO_Register:
534     // TODO: Print the other register flags.
535     if (Op.isImplicit())
536       OS << (Op.isDef() ? "implicit-def " : "implicit ");
537     if (Op.isDead())
538       OS << "dead ";
539     if (Op.isKill())
540       OS << "killed ";
541     if (Op.isUndef())
542       OS << "undef ";
543     if (Op.isEarlyClobber())
544       OS << "early-clobber ";
545     if (Op.isDebug())
546       OS << "debug-use ";
547     printReg(Op.getReg(), OS, TRI);
548     // Print the sub register.
549     if (Op.getSubReg() != 0)
550       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
551     break;
552   case MachineOperand::MO_Immediate:
553     OS << Op.getImm();
554     break;
555   case MachineOperand::MO_CImmediate:
556     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
557     break;
558   case MachineOperand::MO_FPImmediate:
559     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
560     break;
561   case MachineOperand::MO_MachineBasicBlock:
562     printMBBReference(*Op.getMBB());
563     break;
564   case MachineOperand::MO_FrameIndex:
565     printStackObjectReference(Op.getIndex());
566     break;
567   case MachineOperand::MO_ConstantPoolIndex:
568     OS << "%const." << Op.getIndex();
569     printOffset(Op.getOffset());
570     // TODO: Print the target flags.
571     break;
572   case MachineOperand::MO_TargetIndex: {
573     OS << "target-index(";
574     if (const auto *Name = getTargetIndexName(
575             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
576       OS << Name;
577     else
578       OS << "<unknown>";
579     OS << ')';
580     printOffset(Op.getOffset());
581     // TODO: Print the target flags.
582     break;
583   }
584   case MachineOperand::MO_JumpTableIndex:
585     OS << "%jump-table." << Op.getIndex();
586     // TODO: Print target flags.
587     break;
588   case MachineOperand::MO_ExternalSymbol:
589     OS << '$';
590     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
591     printOffset(Op.getOffset());
592     // TODO: Print the target flags.
593     break;
594   case MachineOperand::MO_GlobalAddress:
595     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
596     printOffset(Op.getOffset());
597     // TODO: Print the target flags.
598     break;
599   case MachineOperand::MO_BlockAddress:
600     OS << "blockaddress(";
601     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
602                                                         MST);
603     OS << ", ";
604     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
605     OS << ')';
606     printOffset(Op.getOffset());
607     // TODO: Print the target flags.
608     break;
609   case MachineOperand::MO_RegisterMask: {
610     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
611     if (RegMaskInfo != RegisterMaskIds.end())
612       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
613     else
614       llvm_unreachable("Can't print this machine register mask yet.");
615     break;
616   }
617   case MachineOperand::MO_Metadata:
618     Op.getMetadata()->printAsOperand(OS, MST);
619     break;
620   case MachineOperand::MO_CFIIndex: {
621     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
622     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
623     break;
624   }
625   default:
626     // TODO: Print the other machine operands.
627     llvm_unreachable("Can't print this machine operand at the moment");
628   }
629 }
630
631 void MIPrinter::print(const MachineMemOperand &Op) {
632   OS << '(';
633   // TODO: Print operand's other flags.
634   if (Op.isVolatile())
635     OS << "volatile ";
636   if (Op.isLoad())
637     OS << "load ";
638   else {
639     assert(Op.isStore() && "Non load machine operand must be a store");
640     OS << "store ";
641   }
642   OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
643   if (const Value *Val = Op.getValue())
644     printIRValueReference(*Val);
645   // TODO: Print PseudoSourceValue.
646   // TODO: Print the base alignment.
647   // TODO: Print the metadata attributes.
648   OS << ')';
649 }
650
651 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
652                              const TargetRegisterInfo *TRI) {
653   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
654   if (Reg == -1) {
655     OS << "<badreg>";
656     return;
657   }
658   printReg(Reg, OS, TRI);
659 }
660
661 void MIPrinter::print(const MCCFIInstruction &CFI,
662                       const TargetRegisterInfo *TRI) {
663   switch (CFI.getOperation()) {
664   case MCCFIInstruction::OpOffset:
665     OS << ".cfi_offset ";
666     if (CFI.getLabel())
667       OS << "<mcsymbol> ";
668     printCFIRegister(CFI.getRegister(), OS, TRI);
669     OS << ", " << CFI.getOffset();
670     break;
671   case MCCFIInstruction::OpDefCfaRegister:
672     OS << ".cfi_def_cfa_register ";
673     if (CFI.getLabel())
674       OS << "<mcsymbol> ";
675     printCFIRegister(CFI.getRegister(), OS, TRI);
676     break;
677   case MCCFIInstruction::OpDefCfaOffset:
678     OS << ".cfi_def_cfa_offset ";
679     if (CFI.getLabel())
680       OS << "<mcsymbol> ";
681     OS << CFI.getOffset();
682     break;
683   case MCCFIInstruction::OpDefCfa:
684     OS << ".cfi_def_cfa ";
685     if (CFI.getLabel())
686       OS << "<mcsymbol> ";
687     printCFIRegister(CFI.getRegister(), OS, TRI);
688     OS << ", " << CFI.getOffset();
689     break;
690   default:
691     // TODO: Print the other CFI Operations.
692     OS << "<unserializable cfi operation>";
693     break;
694   }
695 }
696
697 void llvm::printMIR(raw_ostream &OS, const Module &M) {
698   yaml::Output Out(OS);
699   Out << const_cast<Module &>(M);
700 }
701
702 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
703   MIRPrinter Printer(OS);
704   Printer.print(MF);
705 }