StackMaps.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. #define DEBUG_TYPE "stackmaps"
  10. #include "llvm/CodeGen/StackMaps.h"
  11. #include "llvm/CodeGen/AsmPrinter.h"
  12. #include "llvm/CodeGen/MachineFunction.h"
  13. #include "llvm/CodeGen/MachineFrameInfo.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"
  26. #include <iterator>
  27. using namespace llvm;
  28. PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
  29. : MI(MI),
  30. HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  31. !MI->getOperand(0).isImplicit()),
  32. IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
  33. {
  34. #ifndef NDEBUG
  35. unsigned CheckStartIdx = 0, e = MI->getNumOperands();
  36. while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
  37. MI->getOperand(CheckStartIdx).isDef() &&
  38. !MI->getOperand(CheckStartIdx).isImplicit())
  39. ++CheckStartIdx;
  40. assert(getMetaIdx() == CheckStartIdx &&
  41. "Unexpected additional definition in Patchpoint intrinsic.");
  42. #endif
  43. }
  44. unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
  45. if (!StartIdx)
  46. StartIdx = getVarIdx();
  47. // Find the next scratch register (implicit def and early clobber)
  48. unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
  49. while (ScratchIdx < e &&
  50. !(MI->getOperand(ScratchIdx).isReg() &&
  51. MI->getOperand(ScratchIdx).isDef() &&
  52. MI->getOperand(ScratchIdx).isImplicit() &&
  53. MI->getOperand(ScratchIdx).isEarlyClobber()))
  54. ++ScratchIdx;
  55. assert(ScratchIdx != e && "No scratch register available");
  56. return ScratchIdx;
  57. }
  58. MachineInstr::const_mop_iterator
  59. StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
  60. MachineInstr::const_mop_iterator MOE,
  61. LocationVec &Locs, LiveOutVec &LiveOuts) const {
  62. if (MOI->isImm()) {
  63. switch (MOI->getImm()) {
  64. default: llvm_unreachable("Unrecognized operand type.");
  65. case StackMaps::DirectMemRefOp: {
  66. unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
  67. assert((Size % 8) == 0 && "Need pointer size in bytes.");
  68. Size /= 8;
  69. unsigned Reg = (++MOI)->getReg();
  70. int64_t Imm = (++MOI)->getImm();
  71. Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
  72. break;
  73. }
  74. case StackMaps::IndirectMemRefOp: {
  75. int64_t Size = (++MOI)->getImm();
  76. assert(Size > 0 && "Need a valid size for indirect memory locations.");
  77. unsigned Reg = (++MOI)->getReg();
  78. int64_t Imm = (++MOI)->getImm();
  79. Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
  80. break;
  81. }
  82. case StackMaps::ConstantOp: {
  83. ++MOI;
  84. assert(MOI->isImm() && "Expected constant operand.");
  85. int64_t Imm = MOI->getImm();
  86. Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
  87. break;
  88. }
  89. }
  90. return ++MOI;
  91. }
  92. // The physical register number will ultimately be encoded as a DWARF regno.
  93. // The stack map also records the size of a spill slot that can hold the
  94. // register content. (The runtime can track the actual size of the data type
  95. // if it needs to.)
  96. if (MOI->isReg()) {
  97. // Skip implicit registers (this includes our scratch registers)
  98. if (MOI->isImplicit())
  99. return ++MOI;
  100. assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
  101. "Virtreg operands should have been rewritten before now.");
  102. const TargetRegisterClass *RC =
  103. AP.TM.getRegisterInfo()->getMinimalPhysRegClass(MOI->getReg());
  104. assert(!MOI->getSubReg() && "Physical subreg still around.");
  105. Locs.push_back(
  106. Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
  107. return ++MOI;
  108. }
  109. if (MOI->isRegLiveOut())
  110. LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
  111. return ++MOI;
  112. }
  113. /// Go up the super-register chain until we hit a valid dwarf register number.
  114. static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
  115. int RegNo = TRI->getDwarfRegNum(Reg, false);
  116. for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
  117. RegNo = TRI->getDwarfRegNum(*SR, false);
  118. assert(RegNo >= 0 && "Invalid Dwarf register number.");
  119. return (unsigned) RegNo;
  120. }
  121. /// Create a live-out register record for the given register Reg.
  122. StackMaps::LiveOutReg
  123. StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
  124. unsigned RegNo = getDwarfRegNum(Reg, TRI);
  125. unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
  126. return LiveOutReg(Reg, RegNo, Size);
  127. }
  128. /// Parse the register live-out mask and return a vector of live-out registers
  129. /// that need to be recorded in the stackmap.
  130. StackMaps::LiveOutVec
  131. StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
  132. assert(Mask && "No register mask specified");
  133. const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
  134. LiveOutVec LiveOuts;
  135. // Create a LiveOutReg for each bit that is set in the register mask.
  136. for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
  137. if ((Mask[Reg / 32] >> Reg % 32) & 1)
  138. LiveOuts.push_back(createLiveOutReg(Reg, TRI));
  139. // We don't need to keep track of a register if its super-register is already
  140. // in the list. Merge entries that refer to the same dwarf register and use
  141. // the maximum size that needs to be spilled.
  142. std::sort(LiveOuts.begin(), LiveOuts.end());
  143. for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
  144. I != E; ++I) {
  145. for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
  146. if (I->RegNo != II->RegNo) {
  147. // Skip all the now invalid entries.
  148. I = --II;
  149. break;
  150. }
  151. I->Size = std::max(I->Size, II->Size);
  152. if (TRI->isSuperRegister(I->Reg, II->Reg))
  153. I->Reg = II->Reg;
  154. II->MarkInvalid();
  155. }
  156. }
  157. LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
  158. LiveOutReg::IsInvalid), LiveOuts.end());
  159. return LiveOuts;
  160. }
  161. void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
  162. MachineInstr::const_mop_iterator MOI,
  163. MachineInstr::const_mop_iterator MOE,
  164. bool recordResult) {
  165. MCContext &OutContext = AP.OutStreamer.getContext();
  166. MCSymbol *MILabel = OutContext.CreateTempSymbol();
  167. AP.OutStreamer.EmitLabel(MILabel);
  168. LocationVec Locations;
  169. LiveOutVec LiveOuts;
  170. if (recordResult) {
  171. assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
  172. parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
  173. Locations, LiveOuts);
  174. }
  175. // Parse operands.
  176. while (MOI != MOE) {
  177. MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
  178. }
  179. // Move large constants into the constant pool.
  180. for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
  181. I != E; ++I) {
  182. // Constants are encoded as sign-extended integers.
  183. // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
  184. if (I->LocType == Location::Constant &&
  185. ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
  186. I->LocType = Location::ConstantIndex;
  187. I->Offset = ConstPool.getConstantIndex(I->Offset);
  188. }
  189. }
  190. // Create an expression to calculate the offset of the callsite from function
  191. // entry.
  192. const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
  193. MCSymbolRefExpr::Create(MILabel, OutContext),
  194. MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
  195. OutContext);
  196. CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
  197. // Record the stack size of the current function.
  198. const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
  199. FnStackSize[AP.CurrentFnSym] =
  200. MFI->hasVarSizedObjects() ? ~0U : MFI->getStackSize();
  201. }
  202. void StackMaps::recordStackMap(const MachineInstr &MI) {
  203. assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
  204. int64_t ID = MI.getOperand(0).getImm();
  205. recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
  206. MI.operands_end());
  207. }
  208. void StackMaps::recordPatchPoint(const MachineInstr &MI) {
  209. assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
  210. PatchPointOpers opers(&MI);
  211. int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
  212. MachineInstr::const_mop_iterator MOI =
  213. std::next(MI.operands_begin(), opers.getStackMapStartIdx());
  214. recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
  215. opers.isAnyReg() && opers.hasDef());
  216. #ifndef NDEBUG
  217. // verify anyregcc
  218. LocationVec &Locations = CSInfos.back().Locations;
  219. if (opers.isAnyReg()) {
  220. unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
  221. for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
  222. assert(Locations[i].LocType == Location::Register &&
  223. "anyreg arg must be in reg.");
  224. }
  225. #endif
  226. }
  227. /// serializeToStackMapSection conceptually populates the following fields:
  228. ///
  229. /// uint32 : Reserved (header)
  230. /// uint32 : NumFunctions
  231. /// StkSizeRecord[NumFunctions] {
  232. /// uint32 : Function Offset
  233. /// uint32 : Stack Size
  234. /// }
  235. /// uint32 : NumConstants
  236. /// int64 : Constants[NumConstants]
  237. /// uint32 : NumRecords
  238. /// StkMapRecord[NumRecords] {
  239. /// uint64 : PatchPoint ID
  240. /// uint32 : Instruction Offset
  241. /// uint16 : Reserved (record flags)
  242. /// uint16 : NumLocations
  243. /// Location[NumLocations] {
  244. /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
  245. /// uint8 : Size in Bytes
  246. /// uint16 : Dwarf RegNum
  247. /// int32 : Offset
  248. /// }
  249. /// uint16 : NumLiveOuts
  250. /// LiveOuts[NumLiveOuts]
  251. /// uint16 : Dwarf RegNum
  252. /// uint8 : Reserved
  253. /// uint8 : Size in Bytes
  254. /// }
  255. ///
  256. /// Location Encoding, Type, Value:
  257. /// 0x1, Register, Reg (value in register)
  258. /// 0x2, Direct, Reg + Offset (frame index)
  259. /// 0x3, Indirect, [Reg + Offset] (spilled value)
  260. /// 0x4, Constant, Offset (small constant)
  261. /// 0x5, ConstIndex, Constants[Offset] (large constant)
  262. ///
  263. void StackMaps::serializeToStackMapSection() {
  264. // Bail out if there's no stack map data.
  265. if (CSInfos.empty())
  266. return;
  267. MCContext &OutContext = AP.OutStreamer.getContext();
  268. const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
  269. // Create the section.
  270. const MCSection *StackMapSection =
  271. OutContext.getObjectFileInfo()->getStackMapSection();
  272. AP.OutStreamer.SwitchSection(StackMapSection);
  273. // Emit a dummy symbol to force section inclusion.
  274. AP.OutStreamer.EmitLabel(
  275. OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
  276. // Serialize data.
  277. const char *WSMP = "Stack Maps: ";
  278. (void)WSMP;
  279. DEBUG(dbgs() << "********** Stack Map Output **********\n");
  280. // Header.
  281. AP.OutStreamer.EmitIntValue(0, 4);
  282. // Num functions.
  283. AP.OutStreamer.EmitIntValue(FnStackSize.size(), 4);
  284. // Stack size entries.
  285. for (FnStackSizeMap::iterator I = FnStackSize.begin(), E = FnStackSize.end();
  286. I != E; ++I) {
  287. AP.OutStreamer.EmitSymbolValue(I->first, 4);
  288. AP.OutStreamer.EmitIntValue(I->second, 4);
  289. }
  290. // Num constants.
  291. AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
  292. // Constant pool entries.
  293. for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
  294. AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
  295. DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
  296. AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
  297. for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
  298. CSIE = CSInfos.end();
  299. CSII != CSIE; ++CSII) {
  300. uint64_t CallsiteID = CSII->ID;
  301. const LocationVec &CSLocs = CSII->Locations;
  302. const LiveOutVec &LiveOuts = CSII->LiveOuts;
  303. DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
  304. // Verify stack map entry. It's better to communicate a problem to the
  305. // runtime than crash in case of in-process compilation. Currently, we do
  306. // simple overflow checks, but we may eventually communicate other
  307. // compilation errors this way.
  308. if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
  309. AP.OutStreamer.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
  310. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  311. AP.OutStreamer.EmitIntValue(0, 2); // Reserved.
  312. AP.OutStreamer.EmitIntValue(0, 2); // 0 locations.
  313. AP.OutStreamer.EmitIntValue(0, 2); // 0 live-out registers.
  314. continue;
  315. }
  316. AP.OutStreamer.EmitIntValue(CallsiteID, 8);
  317. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  318. // Reserved for flags.
  319. AP.OutStreamer.EmitIntValue(0, 2);
  320. DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
  321. AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
  322. unsigned operIdx = 0;
  323. for (LocationVec::const_iterator LocI = CSLocs.begin(), LocE = CSLocs.end();
  324. LocI != LocE; ++LocI, ++operIdx) {
  325. const Location &Loc = *LocI;
  326. unsigned RegNo = 0;
  327. int Offset = Loc.Offset;
  328. if(Loc.Reg) {
  329. RegNo = getDwarfRegNum(Loc.Reg, TRI);
  330. // If this is a register location, put the subregister byte offset in
  331. // the location offset.
  332. if (Loc.LocType == Location::Register) {
  333. assert(!Loc.Offset && "Register location should have zero offset");
  334. unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
  335. unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
  336. if (SubRegIdx)
  337. Offset = TRI->getSubRegIdxOffset(SubRegIdx);
  338. }
  339. }
  340. else {
  341. assert(Loc.LocType != Location::Register &&
  342. "Missing location register");
  343. }
  344. DEBUG(
  345. dbgs() << WSMP << " Loc " << operIdx << ": ";
  346. switch (Loc.LocType) {
  347. case Location::Unprocessed:
  348. dbgs() << "<Unprocessed operand>";
  349. break;
  350. case Location::Register:
  351. dbgs() << "Register " << TRI->getName(Loc.Reg);
  352. break;
  353. case Location::Direct:
  354. dbgs() << "Direct " << TRI->getName(Loc.Reg);
  355. if (Loc.Offset)
  356. dbgs() << " + " << Loc.Offset;
  357. break;
  358. case Location::Indirect:
  359. dbgs() << "Indirect " << TRI->getName(Loc.Reg)
  360. << " + " << Loc.Offset;
  361. break;
  362. case Location::Constant:
  363. dbgs() << "Constant " << Loc.Offset;
  364. break;
  365. case Location::ConstantIndex:
  366. dbgs() << "Constant Index " << Loc.Offset;
  367. break;
  368. }
  369. dbgs() << " [encoding: .byte " << Loc.LocType
  370. << ", .byte " << Loc.Size
  371. << ", .short " << RegNo
  372. << ", .int " << Offset << "]\n";
  373. );
  374. AP.OutStreamer.EmitIntValue(Loc.LocType, 1);
  375. AP.OutStreamer.EmitIntValue(Loc.Size, 1);
  376. AP.OutStreamer.EmitIntValue(RegNo, 2);
  377. AP.OutStreamer.EmitIntValue(Offset, 4);
  378. }
  379. DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
  380. << " live-out registers\n");
  381. AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
  382. operIdx = 0;
  383. for (LiveOutVec::const_iterator LI = LiveOuts.begin(), LE = LiveOuts.end();
  384. LI != LE; ++LI, ++operIdx) {
  385. DEBUG(dbgs() << WSMP << " LO " << operIdx << ": "
  386. << TRI->getName(LI->Reg)
  387. << " [encoding: .short " << LI->RegNo
  388. << ", .byte 0, .byte " << LI->Size << "]\n");
  389. AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
  390. AP.OutStreamer.EmitIntValue(0, 1);
  391. AP.OutStreamer.EmitIntValue(LI->Size, 1);
  392. }
  393. }
  394. AP.OutStreamer.AddBlankLine();
  395. CSInfos.clear();
  396. }