MIR Printer: Remove an outdated TODO comment and assertion. NFC.
[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/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MIRYamlMapping.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IRPrintingPasses.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ModuleSlotTracker.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 /// This structure describes how to print out stack object references.
39 struct FrameIndexOperand {
40   std::string Name;
41   unsigned ID;
42   bool IsFixed;
43
44   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
45       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
46
47   /// Return an ordinary stack object reference.
48   static FrameIndexOperand create(StringRef Name, unsigned ID) {
49     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
50   }
51
52   /// Return a fixed stack object reference.
53   static FrameIndexOperand createFixed(unsigned ID) {
54     return FrameIndexOperand("", ID, /*IsFixed=*/true);
55   }
56 };
57
58 /// This class prints out the machine functions using the MIR serialization
59 /// format.
60 class MIRPrinter {
61   raw_ostream &OS;
62   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
63   /// Maps from stack object indices to operand indices which will be used when
64   /// printing frame index machine operands.
65   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
66
67 public:
68   MIRPrinter(raw_ostream &OS) : OS(OS) {}
69
70   void print(const MachineFunction &MF);
71
72   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
73                const TargetRegisterInfo *TRI);
74   void convert(yaml::MachineFrameInfo &YamlMFI, const MachineFrameInfo &MFI);
75   void convert(yaml::MachineFunction &MF,
76                const MachineConstantPool &ConstantPool);
77   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
78                const MachineJumpTableInfo &JTI);
79   void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
80                const MachineBasicBlock &MBB);
81   void convertStackObjects(yaml::MachineFunction &MF,
82                            const MachineFrameInfo &MFI,
83                            const TargetRegisterInfo *TRI);
84
85 private:
86   void initRegisterMaskIds(const MachineFunction &MF);
87 };
88
89 /// This class prints out the machine instructions using the MIR serialization
90 /// format.
91 class MIPrinter {
92   raw_ostream &OS;
93   ModuleSlotTracker &MST;
94   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
95   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
96
97 public:
98   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
99             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
100             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
101       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
102         StackObjectOperandMapping(StackObjectOperandMapping) {}
103
104   void print(const MachineInstr &MI);
105   void printMBBReference(const MachineBasicBlock &MBB);
106   void printStackObjectReference(int FrameIndex);
107   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
108
109   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
110 };
111
112 } // end anonymous namespace
113
114 namespace llvm {
115 namespace yaml {
116
117 /// This struct serializes the LLVM IR module.
118 template <> struct BlockScalarTraits<Module> {
119   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
120     Mod.print(OS, nullptr);
121   }
122   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
123     llvm_unreachable("LLVM Module is supposed to be parsed separately");
124     return "";
125   }
126 };
127
128 } // end namespace yaml
129 } // end namespace llvm
130
131 static void printReg(unsigned Reg, raw_ostream &OS,
132                      const TargetRegisterInfo *TRI) {
133   // TODO: Print Stack Slots.
134   if (!Reg)
135     OS << '_';
136   else if (TargetRegisterInfo::isVirtualRegister(Reg))
137     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
138   else if (Reg < TRI->getNumRegs())
139     OS << '%' << StringRef(TRI->getName(Reg)).lower();
140   else
141     llvm_unreachable("Can't print this kind of register yet");
142 }
143
144 static void printReg(unsigned Reg, yaml::StringValue &Dest,
145                      const TargetRegisterInfo *TRI) {
146   raw_string_ostream OS(Dest.Value);
147   printReg(Reg, OS, TRI);
148 }
149
150 void MIRPrinter::print(const MachineFunction &MF) {
151   initRegisterMaskIds(MF);
152
153   yaml::MachineFunction YamlMF;
154   YamlMF.Name = MF.getName();
155   YamlMF.Alignment = MF.getAlignment();
156   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
157   YamlMF.HasInlineAsm = MF.hasInlineAsm();
158   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
159   convert(YamlMF.FrameInfo, *MF.getFrameInfo());
160   convertStackObjects(YamlMF, *MF.getFrameInfo(),
161                       MF.getSubtarget().getRegisterInfo());
162   if (const auto *ConstantPool = MF.getConstantPool())
163     convert(YamlMF, *ConstantPool);
164
165   ModuleSlotTracker MST(MF.getFunction()->getParent());
166   MST.incorporateFunction(*MF.getFunction());
167   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
168     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
169   for (const auto &MBB : MF) {
170     yaml::MachineBasicBlock YamlMBB;
171     convert(MST, YamlMBB, MBB);
172     YamlMF.BasicBlocks.push_back(YamlMBB);
173   }
174   yaml::Output Out(OS);
175   Out << YamlMF;
176 }
177
178 void MIRPrinter::convert(yaml::MachineFunction &MF,
179                          const MachineRegisterInfo &RegInfo,
180                          const TargetRegisterInfo *TRI) {
181   MF.IsSSA = RegInfo.isSSA();
182   MF.TracksRegLiveness = RegInfo.tracksLiveness();
183   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
184
185   // Print the virtual register definitions.
186   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
187     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
188     yaml::VirtualRegisterDefinition VReg;
189     VReg.ID = I;
190     VReg.Class =
191         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
192     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
193     if (PreferredReg)
194       printReg(PreferredReg, VReg.PreferredRegister, TRI);
195     MF.VirtualRegisters.push_back(VReg);
196   }
197
198   // Print the live ins.
199   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
200     yaml::MachineFunctionLiveIn LiveIn;
201     printReg(I->first, LiveIn.Register, TRI);
202     if (I->second)
203       printReg(I->second, LiveIn.VirtualRegister, TRI);
204     MF.LiveIns.push_back(LiveIn);
205   }
206 }
207
208 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
209                          const MachineFrameInfo &MFI) {
210   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
211   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
212   YamlMFI.HasStackMap = MFI.hasStackMap();
213   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
214   YamlMFI.StackSize = MFI.getStackSize();
215   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
216   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
217   YamlMFI.AdjustsStack = MFI.adjustsStack();
218   YamlMFI.HasCalls = MFI.hasCalls();
219   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
220   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
221   YamlMFI.HasVAStart = MFI.hasVAStart();
222   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
223 }
224
225 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
226                                      const MachineFrameInfo &MFI,
227                                      const TargetRegisterInfo *TRI) {
228   // Process fixed stack objects.
229   unsigned ID = 0;
230   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
231     if (MFI.isDeadObjectIndex(I))
232       continue;
233
234     yaml::FixedMachineStackObject YamlObject;
235     YamlObject.ID = ID;
236     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
237                           ? yaml::FixedMachineStackObject::SpillSlot
238                           : yaml::FixedMachineStackObject::DefaultType;
239     YamlObject.Offset = MFI.getObjectOffset(I);
240     YamlObject.Size = MFI.getObjectSize(I);
241     YamlObject.Alignment = MFI.getObjectAlignment(I);
242     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
243     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
244     MF.FixedStackObjects.push_back(YamlObject);
245     StackObjectOperandMapping.insert(
246         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
247   }
248
249   // Process ordinary stack objects.
250   ID = 0;
251   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
252     if (MFI.isDeadObjectIndex(I))
253       continue;
254
255     yaml::MachineStackObject YamlObject;
256     YamlObject.ID = ID;
257     if (const auto *Alloca = MFI.getObjectAllocation(I))
258       YamlObject.Name.Value =
259           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
260     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
261                           ? yaml::MachineStackObject::SpillSlot
262                           : MFI.isVariableSizedObjectIndex(I)
263                                 ? yaml::MachineStackObject::VariableSized
264                                 : yaml::MachineStackObject::DefaultType;
265     YamlObject.Offset = MFI.getObjectOffset(I);
266     YamlObject.Size = MFI.getObjectSize(I);
267     YamlObject.Alignment = MFI.getObjectAlignment(I);
268
269     MF.StackObjects.push_back(YamlObject);
270     StackObjectOperandMapping.insert(std::make_pair(
271         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
272   }
273
274   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
275     yaml::StringValue Reg;
276     printReg(CSInfo.getReg(), Reg, TRI);
277     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
278     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
279            "Invalid stack object index");
280     const FrameIndexOperand &StackObject = StackObjectInfo->second;
281     if (StackObject.IsFixed)
282       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
283     else
284       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
285   }
286 }
287
288 void MIRPrinter::convert(yaml::MachineFunction &MF,
289                          const MachineConstantPool &ConstantPool) {
290   unsigned ID = 0;
291   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
292     // TODO: Serialize target specific constant pool entries.
293     if (Constant.isMachineConstantPoolEntry())
294       llvm_unreachable("Can't print target specific constant pool entries yet");
295
296     yaml::MachineConstantPoolValue YamlConstant;
297     std::string Str;
298     raw_string_ostream StrOS(Str);
299     Constant.Val.ConstVal->printAsOperand(StrOS);
300     YamlConstant.ID = ID++;
301     YamlConstant.Value = StrOS.str();
302     YamlConstant.Alignment = Constant.getAlignment();
303     MF.Constants.push_back(YamlConstant);
304   }
305 }
306
307 void MIRPrinter::convert(ModuleSlotTracker &MST,
308                          yaml::MachineJumpTable &YamlJTI,
309                          const MachineJumpTableInfo &JTI) {
310   YamlJTI.Kind = JTI.getEntryKind();
311   unsigned ID = 0;
312   for (const auto &Table : JTI.getJumpTables()) {
313     std::string Str;
314     yaml::MachineJumpTable::Entry Entry;
315     Entry.ID = ID++;
316     for (const auto *MBB : Table.MBBs) {
317       raw_string_ostream StrOS(Str);
318       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
319           .printMBBReference(*MBB);
320       Entry.Blocks.push_back(StrOS.str());
321       Str.clear();
322     }
323     YamlJTI.Entries.push_back(Entry);
324   }
325 }
326
327 void MIRPrinter::convert(ModuleSlotTracker &MST,
328                          yaml::MachineBasicBlock &YamlMBB,
329                          const MachineBasicBlock &MBB) {
330   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
331   YamlMBB.ID = (unsigned)MBB.getNumber();
332   if (const auto *BB = MBB.getBasicBlock()) {
333     if (BB->hasName()) {
334       YamlMBB.Name.Value = BB->getName();
335     } else {
336       int Slot = MST.getLocalSlot(BB);
337       if (Slot == -1)
338         YamlMBB.IRBlock.Value = "<badref>";
339       else
340         YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
341     }
342   }
343   YamlMBB.Alignment = MBB.getAlignment();
344   YamlMBB.AddressTaken = MBB.hasAddressTaken();
345   YamlMBB.IsLandingPad = MBB.isLandingPad();
346   for (const auto *SuccMBB : MBB.successors()) {
347     std::string Str;
348     raw_string_ostream StrOS(Str);
349     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
350         .printMBBReference(*SuccMBB);
351     YamlMBB.Successors.push_back(StrOS.str());
352   }
353   // Print the live in registers.
354   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
355   assert(TRI && "Expected target register info");
356   for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
357     std::string Str;
358     raw_string_ostream StrOS(Str);
359     printReg(*I, StrOS, TRI);
360     YamlMBB.LiveIns.push_back(StrOS.str());
361   }
362   // Print the machine instructions.
363   YamlMBB.Instructions.reserve(MBB.size());
364   std::string Str;
365   for (const auto &MI : MBB) {
366     raw_string_ostream StrOS(Str);
367     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
368     YamlMBB.Instructions.push_back(StrOS.str());
369     Str.clear();
370   }
371 }
372
373 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
374   const auto *TRI = MF.getSubtarget().getRegisterInfo();
375   unsigned I = 0;
376   for (const uint32_t *Mask : TRI->getRegMasks())
377     RegisterMaskIds.insert(std::make_pair(Mask, I++));
378 }
379
380 void MIPrinter::print(const MachineInstr &MI) {
381   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
382   const auto *TRI = SubTarget.getRegisterInfo();
383   assert(TRI && "Expected target register info");
384   const auto *TII = SubTarget.getInstrInfo();
385   assert(TII && "Expected target instruction info");
386   if (MI.isCFIInstruction())
387     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
388
389   unsigned I = 0, E = MI.getNumOperands();
390   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
391          !MI.getOperand(I).isImplicit();
392        ++I) {
393     if (I)
394       OS << ", ";
395     print(MI.getOperand(I), TRI);
396   }
397
398   if (I)
399     OS << " = ";
400   if (MI.getFlag(MachineInstr::FrameSetup))
401     OS << "frame-setup ";
402   OS << TII->getName(MI.getOpcode());
403   // TODO: Print the bundling instruction flags, machine mem operands.
404   if (I < E)
405     OS << ' ';
406
407   bool NeedComma = false;
408   for (; I < E; ++I) {
409     if (NeedComma)
410       OS << ", ";
411     print(MI.getOperand(I), TRI);
412     NeedComma = true;
413   }
414
415   if (MI.getDebugLoc()) {
416     if (NeedComma)
417       OS << ',';
418     OS << " debug-location ";
419     MI.getDebugLoc()->printAsOperand(OS, MST);
420   }
421 }
422
423 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
424   OS << "%bb." << MBB.getNumber();
425   if (const auto *BB = MBB.getBasicBlock()) {
426     if (BB->hasName())
427       OS << '.' << BB->getName();
428   }
429 }
430
431 void MIPrinter::printStackObjectReference(int FrameIndex) {
432   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
433   assert(ObjectInfo != StackObjectOperandMapping.end() &&
434          "Invalid frame index");
435   const FrameIndexOperand &Operand = ObjectInfo->second;
436   if (Operand.IsFixed) {
437     OS << "%fixed-stack." << Operand.ID;
438     return;
439   }
440   OS << "%stack." << Operand.ID;
441   if (!Operand.Name.empty())
442     OS << '.' << Operand.Name;
443 }
444
445 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
446   switch (Op.getType()) {
447   case MachineOperand::MO_Register:
448     // TODO: Print the other register flags.
449     if (Op.isImplicit())
450       OS << (Op.isDef() ? "implicit-def " : "implicit ");
451     if (Op.isDead())
452       OS << "dead ";
453     if (Op.isKill())
454       OS << "killed ";
455     if (Op.isUndef())
456       OS << "undef ";
457     printReg(Op.getReg(), OS, TRI);
458     // Print the sub register.
459     if (Op.getSubReg() != 0)
460       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
461     break;
462   case MachineOperand::MO_Immediate:
463     OS << Op.getImm();
464     break;
465   case MachineOperand::MO_MachineBasicBlock:
466     printMBBReference(*Op.getMBB());
467     break;
468   case MachineOperand::MO_FrameIndex:
469     printStackObjectReference(Op.getIndex());
470     break;
471   case MachineOperand::MO_ConstantPoolIndex:
472     OS << "%const." << Op.getIndex();
473     // TODO: Print offset and target flags.
474     break;
475   case MachineOperand::MO_JumpTableIndex:
476     OS << "%jump-table." << Op.getIndex();
477     // TODO: Print target flags.
478     break;
479   case MachineOperand::MO_ExternalSymbol:
480     OS << '$';
481     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
482     // TODO: Print the target flags.
483     break;
484   case MachineOperand::MO_GlobalAddress:
485     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
486     // TODO: Print offset and target flags.
487     break;
488   case MachineOperand::MO_RegisterMask: {
489     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
490     if (RegMaskInfo != RegisterMaskIds.end())
491       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
492     else
493       llvm_unreachable("Can't print this machine register mask yet.");
494     break;
495   }
496   case MachineOperand::MO_Metadata:
497     Op.getMetadata()->printAsOperand(OS, MST);
498     break;
499   case MachineOperand::MO_CFIIndex: {
500     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
501     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
502     break;
503   }
504   default:
505     // TODO: Print the other machine operands.
506     llvm_unreachable("Can't print this machine operand at the moment");
507   }
508 }
509
510 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
511                              const TargetRegisterInfo *TRI) {
512   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
513   if (Reg == -1) {
514     OS << "<badreg>";
515     return;
516   }
517   printReg(Reg, OS, TRI);
518 }
519
520 void MIPrinter::print(const MCCFIInstruction &CFI,
521                       const TargetRegisterInfo *TRI) {
522   switch (CFI.getOperation()) {
523   case MCCFIInstruction::OpOffset:
524     OS << ".cfi_offset ";
525     if (CFI.getLabel())
526       OS << "<mcsymbol> ";
527     printCFIRegister(CFI.getRegister(), OS, TRI);
528     OS << ", " << CFI.getOffset();
529     break;
530   case MCCFIInstruction::OpDefCfaRegister:
531     OS << ".cfi_def_cfa_register ";
532     if (CFI.getLabel())
533       OS << "<mcsymbol> ";
534     printCFIRegister(CFI.getRegister(), OS, TRI);
535     break;
536   case MCCFIInstruction::OpDefCfaOffset:
537     OS << ".cfi_def_cfa_offset ";
538     if (CFI.getLabel())
539       OS << "<mcsymbol> ";
540     OS << CFI.getOffset();
541     break;
542   default:
543     // TODO: Print the other CFI Operations.
544     OS << "<unserializable cfi operation>";
545     break;
546   }
547 }
548
549 void llvm::printMIR(raw_ostream &OS, const Module &M) {
550   yaml::Output Out(OS);
551   Out << const_cast<Module &>(M);
552 }
553
554 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
555   MIRPrinter Printer(OS);
556   Printer.print(MF);
557 }