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/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MIRYamlMapping.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/YAMLTraits.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
42 /// This structure describes how to print out stack object references.
43 struct FrameIndexOperand {
48 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
49 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
51 /// Return an ordinary stack object reference.
52 static FrameIndexOperand create(StringRef Name, unsigned ID) {
53 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
56 /// Return a fixed stack object reference.
57 static FrameIndexOperand createFixed(unsigned ID) {
58 return FrameIndexOperand("", ID, /*IsFixed=*/true);
62 } // end anonymous namespace
66 /// This class prints out the machine functions using the MIR serialization
70 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
71 /// Maps from stack object indices to operand indices which will be used when
72 /// printing frame index machine operands.
73 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
76 MIRPrinter(raw_ostream &OS) : OS(OS) {}
78 void print(const MachineFunction &MF);
80 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
81 const TargetRegisterInfo *TRI);
82 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
83 const MachineFrameInfo &MFI);
84 void convert(yaml::MachineFunction &MF,
85 const MachineConstantPool &ConstantPool);
86 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
87 const MachineJumpTableInfo &JTI);
88 void convertStackObjects(yaml::MachineFunction &MF,
89 const MachineFrameInfo &MFI, MachineModuleInfo &MMI,
90 ModuleSlotTracker &MST,
91 const TargetRegisterInfo *TRI);
94 void initRegisterMaskIds(const MachineFunction &MF);
97 /// This class prints out the machine instructions using the MIR serialization
101 ModuleSlotTracker &MST;
102 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
103 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
106 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
107 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
108 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
109 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
110 StackObjectOperandMapping(StackObjectOperandMapping) {}
112 void print(const MachineBasicBlock &MBB);
114 void print(const MachineInstr &MI);
115 void printMBBReference(const MachineBasicBlock &MBB);
116 void printIRBlockReference(const BasicBlock &BB);
117 void printIRValueReference(const Value &V);
118 void printStackObjectReference(int FrameIndex);
119 void printOffset(int64_t Offset);
120 void printTargetFlags(const MachineOperand &Op);
121 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
122 unsigned I, bool ShouldPrintRegisterTies, bool IsDef = false);
123 void print(const MachineMemOperand &Op);
125 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
128 } // end namespace llvm
133 /// This struct serializes the LLVM IR module.
134 template <> struct BlockScalarTraits<Module> {
135 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
136 Mod.print(OS, nullptr);
138 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
139 llvm_unreachable("LLVM Module is supposed to be parsed separately");
144 } // end namespace yaml
145 } // end namespace llvm
147 static void printReg(unsigned Reg, raw_ostream &OS,
148 const TargetRegisterInfo *TRI) {
149 // TODO: Print Stack Slots.
152 else if (TargetRegisterInfo::isVirtualRegister(Reg))
153 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
154 else if (Reg < TRI->getNumRegs())
155 OS << '%' << StringRef(TRI->getName(Reg)).lower();
157 llvm_unreachable("Can't print this kind of register yet");
160 static void printReg(unsigned Reg, yaml::StringValue &Dest,
161 const TargetRegisterInfo *TRI) {
162 raw_string_ostream OS(Dest.Value);
163 printReg(Reg, OS, TRI);
166 void MIRPrinter::print(const MachineFunction &MF) {
167 initRegisterMaskIds(MF);
169 yaml::MachineFunction YamlMF;
170 YamlMF.Name = MF.getName();
171 YamlMF.Alignment = MF.getAlignment();
172 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
173 YamlMF.HasInlineAsm = MF.hasInlineAsm();
174 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
175 ModuleSlotTracker MST(MF.getFunction()->getParent());
176 MST.incorporateFunction(*MF.getFunction());
177 convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
178 convertStackObjects(YamlMF, *MF.getFrameInfo(), MF.getMMI(), MST,
179 MF.getSubtarget().getRegisterInfo());
180 if (const auto *ConstantPool = MF.getConstantPool())
181 convert(YamlMF, *ConstantPool);
182 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
183 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
184 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
185 bool IsNewlineNeeded = false;
186 for (const auto &MBB : MF) {
189 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
191 IsNewlineNeeded = true;
194 yaml::Output Out(OS);
198 void MIRPrinter::convert(yaml::MachineFunction &MF,
199 const MachineRegisterInfo &RegInfo,
200 const TargetRegisterInfo *TRI) {
201 MF.IsSSA = RegInfo.isSSA();
202 MF.TracksRegLiveness = RegInfo.tracksLiveness();
203 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
205 // Print the virtual register definitions.
206 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
207 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
208 yaml::VirtualRegisterDefinition VReg;
211 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
212 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
214 printReg(PreferredReg, VReg.PreferredRegister, TRI);
215 MF.VirtualRegisters.push_back(VReg);
218 // Print the live ins.
219 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
220 yaml::MachineFunctionLiveIn LiveIn;
221 printReg(I->first, LiveIn.Register, TRI);
223 printReg(I->second, LiveIn.VirtualRegister, TRI);
224 MF.LiveIns.push_back(LiveIn);
226 // The used physical register mask is printed as an inverted callee saved
228 const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
229 if (UsedPhysRegMask.none())
231 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
232 for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
233 if (!UsedPhysRegMask[I]) {
234 yaml::FlowStringValue Reg;
235 printReg(I, Reg, TRI);
236 CalleeSavedRegisters.push_back(Reg);
239 MF.CalleeSavedRegisters = CalleeSavedRegisters;
242 void MIRPrinter::convert(ModuleSlotTracker &MST,
243 yaml::MachineFrameInfo &YamlMFI,
244 const MachineFrameInfo &MFI) {
245 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
246 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
247 YamlMFI.HasStackMap = MFI.hasStackMap();
248 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
249 YamlMFI.StackSize = MFI.getStackSize();
250 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
251 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
252 YamlMFI.AdjustsStack = MFI.adjustsStack();
253 YamlMFI.HasCalls = MFI.hasCalls();
254 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
255 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
256 YamlMFI.HasVAStart = MFI.hasVAStart();
257 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
258 if (MFI.getSavePoint()) {
259 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
260 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
261 .printMBBReference(*MFI.getSavePoint());
263 if (MFI.getRestorePoint()) {
264 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
265 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
266 .printMBBReference(*MFI.getRestorePoint());
270 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
271 const MachineFrameInfo &MFI,
272 MachineModuleInfo &MMI,
273 ModuleSlotTracker &MST,
274 const TargetRegisterInfo *TRI) {
275 // Process fixed stack objects.
277 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
278 if (MFI.isDeadObjectIndex(I))
281 yaml::FixedMachineStackObject YamlObject;
283 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
284 ? yaml::FixedMachineStackObject::SpillSlot
285 : yaml::FixedMachineStackObject::DefaultType;
286 YamlObject.Offset = MFI.getObjectOffset(I);
287 YamlObject.Size = MFI.getObjectSize(I);
288 YamlObject.Alignment = MFI.getObjectAlignment(I);
289 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
290 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
291 MF.FixedStackObjects.push_back(YamlObject);
292 StackObjectOperandMapping.insert(
293 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
296 // Process ordinary stack objects.
298 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
299 if (MFI.isDeadObjectIndex(I))
302 yaml::MachineStackObject YamlObject;
304 if (const auto *Alloca = MFI.getObjectAllocation(I))
305 YamlObject.Name.Value =
306 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
307 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
308 ? yaml::MachineStackObject::SpillSlot
309 : MFI.isVariableSizedObjectIndex(I)
310 ? yaml::MachineStackObject::VariableSized
311 : yaml::MachineStackObject::DefaultType;
312 YamlObject.Offset = MFI.getObjectOffset(I);
313 YamlObject.Size = MFI.getObjectSize(I);
314 YamlObject.Alignment = MFI.getObjectAlignment(I);
316 MF.StackObjects.push_back(YamlObject);
317 StackObjectOperandMapping.insert(std::make_pair(
318 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
321 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
322 yaml::StringValue Reg;
323 printReg(CSInfo.getReg(), Reg, TRI);
324 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
325 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
326 "Invalid stack object index");
327 const FrameIndexOperand &StackObject = StackObjectInfo->second;
328 if (StackObject.IsFixed)
329 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
331 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
333 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
334 auto LocalObject = MFI.getLocalFrameObjectMap(I);
335 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
336 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
337 "Invalid stack object index");
338 const FrameIndexOperand &StackObject = StackObjectInfo->second;
339 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
340 MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
343 // Print the stack object references in the frame information class after
344 // converting the stack objects.
345 if (MFI.hasStackProtectorIndex()) {
346 raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
347 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
348 .printStackObjectReference(MFI.getStackProtectorIndex());
351 // Print the debug variable information.
352 for (MachineModuleInfo::VariableDbgInfo &DebugVar :
353 MMI.getVariableDbgInfo()) {
354 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
355 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
356 "Invalid stack object index");
357 const FrameIndexOperand &StackObject = StackObjectInfo->second;
358 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
359 auto &Object = MF.StackObjects[StackObject.ID];
361 raw_string_ostream StrOS(Object.DebugVar.Value);
362 DebugVar.Var->printAsOperand(StrOS, MST);
365 raw_string_ostream StrOS(Object.DebugExpr.Value);
366 DebugVar.Expr->printAsOperand(StrOS, MST);
369 raw_string_ostream StrOS(Object.DebugLoc.Value);
370 DebugVar.Loc->printAsOperand(StrOS, MST);
375 void MIRPrinter::convert(yaml::MachineFunction &MF,
376 const MachineConstantPool &ConstantPool) {
378 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
379 // TODO: Serialize target specific constant pool entries.
380 if (Constant.isMachineConstantPoolEntry())
381 llvm_unreachable("Can't print target specific constant pool entries yet");
383 yaml::MachineConstantPoolValue YamlConstant;
385 raw_string_ostream StrOS(Str);
386 Constant.Val.ConstVal->printAsOperand(StrOS);
387 YamlConstant.ID = ID++;
388 YamlConstant.Value = StrOS.str();
389 YamlConstant.Alignment = Constant.getAlignment();
390 MF.Constants.push_back(YamlConstant);
394 void MIRPrinter::convert(ModuleSlotTracker &MST,
395 yaml::MachineJumpTable &YamlJTI,
396 const MachineJumpTableInfo &JTI) {
397 YamlJTI.Kind = JTI.getEntryKind();
399 for (const auto &Table : JTI.getJumpTables()) {
401 yaml::MachineJumpTable::Entry Entry;
403 for (const auto *MBB : Table.MBBs) {
404 raw_string_ostream StrOS(Str);
405 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
406 .printMBBReference(*MBB);
407 Entry.Blocks.push_back(StrOS.str());
410 YamlJTI.Entries.push_back(Entry);
414 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
415 const auto *TRI = MF.getSubtarget().getRegisterInfo();
417 for (const uint32_t *Mask : TRI->getRegMasks())
418 RegisterMaskIds.insert(std::make_pair(Mask, I++));
421 void MIPrinter::print(const MachineBasicBlock &MBB) {
422 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
423 OS << "bb." << MBB.getNumber();
424 bool HasAttributes = false;
425 if (const auto *BB = MBB.getBasicBlock()) {
427 OS << "." << BB->getName();
429 HasAttributes = true;
431 int Slot = MST.getLocalSlot(BB);
433 OS << "<ir-block badref>";
435 OS << (Twine("%ir-block.") + Twine(Slot)).str();
438 if (MBB.hasAddressTaken()) {
439 OS << (HasAttributes ? ", " : " (");
440 OS << "address-taken";
441 HasAttributes = true;
444 OS << (HasAttributes ? ", " : " (");
446 HasAttributes = true;
448 if (MBB.getAlignment()) {
449 OS << (HasAttributes ? ", " : " (");
450 OS << "align " << MBB.getAlignment();
451 HasAttributes = true;
457 bool HasLineAttributes = false;
458 // Print the successors
459 if (!MBB.succ_empty()) {
460 OS.indent(2) << "successors: ";
461 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
462 if (I != MBB.succ_begin())
464 printMBBReference(**I);
465 if (MBB.hasSuccessorWeights())
466 OS << '(' << MBB.getSuccWeight(I) << ')';
469 HasLineAttributes = true;
472 // Print the live in registers.
473 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
474 assert(TRI && "Expected target register info");
475 if (!MBB.livein_empty()) {
476 OS.indent(2) << "liveins: ";
478 for (const auto &LI : MBB.liveins()) {
482 printReg(LI.PhysReg, OS, TRI);
483 if (LI.LaneMask != ~0u)
484 OS << format(":%08X", LI.LaneMask);
487 HasLineAttributes = true;
490 if (HasLineAttributes)
492 bool IsInBundle = false;
493 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
494 const MachineInstr &MI = *I;
495 if (IsInBundle && !MI.isInsideBundle()) {
496 OS.indent(2) << "}\n";
499 OS.indent(IsInBundle ? 4 : 2);
501 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
508 OS.indent(2) << "}\n";
511 /// Return true when an instruction has tied register that can't be determined
512 /// by the instruction's descriptor.
513 static bool hasComplexRegisterTies(const MachineInstr &MI) {
514 const MCInstrDesc &MCID = MI.getDesc();
515 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
516 const auto &Operand = MI.getOperand(I);
517 if (!Operand.isReg() || Operand.isDef())
518 // Ignore the defined registers as MCID marks only the uses as tied.
520 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
521 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
522 if (ExpectedTiedIdx != TiedIdx)
528 void MIPrinter::print(const MachineInstr &MI) {
529 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
530 const auto *TRI = SubTarget.getRegisterInfo();
531 assert(TRI && "Expected target register info");
532 const auto *TII = SubTarget.getInstrInfo();
533 assert(TII && "Expected target instruction info");
534 if (MI.isCFIInstruction())
535 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
537 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
538 unsigned I = 0, E = MI.getNumOperands();
539 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
540 !MI.getOperand(I).isImplicit();
544 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, /*IsDef=*/true);
549 if (MI.getFlag(MachineInstr::FrameSetup))
550 OS << "frame-setup ";
551 OS << TII->getName(MI.getOpcode());
555 bool NeedComma = false;
559 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies);
563 if (MI.getDebugLoc()) {
566 OS << " debug-location ";
567 MI.getDebugLoc()->printAsOperand(OS, MST);
570 if (!MI.memoperands_empty()) {
572 bool NeedComma = false;
573 for (const auto *Op : MI.memoperands()) {
582 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
583 OS << "%bb." << MBB.getNumber();
584 if (const auto *BB = MBB.getBasicBlock()) {
586 OS << '.' << BB->getName();
590 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
597 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
600 printLLVMNameWithoutPrefix(OS, BB.getName());
603 const Function *F = BB.getParent();
605 if (F == MST.getCurrentFunction()) {
606 Slot = MST.getLocalSlot(&BB);
608 ModuleSlotTracker CustomMST(F->getParent(),
609 /*ShouldInitializeAllMetadata=*/false);
610 CustomMST.incorporateFunction(*F);
611 Slot = CustomMST.getLocalSlot(&BB);
613 printIRSlotNumber(OS, Slot);
616 void MIPrinter::printIRValueReference(const Value &V) {
617 if (isa<GlobalValue>(V)) {
618 V.printAsOperand(OS, /*PrintType=*/false, MST);
621 if (isa<Constant>(V)) {
622 // Machine memory operands can load/store to/from constant value pointers.
624 V.printAsOperand(OS, /*PrintType=*/true, MST);
630 printLLVMNameWithoutPrefix(OS, V.getName());
633 printIRSlotNumber(OS, MST.getLocalSlot(&V));
636 void MIPrinter::printStackObjectReference(int FrameIndex) {
637 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
638 assert(ObjectInfo != StackObjectOperandMapping.end() &&
639 "Invalid frame index");
640 const FrameIndexOperand &Operand = ObjectInfo->second;
641 if (Operand.IsFixed) {
642 OS << "%fixed-stack." << Operand.ID;
645 OS << "%stack." << Operand.ID;
646 if (!Operand.Name.empty())
647 OS << '.' << Operand.Name;
650 void MIPrinter::printOffset(int64_t Offset) {
654 OS << " - " << -Offset;
657 OS << " + " << Offset;
660 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
661 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
662 for (const auto &I : Flags) {
670 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
671 if (!Op.getTargetFlags())
674 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
675 assert(TII && "expected instruction info");
676 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
677 OS << "target-flags(";
678 const bool HasDirectFlags = Flags.first;
679 const bool HasBitmaskFlags = Flags.second;
680 if (!HasDirectFlags && !HasBitmaskFlags) {
684 if (HasDirectFlags) {
685 if (const auto *Name = getTargetFlagName(TII, Flags.first))
688 OS << "<unknown target flag>";
690 if (!HasBitmaskFlags) {
694 bool IsCommaNeeded = HasDirectFlags;
695 unsigned BitMask = Flags.second;
696 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
697 for (const auto &Mask : BitMasks) {
698 // Check if the flag's bitmask has the bits of the current mask set.
699 if ((BitMask & Mask.first) == Mask.first) {
702 IsCommaNeeded = true;
704 // Clear the bits which were serialized from the flag's bitmask.
705 BitMask &= ~(Mask.first);
709 // When the resulting flag's bitmask isn't zero, we know that we didn't
710 // serialize all of the bit flags.
713 OS << "<unknown bitmask target flag>";
718 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
719 const auto *TII = MF.getSubtarget().getInstrInfo();
720 assert(TII && "expected instruction info");
721 auto Indices = TII->getSerializableTargetIndices();
722 for (const auto &I : Indices) {
723 if (I.first == Index) {
730 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
731 unsigned I, bool ShouldPrintRegisterTies, bool IsDef) {
732 printTargetFlags(Op);
733 switch (Op.getType()) {
734 case MachineOperand::MO_Register:
736 OS << (Op.isDef() ? "implicit-def " : "implicit ");
737 else if (!IsDef && Op.isDef())
738 // Print the 'def' flag only when the operand is defined after '='.
740 if (Op.isInternalRead())
748 if (Op.isEarlyClobber())
749 OS << "early-clobber ";
752 printReg(Op.getReg(), OS, TRI);
753 // Print the sub register.
754 if (Op.getSubReg() != 0)
755 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
756 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
757 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
759 case MachineOperand::MO_Immediate:
762 case MachineOperand::MO_CImmediate:
763 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
765 case MachineOperand::MO_FPImmediate:
766 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
768 case MachineOperand::MO_MachineBasicBlock:
769 printMBBReference(*Op.getMBB());
771 case MachineOperand::MO_FrameIndex:
772 printStackObjectReference(Op.getIndex());
774 case MachineOperand::MO_ConstantPoolIndex:
775 OS << "%const." << Op.getIndex();
776 printOffset(Op.getOffset());
778 case MachineOperand::MO_TargetIndex: {
779 OS << "target-index(";
780 if (const auto *Name = getTargetIndexName(
781 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
786 printOffset(Op.getOffset());
789 case MachineOperand::MO_JumpTableIndex:
790 OS << "%jump-table." << Op.getIndex();
792 case MachineOperand::MO_ExternalSymbol:
794 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
795 printOffset(Op.getOffset());
797 case MachineOperand::MO_GlobalAddress:
798 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
799 printOffset(Op.getOffset());
801 case MachineOperand::MO_BlockAddress:
802 OS << "blockaddress(";
803 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
806 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
808 printOffset(Op.getOffset());
810 case MachineOperand::MO_RegisterMask: {
811 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
812 if (RegMaskInfo != RegisterMaskIds.end())
813 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
815 llvm_unreachable("Can't print this machine register mask yet.");
818 case MachineOperand::MO_RegisterLiveOut: {
819 const uint32_t *RegMask = Op.getRegLiveOut();
821 bool IsCommaNeeded = false;
822 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
823 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
826 printReg(Reg, OS, TRI);
827 IsCommaNeeded = true;
833 case MachineOperand::MO_Metadata:
834 Op.getMetadata()->printAsOperand(OS, MST);
836 case MachineOperand::MO_MCSymbol:
837 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
839 case MachineOperand::MO_CFIIndex: {
840 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
841 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
847 void MIPrinter::print(const MachineMemOperand &Op) {
849 // TODO: Print operand's target specific flags.
852 if (Op.isNonTemporal())
853 OS << "non-temporal ";
854 if (Op.isInvariant())
859 assert(Op.isStore() && "Non load machine operand must be a store");
862 OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
863 if (const Value *Val = Op.getValue()) {
864 printIRValueReference(*Val);
866 const PseudoSourceValue *PVal = Op.getPseudoValue();
867 assert(PVal && "Expected a pseudo source value");
868 switch (PVal->kind()) {
869 case PseudoSourceValue::Stack:
872 case PseudoSourceValue::GOT:
875 case PseudoSourceValue::JumpTable:
878 case PseudoSourceValue::ConstantPool:
879 OS << "constant-pool";
881 case PseudoSourceValue::FixedStack:
882 printStackObjectReference(
883 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
885 case PseudoSourceValue::GlobalValueCallEntry:
887 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
888 OS, /*PrintType=*/false, MST);
890 case PseudoSourceValue::ExternalSymbolCallEntry:
891 OS << "call-entry $";
892 printLLVMNameWithoutPrefix(
893 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
897 printOffset(Op.getOffset());
898 if (Op.getBaseAlignment() != Op.getSize())
899 OS << ", align " << Op.getBaseAlignment();
900 auto AAInfo = Op.getAAInfo();
903 AAInfo.TBAA->printAsOperand(OS, MST);
906 OS << ", !alias.scope ";
907 AAInfo.Scope->printAsOperand(OS, MST);
909 if (AAInfo.NoAlias) {
911 AAInfo.NoAlias->printAsOperand(OS, MST);
913 if (Op.getRanges()) {
915 Op.getRanges()->printAsOperand(OS, MST);
920 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
921 const TargetRegisterInfo *TRI) {
922 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
927 printReg(Reg, OS, TRI);
930 void MIPrinter::print(const MCCFIInstruction &CFI,
931 const TargetRegisterInfo *TRI) {
932 switch (CFI.getOperation()) {
933 case MCCFIInstruction::OpSameValue:
934 OS << ".cfi_same_value ";
937 printCFIRegister(CFI.getRegister(), OS, TRI);
939 case MCCFIInstruction::OpOffset:
940 OS << ".cfi_offset ";
943 printCFIRegister(CFI.getRegister(), OS, TRI);
944 OS << ", " << CFI.getOffset();
946 case MCCFIInstruction::OpDefCfaRegister:
947 OS << ".cfi_def_cfa_register ";
950 printCFIRegister(CFI.getRegister(), OS, TRI);
952 case MCCFIInstruction::OpDefCfaOffset:
953 OS << ".cfi_def_cfa_offset ";
956 OS << CFI.getOffset();
958 case MCCFIInstruction::OpDefCfa:
959 OS << ".cfi_def_cfa ";
962 printCFIRegister(CFI.getRegister(), OS, TRI);
963 OS << ", " << CFI.getOffset();
966 // TODO: Print the other CFI Operations.
967 OS << "<unserializable cfi operation>";
972 void llvm::printMIR(raw_ostream &OS, const Module &M) {
973 yaml::Output Out(OS);
974 Out << const_cast<Module &>(M);
977 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
978 MIRPrinter Printer(OS);