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