1f785676fSDimitry Andric //===---------------------------- StackMaps.cpp ---------------------------===//
2f785676fSDimitry Andric //
3f785676fSDimitry Andric //                     The LLVM Compiler Infrastructure
4f785676fSDimitry Andric //
5f785676fSDimitry Andric // This file is distributed under the University of Illinois Open Source
6f785676fSDimitry Andric // License. See LICENSE.TXT for details.
7f785676fSDimitry Andric //
8f785676fSDimitry Andric //===----------------------------------------------------------------------===//
9f785676fSDimitry Andric 
10f785676fSDimitry Andric #include "llvm/CodeGen/StackMaps.h"
11f785676fSDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
1291bc56edSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
1391bc56edSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
14f785676fSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
1591bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
16f785676fSDimitry Andric #include "llvm/MC/MCContext.h"
17f785676fSDimitry Andric #include "llvm/MC/MCExpr.h"
18f785676fSDimitry Andric #include "llvm/MC/MCObjectFileInfo.h"
19f785676fSDimitry Andric #include "llvm/MC/MCSectionMachO.h"
20f785676fSDimitry Andric #include "llvm/MC/MCStreamer.h"
2191bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
22f785676fSDimitry Andric #include "llvm/Target/TargetMachine.h"
2391bc56edSDimitry Andric #include "llvm/Target/TargetOpcodes.h"
24f785676fSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
2539d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
26f785676fSDimitry Andric #include <iterator>
27f785676fSDimitry Andric 
28f785676fSDimitry Andric using namespace llvm;
29f785676fSDimitry Andric 
3091bc56edSDimitry Andric #define DEBUG_TYPE "stackmaps"
3191bc56edSDimitry Andric 
3291bc56edSDimitry Andric static cl::opt<int> StackMapVersion("stackmap-version", cl::init(1),
3391bc56edSDimitry Andric   cl::desc("Specify the stackmap encoding version (default = 1)"));
3491bc56edSDimitry Andric 
3591bc56edSDimitry Andric const char *StackMaps::WSMP = "Stack Maps: ";
3691bc56edSDimitry Andric 
3791bc56edSDimitry Andric PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
3891bc56edSDimitry Andric   : MI(MI),
39f785676fSDimitry Andric     HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
40f785676fSDimitry Andric            !MI->getOperand(0).isImplicit()),
4191bc56edSDimitry Andric     IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
42f785676fSDimitry Andric {
4391bc56edSDimitry Andric #ifndef NDEBUG
44f785676fSDimitry Andric   unsigned CheckStartIdx = 0, e = MI->getNumOperands();
45f785676fSDimitry Andric   while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
46f785676fSDimitry Andric          MI->getOperand(CheckStartIdx).isDef() &&
47f785676fSDimitry Andric          !MI->getOperand(CheckStartIdx).isImplicit())
48f785676fSDimitry Andric     ++CheckStartIdx;
49f785676fSDimitry Andric 
50f785676fSDimitry Andric   assert(getMetaIdx() == CheckStartIdx &&
5191bc56edSDimitry Andric          "Unexpected additional definition in Patchpoint intrinsic.");
52f785676fSDimitry Andric #endif
53f785676fSDimitry Andric }
54f785676fSDimitry Andric 
55f785676fSDimitry Andric unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
56f785676fSDimitry Andric   if (!StartIdx)
57f785676fSDimitry Andric     StartIdx = getVarIdx();
58f785676fSDimitry Andric 
59f785676fSDimitry Andric   // Find the next scratch register (implicit def and early clobber)
60f785676fSDimitry Andric   unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
61f785676fSDimitry Andric   while (ScratchIdx < e &&
62f785676fSDimitry Andric          !(MI->getOperand(ScratchIdx).isReg() &&
63f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isDef() &&
64f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isImplicit() &&
65f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isEarlyClobber()))
66f785676fSDimitry Andric     ++ScratchIdx;
67f785676fSDimitry Andric 
68f785676fSDimitry Andric   assert(ScratchIdx != e && "No scratch register available");
69f785676fSDimitry Andric   return ScratchIdx;
70f785676fSDimitry Andric }
71f785676fSDimitry Andric 
7291bc56edSDimitry Andric StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
7391bc56edSDimitry Andric   if (StackMapVersion != 1)
7491bc56edSDimitry Andric     llvm_unreachable("Unsupported stackmap version!");
7591bc56edSDimitry Andric }
7691bc56edSDimitry Andric 
77ff0cc061SDimitry Andric /// Go up the super-register chain until we hit a valid dwarf register number.
78ff0cc061SDimitry Andric static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
79ff0cc061SDimitry Andric   int RegNo = TRI->getDwarfRegNum(Reg, false);
80ff0cc061SDimitry Andric   for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
81ff0cc061SDimitry Andric     RegNo = TRI->getDwarfRegNum(*SR, false);
82ff0cc061SDimitry Andric 
83ff0cc061SDimitry Andric   assert(RegNo >= 0 && "Invalid Dwarf register number.");
84ff0cc061SDimitry Andric   return (unsigned) RegNo;
85ff0cc061SDimitry Andric }
86ff0cc061SDimitry Andric 
8791bc56edSDimitry Andric MachineInstr::const_mop_iterator
8891bc56edSDimitry Andric StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
8991bc56edSDimitry Andric                         MachineInstr::const_mop_iterator MOE,
9091bc56edSDimitry Andric                         LocationVec &Locs, LiveOutVec &LiveOuts) const {
91ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
9291bc56edSDimitry Andric   if (MOI->isImm()) {
9391bc56edSDimitry Andric     switch (MOI->getImm()) {
9491bc56edSDimitry Andric     default: llvm_unreachable("Unrecognized operand type.");
9591bc56edSDimitry Andric     case StackMaps::DirectMemRefOp: {
96ff0cc061SDimitry Andric       unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
9791bc56edSDimitry Andric       assert((Size % 8) == 0 && "Need pointer size in bytes.");
9891bc56edSDimitry Andric       Size /= 8;
9991bc56edSDimitry Andric       unsigned Reg = (++MOI)->getReg();
10091bc56edSDimitry Andric       int64_t Imm = (++MOI)->getImm();
101ff0cc061SDimitry Andric       Locs.push_back(Location(StackMaps::Location::Direct, Size,
102ff0cc061SDimitry Andric                               getDwarfRegNum(Reg, TRI), Imm));
10391bc56edSDimitry Andric       break;
10491bc56edSDimitry Andric     }
10591bc56edSDimitry Andric     case StackMaps::IndirectMemRefOp: {
10691bc56edSDimitry Andric       int64_t Size = (++MOI)->getImm();
10791bc56edSDimitry Andric       assert(Size > 0 && "Need a valid size for indirect memory locations.");
10891bc56edSDimitry Andric       unsigned Reg = (++MOI)->getReg();
10991bc56edSDimitry Andric       int64_t Imm = (++MOI)->getImm();
110ff0cc061SDimitry Andric       Locs.push_back(Location(StackMaps::Location::Indirect, Size,
111ff0cc061SDimitry Andric                               getDwarfRegNum(Reg, TRI), Imm));
11291bc56edSDimitry Andric       break;
11391bc56edSDimitry Andric     }
11491bc56edSDimitry Andric     case StackMaps::ConstantOp: {
11591bc56edSDimitry Andric       ++MOI;
11691bc56edSDimitry Andric       assert(MOI->isImm() && "Expected constant operand.");
11791bc56edSDimitry Andric       int64_t Imm = MOI->getImm();
11891bc56edSDimitry Andric       Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
11991bc56edSDimitry Andric       break;
12091bc56edSDimitry Andric     }
12191bc56edSDimitry Andric     }
12291bc56edSDimitry Andric     return ++MOI;
12391bc56edSDimitry Andric   }
12491bc56edSDimitry Andric 
12591bc56edSDimitry Andric   // The physical register number will ultimately be encoded as a DWARF regno.
12691bc56edSDimitry Andric   // The stack map also records the size of a spill slot that can hold the
12791bc56edSDimitry Andric   // register content. (The runtime can track the actual size of the data type
12891bc56edSDimitry Andric   // if it needs to.)
12991bc56edSDimitry Andric   if (MOI->isReg()) {
13091bc56edSDimitry Andric     // Skip implicit registers (this includes our scratch registers)
13191bc56edSDimitry Andric     if (MOI->isImplicit())
13291bc56edSDimitry Andric       return ++MOI;
13391bc56edSDimitry Andric 
13491bc56edSDimitry Andric     assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
13591bc56edSDimitry Andric            "Virtreg operands should have been rewritten before now.");
136ff0cc061SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(MOI->getReg());
13791bc56edSDimitry Andric     assert(!MOI->getSubReg() && "Physical subreg still around.");
138ff0cc061SDimitry Andric 
139ff0cc061SDimitry Andric     unsigned Offset = 0;
140ff0cc061SDimitry Andric     unsigned RegNo = getDwarfRegNum(MOI->getReg(), TRI);
141ff0cc061SDimitry Andric     unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
142ff0cc061SDimitry Andric     unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, MOI->getReg());
143ff0cc061SDimitry Andric     if (SubRegIdx)
144ff0cc061SDimitry Andric       Offset = TRI->getSubRegIdxOffset(SubRegIdx);
145ff0cc061SDimitry Andric 
14691bc56edSDimitry Andric     Locs.push_back(
147ff0cc061SDimitry Andric       Location(Location::Register, RC->getSize(), RegNo, Offset));
14891bc56edSDimitry Andric     return ++MOI;
14991bc56edSDimitry Andric   }
15091bc56edSDimitry Andric 
15191bc56edSDimitry Andric   if (MOI->isRegLiveOut())
15291bc56edSDimitry Andric     LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
15391bc56edSDimitry Andric 
15491bc56edSDimitry Andric   return ++MOI;
15591bc56edSDimitry Andric }
15691bc56edSDimitry Andric 
157ff0cc061SDimitry Andric void StackMaps::print(raw_ostream &OS) {
158ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
159ff0cc061SDimitry Andric       AP.MF ? AP.MF->getSubtarget().getRegisterInfo() : nullptr;
160ff0cc061SDimitry Andric   OS << WSMP << "callsites:\n";
161ff0cc061SDimitry Andric   for (const auto &CSI : CSInfos) {
162ff0cc061SDimitry Andric     const LocationVec &CSLocs = CSI.Locations;
163ff0cc061SDimitry Andric     const LiveOutVec &LiveOuts = CSI.LiveOuts;
16491bc56edSDimitry Andric 
165ff0cc061SDimitry Andric     OS << WSMP << "callsite " << CSI.ID << "\n";
166ff0cc061SDimitry Andric     OS << WSMP << "  has " << CSLocs.size() << " locations\n";
167ff0cc061SDimitry Andric 
168ff0cc061SDimitry Andric     unsigned OperIdx = 0;
169ff0cc061SDimitry Andric     for (const auto &Loc : CSLocs) {
170ff0cc061SDimitry Andric       OS << WSMP << "  Loc " << OperIdx << ": ";
171ff0cc061SDimitry Andric       switch (Loc.LocType) {
172ff0cc061SDimitry Andric       case Location::Unprocessed:
173ff0cc061SDimitry Andric         OS << "<Unprocessed operand>";
174ff0cc061SDimitry Andric         break;
175ff0cc061SDimitry Andric       case Location::Register:
176ff0cc061SDimitry Andric         OS << "Register ";
177ff0cc061SDimitry Andric 	if (TRI)
178ff0cc061SDimitry Andric 	  OS << TRI->getName(Loc.Reg);
179ff0cc061SDimitry Andric 	else
180ff0cc061SDimitry Andric 	  OS << Loc.Reg;
181ff0cc061SDimitry Andric         break;
182ff0cc061SDimitry Andric       case Location::Direct:
183ff0cc061SDimitry Andric         OS << "Direct ";
184ff0cc061SDimitry Andric         if (TRI)
185ff0cc061SDimitry Andric           OS << TRI->getName(Loc.Reg);
186ff0cc061SDimitry Andric         else
187ff0cc061SDimitry Andric           OS << Loc.Reg;
188ff0cc061SDimitry Andric         if (Loc.Offset)
189ff0cc061SDimitry Andric           OS << " + " << Loc.Offset;
190ff0cc061SDimitry Andric         break;
191ff0cc061SDimitry Andric       case Location::Indirect:
192ff0cc061SDimitry Andric         OS << "Indirect ";
193ff0cc061SDimitry Andric         if (TRI)
194ff0cc061SDimitry Andric           OS << TRI->getName(Loc.Reg);
195ff0cc061SDimitry Andric         else
196ff0cc061SDimitry Andric           OS << Loc.Reg;
197ff0cc061SDimitry Andric         OS << "+" << Loc.Offset;
198ff0cc061SDimitry Andric         break;
199ff0cc061SDimitry Andric       case Location::Constant:
200ff0cc061SDimitry Andric         OS << "Constant " << Loc.Offset;
201ff0cc061SDimitry Andric         break;
202ff0cc061SDimitry Andric       case Location::ConstantIndex:
203ff0cc061SDimitry Andric         OS << "Constant Index " << Loc.Offset;
204ff0cc061SDimitry Andric         break;
205ff0cc061SDimitry Andric       }
206ff0cc061SDimitry Andric       OS << "     [encoding: .byte " << Loc.LocType << ", .byte " << Loc.Size
207ff0cc061SDimitry Andric          << ", .short " << Loc.Reg << ", .int " << Loc.Offset << "]\n";
208ff0cc061SDimitry Andric       OperIdx++;
209ff0cc061SDimitry Andric     }
210ff0cc061SDimitry Andric 
211ff0cc061SDimitry Andric     OS << WSMP << "  has " << LiveOuts.size() << " live-out registers\n";
212ff0cc061SDimitry Andric 
213ff0cc061SDimitry Andric     OperIdx = 0;
214ff0cc061SDimitry Andric     for (const auto &LO : LiveOuts) {
215ff0cc061SDimitry Andric       OS << WSMP << "  LO " << OperIdx << ": ";
216ff0cc061SDimitry Andric       if (TRI)
217ff0cc061SDimitry Andric         OS << TRI->getName(LO.Reg);
218ff0cc061SDimitry Andric       else
219ff0cc061SDimitry Andric         OS << LO.Reg;
220ff0cc061SDimitry Andric       OS << "      [encoding: .short " << LO.RegNo << ", .byte 0, .byte "
221ff0cc061SDimitry Andric          << LO.Size << "]\n";
222ff0cc061SDimitry Andric       OperIdx++;
223ff0cc061SDimitry Andric     }
224ff0cc061SDimitry Andric   }
22591bc56edSDimitry Andric }
22691bc56edSDimitry Andric 
22791bc56edSDimitry Andric /// Create a live-out register record for the given register Reg.
22891bc56edSDimitry Andric StackMaps::LiveOutReg
22991bc56edSDimitry Andric StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
23091bc56edSDimitry Andric   unsigned RegNo = getDwarfRegNum(Reg, TRI);
23191bc56edSDimitry Andric   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
23291bc56edSDimitry Andric   return LiveOutReg(Reg, RegNo, Size);
23391bc56edSDimitry Andric }
23491bc56edSDimitry Andric 
23591bc56edSDimitry Andric /// Parse the register live-out mask and return a vector of live-out registers
23691bc56edSDimitry Andric /// that need to be recorded in the stackmap.
23791bc56edSDimitry Andric StackMaps::LiveOutVec
23891bc56edSDimitry Andric StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
23991bc56edSDimitry Andric   assert(Mask && "No register mask specified");
240ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
24191bc56edSDimitry Andric   LiveOutVec LiveOuts;
24291bc56edSDimitry Andric 
24391bc56edSDimitry Andric   // Create a LiveOutReg for each bit that is set in the register mask.
24491bc56edSDimitry Andric   for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
24591bc56edSDimitry Andric     if ((Mask[Reg / 32] >> Reg % 32) & 1)
24691bc56edSDimitry Andric       LiveOuts.push_back(createLiveOutReg(Reg, TRI));
24791bc56edSDimitry Andric 
24891bc56edSDimitry Andric   // We don't need to keep track of a register if its super-register is already
24991bc56edSDimitry Andric   // in the list. Merge entries that refer to the same dwarf register and use
25091bc56edSDimitry Andric   // the maximum size that needs to be spilled.
25191bc56edSDimitry Andric   std::sort(LiveOuts.begin(), LiveOuts.end());
25291bc56edSDimitry Andric   for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
25391bc56edSDimitry Andric        I != E; ++I) {
25491bc56edSDimitry Andric     for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
25591bc56edSDimitry Andric       if (I->RegNo != II->RegNo) {
25691bc56edSDimitry Andric         // Skip all the now invalid entries.
25791bc56edSDimitry Andric         I = --II;
25891bc56edSDimitry Andric         break;
25991bc56edSDimitry Andric       }
26091bc56edSDimitry Andric       I->Size = std::max(I->Size, II->Size);
26191bc56edSDimitry Andric       if (TRI->isSuperRegister(I->Reg, II->Reg))
26291bc56edSDimitry Andric         I->Reg = II->Reg;
26391bc56edSDimitry Andric       II->MarkInvalid();
26491bc56edSDimitry Andric     }
26591bc56edSDimitry Andric   }
26691bc56edSDimitry Andric   LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
26791bc56edSDimitry Andric                                 LiveOutReg::IsInvalid), LiveOuts.end());
26891bc56edSDimitry Andric   return LiveOuts;
26991bc56edSDimitry Andric }
27091bc56edSDimitry Andric 
27191bc56edSDimitry Andric void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
272f785676fSDimitry Andric                                     MachineInstr::const_mop_iterator MOI,
273f785676fSDimitry Andric                                     MachineInstr::const_mop_iterator MOE,
274f785676fSDimitry Andric                                     bool recordResult) {
275f785676fSDimitry Andric 
276ff0cc061SDimitry Andric   MCContext &OutContext = AP.OutStreamer->getContext();
277ff0cc061SDimitry Andric   MCSymbol *MILabel = OutContext.createTempSymbol();
278ff0cc061SDimitry Andric   AP.OutStreamer->EmitLabel(MILabel);
279f785676fSDimitry Andric 
28091bc56edSDimitry Andric   LocationVec Locations;
28191bc56edSDimitry Andric   LiveOutVec LiveOuts;
282f785676fSDimitry Andric 
283f785676fSDimitry Andric   if (recordResult) {
28491bc56edSDimitry Andric     assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
28591bc56edSDimitry Andric     parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
28691bc56edSDimitry Andric                  Locations, LiveOuts);
287f785676fSDimitry Andric   }
288f785676fSDimitry Andric 
28991bc56edSDimitry Andric   // Parse operands.
290f785676fSDimitry Andric   while (MOI != MOE) {
29191bc56edSDimitry Andric     MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
29291bc56edSDimitry Andric   }
293f785676fSDimitry Andric 
294f785676fSDimitry Andric   // Move large constants into the constant pool.
29591bc56edSDimitry Andric   for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
29691bc56edSDimitry Andric        I != E; ++I) {
29791bc56edSDimitry Andric     // Constants are encoded as sign-extended integers.
29891bc56edSDimitry Andric     // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
29939d628a0SDimitry Andric     if (I->LocType == Location::Constant && !isInt<32>(I->Offset)) {
30091bc56edSDimitry Andric       I->LocType = Location::ConstantIndex;
30139d628a0SDimitry Andric       // ConstPool is intentionally a MapVector of 'uint64_t's (as
30239d628a0SDimitry Andric       // opposed to 'int64_t's).  We should never be in a situation
30339d628a0SDimitry Andric       // where we have to insert either the tombstone or the empty
30439d628a0SDimitry Andric       // keys into a map, and for a DenseMap<uint64_t, T> these are
30539d628a0SDimitry Andric       // (uint64_t)0 and (uint64_t)-1.  They can be and are
30639d628a0SDimitry Andric       // represented using 32 bit integers.
30739d628a0SDimitry Andric 
30839d628a0SDimitry Andric       assert((uint64_t)I->Offset != DenseMapInfo<uint64_t>::getEmptyKey() &&
30939d628a0SDimitry Andric              (uint64_t)I->Offset != DenseMapInfo<uint64_t>::getTombstoneKey() &&
31039d628a0SDimitry Andric              "empty and tombstone keys should fit in 32 bits!");
31191bc56edSDimitry Andric       auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
31291bc56edSDimitry Andric       I->Offset = Result.first - ConstPool.begin();
31391bc56edSDimitry Andric     }
314f785676fSDimitry Andric   }
315f785676fSDimitry Andric 
31691bc56edSDimitry Andric   // Create an expression to calculate the offset of the callsite from function
31791bc56edSDimitry Andric   // entry.
318f785676fSDimitry Andric   const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
319f785676fSDimitry Andric     MCSymbolRefExpr::Create(MILabel, OutContext),
32039d628a0SDimitry Andric     MCSymbolRefExpr::Create(AP.CurrentFnSymForSize, OutContext),
321f785676fSDimitry Andric     OutContext);
322f785676fSDimitry Andric 
32339d628a0SDimitry Andric   CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
32439d628a0SDimitry Andric                        std::move(LiveOuts));
325f785676fSDimitry Andric 
32691bc56edSDimitry Andric   // Record the stack size of the current function.
32791bc56edSDimitry Andric   const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
32839d628a0SDimitry Andric   const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
32939d628a0SDimitry Andric   const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
33039d628a0SDimitry Andric     RegInfo->needsStackRealignment(*(AP.MF));
33191bc56edSDimitry Andric   FnStackSize[AP.CurrentFnSym] =
33239d628a0SDimitry Andric     DynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
333f785676fSDimitry Andric }
334f785676fSDimitry Andric 
335f785676fSDimitry Andric void StackMaps::recordStackMap(const MachineInstr &MI) {
33691bc56edSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
337f785676fSDimitry Andric 
338f785676fSDimitry Andric   int64_t ID = MI.getOperand(0).getImm();
33991bc56edSDimitry Andric   recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
34091bc56edSDimitry Andric                       MI.operands_end());
341f785676fSDimitry Andric }
342f785676fSDimitry Andric 
343f785676fSDimitry Andric void StackMaps::recordPatchPoint(const MachineInstr &MI) {
34491bc56edSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
345f785676fSDimitry Andric 
346f785676fSDimitry Andric   PatchPointOpers opers(&MI);
347f785676fSDimitry Andric   int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
34891bc56edSDimitry Andric 
349f785676fSDimitry Andric   MachineInstr::const_mop_iterator MOI =
35091bc56edSDimitry Andric     std::next(MI.operands_begin(), opers.getStackMapStartIdx());
35191bc56edSDimitry Andric   recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
352f785676fSDimitry Andric                       opers.isAnyReg() && opers.hasDef());
353f785676fSDimitry Andric 
354f785676fSDimitry Andric #ifndef NDEBUG
355f785676fSDimitry Andric   // verify anyregcc
356f785676fSDimitry Andric   LocationVec &Locations = CSInfos.back().Locations;
357f785676fSDimitry Andric   if (opers.isAnyReg()) {
358f785676fSDimitry Andric     unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
359f785676fSDimitry Andric     for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
360f785676fSDimitry Andric       assert(Locations[i].LocType == Location::Register &&
361f785676fSDimitry Andric              "anyreg arg must be in reg.");
362f785676fSDimitry Andric   }
363f785676fSDimitry Andric #endif
364f785676fSDimitry Andric }
36539d628a0SDimitry Andric void StackMaps::recordStatepoint(const MachineInstr &MI) {
36639d628a0SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::STATEPOINT &&
36739d628a0SDimitry Andric          "expected statepoint");
36839d628a0SDimitry Andric 
36939d628a0SDimitry Andric   StatepointOpers opers(&MI);
37039d628a0SDimitry Andric   // Record all the deopt and gc operands (they're contiguous and run from the
37139d628a0SDimitry Andric   // initial index to the end of the operand list)
37239d628a0SDimitry Andric   const unsigned StartIdx = opers.getVarIdx();
373ff0cc061SDimitry Andric   recordStackMapOpers(MI, opers.getID(), MI.operands_begin() + StartIdx,
374ff0cc061SDimitry Andric                       MI.operands_end(), false);
37539d628a0SDimitry Andric }
376f785676fSDimitry Andric 
37791bc56edSDimitry Andric /// Emit the stackmap header.
378f785676fSDimitry Andric ///
37991bc56edSDimitry Andric /// Header {
38091bc56edSDimitry Andric ///   uint8  : Stack Map Version (currently 1)
38191bc56edSDimitry Andric ///   uint8  : Reserved (expected to be 0)
38291bc56edSDimitry Andric ///   uint16 : Reserved (expected to be 0)
38391bc56edSDimitry Andric /// }
38491bc56edSDimitry Andric /// uint32 : NumFunctions
385f785676fSDimitry Andric /// uint32 : NumConstants
386f785676fSDimitry Andric /// uint32 : NumRecords
38791bc56edSDimitry Andric void StackMaps::emitStackmapHeader(MCStreamer &OS) {
38891bc56edSDimitry Andric   // Header.
38991bc56edSDimitry Andric   OS.EmitIntValue(StackMapVersion, 1); // Version.
39091bc56edSDimitry Andric   OS.EmitIntValue(0, 1); // Reserved.
39191bc56edSDimitry Andric   OS.EmitIntValue(0, 2); // Reserved.
39291bc56edSDimitry Andric 
39391bc56edSDimitry Andric   // Num functions.
39491bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
39591bc56edSDimitry Andric   OS.EmitIntValue(FnStackSize.size(), 4);
39691bc56edSDimitry Andric   // Num constants.
39791bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
39891bc56edSDimitry Andric   OS.EmitIntValue(ConstPool.size(), 4);
39991bc56edSDimitry Andric   // Num callsites.
40091bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
40191bc56edSDimitry Andric   OS.EmitIntValue(CSInfos.size(), 4);
40291bc56edSDimitry Andric }
40391bc56edSDimitry Andric 
40491bc56edSDimitry Andric /// Emit the function frame record for each function.
40591bc56edSDimitry Andric ///
40691bc56edSDimitry Andric /// StkSizeRecord[NumFunctions] {
40791bc56edSDimitry Andric ///   uint64 : Function Address
40891bc56edSDimitry Andric ///   uint64 : Stack Size
40991bc56edSDimitry Andric /// }
41091bc56edSDimitry Andric void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
41191bc56edSDimitry Andric   // Function Frame records.
41291bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "functions:\n");
41391bc56edSDimitry Andric   for (auto const &FR : FnStackSize) {
41491bc56edSDimitry Andric     DEBUG(dbgs() << WSMP << "function addr: " << FR.first
41591bc56edSDimitry Andric                          << " frame size: " << FR.second);
41691bc56edSDimitry Andric     OS.EmitSymbolValue(FR.first, 8);
41791bc56edSDimitry Andric     OS.EmitIntValue(FR.second, 8);
41891bc56edSDimitry Andric   }
41991bc56edSDimitry Andric }
42091bc56edSDimitry Andric 
42191bc56edSDimitry Andric /// Emit the constant pool.
42291bc56edSDimitry Andric ///
42391bc56edSDimitry Andric /// int64  : Constants[NumConstants]
42491bc56edSDimitry Andric void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
42591bc56edSDimitry Andric   // Constant pool entries.
42691bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "constants:\n");
42791bc56edSDimitry Andric   for (auto ConstEntry : ConstPool) {
42891bc56edSDimitry Andric     DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
42991bc56edSDimitry Andric     OS.EmitIntValue(ConstEntry.second, 8);
43091bc56edSDimitry Andric   }
43191bc56edSDimitry Andric }
43291bc56edSDimitry Andric 
43391bc56edSDimitry Andric /// Emit the callsite info for each callsite.
43491bc56edSDimitry Andric ///
435f785676fSDimitry Andric /// StkMapRecord[NumRecords] {
43691bc56edSDimitry Andric ///   uint64 : PatchPoint ID
437f785676fSDimitry Andric ///   uint32 : Instruction Offset
438f785676fSDimitry Andric ///   uint16 : Reserved (record flags)
439f785676fSDimitry Andric ///   uint16 : NumLocations
440f785676fSDimitry Andric ///   Location[NumLocations] {
441f785676fSDimitry Andric ///     uint8  : Register | Direct | Indirect | Constant | ConstantIndex
442f785676fSDimitry Andric ///     uint8  : Size in Bytes
443f785676fSDimitry Andric ///     uint16 : Dwarf RegNum
444f785676fSDimitry Andric ///     int32  : Offset
445f785676fSDimitry Andric ///   }
44691bc56edSDimitry Andric ///   uint16 : Padding
44791bc56edSDimitry Andric ///   uint16 : NumLiveOuts
44891bc56edSDimitry Andric ///   LiveOuts[NumLiveOuts] {
44991bc56edSDimitry Andric ///     uint16 : Dwarf RegNum
45091bc56edSDimitry Andric ///     uint8  : Reserved
45191bc56edSDimitry Andric ///     uint8  : Size in Bytes
45291bc56edSDimitry Andric ///   }
45391bc56edSDimitry Andric ///   uint32 : Padding (only if required to align to 8 byte)
454f785676fSDimitry Andric /// }
455f785676fSDimitry Andric ///
456f785676fSDimitry Andric /// Location Encoding, Type, Value:
457f785676fSDimitry Andric ///   0x1, Register, Reg                 (value in register)
458f785676fSDimitry Andric ///   0x2, Direct, Reg + Offset          (frame index)
459f785676fSDimitry Andric ///   0x3, Indirect, [Reg + Offset]      (spilled value)
460f785676fSDimitry Andric ///   0x4, Constant, Offset              (small constant)
461f785676fSDimitry Andric ///   0x5, ConstIndex, Constants[Offset] (large constant)
462ff0cc061SDimitry Andric void StackMaps::emitCallsiteEntries(MCStreamer &OS) {
463ff0cc061SDimitry Andric   DEBUG(print(dbgs()));
46491bc56edSDimitry Andric   // Callsite entries.
46591bc56edSDimitry Andric   for (const auto &CSI : CSInfos) {
46691bc56edSDimitry Andric     const LocationVec &CSLocs = CSI.Locations;
46791bc56edSDimitry Andric     const LiveOutVec &LiveOuts = CSI.LiveOuts;
468f785676fSDimitry Andric 
469f785676fSDimitry Andric     // Verify stack map entry. It's better to communicate a problem to the
470f785676fSDimitry Andric     // runtime than crash in case of in-process compilation. Currently, we do
471f785676fSDimitry Andric     // simple overflow checks, but we may eventually communicate other
472f785676fSDimitry Andric     // compilation errors this way.
47391bc56edSDimitry Andric     if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
47491bc56edSDimitry Andric       OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
47591bc56edSDimitry Andric       OS.EmitValue(CSI.CSOffsetExpr, 4);
47691bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // Reserved.
47791bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // 0 locations.
47891bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // padding.
47991bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // 0 live-out registers.
48091bc56edSDimitry Andric       OS.EmitIntValue(0, 4); // padding.
481f785676fSDimitry Andric       continue;
482f785676fSDimitry Andric     }
483f785676fSDimitry Andric 
48491bc56edSDimitry Andric     OS.EmitIntValue(CSI.ID, 8);
48591bc56edSDimitry Andric     OS.EmitValue(CSI.CSOffsetExpr, 4);
486f785676fSDimitry Andric 
487f785676fSDimitry Andric     // Reserved for flags.
48891bc56edSDimitry Andric     OS.EmitIntValue(0, 2);
48991bc56edSDimitry Andric     OS.EmitIntValue(CSLocs.size(), 2);
490f785676fSDimitry Andric 
49191bc56edSDimitry Andric     for (const auto &Loc : CSLocs) {
49291bc56edSDimitry Andric       OS.EmitIntValue(Loc.LocType, 1);
49391bc56edSDimitry Andric       OS.EmitIntValue(Loc.Size, 1);
494ff0cc061SDimitry Andric       OS.EmitIntValue(Loc.Reg, 2);
495ff0cc061SDimitry Andric       OS.EmitIntValue(Loc.Offset, 4);
496f785676fSDimitry Andric     }
49791bc56edSDimitry Andric 
49891bc56edSDimitry Andric     // Num live-out registers and padding to align to 4 byte.
49991bc56edSDimitry Andric     OS.EmitIntValue(0, 2);
50091bc56edSDimitry Andric     OS.EmitIntValue(LiveOuts.size(), 2);
50191bc56edSDimitry Andric 
50291bc56edSDimitry Andric     for (const auto &LO : LiveOuts) {
50391bc56edSDimitry Andric       OS.EmitIntValue(LO.RegNo, 2);
50491bc56edSDimitry Andric       OS.EmitIntValue(0, 1);
50591bc56edSDimitry Andric       OS.EmitIntValue(LO.Size, 1);
506f785676fSDimitry Andric     }
50791bc56edSDimitry Andric     // Emit alignment to 8 byte.
50891bc56edSDimitry Andric     OS.EmitValueToAlignment(8);
509f785676fSDimitry Andric   }
510f785676fSDimitry Andric }
511f785676fSDimitry Andric 
51291bc56edSDimitry Andric /// Serialize the stackmap data.
51391bc56edSDimitry Andric void StackMaps::serializeToStackMapSection() {
51491bc56edSDimitry Andric   (void) WSMP;
51591bc56edSDimitry Andric   // Bail out if there's no stack map data.
51691bc56edSDimitry Andric   assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
51791bc56edSDimitry Andric          "Expected empty constant pool too!");
51891bc56edSDimitry Andric   assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
51991bc56edSDimitry Andric          "Expected empty function record too!");
52091bc56edSDimitry Andric   if (CSInfos.empty())
52191bc56edSDimitry Andric     return;
522f785676fSDimitry Andric 
523ff0cc061SDimitry Andric   MCContext &OutContext = AP.OutStreamer->getContext();
524ff0cc061SDimitry Andric   MCStreamer &OS = *AP.OutStreamer;
52591bc56edSDimitry Andric 
52691bc56edSDimitry Andric   // Create the section.
527ff0cc061SDimitry Andric   MCSection *StackMapSection =
52891bc56edSDimitry Andric       OutContext.getObjectFileInfo()->getStackMapSection();
52991bc56edSDimitry Andric   OS.SwitchSection(StackMapSection);
53091bc56edSDimitry Andric 
53191bc56edSDimitry Andric   // Emit a dummy symbol to force section inclusion.
532ff0cc061SDimitry Andric   OS.EmitLabel(OutContext.getOrCreateSymbol(Twine("__LLVM_StackMaps")));
53391bc56edSDimitry Andric 
53491bc56edSDimitry Andric   // Serialize data.
53591bc56edSDimitry Andric   DEBUG(dbgs() << "********** Stack Map Output **********\n");
53691bc56edSDimitry Andric   emitStackmapHeader(OS);
53791bc56edSDimitry Andric   emitFunctionFrameRecords(OS);
53891bc56edSDimitry Andric   emitConstantPoolEntries(OS);
539ff0cc061SDimitry Andric   emitCallsiteEntries(OS);
54091bc56edSDimitry Andric   OS.AddBlankLine();
54191bc56edSDimitry Andric 
54291bc56edSDimitry Andric   // Clean up.
543f785676fSDimitry Andric   CSInfos.clear();
54491bc56edSDimitry Andric   ConstPool.clear();
545f785676fSDimitry Andric }
546