xref: /aosp_15_r20/external/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file includes support code use by SelectionDAGBuilder when lowering a
11*9880d681SAndroid Build Coastguard Worker // statepoint sequence in SelectionDAG IR.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "StatepointLowering.h"
16*9880d681SAndroid Build Coastguard Worker #include "SelectionDAGBuilder.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/FunctionLoweringInfo.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineFrameInfo.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/GCMetadata.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/GCStrategy.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/SelectionDAG.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/StackMaps.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallingConv.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Intrinsics.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Statepoint.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetLowering.h"
31*9880d681SAndroid Build Coastguard Worker #include <algorithm>
32*9880d681SAndroid Build Coastguard Worker using namespace llvm;
33*9880d681SAndroid Build Coastguard Worker 
34*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "statepoint-lowering"
35*9880d681SAndroid Build Coastguard Worker 
36*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSlotsAllocatedForStatepoints,
37*9880d681SAndroid Build Coastguard Worker           "Number of stack slots allocated for statepoints");
38*9880d681SAndroid Build Coastguard Worker STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
39*9880d681SAndroid Build Coastguard Worker STATISTIC(StatepointMaxSlotsRequired,
40*9880d681SAndroid Build Coastguard Worker           "Maximum number of stack slots required for a singe statepoint");
41*9880d681SAndroid Build Coastguard Worker 
pushStackMapConstant(SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder,uint64_t Value)42*9880d681SAndroid Build Coastguard Worker static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
43*9880d681SAndroid Build Coastguard Worker                                  SelectionDAGBuilder &Builder, uint64_t Value) {
44*9880d681SAndroid Build Coastguard Worker   SDLoc L = Builder.getCurSDLoc();
45*9880d681SAndroid Build Coastguard Worker   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
46*9880d681SAndroid Build Coastguard Worker                                               MVT::i64));
47*9880d681SAndroid Build Coastguard Worker   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
48*9880d681SAndroid Build Coastguard Worker }
49*9880d681SAndroid Build Coastguard Worker 
startNewStatepoint(SelectionDAGBuilder & Builder)50*9880d681SAndroid Build Coastguard Worker void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
51*9880d681SAndroid Build Coastguard Worker   // Consistency check
52*9880d681SAndroid Build Coastguard Worker   assert(PendingGCRelocateCalls.empty() &&
53*9880d681SAndroid Build Coastguard Worker          "Trying to visit statepoint before finished processing previous one");
54*9880d681SAndroid Build Coastguard Worker   Locations.clear();
55*9880d681SAndroid Build Coastguard Worker   NextSlotToAllocate = 0;
56*9880d681SAndroid Build Coastguard Worker   // Need to resize this on each safepoint - we need the two to stay in sync and
57*9880d681SAndroid Build Coastguard Worker   // the clear patterns of a SelectionDAGBuilder have no relation to
58*9880d681SAndroid Build Coastguard Worker   // FunctionLoweringInfo.  SmallBitVector::reset initializes all bits to false.
59*9880d681SAndroid Build Coastguard Worker   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
60*9880d681SAndroid Build Coastguard Worker }
61*9880d681SAndroid Build Coastguard Worker 
clear()62*9880d681SAndroid Build Coastguard Worker void StatepointLoweringState::clear() {
63*9880d681SAndroid Build Coastguard Worker   Locations.clear();
64*9880d681SAndroid Build Coastguard Worker   AllocatedStackSlots.clear();
65*9880d681SAndroid Build Coastguard Worker   assert(PendingGCRelocateCalls.empty() &&
66*9880d681SAndroid Build Coastguard Worker          "cleared before statepoint sequence completed");
67*9880d681SAndroid Build Coastguard Worker }
68*9880d681SAndroid Build Coastguard Worker 
69*9880d681SAndroid Build Coastguard Worker SDValue
allocateStackSlot(EVT ValueType,SelectionDAGBuilder & Builder)70*9880d681SAndroid Build Coastguard Worker StatepointLoweringState::allocateStackSlot(EVT ValueType,
71*9880d681SAndroid Build Coastguard Worker                                            SelectionDAGBuilder &Builder) {
72*9880d681SAndroid Build Coastguard Worker   NumSlotsAllocatedForStatepoints++;
73*9880d681SAndroid Build Coastguard Worker   auto *MFI = Builder.DAG.getMachineFunction().getFrameInfo();
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker   unsigned SpillSize = ValueType.getSizeInBits() / 8;
76*9880d681SAndroid Build Coastguard Worker   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
77*9880d681SAndroid Build Coastguard Worker 
78*9880d681SAndroid Build Coastguard Worker   // First look for a previously created stack slot which is not in
79*9880d681SAndroid Build Coastguard Worker   // use (accounting for the fact arbitrary slots may already be
80*9880d681SAndroid Build Coastguard Worker   // reserved), or to create a new stack slot and use it.
81*9880d681SAndroid Build Coastguard Worker 
82*9880d681SAndroid Build Coastguard Worker   const size_t NumSlots = AllocatedStackSlots.size();
83*9880d681SAndroid Build Coastguard Worker   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
84*9880d681SAndroid Build Coastguard Worker 
85*9880d681SAndroid Build Coastguard Worker   // The stack slots in StatepointStackSlots beyond the first NumSlots were
86*9880d681SAndroid Build Coastguard Worker   // added in this instance of StatepointLoweringState, and cannot be re-used.
87*9880d681SAndroid Build Coastguard Worker   assert(NumSlots <= Builder.FuncInfo.StatepointStackSlots.size() &&
88*9880d681SAndroid Build Coastguard Worker          "Broken invariant");
89*9880d681SAndroid Build Coastguard Worker 
90*9880d681SAndroid Build Coastguard Worker   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
91*9880d681SAndroid Build Coastguard Worker     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
92*9880d681SAndroid Build Coastguard Worker       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
93*9880d681SAndroid Build Coastguard Worker       if (MFI->getObjectSize(FI) == SpillSize) {
94*9880d681SAndroid Build Coastguard Worker         AllocatedStackSlots.set(NextSlotToAllocate);
95*9880d681SAndroid Build Coastguard Worker         return Builder.DAG.getFrameIndex(FI, ValueType);
96*9880d681SAndroid Build Coastguard Worker       }
97*9880d681SAndroid Build Coastguard Worker     }
98*9880d681SAndroid Build Coastguard Worker   }
99*9880d681SAndroid Build Coastguard Worker 
100*9880d681SAndroid Build Coastguard Worker   // Couldn't find a free slot, so create a new one:
101*9880d681SAndroid Build Coastguard Worker 
102*9880d681SAndroid Build Coastguard Worker   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
103*9880d681SAndroid Build Coastguard Worker   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
104*9880d681SAndroid Build Coastguard Worker   MFI->markAsStatepointSpillSlotObjectIndex(FI);
105*9880d681SAndroid Build Coastguard Worker 
106*9880d681SAndroid Build Coastguard Worker   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
107*9880d681SAndroid Build Coastguard Worker 
108*9880d681SAndroid Build Coastguard Worker   StatepointMaxSlotsRequired = std::max<unsigned long>(
109*9880d681SAndroid Build Coastguard Worker       StatepointMaxSlotsRequired, Builder.FuncInfo.StatepointStackSlots.size());
110*9880d681SAndroid Build Coastguard Worker 
111*9880d681SAndroid Build Coastguard Worker   return SpillSlot;
112*9880d681SAndroid Build Coastguard Worker }
113*9880d681SAndroid Build Coastguard Worker 
114*9880d681SAndroid Build Coastguard Worker /// Utility function for reservePreviousStackSlotForValue. Tries to find
115*9880d681SAndroid Build Coastguard Worker /// stack slot index to which we have spilled value for previous statepoints.
116*9880d681SAndroid Build Coastguard Worker /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
findPreviousSpillSlot(const Value * Val,SelectionDAGBuilder & Builder,int LookUpDepth)117*9880d681SAndroid Build Coastguard Worker static Optional<int> findPreviousSpillSlot(const Value *Val,
118*9880d681SAndroid Build Coastguard Worker                                            SelectionDAGBuilder &Builder,
119*9880d681SAndroid Build Coastguard Worker                                            int LookUpDepth) {
120*9880d681SAndroid Build Coastguard Worker   // Can not look any further - give up now
121*9880d681SAndroid Build Coastguard Worker   if (LookUpDepth <= 0)
122*9880d681SAndroid Build Coastguard Worker     return None;
123*9880d681SAndroid Build Coastguard Worker 
124*9880d681SAndroid Build Coastguard Worker   // Spill location is known for gc relocates
125*9880d681SAndroid Build Coastguard Worker   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
126*9880d681SAndroid Build Coastguard Worker     const auto &SpillMap =
127*9880d681SAndroid Build Coastguard Worker         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
128*9880d681SAndroid Build Coastguard Worker 
129*9880d681SAndroid Build Coastguard Worker     auto It = SpillMap.find(Relocate->getDerivedPtr());
130*9880d681SAndroid Build Coastguard Worker     if (It == SpillMap.end())
131*9880d681SAndroid Build Coastguard Worker       return None;
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker     return It->second;
134*9880d681SAndroid Build Coastguard Worker   }
135*9880d681SAndroid Build Coastguard Worker 
136*9880d681SAndroid Build Coastguard Worker   // Look through bitcast instructions.
137*9880d681SAndroid Build Coastguard Worker   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
138*9880d681SAndroid Build Coastguard Worker     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
139*9880d681SAndroid Build Coastguard Worker 
140*9880d681SAndroid Build Coastguard Worker   // Look through phi nodes
141*9880d681SAndroid Build Coastguard Worker   // All incoming values should have same known stack slot, otherwise result
142*9880d681SAndroid Build Coastguard Worker   // is unknown.
143*9880d681SAndroid Build Coastguard Worker   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
144*9880d681SAndroid Build Coastguard Worker     Optional<int> MergedResult = None;
145*9880d681SAndroid Build Coastguard Worker 
146*9880d681SAndroid Build Coastguard Worker     for (auto &IncomingValue : Phi->incoming_values()) {
147*9880d681SAndroid Build Coastguard Worker       Optional<int> SpillSlot =
148*9880d681SAndroid Build Coastguard Worker           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
149*9880d681SAndroid Build Coastguard Worker       if (!SpillSlot.hasValue())
150*9880d681SAndroid Build Coastguard Worker         return None;
151*9880d681SAndroid Build Coastguard Worker 
152*9880d681SAndroid Build Coastguard Worker       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
153*9880d681SAndroid Build Coastguard Worker         return None;
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker       MergedResult = SpillSlot;
156*9880d681SAndroid Build Coastguard Worker     }
157*9880d681SAndroid Build Coastguard Worker     return MergedResult;
158*9880d681SAndroid Build Coastguard Worker   }
159*9880d681SAndroid Build Coastguard Worker 
160*9880d681SAndroid Build Coastguard Worker   // TODO: We can do better for PHI nodes. In cases like this:
161*9880d681SAndroid Build Coastguard Worker   //   ptr = phi(relocated_pointer, not_relocated_pointer)
162*9880d681SAndroid Build Coastguard Worker   //   statepoint(ptr)
163*9880d681SAndroid Build Coastguard Worker   // We will return that stack slot for ptr is unknown. And later we might
164*9880d681SAndroid Build Coastguard Worker   // assign different stack slots for ptr and relocated_pointer. This limits
165*9880d681SAndroid Build Coastguard Worker   // llvm's ability to remove redundant stores.
166*9880d681SAndroid Build Coastguard Worker   // Unfortunately it's hard to accomplish in current infrastructure.
167*9880d681SAndroid Build Coastguard Worker   // We use this function to eliminate spill store completely, while
168*9880d681SAndroid Build Coastguard Worker   // in example we still need to emit store, but instead of any location
169*9880d681SAndroid Build Coastguard Worker   // we need to use special "preferred" location.
170*9880d681SAndroid Build Coastguard Worker 
171*9880d681SAndroid Build Coastguard Worker   // TODO: handle simple updates.  If a value is modified and the original
172*9880d681SAndroid Build Coastguard Worker   // value is no longer live, it would be nice to put the modified value in the
173*9880d681SAndroid Build Coastguard Worker   // same slot.  This allows folding of the memory accesses for some
174*9880d681SAndroid Build Coastguard Worker   // instructions types (like an increment).
175*9880d681SAndroid Build Coastguard Worker   //   statepoint (i)
176*9880d681SAndroid Build Coastguard Worker   //   i1 = i+1
177*9880d681SAndroid Build Coastguard Worker   //   statepoint (i1)
178*9880d681SAndroid Build Coastguard Worker   // However we need to be careful for cases like this:
179*9880d681SAndroid Build Coastguard Worker   //   statepoint(i)
180*9880d681SAndroid Build Coastguard Worker   //   i1 = i+1
181*9880d681SAndroid Build Coastguard Worker   //   statepoint(i, i1)
182*9880d681SAndroid Build Coastguard Worker   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
183*9880d681SAndroid Build Coastguard Worker   // put handling of simple modifications in this function like it's done
184*9880d681SAndroid Build Coastguard Worker   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
185*9880d681SAndroid Build Coastguard Worker   // which we visit values is unspecified.
186*9880d681SAndroid Build Coastguard Worker 
187*9880d681SAndroid Build Coastguard Worker   // Don't know any information about this instruction
188*9880d681SAndroid Build Coastguard Worker   return None;
189*9880d681SAndroid Build Coastguard Worker }
190*9880d681SAndroid Build Coastguard Worker 
191*9880d681SAndroid Build Coastguard Worker /// Try to find existing copies of the incoming values in stack slots used for
192*9880d681SAndroid Build Coastguard Worker /// statepoint spilling.  If we can find a spill slot for the incoming value,
193*9880d681SAndroid Build Coastguard Worker /// mark that slot as allocated, and reuse the same slot for this safepoint.
194*9880d681SAndroid Build Coastguard Worker /// This helps to avoid series of loads and stores that only serve to reshuffle
195*9880d681SAndroid Build Coastguard Worker /// values on the stack between calls.
reservePreviousStackSlotForValue(const Value * IncomingValue,SelectionDAGBuilder & Builder)196*9880d681SAndroid Build Coastguard Worker static void reservePreviousStackSlotForValue(const Value *IncomingValue,
197*9880d681SAndroid Build Coastguard Worker                                              SelectionDAGBuilder &Builder) {
198*9880d681SAndroid Build Coastguard Worker 
199*9880d681SAndroid Build Coastguard Worker   SDValue Incoming = Builder.getValue(IncomingValue);
200*9880d681SAndroid Build Coastguard Worker 
201*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
202*9880d681SAndroid Build Coastguard Worker     // We won't need to spill this, so no need to check for previously
203*9880d681SAndroid Build Coastguard Worker     // allocated stack slots
204*9880d681SAndroid Build Coastguard Worker     return;
205*9880d681SAndroid Build Coastguard Worker   }
206*9880d681SAndroid Build Coastguard Worker 
207*9880d681SAndroid Build Coastguard Worker   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
208*9880d681SAndroid Build Coastguard Worker   if (OldLocation.getNode())
209*9880d681SAndroid Build Coastguard Worker     // Duplicates in input
210*9880d681SAndroid Build Coastguard Worker     return;
211*9880d681SAndroid Build Coastguard Worker 
212*9880d681SAndroid Build Coastguard Worker   const int LookUpDepth = 6;
213*9880d681SAndroid Build Coastguard Worker   Optional<int> Index =
214*9880d681SAndroid Build Coastguard Worker       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
215*9880d681SAndroid Build Coastguard Worker   if (!Index.hasValue())
216*9880d681SAndroid Build Coastguard Worker     return;
217*9880d681SAndroid Build Coastguard Worker 
218*9880d681SAndroid Build Coastguard Worker   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker   auto SlotIt = find(StatepointSlots, *Index);
221*9880d681SAndroid Build Coastguard Worker   assert(SlotIt != StatepointSlots.end() &&
222*9880d681SAndroid Build Coastguard Worker          "Value spilled to the unknown stack slot");
223*9880d681SAndroid Build Coastguard Worker 
224*9880d681SAndroid Build Coastguard Worker   // This is one of our dedicated lowering slots
225*9880d681SAndroid Build Coastguard Worker   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
226*9880d681SAndroid Build Coastguard Worker   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
227*9880d681SAndroid Build Coastguard Worker     // stack slot already assigned to someone else, can't use it!
228*9880d681SAndroid Build Coastguard Worker     // TODO: currently we reserve space for gc arguments after doing
229*9880d681SAndroid Build Coastguard Worker     // normal allocation for deopt arguments.  We should reserve for
230*9880d681SAndroid Build Coastguard Worker     // _all_ deopt and gc arguments, then start allocating.  This
231*9880d681SAndroid Build Coastguard Worker     // will prevent some moves being inserted when vm state changes,
232*9880d681SAndroid Build Coastguard Worker     // but gc state doesn't between two calls.
233*9880d681SAndroid Build Coastguard Worker     return;
234*9880d681SAndroid Build Coastguard Worker   }
235*9880d681SAndroid Build Coastguard Worker   // Reserve this stack slot
236*9880d681SAndroid Build Coastguard Worker   Builder.StatepointLowering.reserveStackSlot(Offset);
237*9880d681SAndroid Build Coastguard Worker 
238*9880d681SAndroid Build Coastguard Worker   // Cache this slot so we find it when going through the normal
239*9880d681SAndroid Build Coastguard Worker   // assignment loop.
240*9880d681SAndroid Build Coastguard Worker   SDValue Loc = Builder.DAG.getTargetFrameIndex(*Index, Incoming.getValueType());
241*9880d681SAndroid Build Coastguard Worker   Builder.StatepointLowering.setLocation(Incoming, Loc);
242*9880d681SAndroid Build Coastguard Worker }
243*9880d681SAndroid Build Coastguard Worker 
244*9880d681SAndroid Build Coastguard Worker /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
245*9880d681SAndroid Build Coastguard Worker /// is not required for correctness.  It's purpose is to reduce the size of
246*9880d681SAndroid Build Coastguard Worker /// StackMap section.  It has no effect on the number of spill slots required
247*9880d681SAndroid Build Coastguard Worker /// or the actual lowering.
248*9880d681SAndroid Build Coastguard Worker static void
removeDuplicateGCPtrs(SmallVectorImpl<const Value * > & Bases,SmallVectorImpl<const Value * > & Ptrs,SmallVectorImpl<const GCRelocateInst * > & Relocs,SelectionDAGBuilder & Builder,FunctionLoweringInfo::StatepointSpillMap & SSM)249*9880d681SAndroid Build Coastguard Worker removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
250*9880d681SAndroid Build Coastguard Worker                       SmallVectorImpl<const Value *> &Ptrs,
251*9880d681SAndroid Build Coastguard Worker                       SmallVectorImpl<const GCRelocateInst *> &Relocs,
252*9880d681SAndroid Build Coastguard Worker                       SelectionDAGBuilder &Builder,
253*9880d681SAndroid Build Coastguard Worker                       FunctionLoweringInfo::StatepointSpillMap &SSM) {
254*9880d681SAndroid Build Coastguard Worker   DenseMap<SDValue, const Value *> Seen;
255*9880d681SAndroid Build Coastguard Worker 
256*9880d681SAndroid Build Coastguard Worker   SmallVector<const Value *, 64> NewBases, NewPtrs;
257*9880d681SAndroid Build Coastguard Worker   SmallVector<const GCRelocateInst *, 64> NewRelocs;
258*9880d681SAndroid Build Coastguard Worker   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
259*9880d681SAndroid Build Coastguard Worker     SDValue SD = Builder.getValue(Ptrs[i]);
260*9880d681SAndroid Build Coastguard Worker     auto SeenIt = Seen.find(SD);
261*9880d681SAndroid Build Coastguard Worker 
262*9880d681SAndroid Build Coastguard Worker     if (SeenIt == Seen.end()) {
263*9880d681SAndroid Build Coastguard Worker       // Only add non-duplicates
264*9880d681SAndroid Build Coastguard Worker       NewBases.push_back(Bases[i]);
265*9880d681SAndroid Build Coastguard Worker       NewPtrs.push_back(Ptrs[i]);
266*9880d681SAndroid Build Coastguard Worker       NewRelocs.push_back(Relocs[i]);
267*9880d681SAndroid Build Coastguard Worker       Seen[SD] = Ptrs[i];
268*9880d681SAndroid Build Coastguard Worker     } else {
269*9880d681SAndroid Build Coastguard Worker       // Duplicate pointer found, note in SSM and move on:
270*9880d681SAndroid Build Coastguard Worker       SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
271*9880d681SAndroid Build Coastguard Worker     }
272*9880d681SAndroid Build Coastguard Worker   }
273*9880d681SAndroid Build Coastguard Worker   assert(Bases.size() >= NewBases.size());
274*9880d681SAndroid Build Coastguard Worker   assert(Ptrs.size() >= NewPtrs.size());
275*9880d681SAndroid Build Coastguard Worker   assert(Relocs.size() >= NewRelocs.size());
276*9880d681SAndroid Build Coastguard Worker   Bases = NewBases;
277*9880d681SAndroid Build Coastguard Worker   Ptrs = NewPtrs;
278*9880d681SAndroid Build Coastguard Worker   Relocs = NewRelocs;
279*9880d681SAndroid Build Coastguard Worker   assert(Ptrs.size() == Bases.size());
280*9880d681SAndroid Build Coastguard Worker   assert(Ptrs.size() == Relocs.size());
281*9880d681SAndroid Build Coastguard Worker }
282*9880d681SAndroid Build Coastguard Worker 
283*9880d681SAndroid Build Coastguard Worker /// Extract call from statepoint, lower it and return pointer to the
284*9880d681SAndroid Build Coastguard Worker /// call node. Also update NodeMap so that getValue(statepoint) will
285*9880d681SAndroid Build Coastguard Worker /// reference lowered call result
lowerCallFromStatepointLoweringInfo(SelectionDAGBuilder::StatepointLoweringInfo & SI,SelectionDAGBuilder & Builder,SmallVectorImpl<SDValue> & PendingExports)286*9880d681SAndroid Build Coastguard Worker static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
287*9880d681SAndroid Build Coastguard Worker     SelectionDAGBuilder::StatepointLoweringInfo &SI,
288*9880d681SAndroid Build Coastguard Worker     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
289*9880d681SAndroid Build Coastguard Worker 
290*9880d681SAndroid Build Coastguard Worker   SDValue ReturnValue, CallEndVal;
291*9880d681SAndroid Build Coastguard Worker   std::tie(ReturnValue, CallEndVal) =
292*9880d681SAndroid Build Coastguard Worker       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
293*9880d681SAndroid Build Coastguard Worker   SDNode *CallEnd = CallEndVal.getNode();
294*9880d681SAndroid Build Coastguard Worker 
295*9880d681SAndroid Build Coastguard Worker   // Get a call instruction from the call sequence chain.  Tail calls are not
296*9880d681SAndroid Build Coastguard Worker   // allowed.  The following code is essentially reverse engineering X86's
297*9880d681SAndroid Build Coastguard Worker   // LowerCallTo.
298*9880d681SAndroid Build Coastguard Worker   //
299*9880d681SAndroid Build Coastguard Worker   // We are expecting DAG to have the following form:
300*9880d681SAndroid Build Coastguard Worker   //
301*9880d681SAndroid Build Coastguard Worker   // ch = eh_label (only in case of invoke statepoint)
302*9880d681SAndroid Build Coastguard Worker   //   ch, glue = callseq_start ch
303*9880d681SAndroid Build Coastguard Worker   //   ch, glue = X86::Call ch, glue
304*9880d681SAndroid Build Coastguard Worker   //   ch, glue = callseq_end ch, glue
305*9880d681SAndroid Build Coastguard Worker   //   get_return_value ch, glue
306*9880d681SAndroid Build Coastguard Worker   //
307*9880d681SAndroid Build Coastguard Worker   // get_return_value can either be a sequence of CopyFromReg instructions
308*9880d681SAndroid Build Coastguard Worker   // to grab the return value from the return register(s), or it can be a LOAD
309*9880d681SAndroid Build Coastguard Worker   // to load a value returned by reference via a stack slot.
310*9880d681SAndroid Build Coastguard Worker 
311*9880d681SAndroid Build Coastguard Worker   bool HasDef = !SI.CLI.RetTy->isVoidTy();
312*9880d681SAndroid Build Coastguard Worker   if (HasDef) {
313*9880d681SAndroid Build Coastguard Worker     if (CallEnd->getOpcode() == ISD::LOAD)
314*9880d681SAndroid Build Coastguard Worker       CallEnd = CallEnd->getOperand(0).getNode();
315*9880d681SAndroid Build Coastguard Worker     else
316*9880d681SAndroid Build Coastguard Worker       while (CallEnd->getOpcode() == ISD::CopyFromReg)
317*9880d681SAndroid Build Coastguard Worker         CallEnd = CallEnd->getOperand(0).getNode();
318*9880d681SAndroid Build Coastguard Worker   }
319*9880d681SAndroid Build Coastguard Worker 
320*9880d681SAndroid Build Coastguard Worker   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
321*9880d681SAndroid Build Coastguard Worker   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
322*9880d681SAndroid Build Coastguard Worker }
323*9880d681SAndroid Build Coastguard Worker 
324*9880d681SAndroid Build Coastguard Worker /// Spill a value incoming to the statepoint. It might be either part of
325*9880d681SAndroid Build Coastguard Worker /// vmstate
326*9880d681SAndroid Build Coastguard Worker /// or gcstate. In both cases unconditionally spill it on the stack unless it
327*9880d681SAndroid Build Coastguard Worker /// is a null constant. Return pair with first element being frame index
328*9880d681SAndroid Build Coastguard Worker /// containing saved value and second element with outgoing chain from the
329*9880d681SAndroid Build Coastguard Worker /// emitted store
330*9880d681SAndroid Build Coastguard Worker static std::pair<SDValue, SDValue>
spillIncomingStatepointValue(SDValue Incoming,SDValue Chain,SelectionDAGBuilder & Builder)331*9880d681SAndroid Build Coastguard Worker spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
332*9880d681SAndroid Build Coastguard Worker                              SelectionDAGBuilder &Builder) {
333*9880d681SAndroid Build Coastguard Worker   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
334*9880d681SAndroid Build Coastguard Worker 
335*9880d681SAndroid Build Coastguard Worker   // Emit new store if we didn't do it for this ptr before
336*9880d681SAndroid Build Coastguard Worker   if (!Loc.getNode()) {
337*9880d681SAndroid Build Coastguard Worker     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
338*9880d681SAndroid Build Coastguard Worker                                                        Builder);
339*9880d681SAndroid Build Coastguard Worker     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
340*9880d681SAndroid Build Coastguard Worker     // We use TargetFrameIndex so that isel will not select it into LEA
341*9880d681SAndroid Build Coastguard Worker     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
342*9880d681SAndroid Build Coastguard Worker 
343*9880d681SAndroid Build Coastguard Worker     // TODO: We can create TokenFactor node instead of
344*9880d681SAndroid Build Coastguard Worker     //       chaining stores one after another, this may allow
345*9880d681SAndroid Build Coastguard Worker     //       a bit more optimal scheduling for them
346*9880d681SAndroid Build Coastguard Worker 
347*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
348*9880d681SAndroid Build Coastguard Worker     // Right now we always allocate spill slots that are of the same
349*9880d681SAndroid Build Coastguard Worker     // size as the value we're about to spill (the size of spillee can
350*9880d681SAndroid Build Coastguard Worker     // vary since we spill vectors of pointers too).  At some point we
351*9880d681SAndroid Build Coastguard Worker     // can consider allowing spills of smaller values to larger slots
352*9880d681SAndroid Build Coastguard Worker     // (i.e. change the '==' in the assert below to a '>=').
353*9880d681SAndroid Build Coastguard Worker     auto *MFI = Builder.DAG.getMachineFunction().getFrameInfo();
354*9880d681SAndroid Build Coastguard Worker     assert((MFI->getObjectSize(Index) * 8) ==
355*9880d681SAndroid Build Coastguard Worker                Incoming.getValueType().getSizeInBits() &&
356*9880d681SAndroid Build Coastguard Worker            "Bad spill:  stack slot does not match!");
357*9880d681SAndroid Build Coastguard Worker #endif
358*9880d681SAndroid Build Coastguard Worker 
359*9880d681SAndroid Build Coastguard Worker     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
360*9880d681SAndroid Build Coastguard Worker                                  MachinePointerInfo::getFixedStack(
361*9880d681SAndroid Build Coastguard Worker                                      Builder.DAG.getMachineFunction(), Index),
362*9880d681SAndroid Build Coastguard Worker                                  false, false, 0);
363*9880d681SAndroid Build Coastguard Worker 
364*9880d681SAndroid Build Coastguard Worker     Builder.StatepointLowering.setLocation(Incoming, Loc);
365*9880d681SAndroid Build Coastguard Worker   }
366*9880d681SAndroid Build Coastguard Worker 
367*9880d681SAndroid Build Coastguard Worker   assert(Loc.getNode());
368*9880d681SAndroid Build Coastguard Worker   return std::make_pair(Loc, Chain);
369*9880d681SAndroid Build Coastguard Worker }
370*9880d681SAndroid Build Coastguard Worker 
371*9880d681SAndroid Build Coastguard Worker /// Lower a single value incoming to a statepoint node.  This value can be
372*9880d681SAndroid Build Coastguard Worker /// either a deopt value or a gc value, the handling is the same.  We special
373*9880d681SAndroid Build Coastguard Worker /// case constants and allocas, then fall back to spilling if required.
lowerIncomingStatepointValue(SDValue Incoming,SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder)374*9880d681SAndroid Build Coastguard Worker static void lowerIncomingStatepointValue(SDValue Incoming,
375*9880d681SAndroid Build Coastguard Worker                                          SmallVectorImpl<SDValue> &Ops,
376*9880d681SAndroid Build Coastguard Worker                                          SelectionDAGBuilder &Builder) {
377*9880d681SAndroid Build Coastguard Worker   SDValue Chain = Builder.getRoot();
378*9880d681SAndroid Build Coastguard Worker 
379*9880d681SAndroid Build Coastguard Worker   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
380*9880d681SAndroid Build Coastguard Worker     // If the original value was a constant, make sure it gets recorded as
381*9880d681SAndroid Build Coastguard Worker     // such in the stackmap.  This is required so that the consumer can
382*9880d681SAndroid Build Coastguard Worker     // parse any internal format to the deopt state.  It also handles null
383*9880d681SAndroid Build Coastguard Worker     // pointers and other constant pointers in GC states.  Note the constant
384*9880d681SAndroid Build Coastguard Worker     // vectors do not appear to actually hit this path and that anything larger
385*9880d681SAndroid Build Coastguard Worker     // than an i64 value (not type!) will fail asserts here.
386*9880d681SAndroid Build Coastguard Worker     pushStackMapConstant(Ops, Builder, C->getSExtValue());
387*9880d681SAndroid Build Coastguard Worker   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
388*9880d681SAndroid Build Coastguard Worker     // This handles allocas as arguments to the statepoint (this is only
389*9880d681SAndroid Build Coastguard Worker     // really meaningful for a deopt value.  For GC, we'd be trying to
390*9880d681SAndroid Build Coastguard Worker     // relocate the address of the alloca itself?)
391*9880d681SAndroid Build Coastguard Worker     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
392*9880d681SAndroid Build Coastguard Worker                                                   Incoming.getValueType()));
393*9880d681SAndroid Build Coastguard Worker   } else {
394*9880d681SAndroid Build Coastguard Worker     // Otherwise, locate a spill slot and explicitly spill it so it
395*9880d681SAndroid Build Coastguard Worker     // can be found by the runtime later.  We currently do not support
396*9880d681SAndroid Build Coastguard Worker     // tracking values through callee saved registers to their eventual
397*9880d681SAndroid Build Coastguard Worker     // spill location.  This would be a useful optimization, but would
398*9880d681SAndroid Build Coastguard Worker     // need to be optional since it requires a lot of complexity on the
399*9880d681SAndroid Build Coastguard Worker     // runtime side which not all would support.
400*9880d681SAndroid Build Coastguard Worker     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
401*9880d681SAndroid Build Coastguard Worker     Ops.push_back(Res.first);
402*9880d681SAndroid Build Coastguard Worker     Chain = Res.second;
403*9880d681SAndroid Build Coastguard Worker   }
404*9880d681SAndroid Build Coastguard Worker 
405*9880d681SAndroid Build Coastguard Worker   Builder.DAG.setRoot(Chain);
406*9880d681SAndroid Build Coastguard Worker }
407*9880d681SAndroid Build Coastguard Worker 
408*9880d681SAndroid Build Coastguard Worker /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
409*9880d681SAndroid Build Coastguard Worker /// lowering is described in lowerIncomingStatepointValue.  This function is
410*9880d681SAndroid Build Coastguard Worker /// responsible for lowering everything in the right position and playing some
411*9880d681SAndroid Build Coastguard Worker /// tricks to avoid redundant stack manipulation where possible.  On
412*9880d681SAndroid Build Coastguard Worker /// completion, 'Ops' will contain ready to use operands for machine code
413*9880d681SAndroid Build Coastguard Worker /// statepoint. The chain nodes will have already been created and the DAG root
414*9880d681SAndroid Build Coastguard Worker /// will be set to the last value spilled (if any were).
415*9880d681SAndroid Build Coastguard Worker static void
lowerStatepointMetaArgs(SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder::StatepointLoweringInfo & SI,SelectionDAGBuilder & Builder)416*9880d681SAndroid Build Coastguard Worker lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
417*9880d681SAndroid Build Coastguard Worker                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
418*9880d681SAndroid Build Coastguard Worker                         SelectionDAGBuilder &Builder) {
419*9880d681SAndroid Build Coastguard Worker   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
420*9880d681SAndroid Build Coastguard Worker   // deopt argument length, deopt arguments.., gc arguments...
421*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
422*9880d681SAndroid Build Coastguard Worker   if (auto *GFI = Builder.GFI) {
423*9880d681SAndroid Build Coastguard Worker     // Check that each of the gc pointer and bases we've gotten out of the
424*9880d681SAndroid Build Coastguard Worker     // safepoint is something the strategy thinks might be a pointer (or vector
425*9880d681SAndroid Build Coastguard Worker     // of pointers) into the GC heap.  This is basically just here to help catch
426*9880d681SAndroid Build Coastguard Worker     // errors during statepoint insertion. TODO: This should actually be in the
427*9880d681SAndroid Build Coastguard Worker     // Verifier, but we can't get to the GCStrategy from there (yet).
428*9880d681SAndroid Build Coastguard Worker     GCStrategy &S = GFI->getStrategy();
429*9880d681SAndroid Build Coastguard Worker     for (const Value *V : SI.Bases) {
430*9880d681SAndroid Build Coastguard Worker       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
431*9880d681SAndroid Build Coastguard Worker       if (Opt.hasValue()) {
432*9880d681SAndroid Build Coastguard Worker         assert(Opt.getValue() &&
433*9880d681SAndroid Build Coastguard Worker                "non gc managed base pointer found in statepoint");
434*9880d681SAndroid Build Coastguard Worker       }
435*9880d681SAndroid Build Coastguard Worker     }
436*9880d681SAndroid Build Coastguard Worker     for (const Value *V : SI.Ptrs) {
437*9880d681SAndroid Build Coastguard Worker       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
438*9880d681SAndroid Build Coastguard Worker       if (Opt.hasValue()) {
439*9880d681SAndroid Build Coastguard Worker         assert(Opt.getValue() &&
440*9880d681SAndroid Build Coastguard Worker                "non gc managed derived pointer found in statepoint");
441*9880d681SAndroid Build Coastguard Worker       }
442*9880d681SAndroid Build Coastguard Worker     }
443*9880d681SAndroid Build Coastguard Worker   } else {
444*9880d681SAndroid Build Coastguard Worker     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
445*9880d681SAndroid Build Coastguard Worker     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
446*9880d681SAndroid Build Coastguard Worker   }
447*9880d681SAndroid Build Coastguard Worker #endif
448*9880d681SAndroid Build Coastguard Worker 
449*9880d681SAndroid Build Coastguard Worker   // Before we actually start lowering (and allocating spill slots for values),
450*9880d681SAndroid Build Coastguard Worker   // reserve any stack slots which we judge to be profitable to reuse for a
451*9880d681SAndroid Build Coastguard Worker   // particular value.  This is purely an optimization over the code below and
452*9880d681SAndroid Build Coastguard Worker   // doesn't change semantics at all.  It is important for performance that we
453*9880d681SAndroid Build Coastguard Worker   // reserve slots for both deopt and gc values before lowering either.
454*9880d681SAndroid Build Coastguard Worker   for (const Value *V : SI.DeoptState) {
455*9880d681SAndroid Build Coastguard Worker     reservePreviousStackSlotForValue(V, Builder);
456*9880d681SAndroid Build Coastguard Worker   }
457*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
458*9880d681SAndroid Build Coastguard Worker     reservePreviousStackSlotForValue(SI.Bases[i], Builder);
459*9880d681SAndroid Build Coastguard Worker     reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
460*9880d681SAndroid Build Coastguard Worker   }
461*9880d681SAndroid Build Coastguard Worker 
462*9880d681SAndroid Build Coastguard Worker   // First, prefix the list with the number of unique values to be
463*9880d681SAndroid Build Coastguard Worker   // lowered.  Note that this is the number of *Values* not the
464*9880d681SAndroid Build Coastguard Worker   // number of SDValues required to lower them.
465*9880d681SAndroid Build Coastguard Worker   const int NumVMSArgs = SI.DeoptState.size();
466*9880d681SAndroid Build Coastguard Worker   pushStackMapConstant(Ops, Builder, NumVMSArgs);
467*9880d681SAndroid Build Coastguard Worker 
468*9880d681SAndroid Build Coastguard Worker   // The vm state arguments are lowered in an opaque manner.  We do not know
469*9880d681SAndroid Build Coastguard Worker   // what type of values are contained within.
470*9880d681SAndroid Build Coastguard Worker   for (const Value *V : SI.DeoptState) {
471*9880d681SAndroid Build Coastguard Worker     SDValue Incoming = Builder.getValue(V);
472*9880d681SAndroid Build Coastguard Worker     lowerIncomingStatepointValue(Incoming, Ops, Builder);
473*9880d681SAndroid Build Coastguard Worker   }
474*9880d681SAndroid Build Coastguard Worker 
475*9880d681SAndroid Build Coastguard Worker   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
476*9880d681SAndroid Build Coastguard Worker   // length for this one.  After lowering, we'll have the base and pointer
477*9880d681SAndroid Build Coastguard Worker   // arrays interwoven with each (lowered) base pointer immediately followed by
478*9880d681SAndroid Build Coastguard Worker   // it's (lowered) derived pointer.  i.e
479*9880d681SAndroid Build Coastguard Worker   // (base[0], ptr[0], base[1], ptr[1], ...)
480*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
481*9880d681SAndroid Build Coastguard Worker     const Value *Base = SI.Bases[i];
482*9880d681SAndroid Build Coastguard Worker     lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
483*9880d681SAndroid Build Coastguard Worker 
484*9880d681SAndroid Build Coastguard Worker     const Value *Ptr = SI.Ptrs[i];
485*9880d681SAndroid Build Coastguard Worker     lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
486*9880d681SAndroid Build Coastguard Worker   }
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker   // If there are any explicit spill slots passed to the statepoint, record
489*9880d681SAndroid Build Coastguard Worker   // them, but otherwise do not do anything special.  These are user provided
490*9880d681SAndroid Build Coastguard Worker   // allocas and give control over placement to the consumer.  In this case,
491*9880d681SAndroid Build Coastguard Worker   // it is the contents of the slot which may get updated, not the pointer to
492*9880d681SAndroid Build Coastguard Worker   // the alloca
493*9880d681SAndroid Build Coastguard Worker   for (Value *V : SI.GCArgs) {
494*9880d681SAndroid Build Coastguard Worker     SDValue Incoming = Builder.getValue(V);
495*9880d681SAndroid Build Coastguard Worker     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
496*9880d681SAndroid Build Coastguard Worker       // This handles allocas as arguments to the statepoint
497*9880d681SAndroid Build Coastguard Worker       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
498*9880d681SAndroid Build Coastguard Worker                                                     Incoming.getValueType()));
499*9880d681SAndroid Build Coastguard Worker     }
500*9880d681SAndroid Build Coastguard Worker   }
501*9880d681SAndroid Build Coastguard Worker 
502*9880d681SAndroid Build Coastguard Worker   // Record computed locations for all lowered values.
503*9880d681SAndroid Build Coastguard Worker   // This can not be embedded in lowering loops as we need to record *all*
504*9880d681SAndroid Build Coastguard Worker   // values, while previous loops account only values with unique SDValues.
505*9880d681SAndroid Build Coastguard Worker   const Instruction *StatepointInstr = SI.StatepointInstr;
506*9880d681SAndroid Build Coastguard Worker   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
507*9880d681SAndroid Build Coastguard Worker 
508*9880d681SAndroid Build Coastguard Worker   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
509*9880d681SAndroid Build Coastguard Worker     const Value *V = Relocate->getDerivedPtr();
510*9880d681SAndroid Build Coastguard Worker     SDValue SDV = Builder.getValue(V);
511*9880d681SAndroid Build Coastguard Worker     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
512*9880d681SAndroid Build Coastguard Worker 
513*9880d681SAndroid Build Coastguard Worker     if (Loc.getNode()) {
514*9880d681SAndroid Build Coastguard Worker       SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
515*9880d681SAndroid Build Coastguard Worker     } else {
516*9880d681SAndroid Build Coastguard Worker       // Record value as visited, but not spilled. This is case for allocas
517*9880d681SAndroid Build Coastguard Worker       // and constants. For this values we can avoid emitting spill load while
518*9880d681SAndroid Build Coastguard Worker       // visiting corresponding gc_relocate.
519*9880d681SAndroid Build Coastguard Worker       // Actually we do not need to record them in this map at all.
520*9880d681SAndroid Build Coastguard Worker       // We do this only to check that we are not relocating any unvisited
521*9880d681SAndroid Build Coastguard Worker       // value.
522*9880d681SAndroid Build Coastguard Worker       SpillMap.SlotMap[V] = None;
523*9880d681SAndroid Build Coastguard Worker 
524*9880d681SAndroid Build Coastguard Worker       // Default llvm mechanisms for exporting values which are used in
525*9880d681SAndroid Build Coastguard Worker       // different basic blocks does not work for gc relocates.
526*9880d681SAndroid Build Coastguard Worker       // Note that it would be incorrect to teach llvm that all relocates are
527*9880d681SAndroid Build Coastguard Worker       // uses of the corresponding values so that it would automatically
528*9880d681SAndroid Build Coastguard Worker       // export them. Relocates of the spilled values does not use original
529*9880d681SAndroid Build Coastguard Worker       // value.
530*9880d681SAndroid Build Coastguard Worker       if (Relocate->getParent() != StatepointInstr->getParent())
531*9880d681SAndroid Build Coastguard Worker         Builder.ExportFromCurrentBlock(V);
532*9880d681SAndroid Build Coastguard Worker     }
533*9880d681SAndroid Build Coastguard Worker   }
534*9880d681SAndroid Build Coastguard Worker }
535*9880d681SAndroid Build Coastguard Worker 
LowerAsSTATEPOINT(SelectionDAGBuilder::StatepointLoweringInfo & SI)536*9880d681SAndroid Build Coastguard Worker SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
537*9880d681SAndroid Build Coastguard Worker     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
538*9880d681SAndroid Build Coastguard Worker   // The basic scheme here is that information about both the original call and
539*9880d681SAndroid Build Coastguard Worker   // the safepoint is encoded in the CallInst.  We create a temporary call and
540*9880d681SAndroid Build Coastguard Worker   // lower it, then reverse engineer the calling sequence.
541*9880d681SAndroid Build Coastguard Worker 
542*9880d681SAndroid Build Coastguard Worker   NumOfStatepoints++;
543*9880d681SAndroid Build Coastguard Worker   // Clear state
544*9880d681SAndroid Build Coastguard Worker   StatepointLowering.startNewStatepoint(*this);
545*9880d681SAndroid Build Coastguard Worker 
546*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
547*9880d681SAndroid Build Coastguard Worker   // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
548*9880d681SAndroid Build Coastguard Worker   // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
549*9880d681SAndroid Build Coastguard Worker   for (auto *Reloc : SI.GCRelocates)
550*9880d681SAndroid Build Coastguard Worker     if (Reloc->getParent() == SI.StatepointInstr->getParent())
551*9880d681SAndroid Build Coastguard Worker       StatepointLowering.scheduleRelocCall(*Reloc);
552*9880d681SAndroid Build Coastguard Worker #endif
553*9880d681SAndroid Build Coastguard Worker 
554*9880d681SAndroid Build Coastguard Worker   // Remove any redundant llvm::Values which map to the same SDValue as another
555*9880d681SAndroid Build Coastguard Worker   // input.  Also has the effect of removing duplicates in the original
556*9880d681SAndroid Build Coastguard Worker   // llvm::Value input list as well.  This is a useful optimization for
557*9880d681SAndroid Build Coastguard Worker   // reducing the size of the StackMap section.  It has no other impact.
558*9880d681SAndroid Build Coastguard Worker   removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
559*9880d681SAndroid Build Coastguard Worker                         FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
560*9880d681SAndroid Build Coastguard Worker   assert(SI.Bases.size() == SI.Ptrs.size() &&
561*9880d681SAndroid Build Coastguard Worker          SI.Ptrs.size() == SI.GCRelocates.size());
562*9880d681SAndroid Build Coastguard Worker 
563*9880d681SAndroid Build Coastguard Worker   // Lower statepoint vmstate and gcstate arguments
564*9880d681SAndroid Build Coastguard Worker   SmallVector<SDValue, 10> LoweredMetaArgs;
565*9880d681SAndroid Build Coastguard Worker   lowerStatepointMetaArgs(LoweredMetaArgs, SI, *this);
566*9880d681SAndroid Build Coastguard Worker 
567*9880d681SAndroid Build Coastguard Worker   // Now that we've emitted the spills, we need to update the root so that the
568*9880d681SAndroid Build Coastguard Worker   // call sequence is ordered correctly.
569*9880d681SAndroid Build Coastguard Worker   SI.CLI.setChain(getRoot());
570*9880d681SAndroid Build Coastguard Worker 
571*9880d681SAndroid Build Coastguard Worker   // Get call node, we will replace it later with statepoint
572*9880d681SAndroid Build Coastguard Worker   SDValue ReturnVal;
573*9880d681SAndroid Build Coastguard Worker   SDNode *CallNode;
574*9880d681SAndroid Build Coastguard Worker   std::tie(ReturnVal, CallNode) =
575*9880d681SAndroid Build Coastguard Worker       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
576*9880d681SAndroid Build Coastguard Worker 
577*9880d681SAndroid Build Coastguard Worker   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
578*9880d681SAndroid Build Coastguard Worker   // nodes with all the appropriate arguments and return values.
579*9880d681SAndroid Build Coastguard Worker 
580*9880d681SAndroid Build Coastguard Worker   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
581*9880d681SAndroid Build Coastguard Worker   SDValue Chain = CallNode->getOperand(0);
582*9880d681SAndroid Build Coastguard Worker 
583*9880d681SAndroid Build Coastguard Worker   SDValue Glue;
584*9880d681SAndroid Build Coastguard Worker   bool CallHasIncomingGlue = CallNode->getGluedNode();
585*9880d681SAndroid Build Coastguard Worker   if (CallHasIncomingGlue) {
586*9880d681SAndroid Build Coastguard Worker     // Glue is always last operand
587*9880d681SAndroid Build Coastguard Worker     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
588*9880d681SAndroid Build Coastguard Worker   }
589*9880d681SAndroid Build Coastguard Worker 
590*9880d681SAndroid Build Coastguard Worker   // Build the GC_TRANSITION_START node if necessary.
591*9880d681SAndroid Build Coastguard Worker   //
592*9880d681SAndroid Build Coastguard Worker   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
593*9880d681SAndroid Build Coastguard Worker   // order in which they appear in the call to the statepoint intrinsic. If
594*9880d681SAndroid Build Coastguard Worker   // any of the operands is a pointer-typed, that operand is immediately
595*9880d681SAndroid Build Coastguard Worker   // followed by a SRCVALUE for the pointer that may be used during lowering
596*9880d681SAndroid Build Coastguard Worker   // (e.g. to form MachinePointerInfo values for loads/stores).
597*9880d681SAndroid Build Coastguard Worker   const bool IsGCTransition =
598*9880d681SAndroid Build Coastguard Worker       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
599*9880d681SAndroid Build Coastguard Worker       (uint64_t)StatepointFlags::GCTransition;
600*9880d681SAndroid Build Coastguard Worker   if (IsGCTransition) {
601*9880d681SAndroid Build Coastguard Worker     SmallVector<SDValue, 8> TSOps;
602*9880d681SAndroid Build Coastguard Worker 
603*9880d681SAndroid Build Coastguard Worker     // Add chain
604*9880d681SAndroid Build Coastguard Worker     TSOps.push_back(Chain);
605*9880d681SAndroid Build Coastguard Worker 
606*9880d681SAndroid Build Coastguard Worker     // Add GC transition arguments
607*9880d681SAndroid Build Coastguard Worker     for (const Value *V : SI.GCTransitionArgs) {
608*9880d681SAndroid Build Coastguard Worker       TSOps.push_back(getValue(V));
609*9880d681SAndroid Build Coastguard Worker       if (V->getType()->isPointerTy())
610*9880d681SAndroid Build Coastguard Worker         TSOps.push_back(DAG.getSrcValue(V));
611*9880d681SAndroid Build Coastguard Worker     }
612*9880d681SAndroid Build Coastguard Worker 
613*9880d681SAndroid Build Coastguard Worker     // Add glue if necessary
614*9880d681SAndroid Build Coastguard Worker     if (CallHasIncomingGlue)
615*9880d681SAndroid Build Coastguard Worker       TSOps.push_back(Glue);
616*9880d681SAndroid Build Coastguard Worker 
617*9880d681SAndroid Build Coastguard Worker     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
618*9880d681SAndroid Build Coastguard Worker 
619*9880d681SAndroid Build Coastguard Worker     SDValue GCTransitionStart =
620*9880d681SAndroid Build Coastguard Worker         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
621*9880d681SAndroid Build Coastguard Worker 
622*9880d681SAndroid Build Coastguard Worker     Chain = GCTransitionStart.getValue(0);
623*9880d681SAndroid Build Coastguard Worker     Glue = GCTransitionStart.getValue(1);
624*9880d681SAndroid Build Coastguard Worker   }
625*9880d681SAndroid Build Coastguard Worker 
626*9880d681SAndroid Build Coastguard Worker   // TODO: Currently, all of these operands are being marked as read/write in
627*9880d681SAndroid Build Coastguard Worker   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
628*9880d681SAndroid Build Coastguard Worker   // and flags to be read-only.
629*9880d681SAndroid Build Coastguard Worker   SmallVector<SDValue, 40> Ops;
630*9880d681SAndroid Build Coastguard Worker 
631*9880d681SAndroid Build Coastguard Worker   // Add the <id> and <numBytes> constants.
632*9880d681SAndroid Build Coastguard Worker   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
633*9880d681SAndroid Build Coastguard Worker   Ops.push_back(
634*9880d681SAndroid Build Coastguard Worker       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
635*9880d681SAndroid Build Coastguard Worker 
636*9880d681SAndroid Build Coastguard Worker   // Calculate and push starting position of vmstate arguments
637*9880d681SAndroid Build Coastguard Worker   // Get number of arguments incoming directly into call node
638*9880d681SAndroid Build Coastguard Worker   unsigned NumCallRegArgs =
639*9880d681SAndroid Build Coastguard Worker       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
640*9880d681SAndroid Build Coastguard Worker   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
641*9880d681SAndroid Build Coastguard Worker 
642*9880d681SAndroid Build Coastguard Worker   // Add call target
643*9880d681SAndroid Build Coastguard Worker   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
644*9880d681SAndroid Build Coastguard Worker   Ops.push_back(CallTarget);
645*9880d681SAndroid Build Coastguard Worker 
646*9880d681SAndroid Build Coastguard Worker   // Add call arguments
647*9880d681SAndroid Build Coastguard Worker   // Get position of register mask in the call
648*9880d681SAndroid Build Coastguard Worker   SDNode::op_iterator RegMaskIt;
649*9880d681SAndroid Build Coastguard Worker   if (CallHasIncomingGlue)
650*9880d681SAndroid Build Coastguard Worker     RegMaskIt = CallNode->op_end() - 2;
651*9880d681SAndroid Build Coastguard Worker   else
652*9880d681SAndroid Build Coastguard Worker     RegMaskIt = CallNode->op_end() - 1;
653*9880d681SAndroid Build Coastguard Worker   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
654*9880d681SAndroid Build Coastguard Worker 
655*9880d681SAndroid Build Coastguard Worker   // Add a constant argument for the calling convention
656*9880d681SAndroid Build Coastguard Worker   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
657*9880d681SAndroid Build Coastguard Worker 
658*9880d681SAndroid Build Coastguard Worker   // Add a constant argument for the flags
659*9880d681SAndroid Build Coastguard Worker   uint64_t Flags = SI.StatepointFlags;
660*9880d681SAndroid Build Coastguard Worker   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
661*9880d681SAndroid Build Coastguard Worker          "Unknown flag used");
662*9880d681SAndroid Build Coastguard Worker   pushStackMapConstant(Ops, *this, Flags);
663*9880d681SAndroid Build Coastguard Worker 
664*9880d681SAndroid Build Coastguard Worker   // Insert all vmstate and gcstate arguments
665*9880d681SAndroid Build Coastguard Worker   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
666*9880d681SAndroid Build Coastguard Worker 
667*9880d681SAndroid Build Coastguard Worker   // Add register mask from call node
668*9880d681SAndroid Build Coastguard Worker   Ops.push_back(*RegMaskIt);
669*9880d681SAndroid Build Coastguard Worker 
670*9880d681SAndroid Build Coastguard Worker   // Add chain
671*9880d681SAndroid Build Coastguard Worker   Ops.push_back(Chain);
672*9880d681SAndroid Build Coastguard Worker 
673*9880d681SAndroid Build Coastguard Worker   // Same for the glue, but we add it only if original call had it
674*9880d681SAndroid Build Coastguard Worker   if (Glue.getNode())
675*9880d681SAndroid Build Coastguard Worker     Ops.push_back(Glue);
676*9880d681SAndroid Build Coastguard Worker 
677*9880d681SAndroid Build Coastguard Worker   // Compute return values.  Provide a glue output since we consume one as
678*9880d681SAndroid Build Coastguard Worker   // input.  This allows someone else to chain off us as needed.
679*9880d681SAndroid Build Coastguard Worker   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
680*9880d681SAndroid Build Coastguard Worker 
681*9880d681SAndroid Build Coastguard Worker   SDNode *StatepointMCNode =
682*9880d681SAndroid Build Coastguard Worker       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
683*9880d681SAndroid Build Coastguard Worker 
684*9880d681SAndroid Build Coastguard Worker   SDNode *SinkNode = StatepointMCNode;
685*9880d681SAndroid Build Coastguard Worker 
686*9880d681SAndroid Build Coastguard Worker   // Build the GC_TRANSITION_END node if necessary.
687*9880d681SAndroid Build Coastguard Worker   //
688*9880d681SAndroid Build Coastguard Worker   // See the comment above regarding GC_TRANSITION_START for the layout of
689*9880d681SAndroid Build Coastguard Worker   // the operands to the GC_TRANSITION_END node.
690*9880d681SAndroid Build Coastguard Worker   if (IsGCTransition) {
691*9880d681SAndroid Build Coastguard Worker     SmallVector<SDValue, 8> TEOps;
692*9880d681SAndroid Build Coastguard Worker 
693*9880d681SAndroid Build Coastguard Worker     // Add chain
694*9880d681SAndroid Build Coastguard Worker     TEOps.push_back(SDValue(StatepointMCNode, 0));
695*9880d681SAndroid Build Coastguard Worker 
696*9880d681SAndroid Build Coastguard Worker     // Add GC transition arguments
697*9880d681SAndroid Build Coastguard Worker     for (const Value *V : SI.GCTransitionArgs) {
698*9880d681SAndroid Build Coastguard Worker       TEOps.push_back(getValue(V));
699*9880d681SAndroid Build Coastguard Worker       if (V->getType()->isPointerTy())
700*9880d681SAndroid Build Coastguard Worker         TEOps.push_back(DAG.getSrcValue(V));
701*9880d681SAndroid Build Coastguard Worker     }
702*9880d681SAndroid Build Coastguard Worker 
703*9880d681SAndroid Build Coastguard Worker     // Add glue
704*9880d681SAndroid Build Coastguard Worker     TEOps.push_back(SDValue(StatepointMCNode, 1));
705*9880d681SAndroid Build Coastguard Worker 
706*9880d681SAndroid Build Coastguard Worker     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker     SDValue GCTransitionStart =
709*9880d681SAndroid Build Coastguard Worker         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
710*9880d681SAndroid Build Coastguard Worker 
711*9880d681SAndroid Build Coastguard Worker     SinkNode = GCTransitionStart.getNode();
712*9880d681SAndroid Build Coastguard Worker   }
713*9880d681SAndroid Build Coastguard Worker 
714*9880d681SAndroid Build Coastguard Worker   // Replace original call
715*9880d681SAndroid Build Coastguard Worker   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
716*9880d681SAndroid Build Coastguard Worker   // Remove original call node
717*9880d681SAndroid Build Coastguard Worker   DAG.DeleteNode(CallNode);
718*9880d681SAndroid Build Coastguard Worker 
719*9880d681SAndroid Build Coastguard Worker   // DON'T set the root - under the assumption that it's already set past the
720*9880d681SAndroid Build Coastguard Worker   // inserted node we created.
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker   // TODO: A better future implementation would be to emit a single variable
723*9880d681SAndroid Build Coastguard Worker   // argument, variable return value STATEPOINT node here and then hookup the
724*9880d681SAndroid Build Coastguard Worker   // return value of each gc.relocate to the respective output of the
725*9880d681SAndroid Build Coastguard Worker   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
726*9880d681SAndroid Build Coastguard Worker   // to actually be possible today.
727*9880d681SAndroid Build Coastguard Worker 
728*9880d681SAndroid Build Coastguard Worker   return ReturnVal;
729*9880d681SAndroid Build Coastguard Worker }
730*9880d681SAndroid Build Coastguard Worker 
731*9880d681SAndroid Build Coastguard Worker void
LowerStatepoint(ImmutableStatepoint ISP,const BasicBlock * EHPadBB)732*9880d681SAndroid Build Coastguard Worker SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
733*9880d681SAndroid Build Coastguard Worker                                      const BasicBlock *EHPadBB /*= nullptr*/) {
734*9880d681SAndroid Build Coastguard Worker   assert(ISP.getCallSite().getCallingConv() != CallingConv::AnyReg &&
735*9880d681SAndroid Build Coastguard Worker          "anyregcc is not supported on statepoints!");
736*9880d681SAndroid Build Coastguard Worker 
737*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
738*9880d681SAndroid Build Coastguard Worker   // If this is a malformed statepoint, report it early to simplify debugging.
739*9880d681SAndroid Build Coastguard Worker   // This should catch any IR level mistake that's made when constructing or
740*9880d681SAndroid Build Coastguard Worker   // transforming statepoints.
741*9880d681SAndroid Build Coastguard Worker   ISP.verify();
742*9880d681SAndroid Build Coastguard Worker 
743*9880d681SAndroid Build Coastguard Worker   // Check that the associated GCStrategy expects to encounter statepoints.
744*9880d681SAndroid Build Coastguard Worker   assert(GFI->getStrategy().useStatepoints() &&
745*9880d681SAndroid Build Coastguard Worker          "GCStrategy does not expect to encounter statepoints");
746*9880d681SAndroid Build Coastguard Worker #endif
747*9880d681SAndroid Build Coastguard Worker 
748*9880d681SAndroid Build Coastguard Worker   SDValue ActualCallee;
749*9880d681SAndroid Build Coastguard Worker 
750*9880d681SAndroid Build Coastguard Worker   if (ISP.getNumPatchBytes() > 0) {
751*9880d681SAndroid Build Coastguard Worker     // If we've been asked to emit a nop sequence instead of a call instruction
752*9880d681SAndroid Build Coastguard Worker     // for this statepoint then don't lower the call target, but use a constant
753*9880d681SAndroid Build Coastguard Worker     // `null` instead.  Not lowering the call target lets statepoint clients get
754*9880d681SAndroid Build Coastguard Worker     // away without providing a physical address for the symbolic call target at
755*9880d681SAndroid Build Coastguard Worker     // link time.
756*9880d681SAndroid Build Coastguard Worker 
757*9880d681SAndroid Build Coastguard Worker     const auto &TLI = DAG.getTargetLoweringInfo();
758*9880d681SAndroid Build Coastguard Worker     const auto &DL = DAG.getDataLayout();
759*9880d681SAndroid Build Coastguard Worker 
760*9880d681SAndroid Build Coastguard Worker     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
761*9880d681SAndroid Build Coastguard Worker     ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
762*9880d681SAndroid Build Coastguard Worker   } else {
763*9880d681SAndroid Build Coastguard Worker     ActualCallee = getValue(ISP.getCalledValue());
764*9880d681SAndroid Build Coastguard Worker   }
765*9880d681SAndroid Build Coastguard Worker 
766*9880d681SAndroid Build Coastguard Worker   StatepointLoweringInfo SI(DAG);
767*9880d681SAndroid Build Coastguard Worker   populateCallLoweringInfo(SI.CLI, ISP.getCallSite(),
768*9880d681SAndroid Build Coastguard Worker                            ImmutableStatepoint::CallArgsBeginPos,
769*9880d681SAndroid Build Coastguard Worker                            ISP.getNumCallArgs(), ActualCallee,
770*9880d681SAndroid Build Coastguard Worker                            ISP.getActualReturnType(), false /* IsPatchPoint */);
771*9880d681SAndroid Build Coastguard Worker 
772*9880d681SAndroid Build Coastguard Worker   for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
773*9880d681SAndroid Build Coastguard Worker     SI.GCRelocates.push_back(Relocate);
774*9880d681SAndroid Build Coastguard Worker     SI.Bases.push_back(Relocate->getBasePtr());
775*9880d681SAndroid Build Coastguard Worker     SI.Ptrs.push_back(Relocate->getDerivedPtr());
776*9880d681SAndroid Build Coastguard Worker   }
777*9880d681SAndroid Build Coastguard Worker 
778*9880d681SAndroid Build Coastguard Worker   SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
779*9880d681SAndroid Build Coastguard Worker   SI.StatepointInstr = ISP.getInstruction();
780*9880d681SAndroid Build Coastguard Worker   SI.GCTransitionArgs =
781*9880d681SAndroid Build Coastguard Worker       ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
782*9880d681SAndroid Build Coastguard Worker   SI.ID = ISP.getID();
783*9880d681SAndroid Build Coastguard Worker   SI.DeoptState = ArrayRef<const Use>(ISP.vm_state_begin(), ISP.vm_state_end());
784*9880d681SAndroid Build Coastguard Worker   SI.StatepointFlags = ISP.getFlags();
785*9880d681SAndroid Build Coastguard Worker   SI.NumPatchBytes = ISP.getNumPatchBytes();
786*9880d681SAndroid Build Coastguard Worker   SI.EHPadBB = EHPadBB;
787*9880d681SAndroid Build Coastguard Worker 
788*9880d681SAndroid Build Coastguard Worker   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
789*9880d681SAndroid Build Coastguard Worker 
790*9880d681SAndroid Build Coastguard Worker   // Export the result value if needed
791*9880d681SAndroid Build Coastguard Worker   const GCResultInst *GCResult = ISP.getGCResult();
792*9880d681SAndroid Build Coastguard Worker   Type *RetTy = ISP.getActualReturnType();
793*9880d681SAndroid Build Coastguard Worker   if (!RetTy->isVoidTy() && GCResult) {
794*9880d681SAndroid Build Coastguard Worker     if (GCResult->getParent() != ISP.getCallSite().getParent()) {
795*9880d681SAndroid Build Coastguard Worker       // Result value will be used in a different basic block so we need to
796*9880d681SAndroid Build Coastguard Worker       // export it now.  Default exporting mechanism will not work here because
797*9880d681SAndroid Build Coastguard Worker       // statepoint call has a different type than the actual call. It means
798*9880d681SAndroid Build Coastguard Worker       // that by default llvm will create export register of the wrong type
799*9880d681SAndroid Build Coastguard Worker       // (always i32 in our case). So instead we need to create export register
800*9880d681SAndroid Build Coastguard Worker       // with correct type manually.
801*9880d681SAndroid Build Coastguard Worker       // TODO: To eliminate this problem we can remove gc.result intrinsics
802*9880d681SAndroid Build Coastguard Worker       //       completely and make statepoint call to return a tuple.
803*9880d681SAndroid Build Coastguard Worker       unsigned Reg = FuncInfo.CreateRegs(RetTy);
804*9880d681SAndroid Build Coastguard Worker       RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
805*9880d681SAndroid Build Coastguard Worker                        DAG.getDataLayout(), Reg, RetTy);
806*9880d681SAndroid Build Coastguard Worker       SDValue Chain = DAG.getEntryNode();
807*9880d681SAndroid Build Coastguard Worker 
808*9880d681SAndroid Build Coastguard Worker       RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
809*9880d681SAndroid Build Coastguard Worker       PendingExports.push_back(Chain);
810*9880d681SAndroid Build Coastguard Worker       FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
811*9880d681SAndroid Build Coastguard Worker     } else {
812*9880d681SAndroid Build Coastguard Worker       // Result value will be used in a same basic block. Don't export it or
813*9880d681SAndroid Build Coastguard Worker       // perform any explicit register copies.
814*9880d681SAndroid Build Coastguard Worker       // We'll replace the actuall call node shortly. gc_result will grab
815*9880d681SAndroid Build Coastguard Worker       // this value.
816*9880d681SAndroid Build Coastguard Worker       setValue(ISP.getInstruction(), ReturnValue);
817*9880d681SAndroid Build Coastguard Worker     }
818*9880d681SAndroid Build Coastguard Worker   } else {
819*9880d681SAndroid Build Coastguard Worker     // The token value is never used from here on, just generate a poison value
820*9880d681SAndroid Build Coastguard Worker     setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
821*9880d681SAndroid Build Coastguard Worker   }
822*9880d681SAndroid Build Coastguard Worker }
823*9880d681SAndroid Build Coastguard Worker 
LowerCallSiteWithDeoptBundleImpl(ImmutableCallSite CS,SDValue Callee,const BasicBlock * EHPadBB,bool VarArgDisallowed,bool ForceVoidReturnTy)824*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
825*9880d681SAndroid Build Coastguard Worker     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB,
826*9880d681SAndroid Build Coastguard Worker     bool VarArgDisallowed, bool ForceVoidReturnTy) {
827*9880d681SAndroid Build Coastguard Worker   StatepointLoweringInfo SI(DAG);
828*9880d681SAndroid Build Coastguard Worker   unsigned ArgBeginIndex = CS.arg_begin() - CS.getInstruction()->op_begin();
829*9880d681SAndroid Build Coastguard Worker   populateCallLoweringInfo(
830*9880d681SAndroid Build Coastguard Worker       SI.CLI, CS, ArgBeginIndex, CS.getNumArgOperands(), Callee,
831*9880d681SAndroid Build Coastguard Worker       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : CS.getType(),
832*9880d681SAndroid Build Coastguard Worker       false);
833*9880d681SAndroid Build Coastguard Worker   if (!VarArgDisallowed)
834*9880d681SAndroid Build Coastguard Worker     SI.CLI.IsVarArg = CS.getFunctionType()->isVarArg();
835*9880d681SAndroid Build Coastguard Worker 
836*9880d681SAndroid Build Coastguard Worker   auto DeoptBundle = *CS.getOperandBundle(LLVMContext::OB_deopt);
837*9880d681SAndroid Build Coastguard Worker 
838*9880d681SAndroid Build Coastguard Worker   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
839*9880d681SAndroid Build Coastguard Worker 
840*9880d681SAndroid Build Coastguard Worker   auto SD = parseStatepointDirectivesFromAttrs(CS.getAttributes());
841*9880d681SAndroid Build Coastguard Worker   SI.ID = SD.StatepointID.getValueOr(DefaultID);
842*9880d681SAndroid Build Coastguard Worker   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
843*9880d681SAndroid Build Coastguard Worker 
844*9880d681SAndroid Build Coastguard Worker   SI.DeoptState =
845*9880d681SAndroid Build Coastguard Worker       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
846*9880d681SAndroid Build Coastguard Worker   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
847*9880d681SAndroid Build Coastguard Worker   SI.EHPadBB = EHPadBB;
848*9880d681SAndroid Build Coastguard Worker 
849*9880d681SAndroid Build Coastguard Worker   // NB! The GC arguments are deliberately left empty.
850*9880d681SAndroid Build Coastguard Worker 
851*9880d681SAndroid Build Coastguard Worker   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
852*9880d681SAndroid Build Coastguard Worker     const Instruction *Inst = CS.getInstruction();
853*9880d681SAndroid Build Coastguard Worker     ReturnVal = lowerRangeToAssertZExt(DAG, *Inst, ReturnVal);
854*9880d681SAndroid Build Coastguard Worker     setValue(Inst, ReturnVal);
855*9880d681SAndroid Build Coastguard Worker   }
856*9880d681SAndroid Build Coastguard Worker }
857*9880d681SAndroid Build Coastguard Worker 
LowerCallSiteWithDeoptBundle(ImmutableCallSite CS,SDValue Callee,const BasicBlock * EHPadBB)858*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
859*9880d681SAndroid Build Coastguard Worker     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB) {
860*9880d681SAndroid Build Coastguard Worker   LowerCallSiteWithDeoptBundleImpl(CS, Callee, EHPadBB,
861*9880d681SAndroid Build Coastguard Worker                                    /* VarArgDisallowed = */ false,
862*9880d681SAndroid Build Coastguard Worker                                    /* ForceVoidReturnTy  = */ false);
863*9880d681SAndroid Build Coastguard Worker }
864*9880d681SAndroid Build Coastguard Worker 
visitGCResult(const GCResultInst & CI)865*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
866*9880d681SAndroid Build Coastguard Worker   // The result value of the gc_result is simply the result of the actual
867*9880d681SAndroid Build Coastguard Worker   // call.  We've already emitted this, so just grab the value.
868*9880d681SAndroid Build Coastguard Worker   const Instruction *I = CI.getStatepoint();
869*9880d681SAndroid Build Coastguard Worker 
870*9880d681SAndroid Build Coastguard Worker   if (I->getParent() != CI.getParent()) {
871*9880d681SAndroid Build Coastguard Worker     // Statepoint is in different basic block so we should have stored call
872*9880d681SAndroid Build Coastguard Worker     // result in a virtual register.
873*9880d681SAndroid Build Coastguard Worker     // We can not use default getValue() functionality to copy value from this
874*9880d681SAndroid Build Coastguard Worker     // register because statepoint and actual call return types can be
875*9880d681SAndroid Build Coastguard Worker     // different, and getValue() will use CopyFromReg of the wrong type,
876*9880d681SAndroid Build Coastguard Worker     // which is always i32 in our case.
877*9880d681SAndroid Build Coastguard Worker     PointerType *CalleeType = cast<PointerType>(
878*9880d681SAndroid Build Coastguard Worker         ImmutableStatepoint(I).getCalledValue()->getType());
879*9880d681SAndroid Build Coastguard Worker     Type *RetTy =
880*9880d681SAndroid Build Coastguard Worker         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
881*9880d681SAndroid Build Coastguard Worker     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
882*9880d681SAndroid Build Coastguard Worker 
883*9880d681SAndroid Build Coastguard Worker     assert(CopyFromReg.getNode());
884*9880d681SAndroid Build Coastguard Worker     setValue(&CI, CopyFromReg);
885*9880d681SAndroid Build Coastguard Worker   } else {
886*9880d681SAndroid Build Coastguard Worker     setValue(&CI, getValue(I));
887*9880d681SAndroid Build Coastguard Worker   }
888*9880d681SAndroid Build Coastguard Worker }
889*9880d681SAndroid Build Coastguard Worker 
visitGCRelocate(const GCRelocateInst & Relocate)890*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
891*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
892*9880d681SAndroid Build Coastguard Worker   // Consistency check
893*9880d681SAndroid Build Coastguard Worker   // We skip this check for relocates not in the same basic block as thier
894*9880d681SAndroid Build Coastguard Worker   // statepoint. It would be too expensive to preserve validation info through
895*9880d681SAndroid Build Coastguard Worker   // different basic blocks.
896*9880d681SAndroid Build Coastguard Worker   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
897*9880d681SAndroid Build Coastguard Worker     StatepointLowering.relocCallVisited(Relocate);
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   auto *Ty = Relocate.getType()->getScalarType();
900*9880d681SAndroid Build Coastguard Worker   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
901*9880d681SAndroid Build Coastguard Worker     assert(*IsManaged && "Non gc managed pointer relocated!");
902*9880d681SAndroid Build Coastguard Worker #endif
903*9880d681SAndroid Build Coastguard Worker 
904*9880d681SAndroid Build Coastguard Worker   const Value *DerivedPtr = Relocate.getDerivedPtr();
905*9880d681SAndroid Build Coastguard Worker   SDValue SD = getValue(DerivedPtr);
906*9880d681SAndroid Build Coastguard Worker 
907*9880d681SAndroid Build Coastguard Worker   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
908*9880d681SAndroid Build Coastguard Worker   auto SlotIt = SpillMap.find(DerivedPtr);
909*9880d681SAndroid Build Coastguard Worker   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
910*9880d681SAndroid Build Coastguard Worker   Optional<int> DerivedPtrLocation = SlotIt->second;
911*9880d681SAndroid Build Coastguard Worker 
912*9880d681SAndroid Build Coastguard Worker   // We didn't need to spill these special cases (constants and allocas).
913*9880d681SAndroid Build Coastguard Worker   // See the handling in spillIncomingValueForStatepoint for detail.
914*9880d681SAndroid Build Coastguard Worker   if (!DerivedPtrLocation) {
915*9880d681SAndroid Build Coastguard Worker     setValue(&Relocate, SD);
916*9880d681SAndroid Build Coastguard Worker     return;
917*9880d681SAndroid Build Coastguard Worker   }
918*9880d681SAndroid Build Coastguard Worker 
919*9880d681SAndroid Build Coastguard Worker   SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
920*9880d681SAndroid Build Coastguard Worker                                               SD.getValueType());
921*9880d681SAndroid Build Coastguard Worker 
922*9880d681SAndroid Build Coastguard Worker   // Be conservative: flush all pending loads
923*9880d681SAndroid Build Coastguard Worker   // TODO: Probably we can be less restrictive on this,
924*9880d681SAndroid Build Coastguard Worker   // it may allow more scheduling opportunities.
925*9880d681SAndroid Build Coastguard Worker   SDValue Chain = getRoot();
926*9880d681SAndroid Build Coastguard Worker 
927*9880d681SAndroid Build Coastguard Worker   SDValue SpillLoad =
928*9880d681SAndroid Build Coastguard Worker       DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
929*9880d681SAndroid Build Coastguard Worker                   MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
930*9880d681SAndroid Build Coastguard Worker                                                     *DerivedPtrLocation),
931*9880d681SAndroid Build Coastguard Worker                   false, false, false, 0);
932*9880d681SAndroid Build Coastguard Worker 
933*9880d681SAndroid Build Coastguard Worker   // Again, be conservative, don't emit pending loads
934*9880d681SAndroid Build Coastguard Worker   DAG.setRoot(SpillLoad.getValue(1));
935*9880d681SAndroid Build Coastguard Worker 
936*9880d681SAndroid Build Coastguard Worker   assert(SpillLoad.getNode());
937*9880d681SAndroid Build Coastguard Worker   setValue(&Relocate, SpillLoad);
938*9880d681SAndroid Build Coastguard Worker }
939*9880d681SAndroid Build Coastguard Worker 
LowerDeoptimizeCall(const CallInst * CI)940*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
941*9880d681SAndroid Build Coastguard Worker   const auto &TLI = DAG.getTargetLoweringInfo();
942*9880d681SAndroid Build Coastguard Worker   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
943*9880d681SAndroid Build Coastguard Worker                                          TLI.getPointerTy(DAG.getDataLayout()));
944*9880d681SAndroid Build Coastguard Worker 
945*9880d681SAndroid Build Coastguard Worker   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
946*9880d681SAndroid Build Coastguard Worker   // call.  We also do not lower the return value to any virtual register, and
947*9880d681SAndroid Build Coastguard Worker   // change the immediately following return to a trap instruction.
948*9880d681SAndroid Build Coastguard Worker   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
949*9880d681SAndroid Build Coastguard Worker                                    /* VarArgDisallowed = */ true,
950*9880d681SAndroid Build Coastguard Worker                                    /* ForceVoidReturnTy = */ true);
951*9880d681SAndroid Build Coastguard Worker }
952*9880d681SAndroid Build Coastguard Worker 
LowerDeoptimizingReturn()953*9880d681SAndroid Build Coastguard Worker void SelectionDAGBuilder::LowerDeoptimizingReturn() {
954*9880d681SAndroid Build Coastguard Worker   // We do not lower the return value from llvm.deoptimize to any virtual
955*9880d681SAndroid Build Coastguard Worker   // register, and change the immediately following return to a trap
956*9880d681SAndroid Build Coastguard Worker   // instruction.
957*9880d681SAndroid Build Coastguard Worker   if (DAG.getTarget().Options.TrapUnreachable)
958*9880d681SAndroid Build Coastguard Worker     DAG.setRoot(
959*9880d681SAndroid Build Coastguard Worker         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
960*9880d681SAndroid Build Coastguard Worker }
961