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