6d0c165c8f6a269460b0762335366f390ecd2f72
[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 #define DEBUG_TYPE "stackmaps"
11
12 #include "llvm/CodeGen/StackMaps.h"
13
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"
27
28 #include <iterator>
29
30 using namespace llvm;
31
32 PatchPointOpers::PatchPointOpers(const MachineInstr *MI):
33   MI(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) {
37
38 #ifndef NDEBUG
39   {
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())
44     ++CheckStartIdx;
45
46   assert(getMetaIdx() == CheckStartIdx &&
47          "Unexpected additonal definition in Patchpoint intrinsic.");
48   }
49 #endif
50 }
51
52 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
53   if (!StartIdx)
54     StartIdx = getVarIdx();
55
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()))
63     ++ScratchIdx;
64
65   assert(ScratchIdx != e && "No scratch register available");
66   return ScratchIdx;
67 }
68
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.");
75
76   if (MOP.isImm()) {
77     // Verify anyregcc
78     // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
79
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.");
85         Size /= 8;
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);
90       }
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);
98       }
99       case StackMaps::ConstantOp: {
100         ++MOI;
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);
105       }
106     }
107   }
108
109   if (MOP.isRegMask() || MOP.isRegLiveOut())
110     return std::make_pair(Location(), ++MOI);
111
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);
124 }
125
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);
133
134   assert(RegNo >= 0 && "Invalid Dwarf register number.");
135   return (unsigned short) RegNo;
136 }
137
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);
146   unsigned Offset = 0;
147   if (SubRegIdx)
148     Offset = MCRI.getSubRegIdxOffset(SubRegIdx) / 8;
149
150   return LiveOutReg(Reg, RegNo, Offset + Size);
151 }
152
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();
161   LiveOutVec LiveOuts;
162
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));
166
167   std::sort(LiveOuts.begin(), LiveOuts.end());
168   for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
169        I != E; ++I) {
170     if (!I->Reg)
171       continue;
172     for (LiveOutVec::iterator II = next(I); II != E; ++II) {
173       if (I->RegNo != II->RegNo)
174         break;
175       I->Size = std::max(I->Size, II->Size);
176       if (TRI->isSuperRegister(I->Reg, II->Reg))
177         I->Reg = II->Reg;
178       II->Reg = 0;
179     }
180   }
181   LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
182                                 LiveOutReg::isInvalid), LiveOuts.end());
183   return LiveOuts;
184 }
185
186 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
187                                     MachineInstr::const_mop_iterator MOI,
188                                     MachineInstr::const_mop_iterator MOE,
189                                     bool recordResult) {
190
191   MCContext &OutContext = AP.OutStreamer.getContext();
192   MCSymbol *MILabel = OutContext.CreateTempSymbol();
193   AP.OutStreamer.EmitLabel(MILabel);
194
195   LocationVec Locations;
196   LiveOutVec LiveOuts;
197
198   if (recordResult) {
199     std::pair<Location, MachineInstr::const_mop_iterator> ParseResult =
200       parseOperand(MI.operands_begin(), llvm::next(MI.operands_begin()));
201
202     Location &Loc = ParseResult.first;
203     assert(Loc.LocType == Location::Register &&
204            "Stackmap return location must be a register.");
205     Locations.push_back(Loc);
206   }
207
208   while (MOI != MOE) {
209     Location Loc;
210     tie(Loc, MOI) = parseOperand(MOI, MOE);
211
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);
216     }
217
218     // Skip the register mask and register live-out mask
219     if (Loc.LocType != Location::Unprocessed)
220       Locations.push_back(Loc);
221   }
222
223   const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
224     MCSymbolRefExpr::Create(MILabel, OutContext),
225     MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
226     OutContext);
227
228   if (MOI->isRegLiveOut())
229     LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
230
231   CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
232 }
233
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()))
239       break;
240   return MOI;
241 }
242
243 void StackMaps::recordStackMap(const MachineInstr &MI) {
244   assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
245
246   int64_t ID = MI.getOperand(0).getImm();
247   recordStackMapOpers(MI, ID, llvm::next(MI.operands_begin(), 2),
248                       getStackMapEndMOP(MI.operands_begin(),
249                                         MI.operands_end()));
250 }
251
252 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
253   assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
254
255   PatchPointOpers opers(&MI);
256   int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
257
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());
262
263 #ifndef NDEBUG
264   // verify anyregcc
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.");
271   }
272 #endif
273 }
274
275 /// serializeToStackMapSection conceptually populates the following fields:
276 ///
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
290 ///     int32  : Offset
291 ///   }
292 ///   uint16 : NumLiveOuts
293 ///   LiveOuts[NumLiveOuts]
294 ///     uint16 : Dwarf RegNum
295 ///     uint8  : Reserved
296 ///     uint8  : Size in Bytes
297 /// }
298 ///
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)
305 ///
306 void StackMaps::serializeToStackMapSection() {
307   // Bail out if there's no stack map data.
308   if (CSInfos.empty())
309     return;
310
311   MCContext &OutContext = AP.OutStreamer.getContext();
312   const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
313
314   // Create the section.
315   const MCSection *StackMapSection =
316     OutContext.getObjectFileInfo()->getStackMapSection();
317   AP.OutStreamer.SwitchSection(StackMapSection);
318
319   // Emit a dummy symbol to force section inclusion.
320   AP.OutStreamer.EmitLabel(
321     OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
322
323   // Serialize data.
324   const char *WSMP = "Stack Maps: ";
325   (void)WSMP;
326   const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
327
328   DEBUG(dbgs() << "********** Stack Map Output **********\n");
329
330   // Header.
331   AP.OutStreamer.EmitIntValue(0, 4);
332
333   // Num constants.
334   AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
335
336   // Constant pool entries.
337   for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
338     AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
339
340   DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
341   AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
342
343   for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
344                                         CSIE = CSInfos.end();
345        CSII != CSIE; ++CSII) {
346
347     uint64_t CallsiteID = CSII->ID;
348     const LocationVec &CSLocs = CSII->Locations;
349     const LiveOutVec &LiveOuts = CSII->LiveOuts;
350
351     DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
352
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.
363       continue;
364     }
365
366     AP.OutStreamer.EmitIntValue(CallsiteID, 8);
367     AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
368
369     // Reserved for flags.
370     AP.OutStreamer.EmitIntValue(0, 2);
371
372     DEBUG(dbgs() << WSMP << "  has " << CSLocs.size() << " locations\n");
373
374     AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
375
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;
380       unsigned RegNo = 0;
381       int Offset = Loc.Offset;
382       if(Loc.Reg) {
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);
387         }
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);
394           if (SubRegIdx)
395             Offset = MCRI.getSubRegIdxOffset(SubRegIdx);
396         }
397       }
398       else {
399         assert(Loc.LocType != Location::Register &&
400                "Missing location register");
401       }
402
403       DEBUG(
404         dbgs() << WSMP << "  Loc " << operIdx << ": ";
405         switch (Loc.LocType) {
406         case Location::Unprocessed:
407           dbgs() << "<Unprocessed operand>";
408           break;
409         case Location::Register:
410           dbgs() << "Register " << MCRI.getName(Loc.Reg);
411           break;
412         case Location::Direct:
413           dbgs() << "Direct " << MCRI.getName(Loc.Reg);
414           if (Loc.Offset)
415             dbgs() << " + " << Loc.Offset;
416           break;
417         case Location::Indirect:
418           dbgs() << "Indirect " << MCRI.getName(Loc.Reg)
419                  << " + " << Loc.Offset;
420           break;
421         case Location::Constant:
422           dbgs() << "Constant " << Loc.Offset;
423           break;
424         case Location::ConstantIndex:
425           dbgs() << "Constant Index " << Loc.Offset;
426           break;
427         }
428         dbgs() << "     [encoding: .byte " << Loc.LocType
429                << ", .byte " << Loc.Size
430                << ", .short " << RegNo
431                << ", .int " << Offset << "]\n";
432       );
433
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);
438     }
439
440     DEBUG(dbgs() << WSMP << "  has " << LiveOuts.size()
441                  << " live-out registers\n");
442
443     AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
444
445     operIdx = 0;
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");
452
453       AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
454       AP.OutStreamer.EmitIntValue(0, 1);
455       AP.OutStreamer.EmitIntValue(LI->Size, 1);
456     }
457   }
458
459   AP.OutStreamer.AddBlankLine();
460
461   CSInfos.clear();
462 }