1 //===---------------------------- StackMaps.cpp ---------------------------===//
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 #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/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOpcodes.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
32 #define DEBUG_TYPE "stackmaps"
34 static cl::opt<int> StackMapVersion("stackmap-version", cl::init(1),
35 cl::desc("Specify the stackmap encoding version (default = 1)"));
37 const char *StackMaps::WSMP = "Stack Maps: ";
39 PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
41 HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
42 !MI->getOperand(0).isImplicit()),
43 IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
46 unsigned CheckStartIdx = 0, e = MI->getNumOperands();
47 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
48 MI->getOperand(CheckStartIdx).isDef() &&
49 !MI->getOperand(CheckStartIdx).isImplicit())
52 assert(getMetaIdx() == CheckStartIdx &&
53 "Unexpected additional definition in Patchpoint intrinsic.");
57 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
59 StartIdx = getVarIdx();
61 // Find the next scratch register (implicit def and early clobber)
62 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
63 while (ScratchIdx < e &&
64 !(MI->getOperand(ScratchIdx).isReg() &&
65 MI->getOperand(ScratchIdx).isDef() &&
66 MI->getOperand(ScratchIdx).isImplicit() &&
67 MI->getOperand(ScratchIdx).isEarlyClobber()))
70 assert(ScratchIdx != e && "No scratch register available");
74 StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
75 if (StackMapVersion != 1)
76 llvm_unreachable("Unsupported stackmap version!");
79 MachineInstr::const_mop_iterator
80 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
81 MachineInstr::const_mop_iterator MOE,
82 LocationVec &Locs, LiveOutVec &LiveOuts) const {
84 switch (MOI->getImm()) {
85 default: llvm_unreachable("Unrecognized operand type.");
86 case StackMaps::DirectMemRefOp: {
87 unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
88 assert((Size % 8) == 0 && "Need pointer size in bytes.");
90 unsigned Reg = (++MOI)->getReg();
91 int64_t Imm = (++MOI)->getImm();
92 Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
95 case StackMaps::IndirectMemRefOp: {
96 int64_t Size = (++MOI)->getImm();
97 assert(Size > 0 && "Need a valid size for indirect memory locations.");
98 unsigned Reg = (++MOI)->getReg();
99 int64_t Imm = (++MOI)->getImm();
100 Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
103 case StackMaps::ConstantOp: {
105 assert(MOI->isImm() && "Expected constant operand.");
106 int64_t Imm = MOI->getImm();
107 Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
114 // The physical register number will ultimately be encoded as a DWARF regno.
115 // The stack map also records the size of a spill slot that can hold the
116 // register content. (The runtime can track the actual size of the data type
119 // Skip implicit registers (this includes our scratch registers)
120 if (MOI->isImplicit())
123 assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
124 "Virtreg operands should have been rewritten before now.");
125 const TargetRegisterClass *RC =
126 AP.TM.getSubtargetImpl()->getRegisterInfo()->getMinimalPhysRegClass(
128 assert(!MOI->getSubReg() && "Physical subreg still around.");
130 Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
134 if (MOI->isRegLiveOut())
135 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
140 /// Go up the super-register chain until we hit a valid dwarf register number.
141 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
142 int RegNo = TRI->getDwarfRegNum(Reg, false);
143 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
144 RegNo = TRI->getDwarfRegNum(*SR, false);
146 assert(RegNo >= 0 && "Invalid Dwarf register number.");
147 return (unsigned) RegNo;
150 /// Create a live-out register record for the given register Reg.
151 StackMaps::LiveOutReg
152 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
153 unsigned RegNo = getDwarfRegNum(Reg, TRI);
154 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
155 return LiveOutReg(Reg, RegNo, Size);
158 /// Parse the register live-out mask and return a vector of live-out registers
159 /// that need to be recorded in the stackmap.
160 StackMaps::LiveOutVec
161 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
162 assert(Mask && "No register mask specified");
163 const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
166 // Create a LiveOutReg for each bit that is set in the register mask.
167 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
168 if ((Mask[Reg / 32] >> Reg % 32) & 1)
169 LiveOuts.push_back(createLiveOutReg(Reg, TRI));
171 // We don't need to keep track of a register if its super-register is already
172 // in the list. Merge entries that refer to the same dwarf register and use
173 // the maximum size that needs to be spilled.
174 std::sort(LiveOuts.begin(), LiveOuts.end());
175 for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
177 for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
178 if (I->RegNo != II->RegNo) {
179 // Skip all the now invalid entries.
183 I->Size = std::max(I->Size, II->Size);
184 if (TRI->isSuperRegister(I->Reg, II->Reg))
189 LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
190 LiveOutReg::IsInvalid), LiveOuts.end());
194 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
195 MachineInstr::const_mop_iterator MOI,
196 MachineInstr::const_mop_iterator MOE,
199 MCContext &OutContext = AP.OutStreamer.getContext();
200 MCSymbol *MILabel = OutContext.CreateTempSymbol();
201 AP.OutStreamer.EmitLabel(MILabel);
203 LocationVec Locations;
207 assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
208 parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
209 Locations, LiveOuts);
214 MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
217 // Move large constants into the constant pool.
218 for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
220 // Constants are encoded as sign-extended integers.
221 // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
222 if (I->LocType == Location::Constant && !isInt<32>(I->Offset)) {
223 I->LocType = Location::ConstantIndex;
224 // ConstPool is intentionally a MapVector of 'uint64_t's (as
225 // opposed to 'int64_t's). We should never be in a situation
226 // where we have to insert either the tombstone or the empty
227 // keys into a map, and for a DenseMap<uint64_t, T> these are
228 // (uint64_t)0 and (uint64_t)-1. They can be and are
229 // represented using 32 bit integers.
231 assert((uint64_t)I->Offset != DenseMapInfo<uint64_t>::getEmptyKey() &&
232 (uint64_t)I->Offset != DenseMapInfo<uint64_t>::getTombstoneKey() &&
233 "empty and tombstone keys should fit in 32 bits!");
234 auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
235 I->Offset = Result.first - ConstPool.begin();
239 // Create an expression to calculate the offset of the callsite from function
241 const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
242 MCSymbolRefExpr::Create(MILabel, OutContext),
243 MCSymbolRefExpr::Create(AP.CurrentFnSymForSize, OutContext),
246 CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
247 std::move(LiveOuts));
249 // Record the stack size of the current function.
250 const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
251 const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
252 const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
253 RegInfo->needsStackRealignment(*(AP.MF));
254 FnStackSize[AP.CurrentFnSym] =
255 DynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
258 void StackMaps::recordStackMap(const MachineInstr &MI) {
259 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
261 int64_t ID = MI.getOperand(0).getImm();
262 recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
266 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
267 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
269 PatchPointOpers opers(&MI);
270 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
272 MachineInstr::const_mop_iterator MOI =
273 std::next(MI.operands_begin(), opers.getStackMapStartIdx());
274 recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
275 opers.isAnyReg() && opers.hasDef());
279 LocationVec &Locations = CSInfos.back().Locations;
280 if (opers.isAnyReg()) {
281 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
282 for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
283 assert(Locations[i].LocType == Location::Register &&
284 "anyreg arg must be in reg.");
288 void StackMaps::recordStatepoint(const MachineInstr &MI) {
289 assert(MI.getOpcode() == TargetOpcode::STATEPOINT &&
290 "expected statepoint");
292 StatepointOpers opers(&MI);
293 // Record all the deopt and gc operands (they're contiguous and run from the
294 // initial index to the end of the operand list)
295 const unsigned StartIdx = opers.getVarIdx();
296 recordStackMapOpers(MI, 0xABCDEF00,
297 MI.operands_begin() + StartIdx, MI.operands_end(),
301 /// Emit the stackmap header.
304 /// uint8 : Stack Map Version (currently 1)
305 /// uint8 : Reserved (expected to be 0)
306 /// uint16 : Reserved (expected to be 0)
308 /// uint32 : NumFunctions
309 /// uint32 : NumConstants
310 /// uint32 : NumRecords
311 void StackMaps::emitStackmapHeader(MCStreamer &OS) {
313 OS.EmitIntValue(StackMapVersion, 1); // Version.
314 OS.EmitIntValue(0, 1); // Reserved.
315 OS.EmitIntValue(0, 2); // Reserved.
318 DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
319 OS.EmitIntValue(FnStackSize.size(), 4);
321 DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
322 OS.EmitIntValue(ConstPool.size(), 4);
324 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
325 OS.EmitIntValue(CSInfos.size(), 4);
328 /// Emit the function frame record for each function.
330 /// StkSizeRecord[NumFunctions] {
331 /// uint64 : Function Address
332 /// uint64 : Stack Size
334 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
335 // Function Frame records.
336 DEBUG(dbgs() << WSMP << "functions:\n");
337 for (auto const &FR : FnStackSize) {
338 DEBUG(dbgs() << WSMP << "function addr: " << FR.first
339 << " frame size: " << FR.second);
340 OS.EmitSymbolValue(FR.first, 8);
341 OS.EmitIntValue(FR.second, 8);
345 /// Emit the constant pool.
347 /// int64 : Constants[NumConstants]
348 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
349 // Constant pool entries.
350 DEBUG(dbgs() << WSMP << "constants:\n");
351 for (auto ConstEntry : ConstPool) {
352 DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
353 OS.EmitIntValue(ConstEntry.second, 8);
357 /// Emit the callsite info for each callsite.
359 /// StkMapRecord[NumRecords] {
360 /// uint64 : PatchPoint ID
361 /// uint32 : Instruction Offset
362 /// uint16 : Reserved (record flags)
363 /// uint16 : NumLocations
364 /// Location[NumLocations] {
365 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
366 /// uint8 : Size in Bytes
367 /// uint16 : Dwarf RegNum
371 /// uint16 : NumLiveOuts
372 /// LiveOuts[NumLiveOuts] {
373 /// uint16 : Dwarf RegNum
375 /// uint8 : Size in Bytes
377 /// uint32 : Padding (only if required to align to 8 byte)
380 /// Location Encoding, Type, Value:
381 /// 0x1, Register, Reg (value in register)
382 /// 0x2, Direct, Reg + Offset (frame index)
383 /// 0x3, Indirect, [Reg + Offset] (spilled value)
384 /// 0x4, Constant, Offset (small constant)
385 /// 0x5, ConstIndex, Constants[Offset] (large constant)
386 void StackMaps::emitCallsiteEntries(MCStreamer &OS,
387 const TargetRegisterInfo *TRI) {
389 DEBUG(dbgs() << WSMP << "callsites:\n");
390 for (const auto &CSI : CSInfos) {
391 const LocationVec &CSLocs = CSI.Locations;
392 const LiveOutVec &LiveOuts = CSI.LiveOuts;
394 DEBUG(dbgs() << WSMP << "callsite " << CSI.ID << "\n");
396 // Verify stack map entry. It's better to communicate a problem to the
397 // runtime than crash in case of in-process compilation. Currently, we do
398 // simple overflow checks, but we may eventually communicate other
399 // compilation errors this way.
400 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
401 OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
402 OS.EmitValue(CSI.CSOffsetExpr, 4);
403 OS.EmitIntValue(0, 2); // Reserved.
404 OS.EmitIntValue(0, 2); // 0 locations.
405 OS.EmitIntValue(0, 2); // padding.
406 OS.EmitIntValue(0, 2); // 0 live-out registers.
407 OS.EmitIntValue(0, 4); // padding.
411 OS.EmitIntValue(CSI.ID, 8);
412 OS.EmitValue(CSI.CSOffsetExpr, 4);
414 // Reserved for flags.
415 OS.EmitIntValue(0, 2);
417 DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
419 OS.EmitIntValue(CSLocs.size(), 2);
421 unsigned OperIdx = 0;
422 for (const auto &Loc : CSLocs) {
424 int Offset = Loc.Offset;
426 RegNo = getDwarfRegNum(Loc.Reg, TRI);
428 // If this is a register location, put the subregister byte offset in
429 // the location offset.
430 if (Loc.LocType == Location::Register) {
431 assert(!Loc.Offset && "Register location should have zero offset");
432 unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
433 unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
435 Offset = TRI->getSubRegIdxOffset(SubRegIdx);
439 assert(Loc.LocType != Location::Register &&
440 "Missing location register");
443 DEBUG(dbgs() << WSMP << " Loc " << OperIdx << ": ";
444 switch (Loc.LocType) {
445 case Location::Unprocessed:
446 dbgs() << "<Unprocessed operand>";
448 case Location::Register:
449 dbgs() << "Register " << TRI->getName(Loc.Reg);
451 case Location::Direct:
452 dbgs() << "Direct " << TRI->getName(Loc.Reg);
454 dbgs() << " + " << Loc.Offset;
456 case Location::Indirect:
457 dbgs() << "Indirect " << TRI->getName(Loc.Reg)
458 << " + " << Loc.Offset;
460 case Location::Constant:
461 dbgs() << "Constant " << Loc.Offset;
463 case Location::ConstantIndex:
464 dbgs() << "Constant Index " << Loc.Offset;
467 dbgs() << " [encoding: .byte " << Loc.LocType
468 << ", .byte " << Loc.Size
469 << ", .short " << RegNo
470 << ", .int " << Offset << "]\n";
473 OS.EmitIntValue(Loc.LocType, 1);
474 OS.EmitIntValue(Loc.Size, 1);
475 OS.EmitIntValue(RegNo, 2);
476 OS.EmitIntValue(Offset, 4);
480 DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
481 << " live-out registers\n");
483 // Num live-out registers and padding to align to 4 byte.
484 OS.EmitIntValue(0, 2);
485 OS.EmitIntValue(LiveOuts.size(), 2);
488 for (const auto &LO : LiveOuts) {
489 DEBUG(dbgs() << WSMP << " LO " << OperIdx << ": "
490 << TRI->getName(LO.Reg)
491 << " [encoding: .short " << LO.RegNo
492 << ", .byte 0, .byte " << LO.Size << "]\n");
493 OS.EmitIntValue(LO.RegNo, 2);
494 OS.EmitIntValue(0, 1);
495 OS.EmitIntValue(LO.Size, 1);
497 // Emit alignment to 8 byte.
498 OS.EmitValueToAlignment(8);
502 /// Serialize the stackmap data.
503 void StackMaps::serializeToStackMapSection() {
505 // Bail out if there's no stack map data.
506 assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
507 "Expected empty constant pool too!");
508 assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
509 "Expected empty function record too!");
513 MCContext &OutContext = AP.OutStreamer.getContext();
514 MCStreamer &OS = AP.OutStreamer;
515 const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
517 // Create the section.
518 const MCSection *StackMapSection =
519 OutContext.getObjectFileInfo()->getStackMapSection();
520 OS.SwitchSection(StackMapSection);
522 // Emit a dummy symbol to force section inclusion.
523 OS.EmitLabel(OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
526 DEBUG(dbgs() << "********** Stack Map Output **********\n");
527 emitStackmapHeader(OS);
528 emitFunctionFrameRecords(OS);
529 emitConstantPoolEntries(OS);
530 emitCallsiteEntries(OS, TRI);