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 #define DEBUG_TYPE "stackmaps"
12 #include "llvm/CodeGen/StackMaps.h"
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectFileInfo.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetOpcodes.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
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) {
40 unsigned CheckStartIdx = 0, e = MI->getNumOperands();
41 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
42 MI->getOperand(CheckStartIdx).isDef() &&
43 !MI->getOperand(CheckStartIdx).isImplicit())
46 assert(getMetaIdx() == CheckStartIdx &&
47 "Unexpected additonal definition in Patchpoint intrinsic.");
52 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
54 StartIdx = getVarIdx();
56 // Find the next scratch register (implicit def and early clobber)
57 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
58 while (ScratchIdx < e &&
59 !(MI->getOperand(ScratchIdx).isReg() &&
60 MI->getOperand(ScratchIdx).isDef() &&
61 MI->getOperand(ScratchIdx).isImplicit() &&
62 MI->getOperand(ScratchIdx).isEarlyClobber()))
65 assert(ScratchIdx != e && "No scratch register available");
69 std::pair<StackMaps::Location, MachineInstr::const_mop_iterator>
70 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
71 MachineInstr::const_mop_iterator MOE) const {
72 const MachineOperand &MOP = *MOI;
73 assert((!MOP.isReg() || !MOP.isImplicit()) &&
74 "Implicit operands should not be processed.");
78 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
80 switch (MOP.getImm()) {
81 default: llvm_unreachable("Unrecognized operand type.");
82 case StackMaps::DirectMemRefOp: {
83 unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
84 assert((Size % 8) == 0 && "Need pointer size in bytes.");
86 unsigned Reg = (++MOI)->getReg();
87 int64_t Imm = (++MOI)->getImm();
88 return std::make_pair(
89 Location(StackMaps::Location::Direct, Size, Reg, Imm), ++MOI);
91 case StackMaps::IndirectMemRefOp: {
92 int64_t Size = (++MOI)->getImm();
93 assert(Size > 0 && "Need a valid size for indirect memory locations.");
94 unsigned Reg = (++MOI)->getReg();
95 int64_t Imm = (++MOI)->getImm();
96 return std::make_pair(
97 Location(StackMaps::Location::Indirect, Size, Reg, Imm), ++MOI);
99 case StackMaps::ConstantOp: {
101 assert(MOI->isImm() && "Expected constant operand.");
102 int64_t Imm = MOI->getImm();
103 return std::make_pair(
104 Location(Location::Constant, sizeof(int64_t), 0, Imm), ++MOI);
109 if (MOP.isRegMask() || MOP.isRegLiveOut())
110 return std::make_pair(Location(), ++MOI);
112 // Otherwise this is a reg operand. The physical register number will
113 // ultimately be encoded as a DWARF regno. The stack map also records the size
114 // of a spill slot that can hold the register content. (The runtime can
115 // track the actual size of the data type if it needs to.)
116 assert(MOP.isReg() && "Expected register operand here.");
117 assert(TargetRegisterInfo::isPhysicalRegister(MOP.getReg()) &&
118 "Virtreg operands should have been rewritten before now.");
119 const TargetRegisterClass *RC =
120 AP.TM.getRegisterInfo()->getMinimalPhysRegClass(MOP.getReg());
121 assert(!MOP.getSubReg() && "Physical subreg still around.");
122 return std::make_pair(
123 Location(Location::Register, RC->getSize(), MOP.getReg(), 0), ++MOI);
126 /// Go up the super-register chain until we hit a valid dwarf register number.
127 static short getDwarfRegNum(unsigned Reg, const MCRegisterInfo &MCRI,
128 const TargetRegisterInfo *TRI) {
129 int RegNo = MCRI.getDwarfRegNum(Reg, false);
130 for (MCSuperRegIterator SR(Reg, TRI);
131 SR.isValid() && RegNo < 0; ++SR)
132 RegNo = TRI->getDwarfRegNum(*SR, false);
134 assert(RegNo >= 0 && "Invalid Dwarf register number.");
135 return (unsigned short) RegNo;
138 /// Create a live-out register record for the given register Reg.
139 StackMaps::LiveOutReg
140 StackMaps::createLiveOutReg(unsigned Reg, const MCRegisterInfo &MCRI,
141 const TargetRegisterInfo *TRI) const {
142 unsigned RegNo = getDwarfRegNum(Reg, MCRI, TRI);
143 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
144 unsigned LLVMRegNo = MCRI.getLLVMRegNum(RegNo, false);
145 unsigned SubRegIdx = MCRI.getSubRegIndex(LLVMRegNo, Reg);
148 Offset = MCRI.getSubRegIdxOffset(SubRegIdx) / 8;
150 return LiveOutReg(Reg, RegNo, Offset + Size);
153 /// Parse the register live-out mask and return a vector of live-out registers
154 /// that need to be recorded in the stackmap.
155 StackMaps::LiveOutVec
156 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
157 assert(Mask && "No register mask specified");
158 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
159 MCContext &OutContext = AP.OutStreamer.getContext();
160 const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
163 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
164 if ((Mask[Reg / 32] >> Reg % 32) & 1)
165 LiveOuts.push_back(createLiveOutReg(Reg, MCRI, TRI));
167 std::sort(LiveOuts.begin(), LiveOuts.end());
168 for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
172 for (LiveOutVec::iterator II = next(I); II != E; ++II) {
173 if (I->RegNo != II->RegNo)
175 I->Size = std::max(I->Size, II->Size);
176 if (TRI->isSuperRegister(I->Reg, II->Reg))
181 LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
182 LiveOutReg::isInvalid), LiveOuts.end());
186 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
187 MachineInstr::const_mop_iterator MOI,
188 MachineInstr::const_mop_iterator MOE,
191 MCContext &OutContext = AP.OutStreamer.getContext();
192 MCSymbol *MILabel = OutContext.CreateTempSymbol();
193 AP.OutStreamer.EmitLabel(MILabel);
195 LocationVec Locations;
199 std::pair<Location, MachineInstr::const_mop_iterator> ParseResult =
200 parseOperand(MI.operands_begin(), llvm::next(MI.operands_begin()));
202 Location &Loc = ParseResult.first;
203 assert(Loc.LocType == Location::Register &&
204 "Stackmap return location must be a register.");
205 Locations.push_back(Loc);
210 tie(Loc, MOI) = parseOperand(MOI, MOE);
212 // Move large constants into the constant pool.
213 if (Loc.LocType == Location::Constant && (Loc.Offset & ~0xFFFFFFFFULL)) {
214 Loc.LocType = Location::ConstantIndex;
215 Loc.Offset = ConstPool.getConstantIndex(Loc.Offset);
218 // Skip the register mask and register live-out mask
219 if (Loc.LocType != Location::Unprocessed)
220 Locations.push_back(Loc);
223 const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
224 MCSymbolRefExpr::Create(MILabel, OutContext),
225 MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
228 if (MOI->isRegLiveOut())
229 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
231 CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
234 static MachineInstr::const_mop_iterator
235 getStackMapEndMOP(MachineInstr::const_mop_iterator MOI,
236 MachineInstr::const_mop_iterator MOE) {
237 for (; MOI != MOE; ++MOI)
238 if (MOI->isRegLiveOut() || (MOI->isReg() && MOI->isImplicit()))
243 void StackMaps::recordStackMap(const MachineInstr &MI) {
244 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
246 int64_t ID = MI.getOperand(0).getImm();
247 recordStackMapOpers(MI, ID, llvm::next(MI.operands_begin(), 2),
248 getStackMapEndMOP(MI.operands_begin(),
252 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
253 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
255 PatchPointOpers opers(&MI);
256 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
258 MachineInstr::const_mop_iterator MOI =
259 llvm::next(MI.operands_begin(), opers.getStackMapStartIdx());
260 recordStackMapOpers(MI, ID, MOI, getStackMapEndMOP(MOI, MI.operands_end()),
261 opers.isAnyReg() && opers.hasDef());
265 LocationVec &Locations = CSInfos.back().Locations;
266 if (opers.isAnyReg()) {
267 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
268 for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
269 assert(Locations[i].LocType == Location::Register &&
270 "anyreg arg must be in reg.");
275 /// serializeToStackMapSection conceptually populates the following fields:
277 /// uint32 : Reserved (header)
278 /// uint32 : NumConstants
279 /// int64 : Constants[NumConstants]
280 /// uint32 : NumRecords
281 /// StkMapRecord[NumRecords] {
282 /// uint64 : PatchPoint ID
283 /// uint32 : Instruction Offset
284 /// uint16 : Reserved (record flags)
285 /// uint16 : NumLocations
286 /// Location[NumLocations] {
287 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
288 /// uint8 : Size in Bytes
289 /// uint16 : Dwarf RegNum
292 /// uint16 : NumLiveOuts
293 /// LiveOuts[NumLiveOuts]
294 /// uint16 : Dwarf RegNum
296 /// uint8 : Size in Bytes
299 /// Location Encoding, Type, Value:
300 /// 0x1, Register, Reg (value in register)
301 /// 0x2, Direct, Reg + Offset (frame index)
302 /// 0x3, Indirect, [Reg + Offset] (spilled value)
303 /// 0x4, Constant, Offset (small constant)
304 /// 0x5, ConstIndex, Constants[Offset] (large constant)
306 void StackMaps::serializeToStackMapSection() {
307 // Bail out if there's no stack map data.
311 MCContext &OutContext = AP.OutStreamer.getContext();
312 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
314 // Create the section.
315 const MCSection *StackMapSection =
316 OutContext.getObjectFileInfo()->getStackMapSection();
317 AP.OutStreamer.SwitchSection(StackMapSection);
319 // Emit a dummy symbol to force section inclusion.
320 AP.OutStreamer.EmitLabel(
321 OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
324 const char *WSMP = "Stack Maps: ";
326 const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
328 DEBUG(dbgs() << "********** Stack Map Output **********\n");
331 AP.OutStreamer.EmitIntValue(0, 4);
334 AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
336 // Constant pool entries.
337 for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
338 AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
340 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
341 AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
343 for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
344 CSIE = CSInfos.end();
345 CSII != CSIE; ++CSII) {
347 uint64_t CallsiteID = CSII->ID;
348 const LocationVec &CSLocs = CSII->Locations;
349 const LiveOutVec &LiveOuts = CSII->LiveOuts;
351 DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
353 // Verify stack map entry. It's better to communicate a problem to the
354 // runtime than crash in case of in-process compilation. Currently, we do
355 // simple overflow checks, but we may eventually communicate other
356 // compilation errors this way.
357 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
358 AP.OutStreamer.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
359 AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
360 AP.OutStreamer.EmitIntValue(0, 2); // Reserved.
361 AP.OutStreamer.EmitIntValue(0, 2); // 0 locations.
362 AP.OutStreamer.EmitIntValue(0, 2); // 0 live-out registers.
366 AP.OutStreamer.EmitIntValue(CallsiteID, 8);
367 AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
369 // Reserved for flags.
370 AP.OutStreamer.EmitIntValue(0, 2);
372 DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
374 AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
376 unsigned operIdx = 0;
377 for (LocationVec::const_iterator LocI = CSLocs.begin(), LocE = CSLocs.end();
378 LocI != LocE; ++LocI, ++operIdx) {
379 const Location &Loc = *LocI;
381 int Offset = Loc.Offset;
383 RegNo = MCRI.getDwarfRegNum(Loc.Reg, false);
384 for (MCSuperRegIterator SR(Loc.Reg, TRI);
385 SR.isValid() && (int)RegNo < 0; ++SR) {
386 RegNo = TRI->getDwarfRegNum(*SR, false);
388 // If this is a register location, put the subregister byte offset in
389 // the location offset.
390 if (Loc.LocType == Location::Register) {
391 assert(!Loc.Offset && "Register location should have zero offset");
392 unsigned LLVMRegNo = MCRI.getLLVMRegNum(RegNo, false);
393 unsigned SubRegIdx = MCRI.getSubRegIndex(LLVMRegNo, Loc.Reg);
395 Offset = MCRI.getSubRegIdxOffset(SubRegIdx);
399 assert(Loc.LocType != Location::Register &&
400 "Missing location register");
404 dbgs() << WSMP << " Loc " << operIdx << ": ";
405 switch (Loc.LocType) {
406 case Location::Unprocessed:
407 dbgs() << "<Unprocessed operand>";
409 case Location::Register:
410 dbgs() << "Register " << MCRI.getName(Loc.Reg);
412 case Location::Direct:
413 dbgs() << "Direct " << MCRI.getName(Loc.Reg);
415 dbgs() << " + " << Loc.Offset;
417 case Location::Indirect:
418 dbgs() << "Indirect " << MCRI.getName(Loc.Reg)
419 << " + " << Loc.Offset;
421 case Location::Constant:
422 dbgs() << "Constant " << Loc.Offset;
424 case Location::ConstantIndex:
425 dbgs() << "Constant Index " << Loc.Offset;
428 dbgs() << " [encoding: .byte " << Loc.LocType
429 << ", .byte " << Loc.Size
430 << ", .short " << RegNo
431 << ", .int " << Offset << "]\n";
434 AP.OutStreamer.EmitIntValue(Loc.LocType, 1);
435 AP.OutStreamer.EmitIntValue(Loc.Size, 1);
436 AP.OutStreamer.EmitIntValue(RegNo, 2);
437 AP.OutStreamer.EmitIntValue(Offset, 4);
440 DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
441 << " live-out registers\n");
443 AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
446 for (LiveOutVec::const_iterator LI = LiveOuts.begin(), LE = LiveOuts.end();
447 LI != LE; ++LI, ++operIdx) {
448 DEBUG(dbgs() << WSMP << " LO " << operIdx << ": "
449 << MCRI.getName(LI->Reg)
450 << " [encoding: .short " << LI->RegNo
451 << ", .byte 0, .byte " << LI->Size << "]\n");
453 AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
454 AP.OutStreamer.EmitIntValue(0, 1);
455 AP.OutStreamer.EmitIntValue(LI->Size, 1);
459 AP.OutStreamer.AddBlankLine();