1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the class that prints out the LLVM IR and machine 11 // functions using the MIR serialization format. 12 // 13 //===----------------------------------------------------------------------===// 14 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" 36 37 using namespace llvm; 38 39 namespace { 40 41 /// This structure describes how to print out stack object references. 42 struct FrameIndexOperand { 43 std::string Name; 44 unsigned ID; 45 bool IsFixed; 46 47 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed) 48 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {} 49 50 /// Return an ordinary stack object reference. 51 static FrameIndexOperand create(StringRef Name, unsigned ID) { 52 return FrameIndexOperand(Name, ID, /*IsFixed=*/false); 53 } 54 55 /// Return a fixed stack object reference. 56 static FrameIndexOperand createFixed(unsigned ID) { 57 return FrameIndexOperand("", ID, /*IsFixed=*/true); 58 } 59 }; 60 61 } // end anonymous namespace 62 63 namespace llvm { 64 65 /// This class prints out the machine functions using the MIR serialization 66 /// format. 67 class MIRPrinter { 68 raw_ostream &OS; 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; 73 74 public: 75 MIRPrinter(raw_ostream &OS) : OS(OS) {} 76 77 void print(const MachineFunction &MF); 78 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); 91 92 private: 93 void initRegisterMaskIds(const MachineFunction &MF); 94 }; 95 96 /// This class prints out the machine instructions using the MIR serialization 97 /// format. 98 class MIPrinter { 99 raw_ostream &OS; 100 ModuleSlotTracker &MST; 101 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds; 102 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping; 103 104 public: 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) {} 110 111 void print(const MachineBasicBlock &MBB); 112 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, 122 const MachineRegisterInfo *MRI = nullptr, bool IsDef = false); 123 void print(const MachineMemOperand &Op); 124 125 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI); 126 }; 127 128 } // end namespace llvm 129 130 namespace llvm { 131 namespace yaml { 132 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); 137 } 138 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) { 139 llvm_unreachable("LLVM Module is supposed to be parsed separately"); 140 return ""; 141 } 142 }; 143 144 } // end namespace yaml 145 } // end namespace llvm 146 147 static void printReg(unsigned Reg, raw_ostream &OS, 148 const TargetRegisterInfo *TRI) { 149 // TODO: Print Stack Slots. 150 if (!Reg) 151 OS << '_'; 152 else if (TargetRegisterInfo::isVirtualRegister(Reg)) 153 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg); 154 else if (Reg < TRI->getNumRegs()) 155 OS << '%' << StringRef(TRI->getName(Reg)).lower(); 156 else 157 llvm_unreachable("Can't print this kind of register yet"); 158 } 159 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); 164 } 165 166 void MIRPrinter::print(const MachineFunction &MF) { 167 initRegisterMaskIds(MF); 168 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) { 187 if (IsNewlineNeeded) 188 StrOS << "\n"; 189 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 190 .print(MBB); 191 IsNewlineNeeded = true; 192 } 193 StrOS.flush(); 194 yaml::Output Out(OS); 195 Out << YamlMF; 196 } 197 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(); 204 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; 209 VReg.ID = I; 210 VReg.Class = 211 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower(); 212 unsigned PreferredReg = RegInfo.getSimpleHint(Reg); 213 if (PreferredReg) 214 printReg(PreferredReg, VReg.PreferredRegister, TRI); 215 MF.VirtualRegisters.push_back(VReg); 216 } 217 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); 222 if (I->second) 223 printReg(I->second, LiveIn.VirtualRegister, TRI); 224 MF.LiveIns.push_back(LiveIn); 225 } 226 // The used physical register mask is printed as an inverted callee saved 227 // register mask. 228 const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask(); 229 if (UsedPhysRegMask.none()) 230 return; 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); 237 } 238 } 239 MF.CalleeSavedRegisters = CalleeSavedRegisters; 240 } 241 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()); 262 } 263 if (MFI.getRestorePoint()) { 264 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value); 265 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 266 .printMBBReference(*MFI.getRestorePoint()); 267 } 268 } 269 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. 276 unsigned ID = 0; 277 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) { 278 if (MFI.isDeadObjectIndex(I)) 279 continue; 280 281 yaml::FixedMachineStackObject YamlObject; 282 YamlObject.ID = ID; 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++))); 294 } 295 296 // Process ordinary stack objects. 297 ID = 0; 298 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) { 299 if (MFI.isDeadObjectIndex(I)) 300 continue; 301 302 yaml::MachineStackObject YamlObject; 303 YamlObject.ID = ID; 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); 315 316 MF.StackObjects.push_back(YamlObject); 317 StackObjectOperandMapping.insert(std::make_pair( 318 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++))); 319 } 320 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; 330 else 331 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg; 332 } 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; 341 } 342 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()); 349 } 350 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]; 360 { 361 raw_string_ostream StrOS(Object.DebugVar.Value); 362 DebugVar.Var->printAsOperand(StrOS, MST); 363 } 364 { 365 raw_string_ostream StrOS(Object.DebugExpr.Value); 366 DebugVar.Expr->printAsOperand(StrOS, MST); 367 } 368 { 369 raw_string_ostream StrOS(Object.DebugLoc.Value); 370 DebugVar.Loc->printAsOperand(StrOS, MST); 371 } 372 } 373 } 374 375 void MIRPrinter::convert(yaml::MachineFunction &MF, 376 const MachineConstantPool &ConstantPool) { 377 unsigned ID = 0; 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"); 382 383 yaml::MachineConstantPoolValue YamlConstant; 384 std::string Str; 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); 391 } 392 } 393 394 void MIRPrinter::convert(ModuleSlotTracker &MST, 395 yaml::MachineJumpTable &YamlJTI, 396 const MachineJumpTableInfo &JTI) { 397 YamlJTI.Kind = JTI.getEntryKind(); 398 unsigned ID = 0; 399 for (const auto &Table : JTI.getJumpTables()) { 400 std::string Str; 401 yaml::MachineJumpTable::Entry Entry; 402 Entry.ID = ID++; 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()); 408 Str.clear(); 409 } 410 YamlJTI.Entries.push_back(Entry); 411 } 412 } 413 414 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) { 415 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 416 unsigned I = 0; 417 for (const uint32_t *Mask : TRI->getRegMasks()) 418 RegisterMaskIds.insert(std::make_pair(Mask, I++)); 419 } 420 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()) { 426 if (BB->hasName()) { 427 OS << "." << BB->getName(); 428 } else { 429 HasAttributes = true; 430 OS << " ("; 431 int Slot = MST.getLocalSlot(BB); 432 if (Slot == -1) 433 OS << "<ir-block badref>"; 434 else 435 OS << (Twine("%ir-block.") + Twine(Slot)).str(); 436 } 437 } 438 if (MBB.hasAddressTaken()) { 439 OS << (HasAttributes ? ", " : " ("); 440 OS << "address-taken"; 441 HasAttributes = true; 442 } 443 if (MBB.isEHPad()) { 444 OS << (HasAttributes ? ", " : " ("); 445 OS << "landing-pad"; 446 HasAttributes = true; 447 } 448 if (MBB.getAlignment()) { 449 OS << (HasAttributes ? ", " : " ("); 450 OS << "align " << MBB.getAlignment(); 451 HasAttributes = true; 452 } 453 if (HasAttributes) 454 OS << ")"; 455 OS << ":\n"; 456 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()) 463 OS << ", "; 464 printMBBReference(**I); 465 if (MBB.hasSuccessorProbabilities()) 466 OS << '(' << MBB.getSuccProbability(I) << ')'; 467 } 468 OS << "\n"; 469 HasLineAttributes = true; 470 } 471 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: "; 477 bool First = true; 478 for (const auto &LI : MBB.liveins()) { 479 if (!First) 480 OS << ", "; 481 First = false; 482 printReg(LI.PhysReg, OS, TRI); 483 if (LI.LaneMask != ~0u) 484 OS << ':' << PrintLaneMask(LI.LaneMask); 485 } 486 OS << "\n"; 487 HasLineAttributes = true; 488 } 489 490 if (HasLineAttributes) 491 OS << "\n"; 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"; 497 IsInBundle = false; 498 } 499 OS.indent(IsInBundle ? 4 : 2); 500 print(MI); 501 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 502 OS << " {"; 503 IsInBundle = true; 504 } 505 OS << "\n"; 506 } 507 if (IsInBundle) 508 OS.indent(2) << "}\n"; 509 } 510 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. 519 continue; 520 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 521 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1; 522 if (ExpectedTiedIdx != TiedIdx) 523 return true; 524 } 525 return false; 526 } 527 528 void MIPrinter::print(const MachineInstr &MI) { 529 const auto *MF = MI.getParent()->getParent(); 530 const auto &MRI = MF->getRegInfo(); 531 const auto &SubTarget = MF->getSubtarget(); 532 const auto *TRI = SubTarget.getRegisterInfo(); 533 assert(TRI && "Expected target register info"); 534 const auto *TII = SubTarget.getInstrInfo(); 535 assert(TII && "Expected target instruction info"); 536 if (MI.isCFIInstruction()) 537 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 538 539 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI); 540 unsigned I = 0, E = MI.getNumOperands(); 541 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() && 542 !MI.getOperand(I).isImplicit(); 543 ++I) { 544 if (I) 545 OS << ", "; 546 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, &MRI, 547 /*IsDef=*/true); 548 } 549 550 if (I) 551 OS << " = "; 552 if (MI.getFlag(MachineInstr::FrameSetup)) 553 OS << "frame-setup "; 554 OS << TII->getName(MI.getOpcode()); 555 if (I < E) 556 OS << ' '; 557 558 bool NeedComma = false; 559 for (; I < E; ++I) { 560 if (NeedComma) 561 OS << ", "; 562 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies); 563 NeedComma = true; 564 } 565 566 if (MI.getDebugLoc()) { 567 if (NeedComma) 568 OS << ','; 569 OS << " debug-location "; 570 MI.getDebugLoc()->printAsOperand(OS, MST); 571 } 572 573 if (!MI.memoperands_empty()) { 574 OS << " :: "; 575 bool NeedComma = false; 576 for (const auto *Op : MI.memoperands()) { 577 if (NeedComma) 578 OS << ", "; 579 print(*Op); 580 NeedComma = true; 581 } 582 } 583 } 584 585 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) { 586 OS << "%bb." << MBB.getNumber(); 587 if (const auto *BB = MBB.getBasicBlock()) { 588 if (BB->hasName()) 589 OS << '.' << BB->getName(); 590 } 591 } 592 593 static void printIRSlotNumber(raw_ostream &OS, int Slot) { 594 if (Slot == -1) 595 OS << "<badref>"; 596 else 597 OS << Slot; 598 } 599 600 void MIPrinter::printIRBlockReference(const BasicBlock &BB) { 601 OS << "%ir-block."; 602 if (BB.hasName()) { 603 printLLVMNameWithoutPrefix(OS, BB.getName()); 604 return; 605 } 606 const Function *F = BB.getParent(); 607 int Slot; 608 if (F == MST.getCurrentFunction()) { 609 Slot = MST.getLocalSlot(&BB); 610 } else { 611 ModuleSlotTracker CustomMST(F->getParent(), 612 /*ShouldInitializeAllMetadata=*/false); 613 CustomMST.incorporateFunction(*F); 614 Slot = CustomMST.getLocalSlot(&BB); 615 } 616 printIRSlotNumber(OS, Slot); 617 } 618 619 void MIPrinter::printIRValueReference(const Value &V) { 620 if (isa<GlobalValue>(V)) { 621 V.printAsOperand(OS, /*PrintType=*/false, MST); 622 return; 623 } 624 if (isa<Constant>(V)) { 625 // Machine memory operands can load/store to/from constant value pointers. 626 OS << '`'; 627 V.printAsOperand(OS, /*PrintType=*/true, MST); 628 OS << '`'; 629 return; 630 } 631 OS << "%ir."; 632 if (V.hasName()) { 633 printLLVMNameWithoutPrefix(OS, V.getName()); 634 return; 635 } 636 printIRSlotNumber(OS, MST.getLocalSlot(&V)); 637 } 638 639 void MIPrinter::printStackObjectReference(int FrameIndex) { 640 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex); 641 assert(ObjectInfo != StackObjectOperandMapping.end() && 642 "Invalid frame index"); 643 const FrameIndexOperand &Operand = ObjectInfo->second; 644 if (Operand.IsFixed) { 645 OS << "%fixed-stack." << Operand.ID; 646 return; 647 } 648 OS << "%stack." << Operand.ID; 649 if (!Operand.Name.empty()) 650 OS << '.' << Operand.Name; 651 } 652 653 void MIPrinter::printOffset(int64_t Offset) { 654 if (Offset == 0) 655 return; 656 if (Offset < 0) { 657 OS << " - " << -Offset; 658 return; 659 } 660 OS << " + " << Offset; 661 } 662 663 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) { 664 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags(); 665 for (const auto &I : Flags) { 666 if (I.first == TF) { 667 return I.second; 668 } 669 } 670 return nullptr; 671 } 672 673 void MIPrinter::printTargetFlags(const MachineOperand &Op) { 674 if (!Op.getTargetFlags()) 675 return; 676 const auto *TII = 677 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo(); 678 assert(TII && "expected instruction info"); 679 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags()); 680 OS << "target-flags("; 681 const bool HasDirectFlags = Flags.first; 682 const bool HasBitmaskFlags = Flags.second; 683 if (!HasDirectFlags && !HasBitmaskFlags) { 684 OS << "<unknown>) "; 685 return; 686 } 687 if (HasDirectFlags) { 688 if (const auto *Name = getTargetFlagName(TII, Flags.first)) 689 OS << Name; 690 else 691 OS << "<unknown target flag>"; 692 } 693 if (!HasBitmaskFlags) { 694 OS << ") "; 695 return; 696 } 697 bool IsCommaNeeded = HasDirectFlags; 698 unsigned BitMask = Flags.second; 699 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags(); 700 for (const auto &Mask : BitMasks) { 701 // Check if the flag's bitmask has the bits of the current mask set. 702 if ((BitMask & Mask.first) == Mask.first) { 703 if (IsCommaNeeded) 704 OS << ", "; 705 IsCommaNeeded = true; 706 OS << Mask.second; 707 // Clear the bits which were serialized from the flag's bitmask. 708 BitMask &= ~(Mask.first); 709 } 710 } 711 if (BitMask) { 712 // When the resulting flag's bitmask isn't zero, we know that we didn't 713 // serialize all of the bit flags. 714 if (IsCommaNeeded) 715 OS << ", "; 716 OS << "<unknown bitmask target flag>"; 717 } 718 OS << ") "; 719 } 720 721 static const char *getTargetIndexName(const MachineFunction &MF, int Index) { 722 const auto *TII = MF.getSubtarget().getInstrInfo(); 723 assert(TII && "expected instruction info"); 724 auto Indices = TII->getSerializableTargetIndices(); 725 for (const auto &I : Indices) { 726 if (I.first == Index) { 727 return I.second; 728 } 729 } 730 return nullptr; 731 } 732 733 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI, 734 unsigned I, bool ShouldPrintRegisterTies, 735 const MachineRegisterInfo *MRI, bool IsDef) { 736 printTargetFlags(Op); 737 switch (Op.getType()) { 738 case MachineOperand::MO_Register: 739 if (Op.isImplicit()) 740 OS << (Op.isDef() ? "implicit-def " : "implicit "); 741 else if (!IsDef && Op.isDef()) 742 // Print the 'def' flag only when the operand is defined after '='. 743 OS << "def "; 744 if (Op.isInternalRead()) 745 OS << "internal "; 746 if (Op.isDead()) 747 OS << "dead "; 748 if (Op.isKill()) 749 OS << "killed "; 750 if (Op.isUndef()) 751 OS << "undef "; 752 if (Op.isEarlyClobber()) 753 OS << "early-clobber "; 754 if (Op.isDebug()) 755 OS << "debug-use "; 756 printReg(Op.getReg(), OS, TRI); 757 // Print the sub register. 758 if (Op.getSubReg() != 0) 759 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg()); 760 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef()) 761 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")"; 762 assert((!IsDef || MRI) && "for IsDef, MRI must be provided"); 763 if (IsDef && MRI->getSize(Op.getReg())) 764 OS << '(' << MRI->getSize(Op.getReg()) << ')'; 765 break; 766 case MachineOperand::MO_Immediate: 767 OS << Op.getImm(); 768 break; 769 case MachineOperand::MO_CImmediate: 770 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST); 771 break; 772 case MachineOperand::MO_FPImmediate: 773 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST); 774 break; 775 case MachineOperand::MO_MachineBasicBlock: 776 printMBBReference(*Op.getMBB()); 777 break; 778 case MachineOperand::MO_FrameIndex: 779 printStackObjectReference(Op.getIndex()); 780 break; 781 case MachineOperand::MO_ConstantPoolIndex: 782 OS << "%const." << Op.getIndex(); 783 printOffset(Op.getOffset()); 784 break; 785 case MachineOperand::MO_TargetIndex: { 786 OS << "target-index("; 787 if (const auto *Name = getTargetIndexName( 788 *Op.getParent()->getParent()->getParent(), Op.getIndex())) 789 OS << Name; 790 else 791 OS << "<unknown>"; 792 OS << ')'; 793 printOffset(Op.getOffset()); 794 break; 795 } 796 case MachineOperand::MO_JumpTableIndex: 797 OS << "%jump-table." << Op.getIndex(); 798 break; 799 case MachineOperand::MO_ExternalSymbol: 800 OS << '$'; 801 printLLVMNameWithoutPrefix(OS, Op.getSymbolName()); 802 printOffset(Op.getOffset()); 803 break; 804 case MachineOperand::MO_GlobalAddress: 805 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST); 806 printOffset(Op.getOffset()); 807 break; 808 case MachineOperand::MO_BlockAddress: 809 OS << "blockaddress("; 810 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false, 811 MST); 812 OS << ", "; 813 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock()); 814 OS << ')'; 815 printOffset(Op.getOffset()); 816 break; 817 case MachineOperand::MO_RegisterMask: { 818 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask()); 819 if (RegMaskInfo != RegisterMaskIds.end()) 820 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower(); 821 else 822 llvm_unreachable("Can't print this machine register mask yet."); 823 break; 824 } 825 case MachineOperand::MO_RegisterLiveOut: { 826 const uint32_t *RegMask = Op.getRegLiveOut(); 827 OS << "liveout("; 828 bool IsCommaNeeded = false; 829 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) { 830 if (RegMask[Reg / 32] & (1U << (Reg % 32))) { 831 if (IsCommaNeeded) 832 OS << ", "; 833 printReg(Reg, OS, TRI); 834 IsCommaNeeded = true; 835 } 836 } 837 OS << ")"; 838 break; 839 } 840 case MachineOperand::MO_Metadata: 841 Op.getMetadata()->printAsOperand(OS, MST); 842 break; 843 case MachineOperand::MO_MCSymbol: 844 OS << "<mcsymbol " << *Op.getMCSymbol() << ">"; 845 break; 846 case MachineOperand::MO_CFIIndex: { 847 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI(); 848 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI); 849 break; 850 } 851 } 852 } 853 854 void MIPrinter::print(const MachineMemOperand &Op) { 855 OS << '('; 856 // TODO: Print operand's target specific flags. 857 if (Op.isVolatile()) 858 OS << "volatile "; 859 if (Op.isNonTemporal()) 860 OS << "non-temporal "; 861 if (Op.isInvariant()) 862 OS << "invariant "; 863 if (Op.isLoad()) 864 OS << "load "; 865 else { 866 assert(Op.isStore() && "Non load machine operand must be a store"); 867 OS << "store "; 868 } 869 OS << Op.getSize() << (Op.isLoad() ? " from " : " into "); 870 if (const Value *Val = Op.getValue()) { 871 printIRValueReference(*Val); 872 } else { 873 const PseudoSourceValue *PVal = Op.getPseudoValue(); 874 assert(PVal && "Expected a pseudo source value"); 875 switch (PVal->kind()) { 876 case PseudoSourceValue::Stack: 877 OS << "stack"; 878 break; 879 case PseudoSourceValue::GOT: 880 OS << "got"; 881 break; 882 case PseudoSourceValue::JumpTable: 883 OS << "jump-table"; 884 break; 885 case PseudoSourceValue::ConstantPool: 886 OS << "constant-pool"; 887 break; 888 case PseudoSourceValue::FixedStack: 889 printStackObjectReference( 890 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex()); 891 break; 892 case PseudoSourceValue::GlobalValueCallEntry: 893 OS << "call-entry "; 894 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand( 895 OS, /*PrintType=*/false, MST); 896 break; 897 case PseudoSourceValue::ExternalSymbolCallEntry: 898 OS << "call-entry $"; 899 printLLVMNameWithoutPrefix( 900 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol()); 901 break; 902 } 903 } 904 printOffset(Op.getOffset()); 905 if (Op.getBaseAlignment() != Op.getSize()) 906 OS << ", align " << Op.getBaseAlignment(); 907 auto AAInfo = Op.getAAInfo(); 908 if (AAInfo.TBAA) { 909 OS << ", !tbaa "; 910 AAInfo.TBAA->printAsOperand(OS, MST); 911 } 912 if (AAInfo.Scope) { 913 OS << ", !alias.scope "; 914 AAInfo.Scope->printAsOperand(OS, MST); 915 } 916 if (AAInfo.NoAlias) { 917 OS << ", !noalias "; 918 AAInfo.NoAlias->printAsOperand(OS, MST); 919 } 920 if (Op.getRanges()) { 921 OS << ", !range "; 922 Op.getRanges()->printAsOperand(OS, MST); 923 } 924 OS << ')'; 925 } 926 927 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS, 928 const TargetRegisterInfo *TRI) { 929 int Reg = TRI->getLLVMRegNum(DwarfReg, true); 930 if (Reg == -1) { 931 OS << "<badreg>"; 932 return; 933 } 934 printReg(Reg, OS, TRI); 935 } 936 937 void MIPrinter::print(const MCCFIInstruction &CFI, 938 const TargetRegisterInfo *TRI) { 939 switch (CFI.getOperation()) { 940 case MCCFIInstruction::OpSameValue: 941 OS << ".cfi_same_value "; 942 if (CFI.getLabel()) 943 OS << "<mcsymbol> "; 944 printCFIRegister(CFI.getRegister(), OS, TRI); 945 break; 946 case MCCFIInstruction::OpOffset: 947 OS << ".cfi_offset "; 948 if (CFI.getLabel()) 949 OS << "<mcsymbol> "; 950 printCFIRegister(CFI.getRegister(), OS, TRI); 951 OS << ", " << CFI.getOffset(); 952 break; 953 case MCCFIInstruction::OpDefCfaRegister: 954 OS << ".cfi_def_cfa_register "; 955 if (CFI.getLabel()) 956 OS << "<mcsymbol> "; 957 printCFIRegister(CFI.getRegister(), OS, TRI); 958 break; 959 case MCCFIInstruction::OpDefCfaOffset: 960 OS << ".cfi_def_cfa_offset "; 961 if (CFI.getLabel()) 962 OS << "<mcsymbol> "; 963 OS << CFI.getOffset(); 964 break; 965 case MCCFIInstruction::OpDefCfa: 966 OS << ".cfi_def_cfa "; 967 if (CFI.getLabel()) 968 OS << "<mcsymbol> "; 969 printCFIRegister(CFI.getRegister(), OS, TRI); 970 OS << ", " << CFI.getOffset(); 971 break; 972 default: 973 // TODO: Print the other CFI Operations. 974 OS << "<unserializable cfi operation>"; 975 break; 976 } 977 } 978 979 void llvm::printMIR(raw_ostream &OS, const Module &M) { 980 yaml::Output Out(OS); 981 Out << const_cast<Module &>(M); 982 } 983 984 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) { 985 MIRPrinter Printer(OS); 986 Printer.print(MF); 987 } 988