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/Constants.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ModuleSlotTracker.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/YAMLTraits.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
39 /// This structure describes how to print out stack object references.
40 struct FrameIndexOperand {
45 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
46 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
48 /// Return an ordinary stack object reference.
49 static FrameIndexOperand create(StringRef Name, unsigned ID) {
50 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
53 /// Return a fixed stack object reference.
54 static FrameIndexOperand createFixed(unsigned ID) {
55 return FrameIndexOperand("", ID, /*IsFixed=*/true);
59 /// This class prints out the machine functions using the MIR serialization
63 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
64 /// Maps from stack object indices to operand indices which will be used when
65 /// printing frame index machine operands.
66 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
69 MIRPrinter(raw_ostream &OS) : OS(OS) {}
71 void print(const MachineFunction &MF);
73 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
74 const TargetRegisterInfo *TRI);
75 void convert(yaml::MachineFrameInfo &YamlMFI, const MachineFrameInfo &MFI);
76 void convert(yaml::MachineFunction &MF,
77 const MachineConstantPool &ConstantPool);
78 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
79 const MachineJumpTableInfo &JTI);
80 void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
81 const MachineBasicBlock &MBB);
82 void convertStackObjects(yaml::MachineFunction &MF,
83 const MachineFrameInfo &MFI,
84 const TargetRegisterInfo *TRI);
87 void initRegisterMaskIds(const MachineFunction &MF);
90 /// This class prints out the machine instructions using the MIR serialization
94 ModuleSlotTracker &MST;
95 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
96 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
99 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
100 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
101 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
102 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
103 StackObjectOperandMapping(StackObjectOperandMapping) {}
105 void print(const MachineInstr &MI);
106 void printMBBReference(const MachineBasicBlock &MBB);
107 void printIRBlockReference(const BasicBlock &BB);
108 void printStackObjectReference(int FrameIndex);
109 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
111 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
114 } // end anonymous namespace
119 /// This struct serializes the LLVM IR module.
120 template <> struct BlockScalarTraits<Module> {
121 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
122 Mod.print(OS, nullptr);
124 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
125 llvm_unreachable("LLVM Module is supposed to be parsed separately");
130 } // end namespace yaml
131 } // end namespace llvm
133 static void printReg(unsigned Reg, raw_ostream &OS,
134 const TargetRegisterInfo *TRI) {
135 // TODO: Print Stack Slots.
138 else if (TargetRegisterInfo::isVirtualRegister(Reg))
139 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
140 else if (Reg < TRI->getNumRegs())
141 OS << '%' << StringRef(TRI->getName(Reg)).lower();
143 llvm_unreachable("Can't print this kind of register yet");
146 static void printReg(unsigned Reg, yaml::StringValue &Dest,
147 const TargetRegisterInfo *TRI) {
148 raw_string_ostream OS(Dest.Value);
149 printReg(Reg, OS, TRI);
152 void MIRPrinter::print(const MachineFunction &MF) {
153 initRegisterMaskIds(MF);
155 yaml::MachineFunction YamlMF;
156 YamlMF.Name = MF.getName();
157 YamlMF.Alignment = MF.getAlignment();
158 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
159 YamlMF.HasInlineAsm = MF.hasInlineAsm();
160 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
161 convert(YamlMF.FrameInfo, *MF.getFrameInfo());
162 convertStackObjects(YamlMF, *MF.getFrameInfo(),
163 MF.getSubtarget().getRegisterInfo());
164 if (const auto *ConstantPool = MF.getConstantPool())
165 convert(YamlMF, *ConstantPool);
167 ModuleSlotTracker MST(MF.getFunction()->getParent());
168 MST.incorporateFunction(*MF.getFunction());
169 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
170 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
171 for (const auto &MBB : MF) {
172 yaml::MachineBasicBlock YamlMBB;
173 convert(MST, YamlMBB, MBB);
174 YamlMF.BasicBlocks.push_back(YamlMBB);
176 yaml::Output Out(OS);
180 void MIRPrinter::convert(yaml::MachineFunction &MF,
181 const MachineRegisterInfo &RegInfo,
182 const TargetRegisterInfo *TRI) {
183 MF.IsSSA = RegInfo.isSSA();
184 MF.TracksRegLiveness = RegInfo.tracksLiveness();
185 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
187 // Print the virtual register definitions.
188 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
189 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
190 yaml::VirtualRegisterDefinition VReg;
193 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
194 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
196 printReg(PreferredReg, VReg.PreferredRegister, TRI);
197 MF.VirtualRegisters.push_back(VReg);
200 // Print the live ins.
201 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
202 yaml::MachineFunctionLiveIn LiveIn;
203 printReg(I->first, LiveIn.Register, TRI);
205 printReg(I->second, LiveIn.VirtualRegister, TRI);
206 MF.LiveIns.push_back(LiveIn);
210 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
211 const MachineFrameInfo &MFI) {
212 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
213 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
214 YamlMFI.HasStackMap = MFI.hasStackMap();
215 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
216 YamlMFI.StackSize = MFI.getStackSize();
217 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
218 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
219 YamlMFI.AdjustsStack = MFI.adjustsStack();
220 YamlMFI.HasCalls = MFI.hasCalls();
221 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
222 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
223 YamlMFI.HasVAStart = MFI.hasVAStart();
224 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
227 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
228 const MachineFrameInfo &MFI,
229 const TargetRegisterInfo *TRI) {
230 // Process fixed stack objects.
232 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
233 if (MFI.isDeadObjectIndex(I))
236 yaml::FixedMachineStackObject YamlObject;
238 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
239 ? yaml::FixedMachineStackObject::SpillSlot
240 : yaml::FixedMachineStackObject::DefaultType;
241 YamlObject.Offset = MFI.getObjectOffset(I);
242 YamlObject.Size = MFI.getObjectSize(I);
243 YamlObject.Alignment = MFI.getObjectAlignment(I);
244 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
245 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
246 MF.FixedStackObjects.push_back(YamlObject);
247 StackObjectOperandMapping.insert(
248 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
251 // Process ordinary stack objects.
253 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
254 if (MFI.isDeadObjectIndex(I))
257 yaml::MachineStackObject YamlObject;
259 if (const auto *Alloca = MFI.getObjectAllocation(I))
260 YamlObject.Name.Value =
261 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
262 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
263 ? yaml::MachineStackObject::SpillSlot
264 : MFI.isVariableSizedObjectIndex(I)
265 ? yaml::MachineStackObject::VariableSized
266 : yaml::MachineStackObject::DefaultType;
267 YamlObject.Offset = MFI.getObjectOffset(I);
268 YamlObject.Size = MFI.getObjectSize(I);
269 YamlObject.Alignment = MFI.getObjectAlignment(I);
271 MF.StackObjects.push_back(YamlObject);
272 StackObjectOperandMapping.insert(std::make_pair(
273 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
276 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
277 yaml::StringValue Reg;
278 printReg(CSInfo.getReg(), Reg, TRI);
279 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
280 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
281 "Invalid stack object index");
282 const FrameIndexOperand &StackObject = StackObjectInfo->second;
283 if (StackObject.IsFixed)
284 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
286 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
290 void MIRPrinter::convert(yaml::MachineFunction &MF,
291 const MachineConstantPool &ConstantPool) {
293 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
294 // TODO: Serialize target specific constant pool entries.
295 if (Constant.isMachineConstantPoolEntry())
296 llvm_unreachable("Can't print target specific constant pool entries yet");
298 yaml::MachineConstantPoolValue YamlConstant;
300 raw_string_ostream StrOS(Str);
301 Constant.Val.ConstVal->printAsOperand(StrOS);
302 YamlConstant.ID = ID++;
303 YamlConstant.Value = StrOS.str();
304 YamlConstant.Alignment = Constant.getAlignment();
305 MF.Constants.push_back(YamlConstant);
309 void MIRPrinter::convert(ModuleSlotTracker &MST,
310 yaml::MachineJumpTable &YamlJTI,
311 const MachineJumpTableInfo &JTI) {
312 YamlJTI.Kind = JTI.getEntryKind();
314 for (const auto &Table : JTI.getJumpTables()) {
316 yaml::MachineJumpTable::Entry Entry;
318 for (const auto *MBB : Table.MBBs) {
319 raw_string_ostream StrOS(Str);
320 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
321 .printMBBReference(*MBB);
322 Entry.Blocks.push_back(StrOS.str());
325 YamlJTI.Entries.push_back(Entry);
329 void MIRPrinter::convert(ModuleSlotTracker &MST,
330 yaml::MachineBasicBlock &YamlMBB,
331 const MachineBasicBlock &MBB) {
332 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
333 YamlMBB.ID = (unsigned)MBB.getNumber();
334 if (const auto *BB = MBB.getBasicBlock()) {
336 YamlMBB.Name.Value = BB->getName();
338 int Slot = MST.getLocalSlot(BB);
340 YamlMBB.IRBlock.Value = "<badref>";
342 YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
345 YamlMBB.Alignment = MBB.getAlignment();
346 YamlMBB.AddressTaken = MBB.hasAddressTaken();
347 YamlMBB.IsLandingPad = MBB.isLandingPad();
348 for (const auto *SuccMBB : MBB.successors()) {
350 raw_string_ostream StrOS(Str);
351 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
352 .printMBBReference(*SuccMBB);
353 YamlMBB.Successors.push_back(StrOS.str());
355 // Print the live in registers.
356 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
357 assert(TRI && "Expected target register info");
358 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
360 raw_string_ostream StrOS(Str);
361 printReg(*I, StrOS, TRI);
362 YamlMBB.LiveIns.push_back(StrOS.str());
364 // Print the machine instructions.
365 YamlMBB.Instructions.reserve(MBB.size());
367 for (const auto &MI : MBB) {
368 raw_string_ostream StrOS(Str);
369 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
370 YamlMBB.Instructions.push_back(StrOS.str());
375 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
376 const auto *TRI = MF.getSubtarget().getRegisterInfo();
378 for (const uint32_t *Mask : TRI->getRegMasks())
379 RegisterMaskIds.insert(std::make_pair(Mask, I++));
382 void MIPrinter::print(const MachineInstr &MI) {
383 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
384 const auto *TRI = SubTarget.getRegisterInfo();
385 assert(TRI && "Expected target register info");
386 const auto *TII = SubTarget.getInstrInfo();
387 assert(TII && "Expected target instruction info");
388 if (MI.isCFIInstruction())
389 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
391 unsigned I = 0, E = MI.getNumOperands();
392 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
393 !MI.getOperand(I).isImplicit();
397 print(MI.getOperand(I), TRI);
402 if (MI.getFlag(MachineInstr::FrameSetup))
403 OS << "frame-setup ";
404 OS << TII->getName(MI.getOpcode());
405 // TODO: Print the bundling instruction flags, machine mem operands.
409 bool NeedComma = false;
413 print(MI.getOperand(I), TRI);
417 if (MI.getDebugLoc()) {
420 OS << " debug-location ";
421 MI.getDebugLoc()->printAsOperand(OS, MST);
425 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
426 OS << "%bb." << MBB.getNumber();
427 if (const auto *BB = MBB.getBasicBlock()) {
429 OS << '.' << BB->getName();
433 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
436 printLLVMNameWithoutPrefix(OS, BB.getName());
439 int Slot = MST.getLocalSlot(&BB);
446 void MIPrinter::printStackObjectReference(int FrameIndex) {
447 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
448 assert(ObjectInfo != StackObjectOperandMapping.end() &&
449 "Invalid frame index");
450 const FrameIndexOperand &Operand = ObjectInfo->second;
451 if (Operand.IsFixed) {
452 OS << "%fixed-stack." << Operand.ID;
455 OS << "%stack." << Operand.ID;
456 if (!Operand.Name.empty())
457 OS << '.' << Operand.Name;
460 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
461 switch (Op.getType()) {
462 case MachineOperand::MO_Register:
463 // TODO: Print the other register flags.
465 OS << (Op.isDef() ? "implicit-def " : "implicit ");
472 printReg(Op.getReg(), OS, TRI);
473 // Print the sub register.
474 if (Op.getSubReg() != 0)
475 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
477 case MachineOperand::MO_Immediate:
480 case MachineOperand::MO_MachineBasicBlock:
481 printMBBReference(*Op.getMBB());
483 case MachineOperand::MO_FrameIndex:
484 printStackObjectReference(Op.getIndex());
486 case MachineOperand::MO_ConstantPoolIndex:
487 OS << "%const." << Op.getIndex();
488 // TODO: Print offset and target flags.
490 case MachineOperand::MO_JumpTableIndex:
491 OS << "%jump-table." << Op.getIndex();
492 // TODO: Print target flags.
494 case MachineOperand::MO_ExternalSymbol:
496 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
497 // TODO: Print the target flags.
499 case MachineOperand::MO_GlobalAddress:
500 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
501 // TODO: Print offset and target flags.
503 case MachineOperand::MO_BlockAddress:
504 OS << "blockaddress(";
505 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
508 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
510 // TODO: Print offset and target flags.
512 case MachineOperand::MO_RegisterMask: {
513 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
514 if (RegMaskInfo != RegisterMaskIds.end())
515 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
517 llvm_unreachable("Can't print this machine register mask yet.");
520 case MachineOperand::MO_Metadata:
521 Op.getMetadata()->printAsOperand(OS, MST);
523 case MachineOperand::MO_CFIIndex: {
524 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
525 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
529 // TODO: Print the other machine operands.
530 llvm_unreachable("Can't print this machine operand at the moment");
534 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
535 const TargetRegisterInfo *TRI) {
536 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
541 printReg(Reg, OS, TRI);
544 void MIPrinter::print(const MCCFIInstruction &CFI,
545 const TargetRegisterInfo *TRI) {
546 switch (CFI.getOperation()) {
547 case MCCFIInstruction::OpOffset:
548 OS << ".cfi_offset ";
551 printCFIRegister(CFI.getRegister(), OS, TRI);
552 OS << ", " << CFI.getOffset();
554 case MCCFIInstruction::OpDefCfaRegister:
555 OS << ".cfi_def_cfa_register ";
558 printCFIRegister(CFI.getRegister(), OS, TRI);
560 case MCCFIInstruction::OpDefCfaOffset:
561 OS << ".cfi_def_cfa_offset ";
564 OS << CFI.getOffset();
567 // TODO: Print the other CFI Operations.
568 OS << "<unserializable cfi operation>";
573 void llvm::printMIR(raw_ostream &OS, const Module &M) {
574 yaml::Output Out(OS);
575 Out << const_cast<Module &>(M);
578 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
579 MIRPrinter Printer(OS);