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,
83 const TargetRegisterInfo *TRI);
86 void initRegisterMaskIds(const MachineFunction &MF);
89 /// This class prints out the machine instructions using the MIR serialization
93 ModuleSlotTracker &MST;
94 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
95 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
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) {}
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);
109 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
112 } // end anonymous namespace
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);
122 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
123 llvm_unreachable("LLVM Module is supposed to be parsed separately");
128 } // end namespace yaml
129 } // end namespace llvm
131 static void printReg(unsigned Reg, raw_ostream &OS,
132 const TargetRegisterInfo *TRI) {
133 // TODO: Print Stack Slots.
136 else if (TargetRegisterInfo::isVirtualRegister(Reg))
137 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
138 else if (Reg < TRI->getNumRegs())
139 OS << '%' << StringRef(TRI->getName(Reg)).lower();
141 llvm_unreachable("Can't print this kind of register yet");
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);
150 void MIRPrinter::print(const MachineFunction &MF) {
151 initRegisterMaskIds(MF);
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);
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);
174 yaml::Output Out(OS);
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();
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;
191 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
192 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
194 printReg(PreferredReg, VReg.PreferredRegister, TRI);
195 MF.VirtualRegisters.push_back(VReg);
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);
203 printReg(I->second, LiveIn.VirtualRegister, TRI);
204 MF.LiveIns.push_back(LiveIn);
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();
225 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
226 const MachineFrameInfo &MFI,
227 const TargetRegisterInfo *TRI) {
228 // Process fixed stack objects.
230 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
231 if (MFI.isDeadObjectIndex(I))
234 yaml::FixedMachineStackObject YamlObject;
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++)));
249 // Process ordinary stack objects.
251 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
252 if (MFI.isDeadObjectIndex(I))
255 yaml::MachineStackObject YamlObject;
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);
269 MF.StackObjects.push_back(YamlObject);
270 StackObjectOperandMapping.insert(std::make_pair(
271 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
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;
284 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
288 void MIRPrinter::convert(yaml::MachineFunction &MF,
289 const MachineConstantPool &ConstantPool) {
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");
296 yaml::MachineConstantPoolValue YamlConstant;
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);
307 void MIRPrinter::convert(ModuleSlotTracker &MST,
308 yaml::MachineJumpTable &YamlJTI,
309 const MachineJumpTableInfo &JTI) {
310 YamlJTI.Kind = JTI.getEntryKind();
312 for (const auto &Table : JTI.getJumpTables()) {
314 yaml::MachineJumpTable::Entry Entry;
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());
323 YamlJTI.Entries.push_back(Entry);
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()) {
334 YamlMBB.Name.Value = BB->getName();
336 int Slot = MST.getLocalSlot(BB);
338 YamlMBB.IRBlock.Value = "<badref>";
340 YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
343 YamlMBB.Alignment = MBB.getAlignment();
344 YamlMBB.AddressTaken = MBB.hasAddressTaken();
345 YamlMBB.IsLandingPad = MBB.isLandingPad();
346 for (const auto *SuccMBB : MBB.successors()) {
348 raw_string_ostream StrOS(Str);
349 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
350 .printMBBReference(*SuccMBB);
351 YamlMBB.Successors.push_back(StrOS.str());
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) {
358 raw_string_ostream StrOS(Str);
359 printReg(*I, StrOS, TRI);
360 YamlMBB.LiveIns.push_back(StrOS.str());
362 // Print the machine instructions.
363 YamlMBB.Instructions.reserve(MBB.size());
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());
373 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
374 const auto *TRI = MF.getSubtarget().getRegisterInfo();
376 for (const uint32_t *Mask : TRI->getRegMasks())
377 RegisterMaskIds.insert(std::make_pair(Mask, I++));
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");
389 unsigned I = 0, E = MI.getNumOperands();
390 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
391 !MI.getOperand(I).isImplicit();
395 print(MI.getOperand(I), TRI);
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.
407 bool NeedComma = false;
411 print(MI.getOperand(I), TRI);
415 if (MI.getDebugLoc()) {
418 OS << " debug-location ";
419 MI.getDebugLoc()->printAsOperand(OS, MST);
423 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
424 OS << "%bb." << MBB.getNumber();
425 if (const auto *BB = MBB.getBasicBlock()) {
427 OS << '.' << BB->getName();
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;
440 OS << "%stack." << Operand.ID;
441 if (!Operand.Name.empty())
442 OS << '.' << Operand.Name;
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.
450 OS << (Op.isDef() ? "implicit-def " : "implicit ");
457 printReg(Op.getReg(), OS, TRI);
458 // Print the sub register.
459 if (Op.getSubReg() != 0)
460 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
462 case MachineOperand::MO_Immediate:
465 case MachineOperand::MO_MachineBasicBlock:
466 printMBBReference(*Op.getMBB());
468 case MachineOperand::MO_FrameIndex:
469 printStackObjectReference(Op.getIndex());
471 case MachineOperand::MO_ConstantPoolIndex:
472 OS << "%const." << Op.getIndex();
473 // TODO: Print offset and target flags.
475 case MachineOperand::MO_JumpTableIndex:
476 OS << "%jump-table." << Op.getIndex();
477 // TODO: Print target flags.
479 case MachineOperand::MO_ExternalSymbol:
481 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
482 // TODO: Print the target flags.
484 case MachineOperand::MO_GlobalAddress:
485 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
486 // TODO: Print offset and target flags.
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();
493 llvm_unreachable("Can't print this machine register mask yet.");
496 case MachineOperand::MO_Metadata:
497 Op.getMetadata()->printAsOperand(OS, MST);
499 case MachineOperand::MO_CFIIndex: {
500 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
501 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
505 // TODO: Print the other machine operands.
506 llvm_unreachable("Can't print this machine operand at the moment");
510 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
511 const TargetRegisterInfo *TRI) {
512 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
517 printReg(Reg, OS, TRI);
520 void MIPrinter::print(const MCCFIInstruction &CFI,
521 const TargetRegisterInfo *TRI) {
522 switch (CFI.getOperation()) {
523 case MCCFIInstruction::OpOffset:
524 OS << ".cfi_offset ";
527 printCFIRegister(CFI.getRegister(), OS, TRI);
528 OS << ", " << CFI.getOffset();
530 case MCCFIInstruction::OpDefCfaRegister:
531 OS << ".cfi_def_cfa_register ";
534 printCFIRegister(CFI.getRegister(), OS, TRI);
536 case MCCFIInstruction::OpDefCfaOffset:
537 OS << ".cfi_def_cfa_offset ";
540 OS << CFI.getOffset();
543 // TODO: Print the other CFI Operations.
544 OS << "<unserializable cfi operation>";
549 void llvm::printMIR(raw_ostream &OS, const Module &M) {
550 yaml::Output Out(OS);
551 Out << const_cast<Module &>(M);
554 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
555 MIRPrinter Printer(OS);