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/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOpcodes.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
30 #define DEBUG_TYPE "stackmaps"
32 PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
34 HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
35 !MI->getOperand(0).isImplicit()),
36 IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
39 unsigned CheckStartIdx = 0, e = MI->getNumOperands();
40 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
41 MI->getOperand(CheckStartIdx).isDef() &&
42 !MI->getOperand(CheckStartIdx).isImplicit())
45 assert(getMetaIdx() == CheckStartIdx &&
46 "Unexpected additional definition in Patchpoint intrinsic.");
50 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
52 StartIdx = getVarIdx();
54 // Find the next scratch register (implicit def and early clobber)
55 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
56 while (ScratchIdx < e &&
57 !(MI->getOperand(ScratchIdx).isReg() &&
58 MI->getOperand(ScratchIdx).isDef() &&
59 MI->getOperand(ScratchIdx).isImplicit() &&
60 MI->getOperand(ScratchIdx).isEarlyClobber()))
63 assert(ScratchIdx != e && "No scratch register available");
67 MachineInstr::const_mop_iterator
68 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
69 MachineInstr::const_mop_iterator MOE,
70 LocationVec &Locs, LiveOutVec &LiveOuts) const {
72 switch (MOI->getImm()) {
73 default: llvm_unreachable("Unrecognized operand type.");
74 case StackMaps::DirectMemRefOp: {
75 unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
76 assert((Size % 8) == 0 && "Need pointer size in bytes.");
78 unsigned Reg = (++MOI)->getReg();
79 int64_t Imm = (++MOI)->getImm();
80 Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
83 case StackMaps::IndirectMemRefOp: {
84 int64_t Size = (++MOI)->getImm();
85 assert(Size > 0 && "Need a valid size for indirect memory locations.");
86 unsigned Reg = (++MOI)->getReg();
87 int64_t Imm = (++MOI)->getImm();
88 Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
91 case StackMaps::ConstantOp: {
93 assert(MOI->isImm() && "Expected constant operand.");
94 int64_t Imm = MOI->getImm();
95 Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
102 // The physical register number will ultimately be encoded as a DWARF regno.
103 // The stack map also records the size of a spill slot that can hold the
104 // register content. (The runtime can track the actual size of the data type
107 // Skip implicit registers (this includes our scratch registers)
108 if (MOI->isImplicit())
111 assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
112 "Virtreg operands should have been rewritten before now.");
113 const TargetRegisterClass *RC =
114 AP.TM.getRegisterInfo()->getMinimalPhysRegClass(MOI->getReg());
115 assert(!MOI->getSubReg() && "Physical subreg still around.");
117 Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
121 if (MOI->isRegLiveOut())
122 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
127 /// Go up the super-register chain until we hit a valid dwarf register number.
128 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
129 int RegNo = TRI->getDwarfRegNum(Reg, false);
130 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
131 RegNo = TRI->getDwarfRegNum(*SR, false);
133 assert(RegNo >= 0 && "Invalid Dwarf register number.");
134 return (unsigned) RegNo;
137 /// Create a live-out register record for the given register Reg.
138 StackMaps::LiveOutReg
139 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
140 unsigned RegNo = getDwarfRegNum(Reg, TRI);
141 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
142 return LiveOutReg(Reg, RegNo, Size);
145 /// Parse the register live-out mask and return a vector of live-out registers
146 /// that need to be recorded in the stackmap.
147 StackMaps::LiveOutVec
148 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
149 assert(Mask && "No register mask specified");
150 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
153 // Create a LiveOutReg for each bit that is set in the register mask.
154 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
155 if ((Mask[Reg / 32] >> Reg % 32) & 1)
156 LiveOuts.push_back(createLiveOutReg(Reg, TRI));
158 // We don't need to keep track of a register if its super-register is already
159 // in the list. Merge entries that refer to the same dwarf register and use
160 // the maximum size that needs to be spilled.
161 std::sort(LiveOuts.begin(), LiveOuts.end());
162 for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
164 for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
165 if (I->RegNo != II->RegNo) {
166 // Skip all the now invalid entries.
170 I->Size = std::max(I->Size, II->Size);
171 if (TRI->isSuperRegister(I->Reg, II->Reg))
176 LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
177 LiveOutReg::IsInvalid), LiveOuts.end());
181 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
182 MachineInstr::const_mop_iterator MOI,
183 MachineInstr::const_mop_iterator MOE,
186 MCContext &OutContext = AP.OutStreamer.getContext();
187 MCSymbol *MILabel = OutContext.CreateTempSymbol();
188 AP.OutStreamer.EmitLabel(MILabel);
190 LocationVec Locations;
194 assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
195 parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
196 Locations, LiveOuts);
201 MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
204 // Move large constants into the constant pool.
205 for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
207 // Constants are encoded as sign-extended integers.
208 // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
209 if (I->LocType == Location::Constant &&
210 ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
211 I->LocType = Location::ConstantIndex;
212 auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
213 I->Offset = Result.first - ConstPool.begin();
217 // Create an expression to calculate the offset of the callsite from function
219 const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
220 MCSymbolRefExpr::Create(MILabel, OutContext),
221 MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
224 CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
226 // Record the stack size of the current function.
227 const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
228 FnStackSize[AP.CurrentFnSym] =
229 MFI->hasVarSizedObjects() ? UINT64_MAX : MFI->getStackSize();
232 void StackMaps::recordStackMap(const MachineInstr &MI) {
233 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
235 int64_t ID = MI.getOperand(0).getImm();
236 recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
240 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
241 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
243 PatchPointOpers opers(&MI);
244 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
246 MachineInstr::const_mop_iterator MOI =
247 std::next(MI.operands_begin(), opers.getStackMapStartIdx());
248 recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
249 opers.isAnyReg() && opers.hasDef());
253 LocationVec &Locations = CSInfos.back().Locations;
254 if (opers.isAnyReg()) {
255 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
256 for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
257 assert(Locations[i].LocType == Location::Register &&
258 "anyreg arg must be in reg.");
263 /// Emit the stackmap header.
266 /// uint8 : Stack Map Version (currently 1)
267 /// uint8 : Reserved (expected to be 0)
268 /// uint16 : Reserved (expected to be 0)
270 /// uint32 : NumFunctions
271 /// uint32 : NumConstants
272 /// uint32 : NumRecords
273 void StackMaps::emitStackmapHeader(MCStreamer &OS) {
275 OS.EmitIntValue(1, 1); // Version.
276 OS.EmitIntValue(0, 1); // Reserved.
277 OS.EmitIntValue(0, 2); // Reserved.
280 DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
281 OS.EmitIntValue(FnStackSize.size(), 4);
283 DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
284 OS.EmitIntValue(ConstPool.size(), 4);
286 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
287 OS.EmitIntValue(CSInfos.size(), 4);
290 /// Emit the function frame record for each function.
292 /// StkSizeRecord[NumFunctions] {
293 /// uint64 : Function Address
294 /// uint64 : Stack Size
296 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
297 // Function Frame records.
298 DEBUG(dbgs() << WSMP << "functions:\n");
299 for (auto const &FR : FnStackSize) {
300 DEBUG(dbgs() << WSMP << "function addr: " << FR.first
301 << " frame size: " << FR.second);
302 OS.EmitSymbolValue(FR.first, 8);
303 OS.EmitIntValue(FR.second, 8);
307 /// Emit the constant pool.
309 /// int64 : Constants[NumConstants]
310 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
311 // Constant pool entries.
312 DEBUG(dbgs() << WSMP << "constants:\n");
313 for (auto ConstEntry : ConstPool) {
314 DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
315 OS.EmitIntValue(ConstEntry.second, 8);
319 /// Emit the callsite info for each callsite.
321 /// StkMapRecord[NumRecords] {
322 /// uint64 : PatchPoint ID
323 /// uint32 : Instruction Offset
324 /// uint16 : Reserved (record flags)
325 /// uint16 : NumLocations
326 /// Location[NumLocations] {
327 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
328 /// uint8 : Size in Bytes
329 /// uint16 : Dwarf RegNum
333 /// uint16 : NumLiveOuts
334 /// LiveOuts[NumLiveOuts] {
335 /// uint16 : Dwarf RegNum
337 /// uint8 : Size in Bytes
339 /// uint32 : Padding (only if required to align to 8 byte)
342 /// Location Encoding, Type, Value:
343 /// 0x1, Register, Reg (value in register)
344 /// 0x2, Direct, Reg + Offset (frame index)
345 /// 0x3, Indirect, [Reg + Offset] (spilled value)
346 /// 0x4, Constant, Offset (small constant)
347 /// 0x5, ConstIndex, Constants[Offset] (large constant)
348 void StackMaps::emitCallsiteEntries(MCStreamer &OS,
349 const TargetRegisterInfo *TRI) {
351 DEBUG(dbgs() << WSMP << "callsites:\n");
352 for (const auto &CSI : CSInfos) {
353 const LocationVec &CSLocs = CSI.Locations;
354 const LiveOutVec &LiveOuts = CSI.LiveOuts;
356 DEBUG(dbgs() << WSMP << "callsite " << CSI.ID << "\n");
358 // Verify stack map entry. It's better to communicate a problem to the
359 // runtime than crash in case of in-process compilation. Currently, we do
360 // simple overflow checks, but we may eventually communicate other
361 // compilation errors this way.
362 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
363 OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
364 OS.EmitValue(CSI.CSOffsetExpr, 4);
365 OS.EmitIntValue(0, 2); // Reserved.
366 OS.EmitIntValue(0, 2); // 0 locations.
367 OS.EmitIntValue(0, 2); // padding.
368 OS.EmitIntValue(0, 2); // 0 live-out registers.
369 OS.EmitIntValue(0, 4); // padding.
373 OS.EmitIntValue(CSI.ID, 8);
374 OS.EmitValue(CSI.CSOffsetExpr, 4);
376 // Reserved for flags.
377 OS.EmitIntValue(0, 2);
379 DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
381 OS.EmitIntValue(CSLocs.size(), 2);
383 unsigned OperIdx = 0;
384 for (const auto &Loc : CSLocs) {
386 int Offset = Loc.Offset;
388 RegNo = getDwarfRegNum(Loc.Reg, TRI);
390 // If this is a register location, put the subregister byte offset in
391 // the location offset.
392 if (Loc.LocType == Location::Register) {
393 assert(!Loc.Offset && "Register location should have zero offset");
394 unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
395 unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
397 Offset = TRI->getSubRegIdxOffset(SubRegIdx);
401 assert(Loc.LocType != Location::Register &&
402 "Missing location register");
405 DEBUG(dbgs() << WSMP << " Loc " << OperIdx << ": ";
406 switch (Loc.LocType) {
407 case Location::Unprocessed:
408 dbgs() << "<Unprocessed operand>";
410 case Location::Register:
411 dbgs() << "Register " << TRI->getName(Loc.Reg);
413 case Location::Direct:
414 dbgs() << "Direct " << TRI->getName(Loc.Reg);
416 dbgs() << " + " << Loc.Offset;
418 case Location::Indirect:
419 dbgs() << "Indirect " << TRI->getName(Loc.Reg)
420 << " + " << Loc.Offset;
422 case Location::Constant:
423 dbgs() << "Constant " << Loc.Offset;
425 case Location::ConstantIndex:
426 dbgs() << "Constant Index " << Loc.Offset;
429 dbgs() << " [encoding: .byte " << Loc.LocType
430 << ", .byte " << Loc.Size
431 << ", .short " << RegNo
432 << ", .int " << Offset << "]\n";
435 OS.EmitIntValue(Loc.LocType, 1);
436 OS.EmitIntValue(Loc.Size, 1);
437 OS.EmitIntValue(RegNo, 2);
438 OS.EmitIntValue(Offset, 4);
442 DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
443 << " live-out registers\n");
445 // Num live-out registers and padding to align to 4 byte.
446 OS.EmitIntValue(0, 2);
447 OS.EmitIntValue(LiveOuts.size(), 2);
450 for (const auto &LO : LiveOuts) {
451 DEBUG(dbgs() << WSMP << " LO " << OperIdx << ": "
452 << TRI->getName(LO.Reg)
453 << " [encoding: .short " << LO.RegNo
454 << ", .byte 0, .byte " << LO.Size << "]\n");
455 OS.EmitIntValue(LO.RegNo, 2);
456 OS.EmitIntValue(0, 1);
457 OS.EmitIntValue(LO.Size, 1);
459 // Emit alignment to 8 byte.
460 OS.EmitValueToAlignment(8);
464 /// Serialize the stackmap data.
465 void StackMaps::serializeToStackMapSection() {
466 // Bail out if there's no stack map data.
467 assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
468 "Expected empty constant pool too!");
469 assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
470 "Expected empty function record too!");
474 MCContext &OutContext = AP.OutStreamer.getContext();
475 MCStreamer &OS = AP.OutStreamer;
476 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
478 // Create the section.
479 const MCSection *StackMapSection =
480 OutContext.getObjectFileInfo()->getStackMapSection();
481 OS.SwitchSection(StackMapSection);
483 // Emit a dummy symbol to force section inclusion.
484 OS.EmitLabel(OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
487 DEBUG(dbgs() << "********** Stack Map Output **********\n");
488 emitStackmapHeader(OS);
489 emitFunctionFrameRecords(OS);
490 emitConstantPoolEntries(OS);
491 emitCallsiteEntries(OS, TRI);