1 //===---------------------------- StackMaps.cpp ---------------------------===// 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 #include "llvm/CodeGen/StackMaps.h" 11 #include "llvm/CodeGen/AsmPrinter.h" 12 #include "llvm/CodeGen/MachineFrameInfo.h" 13 #include "llvm/CodeGen/MachineFunction.h" 14 #include "llvm/CodeGen/MachineInstr.h" 15 #include "llvm/IR/DataLayout.h" 16 #include "llvm/MC/MCContext.h" 17 #include "llvm/MC/MCExpr.h" 18 #include "llvm/MC/MCObjectFileInfo.h" 19 #include "llvm/MC/MCSectionMachO.h" 20 #include "llvm/MC/MCStreamer.h" 21 #include "llvm/Support/CommandLine.h" 22 #include "llvm/Target/TargetMachine.h" 23 #include "llvm/Target/TargetOpcodes.h" 24 #include "llvm/Target/TargetRegisterInfo.h" 25 #include "llvm/Target/TargetSubtargetInfo.h" 26 #include <iterator> 27 28 using namespace llvm; 29 30 #define DEBUG_TYPE "stackmaps" 31 32 static cl::opt<int> StackMapVersion( 33 "stackmap-version", cl::init(1), 34 cl::desc("Specify the stackmap encoding version (default = 1)")); 35 36 const char *StackMaps::WSMP = "Stack Maps: "; 37 38 PatchPointOpers::PatchPointOpers(const MachineInstr *MI) 39 : MI(MI), HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() && 40 !MI->getOperand(0).isImplicit()), 41 IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == 42 CallingConv::AnyReg) { 43 #ifndef NDEBUG 44 unsigned CheckStartIdx = 0, e = MI->getNumOperands(); 45 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() && 46 MI->getOperand(CheckStartIdx).isDef() && 47 !MI->getOperand(CheckStartIdx).isImplicit()) 48 ++CheckStartIdx; 49 50 assert(getMetaIdx() == CheckStartIdx && 51 "Unexpected additional definition in Patchpoint intrinsic."); 52 #endif 53 } 54 55 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const { 56 if (!StartIdx) 57 StartIdx = getVarIdx(); 58 59 // Find the next scratch register (implicit def and early clobber) 60 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands(); 61 while (ScratchIdx < e && 62 !(MI->getOperand(ScratchIdx).isReg() && 63 MI->getOperand(ScratchIdx).isDef() && 64 MI->getOperand(ScratchIdx).isImplicit() && 65 MI->getOperand(ScratchIdx).isEarlyClobber())) 66 ++ScratchIdx; 67 68 assert(ScratchIdx != e && "No scratch register available"); 69 return ScratchIdx; 70 } 71 72 StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) { 73 if (StackMapVersion != 1) 74 llvm_unreachable("Unsupported stackmap version!"); 75 } 76 77 /// Go up the super-register chain until we hit a valid dwarf register number. 78 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) { 79 int RegNum = TRI->getDwarfRegNum(Reg, false); 80 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNum < 0; ++SR) 81 RegNum = TRI->getDwarfRegNum(*SR, false); 82 83 assert(RegNum >= 0 && "Invalid Dwarf register number."); 84 return (unsigned)RegNum; 85 } 86 87 MachineInstr::const_mop_iterator 88 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI, 89 MachineInstr::const_mop_iterator MOE, LocationVec &Locs, 90 LiveOutVec &LiveOuts) const { 91 const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo(); 92 if (MOI->isImm()) { 93 switch (MOI->getImm()) { 94 default: 95 llvm_unreachable("Unrecognized operand type."); 96 case StackMaps::DirectMemRefOp: { 97 auto &DL = AP.MF->getDataLayout(); 98 99 unsigned Size = DL.getPointerSizeInBits(); 100 assert((Size % 8) == 0 && "Need pointer size in bytes."); 101 Size /= 8; 102 unsigned Reg = (++MOI)->getReg(); 103 int64_t Imm = (++MOI)->getImm(); 104 Locs.emplace_back(StackMaps::Location::Direct, Size, 105 getDwarfRegNum(Reg, TRI), Imm); 106 break; 107 } 108 case StackMaps::IndirectMemRefOp: { 109 int64_t Size = (++MOI)->getImm(); 110 assert(Size > 0 && "Need a valid size for indirect memory locations."); 111 unsigned Reg = (++MOI)->getReg(); 112 int64_t Imm = (++MOI)->getImm(); 113 Locs.emplace_back(StackMaps::Location::Indirect, Size, 114 getDwarfRegNum(Reg, TRI), Imm); 115 break; 116 } 117 case StackMaps::ConstantOp: { 118 ++MOI; 119 assert(MOI->isImm() && "Expected constant operand."); 120 int64_t Imm = MOI->getImm(); 121 Locs.emplace_back(Location::Constant, sizeof(int64_t), 0, Imm); 122 break; 123 } 124 } 125 return ++MOI; 126 } 127 128 // The physical register number will ultimately be encoded as a DWARF regno. 129 // The stack map also records the size of a spill slot that can hold the 130 // register content. (The runtime can track the actual size of the data type 131 // if it needs to.) 132 if (MOI->isReg()) { 133 // Skip implicit registers (this includes our scratch registers) 134 if (MOI->isImplicit()) 135 return ++MOI; 136 137 assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) && 138 "Virtreg operands should have been rewritten before now."); 139 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(MOI->getReg()); 140 assert(!MOI->getSubReg() && "Physical subreg still around."); 141 142 unsigned Offset = 0; 143 unsigned DwarfRegNum = getDwarfRegNum(MOI->getReg(), TRI); 144 unsigned LLVMRegNum = TRI->getLLVMRegNum(DwarfRegNum, false); 145 unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNum, MOI->getReg()); 146 if (SubRegIdx) 147 Offset = TRI->getSubRegIdxOffset(SubRegIdx); 148 149 Locs.emplace_back(Location::Register, RC->getSize(), DwarfRegNum, Offset); 150 return ++MOI; 151 } 152 153 if (MOI->isRegLiveOut()) 154 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut()); 155 156 return ++MOI; 157 } 158 159 void StackMaps::print(raw_ostream &OS) { 160 const TargetRegisterInfo *TRI = 161 AP.MF ? AP.MF->getSubtarget().getRegisterInfo() : nullptr; 162 OS << WSMP << "callsites:\n"; 163 for (const auto &CSI : CSInfos) { 164 const LocationVec &CSLocs = CSI.Locations; 165 const LiveOutVec &LiveOuts = CSI.LiveOuts; 166 167 OS << WSMP << "callsite " << CSI.ID << "\n"; 168 OS << WSMP << " has " << CSLocs.size() << " locations\n"; 169 170 unsigned Idx = 0; 171 for (const auto &Loc : CSLocs) { 172 OS << WSMP << "\t\tLoc " << Idx << ": "; 173 switch (Loc.Type) { 174 case Location::Unprocessed: 175 OS << "<Unprocessed operand>"; 176 break; 177 case Location::Register: 178 OS << "Register "; 179 if (TRI) 180 OS << TRI->getName(Loc.Reg); 181 else 182 OS << Loc.Reg; 183 break; 184 case Location::Direct: 185 OS << "Direct "; 186 if (TRI) 187 OS << TRI->getName(Loc.Reg); 188 else 189 OS << Loc.Reg; 190 if (Loc.Offset) 191 OS << " + " << Loc.Offset; 192 break; 193 case Location::Indirect: 194 OS << "Indirect "; 195 if (TRI) 196 OS << TRI->getName(Loc.Reg); 197 else 198 OS << Loc.Reg; 199 OS << "+" << Loc.Offset; 200 break; 201 case Location::Constant: 202 OS << "Constant " << Loc.Offset; 203 break; 204 case Location::ConstantIndex: 205 OS << "Constant Index " << Loc.Offset; 206 break; 207 } 208 OS << "\t[encoding: .byte " << Loc.Type << ", .byte " << Loc.Size 209 << ", .short " << Loc.Reg << ", .int " << Loc.Offset << "]\n"; 210 Idx++; 211 } 212 213 OS << WSMP << "\thas " << LiveOuts.size() << " live-out registers\n"; 214 215 Idx = 0; 216 for (const auto &LO : LiveOuts) { 217 OS << WSMP << "\t\tLO " << Idx << ": "; 218 if (TRI) 219 OS << TRI->getName(LO.Reg); 220 else 221 OS << LO.Reg; 222 OS << "\t[encoding: .short " << LO.DwarfRegNum << ", .byte 0, .byte " 223 << LO.Size << "]\n"; 224 Idx++; 225 } 226 } 227 } 228 229 /// Create a live-out register record for the given register Reg. 230 StackMaps::LiveOutReg 231 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const { 232 unsigned DwarfRegNum = getDwarfRegNum(Reg, TRI); 233 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize(); 234 return LiveOutReg(Reg, DwarfRegNum, Size); 235 } 236 237 /// Parse the register live-out mask and return a vector of live-out registers 238 /// that need to be recorded in the stackmap. 239 StackMaps::LiveOutVec 240 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const { 241 assert(Mask && "No register mask specified"); 242 const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo(); 243 LiveOutVec LiveOuts; 244 245 // Create a LiveOutReg for each bit that is set in the register mask. 246 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) 247 if ((Mask[Reg / 32] >> Reg % 32) & 1) 248 LiveOuts.push_back(createLiveOutReg(Reg, TRI)); 249 250 // We don't need to keep track of a register if its super-register is already 251 // in the list. Merge entries that refer to the same dwarf register and use 252 // the maximum size that needs to be spilled. 253 254 std::sort(LiveOuts.begin(), LiveOuts.end(), 255 [](const LiveOutReg &LHS, const LiveOutReg &RHS) { 256 // Only sort by the dwarf register number. 257 return LHS.DwarfRegNum < RHS.DwarfRegNum; 258 }); 259 260 for (auto I = LiveOuts.begin(), E = LiveOuts.end(); I != E; ++I) { 261 for (auto II = std::next(I); II != E; ++II) { 262 if (I->DwarfRegNum != II->DwarfRegNum) { 263 // Skip all the now invalid entries. 264 I = --II; 265 break; 266 } 267 I->Size = std::max(I->Size, II->Size); 268 if (TRI->isSuperRegister(I->Reg, II->Reg)) 269 I->Reg = II->Reg; 270 II->Reg = 0; // mark for deletion. 271 } 272 } 273 274 LiveOuts.erase( 275 remove_if(LiveOuts, [](const LiveOutReg &LO) { return LO.Reg == 0; }), 276 LiveOuts.end()); 277 278 return LiveOuts; 279 } 280 281 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID, 282 MachineInstr::const_mop_iterator MOI, 283 MachineInstr::const_mop_iterator MOE, 284 bool recordResult) { 285 286 MCContext &OutContext = AP.OutStreamer->getContext(); 287 MCSymbol *MILabel = OutContext.createTempSymbol(); 288 AP.OutStreamer->EmitLabel(MILabel); 289 290 LocationVec Locations; 291 LiveOutVec LiveOuts; 292 293 if (recordResult) { 294 assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value."); 295 parseOperand(MI.operands_begin(), std::next(MI.operands_begin()), Locations, 296 LiveOuts); 297 } 298 299 // Parse operands. 300 while (MOI != MOE) { 301 MOI = parseOperand(MOI, MOE, Locations, LiveOuts); 302 } 303 304 // Move large constants into the constant pool. 305 for (auto &Loc : Locations) { 306 // Constants are encoded as sign-extended integers. 307 // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool. 308 if (Loc.Type == Location::Constant && !isInt<32>(Loc.Offset)) { 309 Loc.Type = Location::ConstantIndex; 310 // ConstPool is intentionally a MapVector of 'uint64_t's (as 311 // opposed to 'int64_t's). We should never be in a situation 312 // where we have to insert either the tombstone or the empty 313 // keys into a map, and for a DenseMap<uint64_t, T> these are 314 // (uint64_t)0 and (uint64_t)-1. They can be and are 315 // represented using 32 bit integers. 316 assert((uint64_t)Loc.Offset != DenseMapInfo<uint64_t>::getEmptyKey() && 317 (uint64_t)Loc.Offset != 318 DenseMapInfo<uint64_t>::getTombstoneKey() && 319 "empty and tombstone keys should fit in 32 bits!"); 320 auto Result = ConstPool.insert(std::make_pair(Loc.Offset, Loc.Offset)); 321 Loc.Offset = Result.first - ConstPool.begin(); 322 } 323 } 324 325 // Create an expression to calculate the offset of the callsite from function 326 // entry. 327 const MCExpr *CSOffsetExpr = MCBinaryExpr::createSub( 328 MCSymbolRefExpr::create(MILabel, OutContext), 329 MCSymbolRefExpr::create(AP.CurrentFnSymForSize, OutContext), OutContext); 330 331 CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations), 332 std::move(LiveOuts)); 333 334 // Record the stack size of the current function. 335 const MachineFrameInfo &MFI = AP.MF->getFrameInfo(); 336 const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo(); 337 bool HasDynamicFrameSize = 338 MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(*(AP.MF)); 339 FnStackSize[AP.CurrentFnSym] = 340 HasDynamicFrameSize ? UINT64_MAX : MFI.getStackSize(); 341 } 342 343 void StackMaps::recordStackMap(const MachineInstr &MI) { 344 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap"); 345 346 int64_t ID = MI.getOperand(0).getImm(); 347 recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2), 348 MI.operands_end()); 349 } 350 351 void StackMaps::recordPatchPoint(const MachineInstr &MI) { 352 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint"); 353 354 PatchPointOpers opers(&MI); 355 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm(); 356 357 auto MOI = std::next(MI.operands_begin(), opers.getStackMapStartIdx()); 358 recordStackMapOpers(MI, ID, MOI, MI.operands_end(), 359 opers.isAnyReg() && opers.hasDef()); 360 361 #ifndef NDEBUG 362 // verify anyregcc 363 auto &Locations = CSInfos.back().Locations; 364 if (opers.isAnyReg()) { 365 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm(); 366 for (unsigned i = 0, e = (opers.hasDef() ? NArgs + 1 : NArgs); i != e; ++i) 367 assert(Locations[i].Type == Location::Register && 368 "anyreg arg must be in reg."); 369 } 370 #endif 371 } 372 void StackMaps::recordStatepoint(const MachineInstr &MI) { 373 assert(MI.getOpcode() == TargetOpcode::STATEPOINT && "expected statepoint"); 374 375 StatepointOpers opers(&MI); 376 // Record all the deopt and gc operands (they're contiguous and run from the 377 // initial index to the end of the operand list) 378 const unsigned StartIdx = opers.getVarIdx(); 379 recordStackMapOpers(MI, opers.getID(), MI.operands_begin() + StartIdx, 380 MI.operands_end(), false); 381 } 382 383 /// Emit the stackmap header. 384 /// 385 /// Header { 386 /// uint8 : Stack Map Version (currently 1) 387 /// uint8 : Reserved (expected to be 0) 388 /// uint16 : Reserved (expected to be 0) 389 /// } 390 /// uint32 : NumFunctions 391 /// uint32 : NumConstants 392 /// uint32 : NumRecords 393 void StackMaps::emitStackmapHeader(MCStreamer &OS) { 394 // Header. 395 OS.EmitIntValue(StackMapVersion, 1); // Version. 396 OS.EmitIntValue(0, 1); // Reserved. 397 OS.EmitIntValue(0, 2); // Reserved. 398 399 // Num functions. 400 DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n'); 401 OS.EmitIntValue(FnStackSize.size(), 4); 402 // Num constants. 403 DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n'); 404 OS.EmitIntValue(ConstPool.size(), 4); 405 // Num callsites. 406 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n'); 407 OS.EmitIntValue(CSInfos.size(), 4); 408 } 409 410 /// Emit the function frame record for each function. 411 /// 412 /// StkSizeRecord[NumFunctions] { 413 /// uint64 : Function Address 414 /// uint64 : Stack Size 415 /// } 416 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) { 417 // Function Frame records. 418 DEBUG(dbgs() << WSMP << "functions:\n"); 419 for (auto const &FR : FnStackSize) { 420 DEBUG(dbgs() << WSMP << "function addr: " << FR.first 421 << " frame size: " << FR.second); 422 OS.EmitSymbolValue(FR.first, 8); 423 OS.EmitIntValue(FR.second, 8); 424 } 425 } 426 427 /// Emit the constant pool. 428 /// 429 /// int64 : Constants[NumConstants] 430 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) { 431 // Constant pool entries. 432 DEBUG(dbgs() << WSMP << "constants:\n"); 433 for (const auto &ConstEntry : ConstPool) { 434 DEBUG(dbgs() << WSMP << ConstEntry.second << '\n'); 435 OS.EmitIntValue(ConstEntry.second, 8); 436 } 437 } 438 439 /// Emit the callsite info for each callsite. 440 /// 441 /// StkMapRecord[NumRecords] { 442 /// uint64 : PatchPoint ID 443 /// uint32 : Instruction Offset 444 /// uint16 : Reserved (record flags) 445 /// uint16 : NumLocations 446 /// Location[NumLocations] { 447 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex 448 /// uint8 : Size in Bytes 449 /// uint16 : Dwarf RegNum 450 /// int32 : Offset 451 /// } 452 /// uint16 : Padding 453 /// uint16 : NumLiveOuts 454 /// LiveOuts[NumLiveOuts] { 455 /// uint16 : Dwarf RegNum 456 /// uint8 : Reserved 457 /// uint8 : Size in Bytes 458 /// } 459 /// uint32 : Padding (only if required to align to 8 byte) 460 /// } 461 /// 462 /// Location Encoding, Type, Value: 463 /// 0x1, Register, Reg (value in register) 464 /// 0x2, Direct, Reg + Offset (frame index) 465 /// 0x3, Indirect, [Reg + Offset] (spilled value) 466 /// 0x4, Constant, Offset (small constant) 467 /// 0x5, ConstIndex, Constants[Offset] (large constant) 468 void StackMaps::emitCallsiteEntries(MCStreamer &OS) { 469 DEBUG(print(dbgs())); 470 // Callsite entries. 471 for (const auto &CSI : CSInfos) { 472 const LocationVec &CSLocs = CSI.Locations; 473 const LiveOutVec &LiveOuts = CSI.LiveOuts; 474 475 // Verify stack map entry. It's better to communicate a problem to the 476 // runtime than crash in case of in-process compilation. Currently, we do 477 // simple overflow checks, but we may eventually communicate other 478 // compilation errors this way. 479 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) { 480 OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID. 481 OS.EmitValue(CSI.CSOffsetExpr, 4); 482 OS.EmitIntValue(0, 2); // Reserved. 483 OS.EmitIntValue(0, 2); // 0 locations. 484 OS.EmitIntValue(0, 2); // padding. 485 OS.EmitIntValue(0, 2); // 0 live-out registers. 486 OS.EmitIntValue(0, 4); // padding. 487 continue; 488 } 489 490 OS.EmitIntValue(CSI.ID, 8); 491 OS.EmitValue(CSI.CSOffsetExpr, 4); 492 493 // Reserved for flags. 494 OS.EmitIntValue(0, 2); 495 OS.EmitIntValue(CSLocs.size(), 2); 496 497 for (const auto &Loc : CSLocs) { 498 OS.EmitIntValue(Loc.Type, 1); 499 OS.EmitIntValue(Loc.Size, 1); 500 OS.EmitIntValue(Loc.Reg, 2); 501 OS.EmitIntValue(Loc.Offset, 4); 502 } 503 504 // Num live-out registers and padding to align to 4 byte. 505 OS.EmitIntValue(0, 2); 506 OS.EmitIntValue(LiveOuts.size(), 2); 507 508 for (const auto &LO : LiveOuts) { 509 OS.EmitIntValue(LO.DwarfRegNum, 2); 510 OS.EmitIntValue(0, 1); 511 OS.EmitIntValue(LO.Size, 1); 512 } 513 // Emit alignment to 8 byte. 514 OS.EmitValueToAlignment(8); 515 } 516 } 517 518 /// Serialize the stackmap data. 519 void StackMaps::serializeToStackMapSection() { 520 (void)WSMP; 521 // Bail out if there's no stack map data. 522 assert((!CSInfos.empty() || ConstPool.empty()) && 523 "Expected empty constant pool too!"); 524 assert((!CSInfos.empty() || FnStackSize.empty()) && 525 "Expected empty function record too!"); 526 if (CSInfos.empty()) 527 return; 528 529 MCContext &OutContext = AP.OutStreamer->getContext(); 530 MCStreamer &OS = *AP.OutStreamer; 531 532 // Create the section. 533 MCSection *StackMapSection = 534 OutContext.getObjectFileInfo()->getStackMapSection(); 535 OS.SwitchSection(StackMapSection); 536 537 // Emit a dummy symbol to force section inclusion. 538 OS.EmitLabel(OutContext.getOrCreateSymbol(Twine("__LLVM_StackMaps"))); 539 540 // Serialize data. 541 DEBUG(dbgs() << "********** Stack Map Output **********\n"); 542 emitStackmapHeader(OS); 543 emitFunctionFrameRecords(OS); 544 emitConstantPoolEntries(OS); 545 emitCallsiteEntries(OS); 546 OS.AddBlankLine(); 547 548 // Clean up. 549 CSInfos.clear(); 550 ConstPool.clear(); 551 } 552