adbb38e8b55c88ee54a83a0550c0461510820d20
[oota-llvm.git] / lib / CodeGen / StackMaps.cpp
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
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"
28 #include <iterator>
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "stackmaps"
33
34 static cl::opt<int> StackMapVersion("stackmap-version", cl::init(1),
35   cl::desc("Specify the stackmap encoding version (default = 1)"));
36
37 const char *StackMaps::WSMP = "Stack Maps: ";
38
39 PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
40   : MI(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)
44 {
45 #ifndef NDEBUG
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())
50     ++CheckStartIdx;
51
52   assert(getMetaIdx() == CheckStartIdx &&
53          "Unexpected additional definition in Patchpoint intrinsic.");
54 #endif
55 }
56
57 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
58   if (!StartIdx)
59     StartIdx = getVarIdx();
60
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()))
68     ++ScratchIdx;
69
70   assert(ScratchIdx != e && "No scratch register available");
71   return ScratchIdx;
72 }
73
74 StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
75   if (StackMapVersion != 1)
76     llvm_unreachable("Unsupported stackmap version!");
77 }
78
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 {
83   if (MOI->isImm()) {
84     switch (MOI->getImm()) {
85     default: llvm_unreachable("Unrecognized operand type.");
86     case StackMaps::DirectMemRefOp: {
87       unsigned Size =
88           AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSizeInBits();
89       assert((Size % 8) == 0 && "Need pointer size in bytes.");
90       Size /= 8;
91       unsigned Reg = (++MOI)->getReg();
92       int64_t Imm = (++MOI)->getImm();
93       Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
94       break;
95     }
96     case StackMaps::IndirectMemRefOp: {
97       int64_t Size = (++MOI)->getImm();
98       assert(Size > 0 && "Need a valid size for indirect memory locations.");
99       unsigned Reg = (++MOI)->getReg();
100       int64_t Imm = (++MOI)->getImm();
101       Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
102       break;
103     }
104     case StackMaps::ConstantOp: {
105       ++MOI;
106       assert(MOI->isImm() && "Expected constant operand.");
107       int64_t Imm = MOI->getImm();
108       Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
109       break;
110     }
111     }
112     return ++MOI;
113   }
114
115   // The physical register number will ultimately be encoded as a DWARF regno.
116   // The stack map also records the size of a spill slot that can hold the
117   // register content. (The runtime can track the actual size of the data type
118   // if it needs to.)
119   if (MOI->isReg()) {
120     // Skip implicit registers (this includes our scratch registers)
121     if (MOI->isImplicit())
122       return ++MOI;
123
124     assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
125            "Virtreg operands should have been rewritten before now.");
126     const TargetRegisterClass *RC =
127         AP.TM.getSubtargetImpl()->getRegisterInfo()->getMinimalPhysRegClass(
128             MOI->getReg());
129     assert(!MOI->getSubReg() && "Physical subreg still around.");
130     Locs.push_back(
131       Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
132     return ++MOI;
133   }
134
135   if (MOI->isRegLiveOut())
136     LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
137
138   return ++MOI;
139 }
140
141 /// Go up the super-register chain until we hit a valid dwarf register number.
142 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
143   int RegNo = TRI->getDwarfRegNum(Reg, false);
144   for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
145     RegNo = TRI->getDwarfRegNum(*SR, false);
146
147   assert(RegNo >= 0 && "Invalid Dwarf register number.");
148   return (unsigned) RegNo;
149 }
150
151 /// Create a live-out register record for the given register Reg.
152 StackMaps::LiveOutReg
153 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
154   unsigned RegNo = getDwarfRegNum(Reg, TRI);
155   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
156   return LiveOutReg(Reg, RegNo, Size);
157 }
158
159 /// Parse the register live-out mask and return a vector of live-out registers
160 /// that need to be recorded in the stackmap.
161 StackMaps::LiveOutVec
162 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
163   assert(Mask && "No register mask specified");
164   const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
165   LiveOutVec LiveOuts;
166
167   // Create a LiveOutReg for each bit that is set in the register mask.
168   for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
169     if ((Mask[Reg / 32] >> Reg % 32) & 1)
170       LiveOuts.push_back(createLiveOutReg(Reg, TRI));
171
172   // We don't need to keep track of a register if its super-register is already
173   // in the list. Merge entries that refer to the same dwarf register and use
174   // the maximum size that needs to be spilled.
175   std::sort(LiveOuts.begin(), LiveOuts.end());
176   for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
177        I != E; ++I) {
178     for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
179       if (I->RegNo != II->RegNo) {
180         // Skip all the now invalid entries.
181         I = --II;
182         break;
183       }
184       I->Size = std::max(I->Size, II->Size);
185       if (TRI->isSuperRegister(I->Reg, II->Reg))
186         I->Reg = II->Reg;
187       II->MarkInvalid();
188     }
189   }
190   LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
191                                 LiveOutReg::IsInvalid), LiveOuts.end());
192   return LiveOuts;
193 }
194
195 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
196                                     MachineInstr::const_mop_iterator MOI,
197                                     MachineInstr::const_mop_iterator MOE,
198                                     bool recordResult) {
199
200   MCContext &OutContext = AP.OutStreamer.getContext();
201   MCSymbol *MILabel = OutContext.CreateTempSymbol();
202   AP.OutStreamer.EmitLabel(MILabel);
203
204   LocationVec Locations;
205   LiveOutVec LiveOuts;
206
207   if (recordResult) {
208     assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
209     parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
210                  Locations, LiveOuts);
211   }
212
213   // Parse operands.
214   while (MOI != MOE) {
215     MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
216   }
217
218   // Move large constants into the constant pool.
219   for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
220        I != E; ++I) {
221     // Constants are encoded as sign-extended integers.
222     // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
223     if (I->LocType == Location::Constant &&
224         ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
225       I->LocType = Location::ConstantIndex;
226       auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
227       I->Offset = Result.first - ConstPool.begin();
228     }
229   }
230
231   // Create an expression to calculate the offset of the callsite from function
232   // entry.
233   const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
234     MCSymbolRefExpr::Create(MILabel, OutContext),
235     MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
236     OutContext);
237
238   CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
239
240   // Record the stack size of the current function.
241   const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
242   const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
243   const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
244     RegInfo->needsStackRealignment(*(AP.MF));
245   FnStackSize[AP.CurrentFnSym] =
246     DynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
247 }
248
249 void StackMaps::recordStackMap(const MachineInstr &MI) {
250   assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
251
252   int64_t ID = MI.getOperand(0).getImm();
253   recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
254                       MI.operands_end());
255 }
256
257 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
258   assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
259
260   PatchPointOpers opers(&MI);
261   int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
262
263   MachineInstr::const_mop_iterator MOI =
264     std::next(MI.operands_begin(), opers.getStackMapStartIdx());
265   recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
266                       opers.isAnyReg() && opers.hasDef());
267
268 #ifndef NDEBUG
269   // verify anyregcc
270   LocationVec &Locations = CSInfos.back().Locations;
271   if (opers.isAnyReg()) {
272     unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
273     for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
274       assert(Locations[i].LocType == Location::Register &&
275              "anyreg arg must be in reg.");
276   }
277 #endif
278 }
279
280 /// Emit the stackmap header.
281 ///
282 /// Header {
283 ///   uint8  : Stack Map Version (currently 1)
284 ///   uint8  : Reserved (expected to be 0)
285 ///   uint16 : Reserved (expected to be 0)
286 /// }
287 /// uint32 : NumFunctions
288 /// uint32 : NumConstants
289 /// uint32 : NumRecords
290 void StackMaps::emitStackmapHeader(MCStreamer &OS) {
291   // Header.
292   OS.EmitIntValue(StackMapVersion, 1); // Version.
293   OS.EmitIntValue(0, 1); // Reserved.
294   OS.EmitIntValue(0, 2); // Reserved.
295
296   // Num functions.
297   DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
298   OS.EmitIntValue(FnStackSize.size(), 4);
299   // Num constants.
300   DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
301   OS.EmitIntValue(ConstPool.size(), 4);
302   // Num callsites.
303   DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
304   OS.EmitIntValue(CSInfos.size(), 4);
305 }
306
307 /// Emit the function frame record for each function.
308 ///
309 /// StkSizeRecord[NumFunctions] {
310 ///   uint64 : Function Address
311 ///   uint64 : Stack Size
312 /// }
313 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
314   // Function Frame records.
315   DEBUG(dbgs() << WSMP << "functions:\n");
316   for (auto const &FR : FnStackSize) {
317     DEBUG(dbgs() << WSMP << "function addr: " << FR.first
318                          << " frame size: " << FR.second);
319     OS.EmitSymbolValue(FR.first, 8);
320     OS.EmitIntValue(FR.second, 8);
321   }
322 }
323
324 /// Emit the constant pool.
325 ///
326 /// int64  : Constants[NumConstants]
327 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
328   // Constant pool entries.
329   DEBUG(dbgs() << WSMP << "constants:\n");
330   for (auto ConstEntry : ConstPool) {
331     DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
332     OS.EmitIntValue(ConstEntry.second, 8);
333   }
334 }
335
336 /// Emit the callsite info for each callsite.
337 ///
338 /// StkMapRecord[NumRecords] {
339 ///   uint64 : PatchPoint ID
340 ///   uint32 : Instruction Offset
341 ///   uint16 : Reserved (record flags)
342 ///   uint16 : NumLocations
343 ///   Location[NumLocations] {
344 ///     uint8  : Register | Direct | Indirect | Constant | ConstantIndex
345 ///     uint8  : Size in Bytes
346 ///     uint16 : Dwarf RegNum
347 ///     int32  : Offset
348 ///   }
349 ///   uint16 : Padding
350 ///   uint16 : NumLiveOuts
351 ///   LiveOuts[NumLiveOuts] {
352 ///     uint16 : Dwarf RegNum
353 ///     uint8  : Reserved
354 ///     uint8  : Size in Bytes
355 ///   }
356 ///   uint32 : Padding (only if required to align to 8 byte)
357 /// }
358 ///
359 /// Location Encoding, Type, Value:
360 ///   0x1, Register, Reg                 (value in register)
361 ///   0x2, Direct, Reg + Offset          (frame index)
362 ///   0x3, Indirect, [Reg + Offset]      (spilled value)
363 ///   0x4, Constant, Offset              (small constant)
364 ///   0x5, ConstIndex, Constants[Offset] (large constant)
365 void StackMaps::emitCallsiteEntries(MCStreamer &OS,
366                                     const TargetRegisterInfo *TRI) {
367   // Callsite entries.
368   DEBUG(dbgs() << WSMP << "callsites:\n");
369   for (const auto &CSI : CSInfos) {
370     const LocationVec &CSLocs = CSI.Locations;
371     const LiveOutVec &LiveOuts = CSI.LiveOuts;
372
373     DEBUG(dbgs() << WSMP << "callsite " << CSI.ID << "\n");
374
375     // Verify stack map entry. It's better to communicate a problem to the
376     // runtime than crash in case of in-process compilation. Currently, we do
377     // simple overflow checks, but we may eventually communicate other
378     // compilation errors this way.
379     if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
380       OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
381       OS.EmitValue(CSI.CSOffsetExpr, 4);
382       OS.EmitIntValue(0, 2); // Reserved.
383       OS.EmitIntValue(0, 2); // 0 locations.
384       OS.EmitIntValue(0, 2); // padding.
385       OS.EmitIntValue(0, 2); // 0 live-out registers.
386       OS.EmitIntValue(0, 4); // padding.
387       continue;
388     }
389
390     OS.EmitIntValue(CSI.ID, 8);
391     OS.EmitValue(CSI.CSOffsetExpr, 4);
392
393     // Reserved for flags.
394     OS.EmitIntValue(0, 2);
395
396     DEBUG(dbgs() << WSMP << "  has " << CSLocs.size() << " locations\n");
397
398     OS.EmitIntValue(CSLocs.size(), 2);
399
400     unsigned OperIdx = 0;
401     for (const auto &Loc : CSLocs) {
402       unsigned RegNo = 0;
403       int Offset = Loc.Offset;
404       if(Loc.Reg) {
405         RegNo = getDwarfRegNum(Loc.Reg, TRI);
406
407         // If this is a register location, put the subregister byte offset in
408         // the location offset.
409         if (Loc.LocType == Location::Register) {
410           assert(!Loc.Offset && "Register location should have zero offset");
411           unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
412           unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
413           if (SubRegIdx)
414             Offset = TRI->getSubRegIdxOffset(SubRegIdx);
415         }
416       }
417       else {
418         assert(Loc.LocType != Location::Register &&
419                "Missing location register");
420       }
421
422       DEBUG(dbgs() << WSMP << "  Loc " << OperIdx << ": ";
423             switch (Loc.LocType) {
424             case Location::Unprocessed:
425               dbgs() << "<Unprocessed operand>";
426               break;
427             case Location::Register:
428               dbgs() << "Register " << TRI->getName(Loc.Reg);
429               break;
430             case Location::Direct:
431               dbgs() << "Direct " << TRI->getName(Loc.Reg);
432               if (Loc.Offset)
433               dbgs() << " + " << Loc.Offset;
434               break;
435             case Location::Indirect:
436               dbgs() << "Indirect " << TRI->getName(Loc.Reg)
437               << " + " << Loc.Offset;
438               break;
439             case Location::Constant:
440               dbgs() << "Constant " << Loc.Offset;
441               break;
442             case Location::ConstantIndex:
443               dbgs() << "Constant Index " << Loc.Offset;
444               break;
445               }
446             dbgs() << "     [encoding: .byte " << Loc.LocType
447             << ", .byte " << Loc.Size
448             << ", .short " << RegNo
449             << ", .int " << Offset << "]\n";
450             );
451
452       OS.EmitIntValue(Loc.LocType, 1);
453       OS.EmitIntValue(Loc.Size, 1);
454       OS.EmitIntValue(RegNo, 2);
455       OS.EmitIntValue(Offset, 4);
456       OperIdx++;
457     }
458
459     DEBUG(dbgs() << WSMP << "  has " << LiveOuts.size()
460                          << " live-out registers\n");
461
462     // Num live-out registers and padding to align to 4 byte.
463     OS.EmitIntValue(0, 2);
464     OS.EmitIntValue(LiveOuts.size(), 2);
465
466     OperIdx = 0;
467     for (const auto &LO : LiveOuts) {
468       DEBUG(dbgs() << WSMP << "  LO " << OperIdx << ": "
469                            << TRI->getName(LO.Reg)
470                            << "     [encoding: .short " << LO.RegNo
471                            << ", .byte 0, .byte " << LO.Size << "]\n");
472       OS.EmitIntValue(LO.RegNo, 2);
473       OS.EmitIntValue(0, 1);
474       OS.EmitIntValue(LO.Size, 1);
475     }
476     // Emit alignment to 8 byte.
477     OS.EmitValueToAlignment(8);
478   }
479 }
480
481 /// Serialize the stackmap data.
482 void StackMaps::serializeToStackMapSection() {
483   (void) WSMP;
484   // Bail out if there's no stack map data.
485   assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
486          "Expected empty constant pool too!");
487   assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
488          "Expected empty function record too!");
489   if (CSInfos.empty())
490     return;
491
492   MCContext &OutContext = AP.OutStreamer.getContext();
493   MCStreamer &OS = AP.OutStreamer;
494   const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
495
496   // Create the section.
497   const MCSection *StackMapSection =
498     OutContext.getObjectFileInfo()->getStackMapSection();
499   OS.SwitchSection(StackMapSection);
500
501   // Emit a dummy symbol to force section inclusion.
502   OS.EmitLabel(OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
503
504   // Serialize data.
505   DEBUG(dbgs() << "********** Stack Map Output **********\n");
506   emitStackmapHeader(OS);
507   emitFunctionFrameRecords(OS);
508   emitConstantPoolEntries(OS);
509   emitCallsiteEntries(OS, TRI);
510   OS.AddBlankLine();
511
512   // Clean up.
513   CSInfos.clear();
514   ConstPool.clear();
515 }