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