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/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/YAMLTraits.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
41 /// This structure describes how to print out stack object references.
42 struct FrameIndexOperand {
47 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
48 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
50 /// Return an ordinary stack object reference.
51 static FrameIndexOperand create(StringRef Name, unsigned ID) {
52 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
55 /// Return a fixed stack object reference.
56 static FrameIndexOperand createFixed(unsigned ID) {
57 return FrameIndexOperand("", ID, /*IsFixed=*/true);
61 } // end anonymous namespace
65 /// This class prints out the machine functions using the MIR serialization
69 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
70 /// Maps from stack object indices to operand indices which will be used when
71 /// printing frame index machine operands.
72 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
75 MIRPrinter(raw_ostream &OS) : OS(OS) {}
77 void print(const MachineFunction &MF);
79 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
80 const TargetRegisterInfo *TRI);
81 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
82 const MachineFrameInfo &MFI);
83 void convert(yaml::MachineFunction &MF,
84 const MachineConstantPool &ConstantPool);
85 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
86 const MachineJumpTableInfo &JTI);
87 void convertStackObjects(yaml::MachineFunction &MF,
88 const MachineFrameInfo &MFI, MachineModuleInfo &MMI,
89 ModuleSlotTracker &MST,
90 const TargetRegisterInfo *TRI);
93 void initRegisterMaskIds(const MachineFunction &MF);
96 /// This class prints out the machine instructions using the MIR serialization
100 ModuleSlotTracker &MST;
101 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
102 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
105 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
106 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
107 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
108 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
109 StackObjectOperandMapping(StackObjectOperandMapping) {}
111 void print(const MachineBasicBlock &MBB);
113 void print(const MachineInstr &MI);
114 void printMBBReference(const MachineBasicBlock &MBB);
115 void printIRBlockReference(const BasicBlock &BB);
116 void printIRValueReference(const Value &V);
117 void printStackObjectReference(int FrameIndex);
118 void printOffset(int64_t Offset);
119 void printTargetFlags(const MachineOperand &Op);
120 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
121 unsigned I, bool ShouldPrintRegisterTies, bool IsDef = false);
122 void print(const MachineMemOperand &Op);
124 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
127 } // end namespace llvm
132 /// This struct serializes the LLVM IR module.
133 template <> struct BlockScalarTraits<Module> {
134 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
135 Mod.print(OS, nullptr);
137 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
138 llvm_unreachable("LLVM Module is supposed to be parsed separately");
143 } // end namespace yaml
144 } // end namespace llvm
146 static void printReg(unsigned Reg, raw_ostream &OS,
147 const TargetRegisterInfo *TRI) {
148 // TODO: Print Stack Slots.
151 else if (TargetRegisterInfo::isVirtualRegister(Reg))
152 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
153 else if (Reg < TRI->getNumRegs())
154 OS << '%' << StringRef(TRI->getName(Reg)).lower();
156 llvm_unreachable("Can't print this kind of register yet");
159 static void printReg(unsigned Reg, yaml::StringValue &Dest,
160 const TargetRegisterInfo *TRI) {
161 raw_string_ostream OS(Dest.Value);
162 printReg(Reg, OS, TRI);
165 void MIRPrinter::print(const MachineFunction &MF) {
166 initRegisterMaskIds(MF);
168 yaml::MachineFunction YamlMF;
169 YamlMF.Name = MF.getName();
170 YamlMF.Alignment = MF.getAlignment();
171 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
172 YamlMF.HasInlineAsm = MF.hasInlineAsm();
173 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
174 ModuleSlotTracker MST(MF.getFunction()->getParent());
175 MST.incorporateFunction(*MF.getFunction());
176 convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
177 convertStackObjects(YamlMF, *MF.getFrameInfo(), MF.getMMI(), MST,
178 MF.getSubtarget().getRegisterInfo());
179 if (const auto *ConstantPool = MF.getConstantPool())
180 convert(YamlMF, *ConstantPool);
181 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
182 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
183 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
184 bool IsNewlineNeeded = false;
185 for (const auto &MBB : MF) {
188 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
190 IsNewlineNeeded = true;
193 yaml::Output Out(OS);
197 void MIRPrinter::convert(yaml::MachineFunction &MF,
198 const MachineRegisterInfo &RegInfo,
199 const TargetRegisterInfo *TRI) {
200 MF.IsSSA = RegInfo.isSSA();
201 MF.TracksRegLiveness = RegInfo.tracksLiveness();
202 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
204 // Print the virtual register definitions.
205 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
206 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
207 yaml::VirtualRegisterDefinition VReg;
210 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
211 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
213 printReg(PreferredReg, VReg.PreferredRegister, TRI);
214 MF.VirtualRegisters.push_back(VReg);
217 // Print the live ins.
218 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
219 yaml::MachineFunctionLiveIn LiveIn;
220 printReg(I->first, LiveIn.Register, TRI);
222 printReg(I->second, LiveIn.VirtualRegister, TRI);
223 MF.LiveIns.push_back(LiveIn);
225 // The used physical register mask is printed as an inverted callee saved
227 const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
228 if (UsedPhysRegMask.none())
230 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
231 for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
232 if (!UsedPhysRegMask[I]) {
233 yaml::FlowStringValue Reg;
234 printReg(I, Reg, TRI);
235 CalleeSavedRegisters.push_back(Reg);
238 MF.CalleeSavedRegisters = CalleeSavedRegisters;
241 void MIRPrinter::convert(ModuleSlotTracker &MST,
242 yaml::MachineFrameInfo &YamlMFI,
243 const MachineFrameInfo &MFI) {
244 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
245 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
246 YamlMFI.HasStackMap = MFI.hasStackMap();
247 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
248 YamlMFI.StackSize = MFI.getStackSize();
249 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
250 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
251 YamlMFI.AdjustsStack = MFI.adjustsStack();
252 YamlMFI.HasCalls = MFI.hasCalls();
253 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
254 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
255 YamlMFI.HasVAStart = MFI.hasVAStart();
256 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
257 if (MFI.getSavePoint()) {
258 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
259 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
260 .printMBBReference(*MFI.getSavePoint());
262 if (MFI.getRestorePoint()) {
263 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
264 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
265 .printMBBReference(*MFI.getRestorePoint());
269 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
270 const MachineFrameInfo &MFI,
271 MachineModuleInfo &MMI,
272 ModuleSlotTracker &MST,
273 const TargetRegisterInfo *TRI) {
274 // Process fixed stack objects.
276 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
277 if (MFI.isDeadObjectIndex(I))
280 yaml::FixedMachineStackObject YamlObject;
282 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
283 ? yaml::FixedMachineStackObject::SpillSlot
284 : yaml::FixedMachineStackObject::DefaultType;
285 YamlObject.Offset = MFI.getObjectOffset(I);
286 YamlObject.Size = MFI.getObjectSize(I);
287 YamlObject.Alignment = MFI.getObjectAlignment(I);
288 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
289 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
290 MF.FixedStackObjects.push_back(YamlObject);
291 StackObjectOperandMapping.insert(
292 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
295 // Process ordinary stack objects.
297 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
298 if (MFI.isDeadObjectIndex(I))
301 yaml::MachineStackObject YamlObject;
303 if (const auto *Alloca = MFI.getObjectAllocation(I))
304 YamlObject.Name.Value =
305 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
306 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
307 ? yaml::MachineStackObject::SpillSlot
308 : MFI.isVariableSizedObjectIndex(I)
309 ? yaml::MachineStackObject::VariableSized
310 : yaml::MachineStackObject::DefaultType;
311 YamlObject.Offset = MFI.getObjectOffset(I);
312 YamlObject.Size = MFI.getObjectSize(I);
313 YamlObject.Alignment = MFI.getObjectAlignment(I);
315 MF.StackObjects.push_back(YamlObject);
316 StackObjectOperandMapping.insert(std::make_pair(
317 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
320 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
321 yaml::StringValue Reg;
322 printReg(CSInfo.getReg(), Reg, TRI);
323 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
324 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
325 "Invalid stack object index");
326 const FrameIndexOperand &StackObject = StackObjectInfo->second;
327 if (StackObject.IsFixed)
328 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
330 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
332 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
333 auto LocalObject = MFI.getLocalFrameObjectMap(I);
334 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
335 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
336 "Invalid stack object index");
337 const FrameIndexOperand &StackObject = StackObjectInfo->second;
338 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
339 MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
342 // Print the stack object references in the frame information class after
343 // converting the stack objects.
344 if (MFI.hasStackProtectorIndex()) {
345 raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
346 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
347 .printStackObjectReference(MFI.getStackProtectorIndex());
350 // Print the debug variable information.
351 for (MachineModuleInfo::VariableDbgInfo &DebugVar :
352 MMI.getVariableDbgInfo()) {
353 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
354 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
355 "Invalid stack object index");
356 const FrameIndexOperand &StackObject = StackObjectInfo->second;
357 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
358 auto &Object = MF.StackObjects[StackObject.ID];
360 raw_string_ostream StrOS(Object.DebugVar.Value);
361 DebugVar.Var->printAsOperand(StrOS, MST);
364 raw_string_ostream StrOS(Object.DebugExpr.Value);
365 DebugVar.Expr->printAsOperand(StrOS, MST);
368 raw_string_ostream StrOS(Object.DebugLoc.Value);
369 DebugVar.Loc->printAsOperand(StrOS, MST);
374 void MIRPrinter::convert(yaml::MachineFunction &MF,
375 const MachineConstantPool &ConstantPool) {
377 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
378 // TODO: Serialize target specific constant pool entries.
379 if (Constant.isMachineConstantPoolEntry())
380 llvm_unreachable("Can't print target specific constant pool entries yet");
382 yaml::MachineConstantPoolValue YamlConstant;
384 raw_string_ostream StrOS(Str);
385 Constant.Val.ConstVal->printAsOperand(StrOS);
386 YamlConstant.ID = ID++;
387 YamlConstant.Value = StrOS.str();
388 YamlConstant.Alignment = Constant.getAlignment();
389 MF.Constants.push_back(YamlConstant);
393 void MIRPrinter::convert(ModuleSlotTracker &MST,
394 yaml::MachineJumpTable &YamlJTI,
395 const MachineJumpTableInfo &JTI) {
396 YamlJTI.Kind = JTI.getEntryKind();
398 for (const auto &Table : JTI.getJumpTables()) {
400 yaml::MachineJumpTable::Entry Entry;
402 for (const auto *MBB : Table.MBBs) {
403 raw_string_ostream StrOS(Str);
404 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
405 .printMBBReference(*MBB);
406 Entry.Blocks.push_back(StrOS.str());
409 YamlJTI.Entries.push_back(Entry);
413 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
414 const auto *TRI = MF.getSubtarget().getRegisterInfo();
416 for (const uint32_t *Mask : TRI->getRegMasks())
417 RegisterMaskIds.insert(std::make_pair(Mask, I++));
420 void MIPrinter::print(const MachineBasicBlock &MBB) {
421 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
422 OS << "bb." << MBB.getNumber();
423 bool HasAttributes = false;
424 if (const auto *BB = MBB.getBasicBlock()) {
426 OS << "." << BB->getName();
428 HasAttributes = true;
430 int Slot = MST.getLocalSlot(BB);
432 OS << "<ir-block badref>";
434 OS << (Twine("%ir-block.") + Twine(Slot)).str();
437 if (MBB.hasAddressTaken()) {
438 OS << (HasAttributes ? ", " : " (");
439 OS << "address-taken";
440 HasAttributes = true;
443 OS << (HasAttributes ? ", " : " (");
445 HasAttributes = true;
447 if (MBB.getAlignment()) {
448 OS << (HasAttributes ? ", " : " (");
449 OS << "align " << MBB.getAlignment();
450 HasAttributes = true;
456 bool HasLineAttributes = false;
457 // Print the successors
458 if (!MBB.succ_empty()) {
459 OS.indent(2) << "successors: ";
460 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
461 if (I != MBB.succ_begin())
463 printMBBReference(**I);
464 if (MBB.hasSuccessorProbabilities())
465 OS << '(' << MBB.getSuccProbability(I) << ')';
468 HasLineAttributes = true;
471 // Print the live in registers.
472 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
473 assert(TRI && "Expected target register info");
474 if (!MBB.livein_empty()) {
475 OS.indent(2) << "liveins: ";
477 for (const auto &LI : MBB.liveins()) {
481 printReg(LI.PhysReg, OS, TRI);
482 if (LI.LaneMask != ~0u)
483 OS << ':' << PrintLaneMask(LI.LaneMask);
486 HasLineAttributes = true;
489 if (HasLineAttributes)
491 bool IsInBundle = false;
492 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
493 const MachineInstr &MI = *I;
494 if (IsInBundle && !MI.isInsideBundle()) {
495 OS.indent(2) << "}\n";
498 OS.indent(IsInBundle ? 4 : 2);
500 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
507 OS.indent(2) << "}\n";
510 /// Return true when an instruction has tied register that can't be determined
511 /// by the instruction's descriptor.
512 static bool hasComplexRegisterTies(const MachineInstr &MI) {
513 const MCInstrDesc &MCID = MI.getDesc();
514 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
515 const auto &Operand = MI.getOperand(I);
516 if (!Operand.isReg() || Operand.isDef())
517 // Ignore the defined registers as MCID marks only the uses as tied.
519 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
520 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
521 if (ExpectedTiedIdx != TiedIdx)
527 void MIPrinter::print(const MachineInstr &MI) {
528 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
529 const auto *TRI = SubTarget.getRegisterInfo();
530 assert(TRI && "Expected target register info");
531 const auto *TII = SubTarget.getInstrInfo();
532 assert(TII && "Expected target instruction info");
533 if (MI.isCFIInstruction())
534 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
536 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
537 unsigned I = 0, E = MI.getNumOperands();
538 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
539 !MI.getOperand(I).isImplicit();
543 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, /*IsDef=*/true);
548 if (MI.getFlag(MachineInstr::FrameSetup))
549 OS << "frame-setup ";
550 OS << TII->getName(MI.getOpcode());
554 bool NeedComma = false;
558 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies);
562 if (MI.getDebugLoc()) {
565 OS << " debug-location ";
566 MI.getDebugLoc()->printAsOperand(OS, MST);
569 if (!MI.memoperands_empty()) {
571 bool NeedComma = false;
572 for (const auto *Op : MI.memoperands()) {
581 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
582 OS << "%bb." << MBB.getNumber();
583 if (const auto *BB = MBB.getBasicBlock()) {
585 OS << '.' << BB->getName();
589 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
596 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
599 printLLVMNameWithoutPrefix(OS, BB.getName());
602 const Function *F = BB.getParent();
604 if (F == MST.getCurrentFunction()) {
605 Slot = MST.getLocalSlot(&BB);
607 ModuleSlotTracker CustomMST(F->getParent(),
608 /*ShouldInitializeAllMetadata=*/false);
609 CustomMST.incorporateFunction(*F);
610 Slot = CustomMST.getLocalSlot(&BB);
612 printIRSlotNumber(OS, Slot);
615 void MIPrinter::printIRValueReference(const Value &V) {
616 if (isa<GlobalValue>(V)) {
617 V.printAsOperand(OS, /*PrintType=*/false, MST);
620 if (isa<Constant>(V)) {
621 // Machine memory operands can load/store to/from constant value pointers.
623 V.printAsOperand(OS, /*PrintType=*/true, MST);
629 printLLVMNameWithoutPrefix(OS, V.getName());
632 printIRSlotNumber(OS, MST.getLocalSlot(&V));
635 void MIPrinter::printStackObjectReference(int FrameIndex) {
636 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
637 assert(ObjectInfo != StackObjectOperandMapping.end() &&
638 "Invalid frame index");
639 const FrameIndexOperand &Operand = ObjectInfo->second;
640 if (Operand.IsFixed) {
641 OS << "%fixed-stack." << Operand.ID;
644 OS << "%stack." << Operand.ID;
645 if (!Operand.Name.empty())
646 OS << '.' << Operand.Name;
649 void MIPrinter::printOffset(int64_t Offset) {
653 OS << " - " << -Offset;
656 OS << " + " << Offset;
659 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
660 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
661 for (const auto &I : Flags) {
669 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
670 if (!Op.getTargetFlags())
673 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
674 assert(TII && "expected instruction info");
675 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
676 OS << "target-flags(";
677 const bool HasDirectFlags = Flags.first;
678 const bool HasBitmaskFlags = Flags.second;
679 if (!HasDirectFlags && !HasBitmaskFlags) {
683 if (HasDirectFlags) {
684 if (const auto *Name = getTargetFlagName(TII, Flags.first))
687 OS << "<unknown target flag>";
689 if (!HasBitmaskFlags) {
693 bool IsCommaNeeded = HasDirectFlags;
694 unsigned BitMask = Flags.second;
695 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
696 for (const auto &Mask : BitMasks) {
697 // Check if the flag's bitmask has the bits of the current mask set.
698 if ((BitMask & Mask.first) == Mask.first) {
701 IsCommaNeeded = true;
703 // Clear the bits which were serialized from the flag's bitmask.
704 BitMask &= ~(Mask.first);
708 // When the resulting flag's bitmask isn't zero, we know that we didn't
709 // serialize all of the bit flags.
712 OS << "<unknown bitmask target flag>";
717 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
718 const auto *TII = MF.getSubtarget().getInstrInfo();
719 assert(TII && "expected instruction info");
720 auto Indices = TII->getSerializableTargetIndices();
721 for (const auto &I : Indices) {
722 if (I.first == Index) {
729 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
730 unsigned I, bool ShouldPrintRegisterTies, bool IsDef) {
731 printTargetFlags(Op);
732 switch (Op.getType()) {
733 case MachineOperand::MO_Register:
735 OS << (Op.isDef() ? "implicit-def " : "implicit ");
736 else if (!IsDef && Op.isDef())
737 // Print the 'def' flag only when the operand is defined after '='.
739 if (Op.isInternalRead())
747 if (Op.isEarlyClobber())
748 OS << "early-clobber ";
751 printReg(Op.getReg(), OS, TRI);
752 // Print the sub register.
753 if (Op.getSubReg() != 0)
754 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
755 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
756 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
758 case MachineOperand::MO_Immediate:
761 case MachineOperand::MO_CImmediate:
762 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
764 case MachineOperand::MO_FPImmediate:
765 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
767 case MachineOperand::MO_MachineBasicBlock:
768 printMBBReference(*Op.getMBB());
770 case MachineOperand::MO_FrameIndex:
771 printStackObjectReference(Op.getIndex());
773 case MachineOperand::MO_ConstantPoolIndex:
774 OS << "%const." << Op.getIndex();
775 printOffset(Op.getOffset());
777 case MachineOperand::MO_TargetIndex: {
778 OS << "target-index(";
779 if (const auto *Name = getTargetIndexName(
780 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
785 printOffset(Op.getOffset());
788 case MachineOperand::MO_JumpTableIndex:
789 OS << "%jump-table." << Op.getIndex();
791 case MachineOperand::MO_ExternalSymbol:
793 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
794 printOffset(Op.getOffset());
796 case MachineOperand::MO_GlobalAddress:
797 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
798 printOffset(Op.getOffset());
800 case MachineOperand::MO_BlockAddress:
801 OS << "blockaddress(";
802 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
805 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
807 printOffset(Op.getOffset());
809 case MachineOperand::MO_RegisterMask: {
810 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
811 if (RegMaskInfo != RegisterMaskIds.end())
812 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
814 llvm_unreachable("Can't print this machine register mask yet.");
817 case MachineOperand::MO_RegisterLiveOut: {
818 const uint32_t *RegMask = Op.getRegLiveOut();
820 bool IsCommaNeeded = false;
821 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
822 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
825 printReg(Reg, OS, TRI);
826 IsCommaNeeded = true;
832 case MachineOperand::MO_Metadata:
833 Op.getMetadata()->printAsOperand(OS, MST);
835 case MachineOperand::MO_MCSymbol:
836 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
838 case MachineOperand::MO_CFIIndex: {
839 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
840 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
846 void MIPrinter::print(const MachineMemOperand &Op) {
848 // TODO: Print operand's target specific flags.
851 if (Op.isNonTemporal())
852 OS << "non-temporal ";
853 if (Op.isInvariant())
858 assert(Op.isStore() && "Non load machine operand must be a store");
861 OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
862 if (const Value *Val = Op.getValue()) {
863 printIRValueReference(*Val);
865 const PseudoSourceValue *PVal = Op.getPseudoValue();
866 assert(PVal && "Expected a pseudo source value");
867 switch (PVal->kind()) {
868 case PseudoSourceValue::Stack:
871 case PseudoSourceValue::GOT:
874 case PseudoSourceValue::JumpTable:
877 case PseudoSourceValue::ConstantPool:
878 OS << "constant-pool";
880 case PseudoSourceValue::FixedStack:
881 printStackObjectReference(
882 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
884 case PseudoSourceValue::GlobalValueCallEntry:
886 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
887 OS, /*PrintType=*/false, MST);
889 case PseudoSourceValue::ExternalSymbolCallEntry:
890 OS << "call-entry $";
891 printLLVMNameWithoutPrefix(
892 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
896 printOffset(Op.getOffset());
897 if (Op.getBaseAlignment() != Op.getSize())
898 OS << ", align " << Op.getBaseAlignment();
899 auto AAInfo = Op.getAAInfo();
902 AAInfo.TBAA->printAsOperand(OS, MST);
905 OS << ", !alias.scope ";
906 AAInfo.Scope->printAsOperand(OS, MST);
908 if (AAInfo.NoAlias) {
910 AAInfo.NoAlias->printAsOperand(OS, MST);
912 if (Op.getRanges()) {
914 Op.getRanges()->printAsOperand(OS, MST);
919 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
920 const TargetRegisterInfo *TRI) {
921 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
926 printReg(Reg, OS, TRI);
929 void MIPrinter::print(const MCCFIInstruction &CFI,
930 const TargetRegisterInfo *TRI) {
931 switch (CFI.getOperation()) {
932 case MCCFIInstruction::OpSameValue:
933 OS << ".cfi_same_value ";
936 printCFIRegister(CFI.getRegister(), OS, TRI);
938 case MCCFIInstruction::OpOffset:
939 OS << ".cfi_offset ";
942 printCFIRegister(CFI.getRegister(), OS, TRI);
943 OS << ", " << CFI.getOffset();
945 case MCCFIInstruction::OpDefCfaRegister:
946 OS << ".cfi_def_cfa_register ";
949 printCFIRegister(CFI.getRegister(), OS, TRI);
951 case MCCFIInstruction::OpDefCfaOffset:
952 OS << ".cfi_def_cfa_offset ";
955 OS << CFI.getOffset();
957 case MCCFIInstruction::OpDefCfa:
958 OS << ".cfi_def_cfa ";
961 printCFIRegister(CFI.getRegister(), OS, TRI);
962 OS << ", " << CFI.getOffset();
965 // TODO: Print the other CFI Operations.
966 OS << "<unserializable cfi operation>";
971 void llvm::printMIR(raw_ostream &OS, const Module &M) {
972 yaml::Output Out(OS);
973 Out << const_cast<Module &>(M);
976 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
977 MIRPrinter Printer(OS);