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 "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/MIRPrinter.h"
35 #include "llvm/CodeGen/MIRYamlMapping.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DebugInfo.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalValue.h"
43 #include "llvm/IR/InstrTypes.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/IRPrintingPasses.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/ModuleSlotTracker.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/MC/LaneBitmask.h"
51 #include "llvm/MC/MCDwarf.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/AtomicOrdering.h"
54 #include "llvm/Support/BranchProbability.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/Format.h"
59 #include "llvm/Support/LowLevelTypeImpl.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Support/YAMLTraits.h"
62 #include "llvm/Target/TargetInstrInfo.h"
63 #include "llvm/Target/TargetIntrinsicInfo.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetRegisterInfo.h"
66 #include "llvm/Target/TargetSubtargetInfo.h"
78 static cl::opt<bool> SimplifyMIR("simplify-mir",
79 cl::desc("Leave out unnecessary information when printing MIR"));
83 /// This structure describes how to print out stack object references.
84 struct FrameIndexOperand {
89 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
90 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
92 /// Return an ordinary stack object reference.
93 static FrameIndexOperand create(StringRef Name, unsigned ID) {
94 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
97 /// Return a fixed stack object reference.
98 static FrameIndexOperand createFixed(unsigned ID) {
99 return FrameIndexOperand("", ID, /*IsFixed=*/true);
103 } // end anonymous namespace
107 /// This class prints out the machine functions using the MIR serialization
111 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
112 /// Maps from stack object indices to operand indices which will be used when
113 /// printing frame index machine operands.
114 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
117 MIRPrinter(raw_ostream &OS) : OS(OS) {}
119 void print(const MachineFunction &MF);
121 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
122 const TargetRegisterInfo *TRI);
123 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
124 const MachineFrameInfo &MFI);
125 void convert(yaml::MachineFunction &MF,
126 const MachineConstantPool &ConstantPool);
127 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
128 const MachineJumpTableInfo &JTI);
129 void convertStackObjects(yaml::MachineFunction &YMF,
130 const MachineFunction &MF, ModuleSlotTracker &MST);
133 void initRegisterMaskIds(const MachineFunction &MF);
136 /// This class prints out the machine instructions using the MIR serialization
140 ModuleSlotTracker &MST;
141 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
142 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
143 /// Synchronization scope names registered with LLVMContext.
144 SmallVector<StringRef, 8> SSNs;
146 bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
147 bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
150 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
151 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
152 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
153 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
154 StackObjectOperandMapping(StackObjectOperandMapping) {}
156 void print(const MachineBasicBlock &MBB);
158 void print(const MachineInstr &MI);
159 void printMBBReference(const MachineBasicBlock &MBB);
160 void printIRBlockReference(const BasicBlock &BB);
161 void printIRValueReference(const Value &V);
162 void printStackObjectReference(int FrameIndex);
163 void printOffset(int64_t Offset);
164 void printTargetFlags(const MachineOperand &Op);
165 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
166 unsigned I, bool ShouldPrintRegisterTies,
167 LLT TypeToPrint, bool IsDef = false);
168 void print(const LLVMContext &Context, const TargetInstrInfo &TII,
169 const MachineMemOperand &Op);
170 void printSyncScope(const LLVMContext &Context, SyncScope::ID SSID);
172 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
175 } // end namespace llvm
180 /// This struct serializes the LLVM IR module.
181 template <> struct BlockScalarTraits<Module> {
182 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
183 Mod.print(OS, nullptr);
186 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
187 llvm_unreachable("LLVM Module is supposed to be parsed separately");
192 } // end namespace yaml
193 } // end namespace llvm
195 static void printReg(unsigned Reg, raw_ostream &OS,
196 const TargetRegisterInfo *TRI) {
197 // TODO: Print Stack Slots.
200 else if (TargetRegisterInfo::isVirtualRegister(Reg))
201 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
202 else if (Reg < TRI->getNumRegs())
203 OS << '%' << StringRef(TRI->getName(Reg)).lower();
205 llvm_unreachable("Can't print this kind of register yet");
208 static void printReg(unsigned Reg, yaml::StringValue &Dest,
209 const TargetRegisterInfo *TRI) {
210 raw_string_ostream OS(Dest.Value);
211 printReg(Reg, OS, TRI);
214 void MIRPrinter::print(const MachineFunction &MF) {
215 initRegisterMaskIds(MF);
217 yaml::MachineFunction YamlMF;
218 YamlMF.Name = MF.getName();
219 YamlMF.Alignment = MF.getAlignment();
220 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
222 YamlMF.Legalized = MF.getProperties().hasProperty(
223 MachineFunctionProperties::Property::Legalized);
224 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
225 MachineFunctionProperties::Property::RegBankSelected);
226 YamlMF.Selected = MF.getProperties().hasProperty(
227 MachineFunctionProperties::Property::Selected);
229 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
230 ModuleSlotTracker MST(MF.getFunction()->getParent());
231 MST.incorporateFunction(*MF.getFunction());
232 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
233 convertStackObjects(YamlMF, MF, MST);
234 if (const auto *ConstantPool = MF.getConstantPool())
235 convert(YamlMF, *ConstantPool);
236 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
237 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
238 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
239 bool IsNewlineNeeded = false;
240 for (const auto &MBB : MF) {
243 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
245 IsNewlineNeeded = true;
248 yaml::Output Out(OS);
250 Out.setWriteDefaultValues(true);
254 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
255 const TargetRegisterInfo *TRI) {
256 assert(RegMask && "Can't print an empty register mask");
257 OS << StringRef("CustomRegMask(");
259 bool IsRegInRegMaskFound = false;
260 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
261 // Check whether the register is asserted in regmask.
262 if (RegMask[I / 32] & (1u << (I % 32))) {
263 if (IsRegInRegMaskFound)
265 printReg(I, OS, TRI);
266 IsRegInRegMaskFound = true;
273 void MIRPrinter::convert(yaml::MachineFunction &MF,
274 const MachineRegisterInfo &RegInfo,
275 const TargetRegisterInfo *TRI) {
276 MF.TracksRegLiveness = RegInfo.tracksLiveness();
278 // Print the virtual register definitions.
279 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
280 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
281 yaml::VirtualRegisterDefinition VReg;
283 if (RegInfo.getRegClassOrNull(Reg))
285 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
286 else if (RegInfo.getRegBankOrNull(Reg))
287 VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
289 VReg.Class = std::string("_");
290 assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
291 "Generic registers must have a valid type");
293 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
295 printReg(PreferredReg, VReg.PreferredRegister, TRI);
296 MF.VirtualRegisters.push_back(VReg);
299 // Print the live ins.
300 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
301 yaml::MachineFunctionLiveIn LiveIn;
302 printReg(I->first, LiveIn.Register, TRI);
304 printReg(I->second, LiveIn.VirtualRegister, TRI);
305 MF.LiveIns.push_back(LiveIn);
308 // Prints the callee saved registers.
309 if (RegInfo.isUpdatedCSRsInitialized()) {
310 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
311 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
312 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
313 yaml::FlowStringValue Reg;
314 printReg(*I, Reg, TRI);
315 CalleeSavedRegisters.push_back(Reg);
317 MF.CalleeSavedRegisters = CalleeSavedRegisters;
321 void MIRPrinter::convert(ModuleSlotTracker &MST,
322 yaml::MachineFrameInfo &YamlMFI,
323 const MachineFrameInfo &MFI) {
324 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
325 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
326 YamlMFI.HasStackMap = MFI.hasStackMap();
327 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
328 YamlMFI.StackSize = MFI.getStackSize();
329 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
330 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
331 YamlMFI.AdjustsStack = MFI.adjustsStack();
332 YamlMFI.HasCalls = MFI.hasCalls();
333 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
334 ? MFI.getMaxCallFrameSize() : ~0u;
335 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
336 YamlMFI.HasVAStart = MFI.hasVAStart();
337 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
338 if (MFI.getSavePoint()) {
339 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
340 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
341 .printMBBReference(*MFI.getSavePoint());
343 if (MFI.getRestorePoint()) {
344 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
345 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
346 .printMBBReference(*MFI.getRestorePoint());
350 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
351 const MachineFunction &MF,
352 ModuleSlotTracker &MST) {
353 const MachineFrameInfo &MFI = MF.getFrameInfo();
354 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
355 // Process fixed stack objects.
357 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
358 if (MFI.isDeadObjectIndex(I))
361 yaml::FixedMachineStackObject YamlObject;
363 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
364 ? yaml::FixedMachineStackObject::SpillSlot
365 : yaml::FixedMachineStackObject::DefaultType;
366 YamlObject.Offset = MFI.getObjectOffset(I);
367 YamlObject.Size = MFI.getObjectSize(I);
368 YamlObject.Alignment = MFI.getObjectAlignment(I);
369 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
370 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
371 YMF.FixedStackObjects.push_back(YamlObject);
372 StackObjectOperandMapping.insert(
373 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
376 // Process ordinary stack objects.
378 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
379 if (MFI.isDeadObjectIndex(I))
382 yaml::MachineStackObject YamlObject;
384 if (const auto *Alloca = MFI.getObjectAllocation(I))
385 YamlObject.Name.Value =
386 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
387 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
388 ? yaml::MachineStackObject::SpillSlot
389 : MFI.isVariableSizedObjectIndex(I)
390 ? yaml::MachineStackObject::VariableSized
391 : yaml::MachineStackObject::DefaultType;
392 YamlObject.Offset = MFI.getObjectOffset(I);
393 YamlObject.Size = MFI.getObjectSize(I);
394 YamlObject.Alignment = MFI.getObjectAlignment(I);
396 YMF.StackObjects.push_back(YamlObject);
397 StackObjectOperandMapping.insert(std::make_pair(
398 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
401 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
402 yaml::StringValue Reg;
403 printReg(CSInfo.getReg(), Reg, TRI);
404 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
405 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
406 "Invalid stack object index");
407 const FrameIndexOperand &StackObject = StackObjectInfo->second;
408 if (StackObject.IsFixed)
409 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
411 YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
413 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
414 auto LocalObject = MFI.getLocalFrameObjectMap(I);
415 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
416 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
417 "Invalid stack object index");
418 const FrameIndexOperand &StackObject = StackObjectInfo->second;
419 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
420 YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
423 // Print the stack object references in the frame information class after
424 // converting the stack objects.
425 if (MFI.hasStackProtectorIndex()) {
426 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
427 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
428 .printStackObjectReference(MFI.getStackProtectorIndex());
431 // Print the debug variable information.
432 for (const MachineFunction::VariableDbgInfo &DebugVar :
433 MF.getVariableDbgInfo()) {
434 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
435 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
436 "Invalid stack object index");
437 const FrameIndexOperand &StackObject = StackObjectInfo->second;
438 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
439 auto &Object = YMF.StackObjects[StackObject.ID];
441 raw_string_ostream StrOS(Object.DebugVar.Value);
442 DebugVar.Var->printAsOperand(StrOS, MST);
445 raw_string_ostream StrOS(Object.DebugExpr.Value);
446 DebugVar.Expr->printAsOperand(StrOS, MST);
449 raw_string_ostream StrOS(Object.DebugLoc.Value);
450 DebugVar.Loc->printAsOperand(StrOS, MST);
455 void MIRPrinter::convert(yaml::MachineFunction &MF,
456 const MachineConstantPool &ConstantPool) {
458 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
459 // TODO: Serialize target specific constant pool entries.
460 if (Constant.isMachineConstantPoolEntry())
461 llvm_unreachable("Can't print target specific constant pool entries yet");
463 yaml::MachineConstantPoolValue YamlConstant;
465 raw_string_ostream StrOS(Str);
466 Constant.Val.ConstVal->printAsOperand(StrOS);
467 YamlConstant.ID = ID++;
468 YamlConstant.Value = StrOS.str();
469 YamlConstant.Alignment = Constant.getAlignment();
470 MF.Constants.push_back(YamlConstant);
474 void MIRPrinter::convert(ModuleSlotTracker &MST,
475 yaml::MachineJumpTable &YamlJTI,
476 const MachineJumpTableInfo &JTI) {
477 YamlJTI.Kind = JTI.getEntryKind();
479 for (const auto &Table : JTI.getJumpTables()) {
481 yaml::MachineJumpTable::Entry Entry;
483 for (const auto *MBB : Table.MBBs) {
484 raw_string_ostream StrOS(Str);
485 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
486 .printMBBReference(*MBB);
487 Entry.Blocks.push_back(StrOS.str());
490 YamlJTI.Entries.push_back(Entry);
494 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
495 const auto *TRI = MF.getSubtarget().getRegisterInfo();
497 for (const uint32_t *Mask : TRI->getRegMasks())
498 RegisterMaskIds.insert(std::make_pair(Mask, I++));
501 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
502 SmallVectorImpl<MachineBasicBlock*> &Result,
503 bool &IsFallthrough) {
504 SmallPtrSet<MachineBasicBlock*,8> Seen;
506 for (const MachineInstr &MI : MBB) {
509 for (const MachineOperand &MO : MI.operands()) {
512 MachineBasicBlock *Succ = MO.getMBB();
513 auto RP = Seen.insert(Succ);
515 Result.push_back(Succ);
518 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
519 IsFallthrough = I == MBB.end() || !I->isBarrier();
523 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
524 if (MBB.succ_size() <= 1)
526 if (!MBB.hasSuccessorProbabilities())
529 SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
531 BranchProbability::normalizeProbabilities(Normalized.begin(),
533 SmallVector<BranchProbability,8> Equal(Normalized.size());
534 BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
536 return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
539 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
540 SmallVector<MachineBasicBlock*,8> GuessedSuccs;
541 bool GuessedFallthrough;
542 guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
543 if (GuessedFallthrough) {
544 const MachineFunction &MF = *MBB.getParent();
545 MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
546 if (NextI != MF.end()) {
547 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
548 if (!is_contained(GuessedSuccs, Next))
549 GuessedSuccs.push_back(Next);
552 if (GuessedSuccs.size() != MBB.succ_size())
554 return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
557 void MIPrinter::print(const MachineBasicBlock &MBB) {
558 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
559 OS << "bb." << MBB.getNumber();
560 bool HasAttributes = false;
561 if (const auto *BB = MBB.getBasicBlock()) {
563 OS << "." << BB->getName();
565 HasAttributes = true;
567 int Slot = MST.getLocalSlot(BB);
569 OS << "<ir-block badref>";
571 OS << (Twine("%ir-block.") + Twine(Slot)).str();
574 if (MBB.hasAddressTaken()) {
575 OS << (HasAttributes ? ", " : " (");
576 OS << "address-taken";
577 HasAttributes = true;
580 OS << (HasAttributes ? ", " : " (");
582 HasAttributes = true;
584 if (MBB.getAlignment()) {
585 OS << (HasAttributes ? ", " : " (");
586 OS << "align " << MBB.getAlignment();
587 HasAttributes = true;
593 bool HasLineAttributes = false;
594 // Print the successors
595 bool canPredictProbs = canPredictBranchProbabilities(MBB);
596 if (!MBB.succ_empty() && (!SimplifyMIR || !canPredictProbs ||
597 !canPredictSuccessors(MBB))) {
598 OS.indent(2) << "successors: ";
599 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
600 if (I != MBB.succ_begin())
602 printMBBReference(**I);
603 if (!SimplifyMIR || !canPredictProbs)
605 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
609 HasLineAttributes = true;
612 // Print the live in registers.
613 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
614 if (MRI.tracksLiveness() && !MBB.livein_empty()) {
615 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
616 OS.indent(2) << "liveins: ";
618 for (const auto &LI : MBB.liveins()) {
622 printReg(LI.PhysReg, OS, &TRI);
623 if (!LI.LaneMask.all())
624 OS << ":0x" << PrintLaneMask(LI.LaneMask);
627 HasLineAttributes = true;
630 if (HasLineAttributes)
632 bool IsInBundle = false;
633 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
634 const MachineInstr &MI = *I;
635 if (IsInBundle && !MI.isInsideBundle()) {
636 OS.indent(2) << "}\n";
639 OS.indent(IsInBundle ? 4 : 2);
641 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
648 OS.indent(2) << "}\n";
651 /// Return true when an instruction has tied register that can't be determined
652 /// by the instruction's descriptor.
653 static bool hasComplexRegisterTies(const MachineInstr &MI) {
654 const MCInstrDesc &MCID = MI.getDesc();
655 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
656 const auto &Operand = MI.getOperand(I);
657 if (!Operand.isReg() || Operand.isDef())
658 // Ignore the defined registers as MCID marks only the uses as tied.
660 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
661 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
662 if (ExpectedTiedIdx != TiedIdx)
668 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
669 SmallBitVector &PrintedTypes,
670 const MachineRegisterInfo &MRI) {
671 const MachineOperand &Op = MI.getOperand(OpIdx);
675 if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
676 return MRI.getType(Op.getReg());
678 auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
679 if (!OpInfo.isGenericType())
680 return MRI.getType(Op.getReg());
682 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
685 PrintedTypes.set(OpInfo.getGenericTypeIndex());
686 return MRI.getType(Op.getReg());
689 void MIPrinter::print(const MachineInstr &MI) {
690 const auto *MF = MI.getParent()->getParent();
691 const auto &MRI = MF->getRegInfo();
692 const auto &SubTarget = MF->getSubtarget();
693 const auto *TRI = SubTarget.getRegisterInfo();
694 assert(TRI && "Expected target register info");
695 const auto *TII = SubTarget.getInstrInfo();
696 assert(TII && "Expected target instruction info");
697 if (MI.isCFIInstruction())
698 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
700 SmallBitVector PrintedTypes(8);
701 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
702 unsigned I = 0, E = MI.getNumOperands();
703 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
704 !MI.getOperand(I).isImplicit();
708 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
709 getTypeToPrint(MI, I, PrintedTypes, MRI),
715 if (MI.getFlag(MachineInstr::FrameSetup))
716 OS << "frame-setup ";
717 OS << TII->getName(MI.getOpcode());
721 bool NeedComma = false;
725 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
726 getTypeToPrint(MI, I, PrintedTypes, MRI));
730 if (MI.getDebugLoc()) {
733 OS << " debug-location ";
734 MI.getDebugLoc()->printAsOperand(OS, MST);
737 if (!MI.memoperands_empty()) {
739 const LLVMContext &Context = MF->getFunction()->getContext();
740 bool NeedComma = false;
741 for (const auto *Op : MI.memoperands()) {
744 print(Context, *TII, *Op);
750 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
751 OS << "%bb." << MBB.getNumber();
752 if (const auto *BB = MBB.getBasicBlock()) {
754 OS << '.' << BB->getName();
758 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
765 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
768 printLLVMNameWithoutPrefix(OS, BB.getName());
771 const Function *F = BB.getParent();
773 if (F == MST.getCurrentFunction()) {
774 Slot = MST.getLocalSlot(&BB);
776 ModuleSlotTracker CustomMST(F->getParent(),
777 /*ShouldInitializeAllMetadata=*/false);
778 CustomMST.incorporateFunction(*F);
779 Slot = CustomMST.getLocalSlot(&BB);
781 printIRSlotNumber(OS, Slot);
784 void MIPrinter::printIRValueReference(const Value &V) {
785 if (isa<GlobalValue>(V)) {
786 V.printAsOperand(OS, /*PrintType=*/false, MST);
789 if (isa<Constant>(V)) {
790 // Machine memory operands can load/store to/from constant value pointers.
792 V.printAsOperand(OS, /*PrintType=*/true, MST);
798 printLLVMNameWithoutPrefix(OS, V.getName());
801 printIRSlotNumber(OS, MST.getLocalSlot(&V));
804 void MIPrinter::printStackObjectReference(int FrameIndex) {
805 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
806 assert(ObjectInfo != StackObjectOperandMapping.end() &&
807 "Invalid frame index");
808 const FrameIndexOperand &Operand = ObjectInfo->second;
809 if (Operand.IsFixed) {
810 OS << "%fixed-stack." << Operand.ID;
813 OS << "%stack." << Operand.ID;
814 if (!Operand.Name.empty())
815 OS << '.' << Operand.Name;
818 void MIPrinter::printOffset(int64_t Offset) {
822 OS << " - " << -Offset;
825 OS << " + " << Offset;
828 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
829 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
830 for (const auto &I : Flags) {
838 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
839 if (!Op.getTargetFlags())
842 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
843 assert(TII && "expected instruction info");
844 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
845 OS << "target-flags(";
846 const bool HasDirectFlags = Flags.first;
847 const bool HasBitmaskFlags = Flags.second;
848 if (!HasDirectFlags && !HasBitmaskFlags) {
852 if (HasDirectFlags) {
853 if (const auto *Name = getTargetFlagName(TII, Flags.first))
856 OS << "<unknown target flag>";
858 if (!HasBitmaskFlags) {
862 bool IsCommaNeeded = HasDirectFlags;
863 unsigned BitMask = Flags.second;
864 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
865 for (const auto &Mask : BitMasks) {
866 // Check if the flag's bitmask has the bits of the current mask set.
867 if ((BitMask & Mask.first) == Mask.first) {
870 IsCommaNeeded = true;
872 // Clear the bits which were serialized from the flag's bitmask.
873 BitMask &= ~(Mask.first);
877 // When the resulting flag's bitmask isn't zero, we know that we didn't
878 // serialize all of the bit flags.
881 OS << "<unknown bitmask target flag>";
886 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
887 const auto *TII = MF.getSubtarget().getInstrInfo();
888 assert(TII && "expected instruction info");
889 auto Indices = TII->getSerializableTargetIndices();
890 for (const auto &I : Indices) {
891 if (I.first == Index) {
898 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
899 unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
901 printTargetFlags(Op);
902 switch (Op.getType()) {
903 case MachineOperand::MO_Register:
905 OS << (Op.isDef() ? "implicit-def " : "implicit ");
906 else if (!IsDef && Op.isDef())
907 // Print the 'def' flag only when the operand is defined after '='.
909 if (Op.isInternalRead())
917 if (Op.isEarlyClobber())
918 OS << "early-clobber ";
921 printReg(Op.getReg(), OS, TRI);
922 // Print the sub register.
923 if (Op.getSubReg() != 0)
924 OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
925 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
926 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
927 if (TypeToPrint.isValid())
928 OS << '(' << TypeToPrint << ')';
930 case MachineOperand::MO_Immediate:
933 case MachineOperand::MO_CImmediate:
934 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
936 case MachineOperand::MO_FPImmediate:
937 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
939 case MachineOperand::MO_MachineBasicBlock:
940 printMBBReference(*Op.getMBB());
942 case MachineOperand::MO_FrameIndex:
943 printStackObjectReference(Op.getIndex());
945 case MachineOperand::MO_ConstantPoolIndex:
946 OS << "%const." << Op.getIndex();
947 printOffset(Op.getOffset());
949 case MachineOperand::MO_TargetIndex:
950 OS << "target-index(";
951 if (const auto *Name = getTargetIndexName(
952 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
957 printOffset(Op.getOffset());
959 case MachineOperand::MO_JumpTableIndex:
960 OS << "%jump-table." << Op.getIndex();
962 case MachineOperand::MO_ExternalSymbol: {
963 StringRef Name = Op.getSymbolName();
968 printLLVMNameWithoutPrefix(OS, Name);
970 printOffset(Op.getOffset());
973 case MachineOperand::MO_GlobalAddress:
974 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
975 printOffset(Op.getOffset());
977 case MachineOperand::MO_BlockAddress:
978 OS << "blockaddress(";
979 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
982 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
984 printOffset(Op.getOffset());
986 case MachineOperand::MO_RegisterMask: {
987 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
988 if (RegMaskInfo != RegisterMaskIds.end())
989 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
991 printCustomRegMask(Op.getRegMask(), OS, TRI);
994 case MachineOperand::MO_RegisterLiveOut: {
995 const uint32_t *RegMask = Op.getRegLiveOut();
997 bool IsCommaNeeded = false;
998 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
999 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
1002 printReg(Reg, OS, TRI);
1003 IsCommaNeeded = true;
1009 case MachineOperand::MO_Metadata:
1010 Op.getMetadata()->printAsOperand(OS, MST);
1012 case MachineOperand::MO_MCSymbol:
1013 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
1015 case MachineOperand::MO_CFIIndex: {
1016 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
1017 print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
1020 case MachineOperand::MO_IntrinsicID: {
1021 Intrinsic::ID ID = Op.getIntrinsicID();
1022 if (ID < Intrinsic::num_intrinsics)
1023 OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
1025 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
1026 const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
1027 OS << "intrinsic(@" << TII->getName(ID) << ')';
1031 case MachineOperand::MO_Predicate: {
1032 auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
1033 OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
1034 << CmpInst::getPredicateName(Pred) << ')';
1040 static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
1041 unsigned TMMOFlag) {
1042 auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
1043 for (const auto &I : Flags) {
1044 if (I.first == TMMOFlag) {
1051 void MIPrinter::print(const LLVMContext &Context, const TargetInstrInfo &TII,
1052 const MachineMemOperand &Op) {
1054 if (Op.isVolatile())
1056 if (Op.isNonTemporal())
1057 OS << "non-temporal ";
1058 if (Op.isDereferenceable())
1059 OS << "dereferenceable ";
1060 if (Op.isInvariant())
1062 if (Op.getFlags() & MachineMemOperand::MOTargetFlag1)
1063 OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag1)
1065 if (Op.getFlags() & MachineMemOperand::MOTargetFlag2)
1066 OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag2)
1068 if (Op.getFlags() & MachineMemOperand::MOTargetFlag3)
1069 OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag3)
1074 assert(Op.isStore() && "Non load machine operand must be a store");
1078 printSyncScope(Context, Op.getSyncScopeID());
1080 if (Op.getOrdering() != AtomicOrdering::NotAtomic)
1081 OS << toIRString(Op.getOrdering()) << ' ';
1082 if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
1083 OS << toIRString(Op.getFailureOrdering()) << ' ';
1086 if (const Value *Val = Op.getValue()) {
1087 OS << (Op.isLoad() ? " from " : " into ");
1088 printIRValueReference(*Val);
1089 } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
1090 OS << (Op.isLoad() ? " from " : " into ");
1091 assert(PVal && "Expected a pseudo source value");
1092 switch (PVal->kind()) {
1093 case PseudoSourceValue::Stack:
1096 case PseudoSourceValue::GOT:
1099 case PseudoSourceValue::JumpTable:
1102 case PseudoSourceValue::ConstantPool:
1103 OS << "constant-pool";
1105 case PseudoSourceValue::FixedStack:
1106 printStackObjectReference(
1107 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
1109 case PseudoSourceValue::GlobalValueCallEntry:
1110 OS << "call-entry ";
1111 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1112 OS, /*PrintType=*/false, MST);
1114 case PseudoSourceValue::ExternalSymbolCallEntry:
1115 OS << "call-entry $";
1116 printLLVMNameWithoutPrefix(
1117 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1119 case PseudoSourceValue::TargetCustom:
1120 llvm_unreachable("TargetCustom pseudo source values are not supported");
1124 printOffset(Op.getOffset());
1125 if (Op.getBaseAlignment() != Op.getSize())
1126 OS << ", align " << Op.getBaseAlignment();
1127 auto AAInfo = Op.getAAInfo();
1130 AAInfo.TBAA->printAsOperand(OS, MST);
1133 OS << ", !alias.scope ";
1134 AAInfo.Scope->printAsOperand(OS, MST);
1136 if (AAInfo.NoAlias) {
1137 OS << ", !noalias ";
1138 AAInfo.NoAlias->printAsOperand(OS, MST);
1140 if (Op.getRanges()) {
1142 Op.getRanges()->printAsOperand(OS, MST);
1147 void MIPrinter::printSyncScope(const LLVMContext &Context, SyncScope::ID SSID) {
1149 case SyncScope::System: {
1154 Context.getSyncScopeNames(SSNs);
1156 OS << "syncscope(\"";
1157 PrintEscapedString(SSNs[SSID], OS);
1164 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1165 const TargetRegisterInfo *TRI) {
1166 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1171 printReg(Reg, OS, TRI);
1174 void MIPrinter::print(const MCCFIInstruction &CFI,
1175 const TargetRegisterInfo *TRI) {
1176 switch (CFI.getOperation()) {
1177 case MCCFIInstruction::OpSameValue:
1178 OS << "same_value ";
1180 OS << "<mcsymbol> ";
1181 printCFIRegister(CFI.getRegister(), OS, TRI);
1183 case MCCFIInstruction::OpOffset:
1186 OS << "<mcsymbol> ";
1187 printCFIRegister(CFI.getRegister(), OS, TRI);
1188 OS << ", " << CFI.getOffset();
1190 case MCCFIInstruction::OpDefCfaRegister:
1191 OS << "def_cfa_register ";
1193 OS << "<mcsymbol> ";
1194 printCFIRegister(CFI.getRegister(), OS, TRI);
1196 case MCCFIInstruction::OpDefCfaOffset:
1197 OS << "def_cfa_offset ";
1199 OS << "<mcsymbol> ";
1200 OS << CFI.getOffset();
1202 case MCCFIInstruction::OpDefCfa:
1205 OS << "<mcsymbol> ";
1206 printCFIRegister(CFI.getRegister(), OS, TRI);
1207 OS << ", " << CFI.getOffset();
1210 // TODO: Print the other CFI Operations.
1211 OS << "<unserializable cfi operation>";
1216 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1217 yaml::Output Out(OS);
1218 Out << const_cast<Module &>(M);
1221 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1222 MIRPrinter Printer(OS);