1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
13 //===----------------------------------------------------------------------===//
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"
38 /// This structure describes how to print out stack object references.
39 struct FrameIndexOperand {
44 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
45 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
47 /// Return an ordinary stack object reference.
48 static FrameIndexOperand create(StringRef Name, unsigned ID) {
49 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
52 /// Return a fixed stack object reference.
53 static FrameIndexOperand createFixed(unsigned ID) {
54 return FrameIndexOperand("", ID, /*IsFixed=*/true);
58 /// This class prints out the machine functions using the MIR serialization
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;
68 MIRPrinter(raw_ostream &OS) : OS(OS) {}
70 void print(const MachineFunction &MF);
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);
85 void initRegisterMaskIds(const MachineFunction &MF);
88 /// This class prints out the machine instructions using the MIR serialization
92 ModuleSlotTracker &MST;
93 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
94 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
97 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
98 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
99 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
100 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
101 StackObjectOperandMapping(StackObjectOperandMapping) {}
103 void print(const MachineInstr &MI);
104 void printMBBReference(const MachineBasicBlock &MBB);
105 void printStackObjectReference(int FrameIndex);
106 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
108 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
111 } // end anonymous namespace
116 /// This struct serializes the LLVM IR module.
117 template <> struct BlockScalarTraits<Module> {
118 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
119 Mod.print(OS, nullptr);
121 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
122 llvm_unreachable("LLVM Module is supposed to be parsed separately");
127 } // end namespace yaml
128 } // end namespace llvm
130 static void printReg(unsigned Reg, raw_ostream &OS,
131 const TargetRegisterInfo *TRI) {
132 // TODO: Print Stack Slots.
135 else if (TargetRegisterInfo::isVirtualRegister(Reg))
136 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
137 else if (Reg < TRI->getNumRegs())
138 OS << '%' << StringRef(TRI->getName(Reg)).lower();
140 llvm_unreachable("Can't print this kind of register yet");
143 static void printReg(unsigned Reg, yaml::StringValue &Dest,
144 const TargetRegisterInfo *TRI) {
145 raw_string_ostream OS(Dest.Value);
146 printReg(Reg, OS, TRI);
149 void MIRPrinter::print(const MachineFunction &MF) {
150 initRegisterMaskIds(MF);
152 yaml::MachineFunction YamlMF;
153 YamlMF.Name = MF.getName();
154 YamlMF.Alignment = MF.getAlignment();
155 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
156 YamlMF.HasInlineAsm = MF.hasInlineAsm();
157 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
158 convert(YamlMF.FrameInfo, *MF.getFrameInfo());
159 convertStackObjects(YamlMF, *MF.getFrameInfo());
160 if (const auto *ConstantPool = MF.getConstantPool())
161 convert(YamlMF, *ConstantPool);
163 ModuleSlotTracker MST(MF.getFunction()->getParent());
164 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
165 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
167 for (const auto &MBB : MF) {
168 // TODO: Allow printing of non sequentially numbered MBBs.
169 // This is currently needed as the basic block references get their index
170 // from MBB.getNumber(), thus it should be sequential so that the parser can
171 // map back to the correct MBBs when parsing the output.
172 assert(MBB.getNumber() == I++ &&
173 "Can't print MBBs that aren't sequentially numbered");
175 yaml::MachineBasicBlock YamlMBB;
176 convert(MST, YamlMBB, MBB);
177 YamlMF.BasicBlocks.push_back(YamlMBB);
179 yaml::Output Out(OS);
183 void MIRPrinter::convert(yaml::MachineFunction &MF,
184 const MachineRegisterInfo &RegInfo,
185 const TargetRegisterInfo *TRI) {
186 MF.IsSSA = RegInfo.isSSA();
187 MF.TracksRegLiveness = RegInfo.tracksLiveness();
188 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
190 // Print the virtual register definitions.
191 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
192 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
193 yaml::VirtualRegisterDefinition VReg;
196 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
197 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
199 printReg(PreferredReg, VReg.PreferredRegister, TRI);
200 MF.VirtualRegisters.push_back(VReg);
204 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
205 const MachineFrameInfo &MFI) {
206 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
207 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
208 YamlMFI.HasStackMap = MFI.hasStackMap();
209 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
210 YamlMFI.StackSize = MFI.getStackSize();
211 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
212 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
213 YamlMFI.AdjustsStack = MFI.adjustsStack();
214 YamlMFI.HasCalls = MFI.hasCalls();
215 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
216 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
217 YamlMFI.HasVAStart = MFI.hasVAStart();
218 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
221 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
222 const MachineFrameInfo &MFI) {
223 // Process fixed stack objects.
225 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
226 if (MFI.isDeadObjectIndex(I))
229 yaml::FixedMachineStackObject YamlObject;
231 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
232 ? yaml::FixedMachineStackObject::SpillSlot
233 : yaml::FixedMachineStackObject::DefaultType;
234 YamlObject.Offset = MFI.getObjectOffset(I);
235 YamlObject.Size = MFI.getObjectSize(I);
236 YamlObject.Alignment = MFI.getObjectAlignment(I);
237 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
238 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
239 MF.FixedStackObjects.push_back(YamlObject);
240 StackObjectOperandMapping.insert(
241 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
244 // Process ordinary stack objects.
246 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
247 if (MFI.isDeadObjectIndex(I))
250 yaml::MachineStackObject YamlObject;
252 if (const auto *Alloca = MFI.getObjectAllocation(I))
253 YamlObject.Name.Value =
254 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
255 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
256 ? yaml::MachineStackObject::SpillSlot
257 : MFI.isVariableSizedObjectIndex(I)
258 ? yaml::MachineStackObject::VariableSized
259 : yaml::MachineStackObject::DefaultType;
260 YamlObject.Offset = MFI.getObjectOffset(I);
261 YamlObject.Size = MFI.getObjectSize(I);
262 YamlObject.Alignment = MFI.getObjectAlignment(I);
264 MF.StackObjects.push_back(YamlObject);
265 StackObjectOperandMapping.insert(std::make_pair(
266 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
270 void MIRPrinter::convert(yaml::MachineFunction &MF,
271 const MachineConstantPool &ConstantPool) {
273 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
274 // TODO: Serialize target specific constant pool entries.
275 if (Constant.isMachineConstantPoolEntry())
276 llvm_unreachable("Can't print target specific constant pool entries yet");
278 yaml::MachineConstantPoolValue YamlConstant;
280 raw_string_ostream StrOS(Str);
281 Constant.Val.ConstVal->printAsOperand(StrOS);
282 YamlConstant.ID = ID++;
283 YamlConstant.Value = StrOS.str();
284 YamlConstant.Alignment = Constant.getAlignment();
285 MF.Constants.push_back(YamlConstant);
289 void MIRPrinter::convert(ModuleSlotTracker &MST,
290 yaml::MachineJumpTable &YamlJTI,
291 const MachineJumpTableInfo &JTI) {
292 YamlJTI.Kind = JTI.getEntryKind();
294 for (const auto &Table : JTI.getJumpTables()) {
296 yaml::MachineJumpTable::Entry Entry;
298 for (const auto *MBB : Table.MBBs) {
299 raw_string_ostream StrOS(Str);
300 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
301 .printMBBReference(*MBB);
302 Entry.Blocks.push_back(StrOS.str());
305 YamlJTI.Entries.push_back(Entry);
309 void MIRPrinter::convert(ModuleSlotTracker &MST,
310 yaml::MachineBasicBlock &YamlMBB,
311 const MachineBasicBlock &MBB) {
312 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
313 YamlMBB.ID = (unsigned)MBB.getNumber();
314 // TODO: Serialize unnamed BB references.
315 if (const auto *BB = MBB.getBasicBlock())
316 YamlMBB.Name.Value = BB->hasName() ? BB->getName() : "<unnamed bb>";
318 YamlMBB.Name.Value = "";
319 YamlMBB.Alignment = MBB.getAlignment();
320 YamlMBB.AddressTaken = MBB.hasAddressTaken();
321 YamlMBB.IsLandingPad = MBB.isLandingPad();
322 for (const auto *SuccMBB : MBB.successors()) {
324 raw_string_ostream StrOS(Str);
325 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
326 .printMBBReference(*SuccMBB);
327 YamlMBB.Successors.push_back(StrOS.str());
329 // Print the live in registers.
330 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
331 assert(TRI && "Expected target register info");
332 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
334 raw_string_ostream StrOS(Str);
335 printReg(*I, StrOS, TRI);
336 YamlMBB.LiveIns.push_back(StrOS.str());
338 // Print the machine instructions.
339 YamlMBB.Instructions.reserve(MBB.size());
341 for (const auto &MI : MBB) {
342 raw_string_ostream StrOS(Str);
343 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
344 YamlMBB.Instructions.push_back(StrOS.str());
349 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
350 const auto *TRI = MF.getSubtarget().getRegisterInfo();
352 for (const uint32_t *Mask : TRI->getRegMasks())
353 RegisterMaskIds.insert(std::make_pair(Mask, I++));
356 void MIPrinter::print(const MachineInstr &MI) {
357 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
358 const auto *TRI = SubTarget.getRegisterInfo();
359 assert(TRI && "Expected target register info");
360 const auto *TII = SubTarget.getInstrInfo();
361 assert(TII && "Expected target instruction info");
362 if (MI.isCFIInstruction())
363 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
365 unsigned I = 0, E = MI.getNumOperands();
366 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
367 !MI.getOperand(I).isImplicit();
371 print(MI.getOperand(I), TRI);
376 if (MI.getFlag(MachineInstr::FrameSetup))
377 OS << "frame-setup ";
378 OS << TII->getName(MI.getOpcode());
379 // TODO: Print the bundling instruction flags, machine mem operands.
383 bool NeedComma = false;
387 print(MI.getOperand(I), TRI);
391 if (MI.getDebugLoc()) {
394 OS << " debug-location ";
395 MI.getDebugLoc()->printAsOperand(OS, MST);
399 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
400 OS << "%bb." << MBB.getNumber();
401 if (const auto *BB = MBB.getBasicBlock()) {
403 OS << '.' << BB->getName();
407 void MIPrinter::printStackObjectReference(int FrameIndex) {
408 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
409 assert(ObjectInfo != StackObjectOperandMapping.end() &&
410 "Invalid frame index");
411 const FrameIndexOperand &Operand = ObjectInfo->second;
412 if (Operand.IsFixed) {
413 OS << "%fixed-stack." << Operand.ID;
416 OS << "%stack." << Operand.ID;
417 if (!Operand.Name.empty())
418 OS << '.' << Operand.Name;
421 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
422 switch (Op.getType()) {
423 case MachineOperand::MO_Register:
424 // TODO: Print the other register flags.
426 OS << (Op.isDef() ? "implicit-def " : "implicit ");
433 printReg(Op.getReg(), OS, TRI);
434 // Print the sub register.
435 if (Op.getSubReg() != 0)
436 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
438 case MachineOperand::MO_Immediate:
441 case MachineOperand::MO_MachineBasicBlock:
442 printMBBReference(*Op.getMBB());
444 case MachineOperand::MO_FrameIndex:
445 printStackObjectReference(Op.getIndex());
447 case MachineOperand::MO_ConstantPoolIndex:
448 OS << "%const." << Op.getIndex();
449 // TODO: Print offset and target flags.
451 case MachineOperand::MO_JumpTableIndex:
452 OS << "%jump-table." << Op.getIndex();
453 // TODO: Print target flags.
455 case MachineOperand::MO_ExternalSymbol:
457 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
458 // TODO: Print the target flags.
460 case MachineOperand::MO_GlobalAddress:
461 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
462 // TODO: Print offset and target flags.
464 case MachineOperand::MO_RegisterMask: {
465 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
466 if (RegMaskInfo != RegisterMaskIds.end())
467 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
469 llvm_unreachable("Can't print this machine register mask yet.");
472 case MachineOperand::MO_Metadata:
473 Op.getMetadata()->printAsOperand(OS, MST);
475 case MachineOperand::MO_CFIIndex: {
476 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
477 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
481 // TODO: Print the other machine operands.
482 llvm_unreachable("Can't print this machine operand at the moment");
486 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
487 const TargetRegisterInfo *TRI) {
488 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
493 printReg(Reg, OS, TRI);
496 void MIPrinter::print(const MCCFIInstruction &CFI,
497 const TargetRegisterInfo *TRI) {
498 switch (CFI.getOperation()) {
499 case MCCFIInstruction::OpOffset:
500 OS << ".cfi_offset ";
503 printCFIRegister(CFI.getRegister(), OS, TRI);
504 OS << ", " << CFI.getOffset();
506 case MCCFIInstruction::OpDefCfaOffset:
507 OS << ".cfi_def_cfa_offset ";
510 OS << CFI.getOffset();
513 // TODO: Print the other CFI Operations.
514 OS << "<unserializable cfi operation>";
519 void llvm::printMIR(raw_ostream &OS, const Module &M) {
520 yaml::Output Out(OS);
521 Out << const_cast<Module &>(M);
524 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
525 MIRPrinter Printer(OS);