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