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 } // end anonymous namespace
63 /// This class prints out the machine functions using the MIR serialization
67 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
68 /// Maps from stack object indices to operand indices which will be used when
69 /// printing frame index machine operands.
70 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
73 MIRPrinter(raw_ostream &OS) : OS(OS) {}
75 void print(const MachineFunction &MF);
77 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
78 const TargetRegisterInfo *TRI);
79 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
80 const MachineFrameInfo &MFI);
81 void convert(yaml::MachineFunction &MF,
82 const MachineConstantPool &ConstantPool);
83 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
84 const MachineJumpTableInfo &JTI);
85 void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
86 const MachineBasicBlock &MBB);
87 void convertStackObjects(yaml::MachineFunction &MF,
88 const MachineFrameInfo &MFI,
89 const TargetRegisterInfo *TRI);
92 void initRegisterMaskIds(const MachineFunction &MF);
95 } // end namespace llvm
99 /// This class prints out the machine instructions using the MIR serialization
103 ModuleSlotTracker &MST;
104 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
105 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
108 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
109 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
110 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
111 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
112 StackObjectOperandMapping(StackObjectOperandMapping) {}
114 void print(const MachineInstr &MI);
115 void printMBBReference(const MachineBasicBlock &MBB);
116 void printIRBlockReference(const BasicBlock &BB);
117 void printStackObjectReference(int FrameIndex);
118 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
120 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
123 } // end anonymous namespace
128 /// This struct serializes the LLVM IR module.
129 template <> struct BlockScalarTraits<Module> {
130 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
131 Mod.print(OS, nullptr);
133 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
134 llvm_unreachable("LLVM Module is supposed to be parsed separately");
139 } // end namespace yaml
140 } // end namespace llvm
142 static void printReg(unsigned Reg, raw_ostream &OS,
143 const TargetRegisterInfo *TRI) {
144 // TODO: Print Stack Slots.
147 else if (TargetRegisterInfo::isVirtualRegister(Reg))
148 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
149 else if (Reg < TRI->getNumRegs())
150 OS << '%' << StringRef(TRI->getName(Reg)).lower();
152 llvm_unreachable("Can't print this kind of register yet");
155 static void printReg(unsigned Reg, yaml::StringValue &Dest,
156 const TargetRegisterInfo *TRI) {
157 raw_string_ostream OS(Dest.Value);
158 printReg(Reg, OS, TRI);
161 void MIRPrinter::print(const MachineFunction &MF) {
162 initRegisterMaskIds(MF);
164 yaml::MachineFunction YamlMF;
165 YamlMF.Name = MF.getName();
166 YamlMF.Alignment = MF.getAlignment();
167 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
168 YamlMF.HasInlineAsm = MF.hasInlineAsm();
169 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
170 ModuleSlotTracker MST(MF.getFunction()->getParent());
171 MST.incorporateFunction(*MF.getFunction());
172 convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
173 convertStackObjects(YamlMF, *MF.getFrameInfo(),
174 MF.getSubtarget().getRegisterInfo());
175 if (const auto *ConstantPool = MF.getConstantPool())
176 convert(YamlMF, *ConstantPool);
177 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
178 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
179 for (const auto &MBB : MF) {
180 yaml::MachineBasicBlock YamlMBB;
181 convert(MST, YamlMBB, MBB);
182 YamlMF.BasicBlocks.push_back(YamlMBB);
184 yaml::Output Out(OS);
188 void MIRPrinter::convert(yaml::MachineFunction &MF,
189 const MachineRegisterInfo &RegInfo,
190 const TargetRegisterInfo *TRI) {
191 MF.IsSSA = RegInfo.isSSA();
192 MF.TracksRegLiveness = RegInfo.tracksLiveness();
193 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
195 // Print the virtual register definitions.
196 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
197 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
198 yaml::VirtualRegisterDefinition VReg;
201 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
202 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
204 printReg(PreferredReg, VReg.PreferredRegister, TRI);
205 MF.VirtualRegisters.push_back(VReg);
208 // Print the live ins.
209 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
210 yaml::MachineFunctionLiveIn LiveIn;
211 printReg(I->first, LiveIn.Register, TRI);
213 printReg(I->second, LiveIn.VirtualRegister, TRI);
214 MF.LiveIns.push_back(LiveIn);
218 void MIRPrinter::convert(ModuleSlotTracker &MST,
219 yaml::MachineFrameInfo &YamlMFI,
220 const MachineFrameInfo &MFI) {
221 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
222 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
223 YamlMFI.HasStackMap = MFI.hasStackMap();
224 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
225 YamlMFI.StackSize = MFI.getStackSize();
226 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
227 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
228 YamlMFI.AdjustsStack = MFI.adjustsStack();
229 YamlMFI.HasCalls = MFI.hasCalls();
230 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
231 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
232 YamlMFI.HasVAStart = MFI.hasVAStart();
233 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
234 if (MFI.getSavePoint()) {
235 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
236 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
237 .printMBBReference(*MFI.getSavePoint());
239 if (MFI.getRestorePoint()) {
240 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
241 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
242 .printMBBReference(*MFI.getRestorePoint());
246 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
247 const MachineFrameInfo &MFI,
248 const TargetRegisterInfo *TRI) {
249 // Process fixed stack objects.
251 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
252 if (MFI.isDeadObjectIndex(I))
255 yaml::FixedMachineStackObject YamlObject;
257 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
258 ? yaml::FixedMachineStackObject::SpillSlot
259 : yaml::FixedMachineStackObject::DefaultType;
260 YamlObject.Offset = MFI.getObjectOffset(I);
261 YamlObject.Size = MFI.getObjectSize(I);
262 YamlObject.Alignment = MFI.getObjectAlignment(I);
263 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
264 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
265 MF.FixedStackObjects.push_back(YamlObject);
266 StackObjectOperandMapping.insert(
267 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
270 // Process ordinary stack objects.
272 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
273 if (MFI.isDeadObjectIndex(I))
276 yaml::MachineStackObject YamlObject;
278 if (const auto *Alloca = MFI.getObjectAllocation(I))
279 YamlObject.Name.Value =
280 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
281 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
282 ? yaml::MachineStackObject::SpillSlot
283 : MFI.isVariableSizedObjectIndex(I)
284 ? yaml::MachineStackObject::VariableSized
285 : yaml::MachineStackObject::DefaultType;
286 YamlObject.Offset = MFI.getObjectOffset(I);
287 YamlObject.Size = MFI.getObjectSize(I);
288 YamlObject.Alignment = MFI.getObjectAlignment(I);
290 MF.StackObjects.push_back(YamlObject);
291 StackObjectOperandMapping.insert(std::make_pair(
292 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
295 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
296 yaml::StringValue Reg;
297 printReg(CSInfo.getReg(), Reg, TRI);
298 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
299 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
300 "Invalid stack object index");
301 const FrameIndexOperand &StackObject = StackObjectInfo->second;
302 if (StackObject.IsFixed)
303 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
305 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
309 void MIRPrinter::convert(yaml::MachineFunction &MF,
310 const MachineConstantPool &ConstantPool) {
312 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
313 // TODO: Serialize target specific constant pool entries.
314 if (Constant.isMachineConstantPoolEntry())
315 llvm_unreachable("Can't print target specific constant pool entries yet");
317 yaml::MachineConstantPoolValue YamlConstant;
319 raw_string_ostream StrOS(Str);
320 Constant.Val.ConstVal->printAsOperand(StrOS);
321 YamlConstant.ID = ID++;
322 YamlConstant.Value = StrOS.str();
323 YamlConstant.Alignment = Constant.getAlignment();
324 MF.Constants.push_back(YamlConstant);
328 void MIRPrinter::convert(ModuleSlotTracker &MST,
329 yaml::MachineJumpTable &YamlJTI,
330 const MachineJumpTableInfo &JTI) {
331 YamlJTI.Kind = JTI.getEntryKind();
333 for (const auto &Table : JTI.getJumpTables()) {
335 yaml::MachineJumpTable::Entry Entry;
337 for (const auto *MBB : Table.MBBs) {
338 raw_string_ostream StrOS(Str);
339 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
340 .printMBBReference(*MBB);
341 Entry.Blocks.push_back(StrOS.str());
344 YamlJTI.Entries.push_back(Entry);
348 void MIRPrinter::convert(ModuleSlotTracker &MST,
349 yaml::MachineBasicBlock &YamlMBB,
350 const MachineBasicBlock &MBB) {
351 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
352 YamlMBB.ID = (unsigned)MBB.getNumber();
353 if (const auto *BB = MBB.getBasicBlock()) {
355 YamlMBB.Name.Value = BB->getName();
357 int Slot = MST.getLocalSlot(BB);
359 YamlMBB.IRBlock.Value = "<badref>";
361 YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
364 YamlMBB.Alignment = MBB.getAlignment();
365 YamlMBB.AddressTaken = MBB.hasAddressTaken();
366 YamlMBB.IsLandingPad = MBB.isLandingPad();
367 for (const auto *SuccMBB : MBB.successors()) {
369 raw_string_ostream StrOS(Str);
370 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
371 .printMBBReference(*SuccMBB);
372 YamlMBB.Successors.push_back(StrOS.str());
374 if (MBB.hasSuccessorWeights()) {
375 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I)
376 YamlMBB.SuccessorWeights.push_back(
377 yaml::UnsignedValue(MBB.getSuccWeight(I)));
379 // Print the live in registers.
380 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
381 assert(TRI && "Expected target register info");
382 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
384 raw_string_ostream StrOS(Str);
385 printReg(*I, StrOS, TRI);
386 YamlMBB.LiveIns.push_back(StrOS.str());
388 // Print the machine instructions.
389 YamlMBB.Instructions.reserve(MBB.size());
391 for (const auto &MI : MBB) {
392 raw_string_ostream StrOS(Str);
393 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
394 YamlMBB.Instructions.push_back(StrOS.str());
399 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
400 const auto *TRI = MF.getSubtarget().getRegisterInfo();
402 for (const uint32_t *Mask : TRI->getRegMasks())
403 RegisterMaskIds.insert(std::make_pair(Mask, I++));
406 void MIPrinter::print(const MachineInstr &MI) {
407 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
408 const auto *TRI = SubTarget.getRegisterInfo();
409 assert(TRI && "Expected target register info");
410 const auto *TII = SubTarget.getInstrInfo();
411 assert(TII && "Expected target instruction info");
412 if (MI.isCFIInstruction())
413 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
415 unsigned I = 0, E = MI.getNumOperands();
416 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
417 !MI.getOperand(I).isImplicit();
421 print(MI.getOperand(I), TRI);
426 if (MI.getFlag(MachineInstr::FrameSetup))
427 OS << "frame-setup ";
428 OS << TII->getName(MI.getOpcode());
429 // TODO: Print the bundling instruction flags, machine mem operands.
433 bool NeedComma = false;
437 print(MI.getOperand(I), TRI);
441 if (MI.getDebugLoc()) {
444 OS << " debug-location ";
445 MI.getDebugLoc()->printAsOperand(OS, MST);
449 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
450 OS << "%bb." << MBB.getNumber();
451 if (const auto *BB = MBB.getBasicBlock()) {
453 OS << '.' << BB->getName();
457 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
460 printLLVMNameWithoutPrefix(OS, BB.getName());
463 int Slot = MST.getLocalSlot(&BB);
470 void MIPrinter::printStackObjectReference(int FrameIndex) {
471 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
472 assert(ObjectInfo != StackObjectOperandMapping.end() &&
473 "Invalid frame index");
474 const FrameIndexOperand &Operand = ObjectInfo->second;
475 if (Operand.IsFixed) {
476 OS << "%fixed-stack." << Operand.ID;
479 OS << "%stack." << Operand.ID;
480 if (!Operand.Name.empty())
481 OS << '.' << Operand.Name;
484 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
485 const auto *TII = MF.getSubtarget().getInstrInfo();
486 assert(TII && "expected instruction info");
487 auto Indices = TII->getSerializableTargetIndices();
488 for (const auto &I : Indices) {
489 if (I.first == Index) {
496 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
497 switch (Op.getType()) {
498 case MachineOperand::MO_Register:
499 // TODO: Print the other register flags.
501 OS << (Op.isDef() ? "implicit-def " : "implicit ");
508 printReg(Op.getReg(), OS, TRI);
509 // Print the sub register.
510 if (Op.getSubReg() != 0)
511 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
513 case MachineOperand::MO_Immediate:
516 case MachineOperand::MO_MachineBasicBlock:
517 printMBBReference(*Op.getMBB());
519 case MachineOperand::MO_FrameIndex:
520 printStackObjectReference(Op.getIndex());
522 case MachineOperand::MO_ConstantPoolIndex:
523 OS << "%const." << Op.getIndex();
524 // TODO: Print offset and target flags.
526 case MachineOperand::MO_TargetIndex: {
527 OS << "target-index(";
528 if (const auto *Name = getTargetIndexName(
529 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
534 // TODO: Print the offset and target flags.
537 case MachineOperand::MO_JumpTableIndex:
538 OS << "%jump-table." << Op.getIndex();
539 // TODO: Print target flags.
541 case MachineOperand::MO_ExternalSymbol:
543 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
544 // TODO: Print the target flags.
546 case MachineOperand::MO_GlobalAddress:
547 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
548 // TODO: Print offset and target flags.
550 case MachineOperand::MO_BlockAddress:
551 OS << "blockaddress(";
552 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
555 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
557 // TODO: Print offset and target flags.
559 case MachineOperand::MO_RegisterMask: {
560 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
561 if (RegMaskInfo != RegisterMaskIds.end())
562 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
564 llvm_unreachable("Can't print this machine register mask yet.");
567 case MachineOperand::MO_Metadata:
568 Op.getMetadata()->printAsOperand(OS, MST);
570 case MachineOperand::MO_CFIIndex: {
571 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
572 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
576 // TODO: Print the other machine operands.
577 llvm_unreachable("Can't print this machine operand at the moment");
581 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
582 const TargetRegisterInfo *TRI) {
583 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
588 printReg(Reg, OS, TRI);
591 void MIPrinter::print(const MCCFIInstruction &CFI,
592 const TargetRegisterInfo *TRI) {
593 switch (CFI.getOperation()) {
594 case MCCFIInstruction::OpOffset:
595 OS << ".cfi_offset ";
598 printCFIRegister(CFI.getRegister(), OS, TRI);
599 OS << ", " << CFI.getOffset();
601 case MCCFIInstruction::OpDefCfaRegister:
602 OS << ".cfi_def_cfa_register ";
605 printCFIRegister(CFI.getRegister(), OS, TRI);
607 case MCCFIInstruction::OpDefCfaOffset:
608 OS << ".cfi_def_cfa_offset ";
611 OS << CFI.getOffset();
613 case MCCFIInstruction::OpDefCfa:
614 OS << ".cfi_def_cfa ";
617 printCFIRegister(CFI.getRegister(), OS, TRI);
618 OS << ", " << CFI.getOffset();
621 // TODO: Print the other CFI Operations.
622 OS << "<unserializable cfi operation>";
627 void llvm::printMIR(raw_ostream &OS, const Module &M) {
628 yaml::Output Out(OS);
629 Out << const_cast<Module &>(M);
632 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
633 MIRPrinter Printer(OS);