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