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/CodeGen/MIRPrinter.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
20 #include "llvm/CodeGen/MIRYamlMapping.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSlotTracker.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Options.h"
39 #include "llvm/Support/YAMLTraits.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetIntrinsicInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
47 static cl::opt<bool> SimplifyMIR("simplify-mir",
48 cl::desc("Leave out unnecessary information when printing MIR"));
52 /// This structure describes how to print out stack object references.
53 struct FrameIndexOperand {
58 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
59 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
61 /// Return an ordinary stack object reference.
62 static FrameIndexOperand create(StringRef Name, unsigned ID) {
63 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
66 /// Return a fixed stack object reference.
67 static FrameIndexOperand createFixed(unsigned ID) {
68 return FrameIndexOperand("", ID, /*IsFixed=*/true);
72 } // end anonymous namespace
76 /// This class prints out the machine functions using the MIR serialization
80 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
81 /// Maps from stack object indices to operand indices which will be used when
82 /// printing frame index machine operands.
83 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
86 MIRPrinter(raw_ostream &OS) : OS(OS) {}
88 void print(const MachineFunction &MF);
90 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
91 const TargetRegisterInfo *TRI);
92 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
93 const MachineFrameInfo &MFI);
94 void convert(yaml::MachineFunction &MF,
95 const MachineConstantPool &ConstantPool);
96 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
97 const MachineJumpTableInfo &JTI);
98 void convertStackObjects(yaml::MachineFunction &YMF,
99 const MachineFunction &MF, ModuleSlotTracker &MST);
102 void initRegisterMaskIds(const MachineFunction &MF);
105 /// This class prints out the machine instructions using the MIR serialization
109 ModuleSlotTracker &MST;
110 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
111 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
113 bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
114 bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
117 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
118 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
119 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
120 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
121 StackObjectOperandMapping(StackObjectOperandMapping) {}
123 void print(const MachineBasicBlock &MBB);
125 void print(const MachineInstr &MI);
126 void printMBBReference(const MachineBasicBlock &MBB);
127 void printIRBlockReference(const BasicBlock &BB);
128 void printIRValueReference(const Value &V);
129 void printStackObjectReference(int FrameIndex);
130 void printOffset(int64_t Offset);
131 void printTargetFlags(const MachineOperand &Op);
132 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
133 unsigned I, bool ShouldPrintRegisterTies,
134 LLT TypeToPrint, bool IsDef = false);
135 void print(const MachineMemOperand &Op);
137 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
140 } // end namespace llvm
145 /// This struct serializes the LLVM IR module.
146 template <> struct BlockScalarTraits<Module> {
147 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
148 Mod.print(OS, nullptr);
150 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
151 llvm_unreachable("LLVM Module is supposed to be parsed separately");
156 } // end namespace yaml
157 } // end namespace llvm
159 static void printReg(unsigned Reg, raw_ostream &OS,
160 const TargetRegisterInfo *TRI) {
161 // TODO: Print Stack Slots.
164 else if (TargetRegisterInfo::isVirtualRegister(Reg))
165 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
166 else if (Reg < TRI->getNumRegs())
167 OS << '%' << StringRef(TRI->getName(Reg)).lower();
169 llvm_unreachable("Can't print this kind of register yet");
172 static void printReg(unsigned Reg, yaml::StringValue &Dest,
173 const TargetRegisterInfo *TRI) {
174 raw_string_ostream OS(Dest.Value);
175 printReg(Reg, OS, TRI);
178 void MIRPrinter::print(const MachineFunction &MF) {
179 initRegisterMaskIds(MF);
181 yaml::MachineFunction YamlMF;
182 YamlMF.Name = MF.getName();
183 YamlMF.Alignment = MF.getAlignment();
184 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
186 YamlMF.NoVRegs = MF.getProperties().hasProperty(
187 MachineFunctionProperties::Property::NoVRegs);
188 YamlMF.Legalized = MF.getProperties().hasProperty(
189 MachineFunctionProperties::Property::Legalized);
190 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
191 MachineFunctionProperties::Property::RegBankSelected);
192 YamlMF.Selected = MF.getProperties().hasProperty(
193 MachineFunctionProperties::Property::Selected);
195 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
196 ModuleSlotTracker MST(MF.getFunction()->getParent());
197 MST.incorporateFunction(*MF.getFunction());
198 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
199 convertStackObjects(YamlMF, MF, MST);
200 if (const auto *ConstantPool = MF.getConstantPool())
201 convert(YamlMF, *ConstantPool);
202 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
203 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
204 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
205 bool IsNewlineNeeded = false;
206 for (const auto &MBB : MF) {
209 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
211 IsNewlineNeeded = true;
214 yaml::Output Out(OS);
218 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
219 const TargetRegisterInfo *TRI) {
220 assert(RegMask && "Can't print an empty register mask");
221 OS << StringRef("CustomRegMask(");
223 bool IsRegInRegMaskFound = false;
224 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
225 // Check whether the register is asserted in regmask.
226 if (RegMask[I / 32] & (1u << (I % 32))) {
227 if (IsRegInRegMaskFound)
229 printReg(I, OS, TRI);
230 IsRegInRegMaskFound = true;
237 void MIRPrinter::convert(yaml::MachineFunction &MF,
238 const MachineRegisterInfo &RegInfo,
239 const TargetRegisterInfo *TRI) {
240 MF.TracksRegLiveness = RegInfo.tracksLiveness();
242 // Print the virtual register definitions.
243 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
244 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
245 yaml::VirtualRegisterDefinition VReg;
247 if (RegInfo.getRegClassOrNull(Reg))
249 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
250 else if (RegInfo.getRegBankOrNull(Reg))
251 VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
253 VReg.Class = std::string("_");
254 assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
255 "Generic registers must have a valid type");
257 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
259 printReg(PreferredReg, VReg.PreferredRegister, TRI);
260 MF.VirtualRegisters.push_back(VReg);
263 // Print the live ins.
264 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
265 yaml::MachineFunctionLiveIn LiveIn;
266 printReg(I->first, LiveIn.Register, TRI);
268 printReg(I->second, LiveIn.VirtualRegister, TRI);
269 MF.LiveIns.push_back(LiveIn);
272 // Prints the callee saved registers.
273 if (RegInfo.isUpdatedCSRsInitialized()) {
274 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
275 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
276 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
277 yaml::FlowStringValue Reg;
278 printReg(*I, Reg, TRI);
279 CalleeSavedRegisters.push_back(Reg);
281 MF.CalleeSavedRegisters = CalleeSavedRegisters;
285 void MIRPrinter::convert(ModuleSlotTracker &MST,
286 yaml::MachineFrameInfo &YamlMFI,
287 const MachineFrameInfo &MFI) {
288 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
289 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
290 YamlMFI.HasStackMap = MFI.hasStackMap();
291 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
292 YamlMFI.StackSize = MFI.getStackSize();
293 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
294 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
295 YamlMFI.AdjustsStack = MFI.adjustsStack();
296 YamlMFI.HasCalls = MFI.hasCalls();
297 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
298 ? MFI.getMaxCallFrameSize() : ~0u;
299 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
300 YamlMFI.HasVAStart = MFI.hasVAStart();
301 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
302 if (MFI.getSavePoint()) {
303 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
304 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
305 .printMBBReference(*MFI.getSavePoint());
307 if (MFI.getRestorePoint()) {
308 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
309 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
310 .printMBBReference(*MFI.getRestorePoint());
314 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
315 const MachineFunction &MF,
316 ModuleSlotTracker &MST) {
317 const MachineFrameInfo &MFI = MF.getFrameInfo();
318 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
319 // Process fixed stack objects.
321 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
322 if (MFI.isDeadObjectIndex(I))
325 yaml::FixedMachineStackObject YamlObject;
327 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
328 ? yaml::FixedMachineStackObject::SpillSlot
329 : yaml::FixedMachineStackObject::DefaultType;
330 YamlObject.Offset = MFI.getObjectOffset(I);
331 YamlObject.Size = MFI.getObjectSize(I);
332 YamlObject.Alignment = MFI.getObjectAlignment(I);
333 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
334 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
335 YMF.FixedStackObjects.push_back(YamlObject);
336 StackObjectOperandMapping.insert(
337 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
340 // Process ordinary stack objects.
342 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
343 if (MFI.isDeadObjectIndex(I))
346 yaml::MachineStackObject YamlObject;
348 if (const auto *Alloca = MFI.getObjectAllocation(I))
349 YamlObject.Name.Value =
350 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
351 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
352 ? yaml::MachineStackObject::SpillSlot
353 : MFI.isVariableSizedObjectIndex(I)
354 ? yaml::MachineStackObject::VariableSized
355 : yaml::MachineStackObject::DefaultType;
356 YamlObject.Offset = MFI.getObjectOffset(I);
357 YamlObject.Size = MFI.getObjectSize(I);
358 YamlObject.Alignment = MFI.getObjectAlignment(I);
360 YMF.StackObjects.push_back(YamlObject);
361 StackObjectOperandMapping.insert(std::make_pair(
362 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
365 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
366 yaml::StringValue Reg;
367 printReg(CSInfo.getReg(), Reg, TRI);
368 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
369 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
370 "Invalid stack object index");
371 const FrameIndexOperand &StackObject = StackObjectInfo->second;
372 if (StackObject.IsFixed)
373 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
375 YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
377 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
378 auto LocalObject = MFI.getLocalFrameObjectMap(I);
379 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
380 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
381 "Invalid stack object index");
382 const FrameIndexOperand &StackObject = StackObjectInfo->second;
383 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
384 YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
387 // Print the stack object references in the frame information class after
388 // converting the stack objects.
389 if (MFI.hasStackProtectorIndex()) {
390 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
391 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
392 .printStackObjectReference(MFI.getStackProtectorIndex());
395 // Print the debug variable information.
396 for (const MachineFunction::VariableDbgInfo &DebugVar :
397 MF.getVariableDbgInfo()) {
398 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
399 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
400 "Invalid stack object index");
401 const FrameIndexOperand &StackObject = StackObjectInfo->second;
402 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
403 auto &Object = YMF.StackObjects[StackObject.ID];
405 raw_string_ostream StrOS(Object.DebugVar.Value);
406 DebugVar.Var->printAsOperand(StrOS, MST);
409 raw_string_ostream StrOS(Object.DebugExpr.Value);
410 DebugVar.Expr->printAsOperand(StrOS, MST);
413 raw_string_ostream StrOS(Object.DebugLoc.Value);
414 DebugVar.Loc->printAsOperand(StrOS, MST);
419 void MIRPrinter::convert(yaml::MachineFunction &MF,
420 const MachineConstantPool &ConstantPool) {
422 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
423 // TODO: Serialize target specific constant pool entries.
424 if (Constant.isMachineConstantPoolEntry())
425 llvm_unreachable("Can't print target specific constant pool entries yet");
427 yaml::MachineConstantPoolValue YamlConstant;
429 raw_string_ostream StrOS(Str);
430 Constant.Val.ConstVal->printAsOperand(StrOS);
431 YamlConstant.ID = ID++;
432 YamlConstant.Value = StrOS.str();
433 YamlConstant.Alignment = Constant.getAlignment();
434 MF.Constants.push_back(YamlConstant);
438 void MIRPrinter::convert(ModuleSlotTracker &MST,
439 yaml::MachineJumpTable &YamlJTI,
440 const MachineJumpTableInfo &JTI) {
441 YamlJTI.Kind = JTI.getEntryKind();
443 for (const auto &Table : JTI.getJumpTables()) {
445 yaml::MachineJumpTable::Entry Entry;
447 for (const auto *MBB : Table.MBBs) {
448 raw_string_ostream StrOS(Str);
449 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
450 .printMBBReference(*MBB);
451 Entry.Blocks.push_back(StrOS.str());
454 YamlJTI.Entries.push_back(Entry);
458 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
459 const auto *TRI = MF.getSubtarget().getRegisterInfo();
461 for (const uint32_t *Mask : TRI->getRegMasks())
462 RegisterMaskIds.insert(std::make_pair(Mask, I++));
465 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
466 SmallVectorImpl<MachineBasicBlock*> &Result,
467 bool &IsFallthrough) {
468 SmallPtrSet<MachineBasicBlock*,8> Seen;
470 for (const MachineInstr &MI : MBB) {
473 for (const MachineOperand &MO : MI.operands()) {
476 MachineBasicBlock *Succ = MO.getMBB();
477 auto RP = Seen.insert(Succ);
479 Result.push_back(Succ);
482 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
483 IsFallthrough = I == MBB.end() || !I->isBarrier();
487 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
488 if (MBB.succ_size() <= 1)
490 if (!MBB.hasSuccessorProbabilities())
493 SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
495 BranchProbability::normalizeProbabilities(Normalized.begin(),
497 SmallVector<BranchProbability,8> Equal(Normalized.size());
498 BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
500 return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
503 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
504 SmallVector<MachineBasicBlock*,8> GuessedSuccs;
505 bool GuessedFallthrough;
506 guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
507 if (GuessedFallthrough) {
508 const MachineFunction &MF = *MBB.getParent();
509 MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
510 if (NextI != MF.end()) {
511 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
512 if (!is_contained(GuessedSuccs, Next))
513 GuessedSuccs.push_back(Next);
516 if (GuessedSuccs.size() != MBB.succ_size())
518 return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
522 void MIPrinter::print(const MachineBasicBlock &MBB) {
523 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
524 OS << "bb." << MBB.getNumber();
525 bool HasAttributes = false;
526 if (const auto *BB = MBB.getBasicBlock()) {
528 OS << "." << BB->getName();
530 HasAttributes = true;
532 int Slot = MST.getLocalSlot(BB);
534 OS << "<ir-block badref>";
536 OS << (Twine("%ir-block.") + Twine(Slot)).str();
539 if (MBB.hasAddressTaken()) {
540 OS << (HasAttributes ? ", " : " (");
541 OS << "address-taken";
542 HasAttributes = true;
545 OS << (HasAttributes ? ", " : " (");
547 HasAttributes = true;
549 if (MBB.getAlignment()) {
550 OS << (HasAttributes ? ", " : " (");
551 OS << "align " << MBB.getAlignment();
552 HasAttributes = true;
558 bool HasLineAttributes = false;
559 // Print the successors
560 bool canPredictProbs = canPredictBranchProbabilities(MBB);
561 if (!MBB.succ_empty() && (!SimplifyMIR || !canPredictProbs ||
562 !canPredictSuccessors(MBB))) {
563 OS.indent(2) << "successors: ";
564 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
565 if (I != MBB.succ_begin())
567 printMBBReference(**I);
568 if (!SimplifyMIR || !canPredictProbs)
570 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
574 HasLineAttributes = true;
577 // Print the live in registers.
578 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
579 if (MRI.tracksLiveness() && !MBB.livein_empty()) {
580 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
581 OS.indent(2) << "liveins: ";
583 for (const auto &LI : MBB.liveins()) {
587 printReg(LI.PhysReg, OS, &TRI);
588 if (!LI.LaneMask.all())
589 OS << ":0x" << PrintLaneMask(LI.LaneMask);
592 HasLineAttributes = true;
595 if (HasLineAttributes)
597 bool IsInBundle = false;
598 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
599 const MachineInstr &MI = *I;
600 if (IsInBundle && !MI.isInsideBundle()) {
601 OS.indent(2) << "}\n";
604 OS.indent(IsInBundle ? 4 : 2);
606 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
613 OS.indent(2) << "}\n";
616 /// Return true when an instruction has tied register that can't be determined
617 /// by the instruction's descriptor.
618 static bool hasComplexRegisterTies(const MachineInstr &MI) {
619 const MCInstrDesc &MCID = MI.getDesc();
620 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
621 const auto &Operand = MI.getOperand(I);
622 if (!Operand.isReg() || Operand.isDef())
623 // Ignore the defined registers as MCID marks only the uses as tied.
625 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
626 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
627 if (ExpectedTiedIdx != TiedIdx)
633 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
634 SmallBitVector &PrintedTypes,
635 const MachineRegisterInfo &MRI) {
636 const MachineOperand &Op = MI.getOperand(OpIdx);
640 if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
641 return MRI.getType(Op.getReg());
643 auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
644 if (!OpInfo.isGenericType())
645 return MRI.getType(Op.getReg());
647 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
650 PrintedTypes.set(OpInfo.getGenericTypeIndex());
651 return MRI.getType(Op.getReg());
654 void MIPrinter::print(const MachineInstr &MI) {
655 const auto *MF = MI.getParent()->getParent();
656 const auto &MRI = MF->getRegInfo();
657 const auto &SubTarget = MF->getSubtarget();
658 const auto *TRI = SubTarget.getRegisterInfo();
659 assert(TRI && "Expected target register info");
660 const auto *TII = SubTarget.getInstrInfo();
661 assert(TII && "Expected target instruction info");
662 if (MI.isCFIInstruction())
663 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
665 SmallBitVector PrintedTypes(8);
666 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
667 unsigned I = 0, E = MI.getNumOperands();
668 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
669 !MI.getOperand(I).isImplicit();
673 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
674 getTypeToPrint(MI, I, PrintedTypes, MRI),
680 if (MI.getFlag(MachineInstr::FrameSetup))
681 OS << "frame-setup ";
682 OS << TII->getName(MI.getOpcode());
686 bool NeedComma = false;
690 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
691 getTypeToPrint(MI, I, PrintedTypes, MRI));
695 if (MI.getDebugLoc()) {
698 OS << " debug-location ";
699 MI.getDebugLoc()->printAsOperand(OS, MST);
702 if (!MI.memoperands_empty()) {
704 bool NeedComma = false;
705 for (const auto *Op : MI.memoperands()) {
714 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
715 OS << "%bb." << MBB.getNumber();
716 if (const auto *BB = MBB.getBasicBlock()) {
718 OS << '.' << BB->getName();
722 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
729 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
732 printLLVMNameWithoutPrefix(OS, BB.getName());
735 const Function *F = BB.getParent();
737 if (F == MST.getCurrentFunction()) {
738 Slot = MST.getLocalSlot(&BB);
740 ModuleSlotTracker CustomMST(F->getParent(),
741 /*ShouldInitializeAllMetadata=*/false);
742 CustomMST.incorporateFunction(*F);
743 Slot = CustomMST.getLocalSlot(&BB);
745 printIRSlotNumber(OS, Slot);
748 void MIPrinter::printIRValueReference(const Value &V) {
749 if (isa<GlobalValue>(V)) {
750 V.printAsOperand(OS, /*PrintType=*/false, MST);
753 if (isa<Constant>(V)) {
754 // Machine memory operands can load/store to/from constant value pointers.
756 V.printAsOperand(OS, /*PrintType=*/true, MST);
762 printLLVMNameWithoutPrefix(OS, V.getName());
765 printIRSlotNumber(OS, MST.getLocalSlot(&V));
768 void MIPrinter::printStackObjectReference(int FrameIndex) {
769 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
770 assert(ObjectInfo != StackObjectOperandMapping.end() &&
771 "Invalid frame index");
772 const FrameIndexOperand &Operand = ObjectInfo->second;
773 if (Operand.IsFixed) {
774 OS << "%fixed-stack." << Operand.ID;
777 OS << "%stack." << Operand.ID;
778 if (!Operand.Name.empty())
779 OS << '.' << Operand.Name;
782 void MIPrinter::printOffset(int64_t Offset) {
786 OS << " - " << -Offset;
789 OS << " + " << Offset;
792 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
793 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
794 for (const auto &I : Flags) {
802 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
803 if (!Op.getTargetFlags())
806 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
807 assert(TII && "expected instruction info");
808 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
809 OS << "target-flags(";
810 const bool HasDirectFlags = Flags.first;
811 const bool HasBitmaskFlags = Flags.second;
812 if (!HasDirectFlags && !HasBitmaskFlags) {
816 if (HasDirectFlags) {
817 if (const auto *Name = getTargetFlagName(TII, Flags.first))
820 OS << "<unknown target flag>";
822 if (!HasBitmaskFlags) {
826 bool IsCommaNeeded = HasDirectFlags;
827 unsigned BitMask = Flags.second;
828 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
829 for (const auto &Mask : BitMasks) {
830 // Check if the flag's bitmask has the bits of the current mask set.
831 if ((BitMask & Mask.first) == Mask.first) {
834 IsCommaNeeded = true;
836 // Clear the bits which were serialized from the flag's bitmask.
837 BitMask &= ~(Mask.first);
841 // When the resulting flag's bitmask isn't zero, we know that we didn't
842 // serialize all of the bit flags.
845 OS << "<unknown bitmask target flag>";
850 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
851 const auto *TII = MF.getSubtarget().getInstrInfo();
852 assert(TII && "expected instruction info");
853 auto Indices = TII->getSerializableTargetIndices();
854 for (const auto &I : Indices) {
855 if (I.first == Index) {
862 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
863 unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
865 printTargetFlags(Op);
866 switch (Op.getType()) {
867 case MachineOperand::MO_Register:
869 OS << (Op.isDef() ? "implicit-def " : "implicit ");
870 else if (!IsDef && Op.isDef())
871 // Print the 'def' flag only when the operand is defined after '='.
873 if (Op.isInternalRead())
881 if (Op.isEarlyClobber())
882 OS << "early-clobber ";
885 printReg(Op.getReg(), OS, TRI);
886 // Print the sub register.
887 if (Op.getSubReg() != 0)
888 OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
889 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
890 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
891 if (TypeToPrint.isValid())
892 OS << '(' << TypeToPrint << ')';
894 case MachineOperand::MO_Immediate:
897 case MachineOperand::MO_CImmediate:
898 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
900 case MachineOperand::MO_FPImmediate:
901 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
903 case MachineOperand::MO_MachineBasicBlock:
904 printMBBReference(*Op.getMBB());
906 case MachineOperand::MO_FrameIndex:
907 printStackObjectReference(Op.getIndex());
909 case MachineOperand::MO_ConstantPoolIndex:
910 OS << "%const." << Op.getIndex();
911 printOffset(Op.getOffset());
913 case MachineOperand::MO_TargetIndex: {
914 OS << "target-index(";
915 if (const auto *Name = getTargetIndexName(
916 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
921 printOffset(Op.getOffset());
924 case MachineOperand::MO_JumpTableIndex:
925 OS << "%jump-table." << Op.getIndex();
927 case MachineOperand::MO_ExternalSymbol:
929 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
930 printOffset(Op.getOffset());
932 case MachineOperand::MO_GlobalAddress:
933 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
934 printOffset(Op.getOffset());
936 case MachineOperand::MO_BlockAddress:
937 OS << "blockaddress(";
938 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
941 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
943 printOffset(Op.getOffset());
945 case MachineOperand::MO_RegisterMask: {
946 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
947 if (RegMaskInfo != RegisterMaskIds.end())
948 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
950 printCustomRegMask(Op.getRegMask(), OS, TRI);
953 case MachineOperand::MO_RegisterLiveOut: {
954 const uint32_t *RegMask = Op.getRegLiveOut();
956 bool IsCommaNeeded = false;
957 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
958 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
961 printReg(Reg, OS, TRI);
962 IsCommaNeeded = true;
968 case MachineOperand::MO_Metadata:
969 Op.getMetadata()->printAsOperand(OS, MST);
971 case MachineOperand::MO_MCSymbol:
972 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
974 case MachineOperand::MO_CFIIndex: {
975 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
976 print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
979 case MachineOperand::MO_IntrinsicID: {
980 Intrinsic::ID ID = Op.getIntrinsicID();
981 if (ID < Intrinsic::num_intrinsics)
982 OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
984 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
985 const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
986 OS << "intrinsic(@" << TII->getName(ID) << ')';
990 case MachineOperand::MO_Predicate: {
991 auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
992 OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
993 << CmpInst::getPredicateName(Pred) << ')';
999 void MIPrinter::print(const MachineMemOperand &Op) {
1001 // TODO: Print operand's target specific flags.
1002 if (Op.isVolatile())
1004 if (Op.isNonTemporal())
1005 OS << "non-temporal ";
1006 if (Op.isDereferenceable())
1007 OS << "dereferenceable ";
1008 if (Op.isInvariant())
1013 assert(Op.isStore() && "Non load machine operand must be a store");
1017 if (Op.getSynchScope() == SynchronizationScope::SingleThread)
1018 OS << "singlethread ";
1020 if (Op.getOrdering() != AtomicOrdering::NotAtomic)
1021 OS << toIRString(Op.getOrdering()) << ' ';
1022 if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
1023 OS << toIRString(Op.getFailureOrdering()) << ' ';
1026 if (const Value *Val = Op.getValue()) {
1027 OS << (Op.isLoad() ? " from " : " into ");
1028 printIRValueReference(*Val);
1029 } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
1030 OS << (Op.isLoad() ? " from " : " into ");
1031 assert(PVal && "Expected a pseudo source value");
1032 switch (PVal->kind()) {
1033 case PseudoSourceValue::Stack:
1036 case PseudoSourceValue::GOT:
1039 case PseudoSourceValue::JumpTable:
1042 case PseudoSourceValue::ConstantPool:
1043 OS << "constant-pool";
1045 case PseudoSourceValue::FixedStack:
1046 printStackObjectReference(
1047 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
1049 case PseudoSourceValue::GlobalValueCallEntry:
1050 OS << "call-entry ";
1051 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1052 OS, /*PrintType=*/false, MST);
1054 case PseudoSourceValue::ExternalSymbolCallEntry:
1055 OS << "call-entry $";
1056 printLLVMNameWithoutPrefix(
1057 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1059 case PseudoSourceValue::TargetCustom:
1060 llvm_unreachable("TargetCustom pseudo source values are not supported");
1064 printOffset(Op.getOffset());
1065 if (Op.getBaseAlignment() != Op.getSize())
1066 OS << ", align " << Op.getBaseAlignment();
1067 auto AAInfo = Op.getAAInfo();
1070 AAInfo.TBAA->printAsOperand(OS, MST);
1073 OS << ", !alias.scope ";
1074 AAInfo.Scope->printAsOperand(OS, MST);
1076 if (AAInfo.NoAlias) {
1077 OS << ", !noalias ";
1078 AAInfo.NoAlias->printAsOperand(OS, MST);
1080 if (Op.getRanges()) {
1082 Op.getRanges()->printAsOperand(OS, MST);
1087 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1088 const TargetRegisterInfo *TRI) {
1089 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1094 printReg(Reg, OS, TRI);
1097 void MIPrinter::print(const MCCFIInstruction &CFI,
1098 const TargetRegisterInfo *TRI) {
1099 switch (CFI.getOperation()) {
1100 case MCCFIInstruction::OpSameValue:
1101 OS << "same_value ";
1103 OS << "<mcsymbol> ";
1104 printCFIRegister(CFI.getRegister(), OS, TRI);
1106 case MCCFIInstruction::OpOffset:
1109 OS << "<mcsymbol> ";
1110 printCFIRegister(CFI.getRegister(), OS, TRI);
1111 OS << ", " << CFI.getOffset();
1113 case MCCFIInstruction::OpDefCfaRegister:
1114 OS << "def_cfa_register ";
1116 OS << "<mcsymbol> ";
1117 printCFIRegister(CFI.getRegister(), OS, TRI);
1119 case MCCFIInstruction::OpDefCfaOffset:
1120 OS << "def_cfa_offset ";
1122 OS << "<mcsymbol> ";
1123 OS << CFI.getOffset();
1125 case MCCFIInstruction::OpDefCfa:
1128 OS << "<mcsymbol> ";
1129 printCFIRegister(CFI.getRegister(), OS, TRI);
1130 OS << ", " << CFI.getOffset();
1133 // TODO: Print the other CFI Operations.
1134 OS << "<unserializable cfi operation>";
1139 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1140 yaml::Output Out(OS);
1141 Out << const_cast<Module &>(M);
1144 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1145 MIRPrinter Printer(OS);