blob: 521e27334ffe62032144b593b434aa6eb3560000 [file] [log] [blame]
Philip Reames1a1bdb22014-12-02 18:50:36 +00001//===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
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// This file includes support code use by SelectionDAGBuilder when lowering a
11// statepoint sequence in SelectionDAG IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "StatepointLowering.h"
16#include "SelectionDAGBuilder.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000020#include "llvm/CodeGen/GCMetadata.h"
Philip Reames56a03932015-01-26 18:26:35 +000021#include "llvm/CodeGen/GCStrategy.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000022#include "llvm/CodeGen/SelectionDAG.h"
23#include "llvm/CodeGen/StackMaps.h"
24#include "llvm/IR/CallingConv.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Statepoint.h"
29#include "llvm/Target/TargetLowering.h"
30#include <algorithm>
31using namespace llvm;
32
33#define DEBUG_TYPE "statepoint-lowering"
34
35STATISTIC(NumSlotsAllocatedForStatepoints,
36 "Number of stack slots allocated for statepoints");
37STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
38STATISTIC(StatepointMaxSlotsRequired,
39 "Maximum number of stack slots required for a singe statepoint");
40
Pat Gavlin022c5ac2015-04-29 21:52:45 +000041void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
Philip Reames1a1bdb22014-12-02 18:50:36 +000042 // Consistency check
43 assert(PendingGCRelocateCalls.empty() &&
44 "Trying to visit statepoint before finished processing previous one");
45 Locations.clear();
46 RelocLocations.clear();
47 NextSlotToAllocate = 0;
48 // Need to resize this on each safepoint - we need the two to stay in
49 // sync and the clear patterns of a SelectionDAGBuilder have no relation
50 // to FunctionLoweringInfo.
51 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
52 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
53 AllocatedStackSlots[i] = false;
54 }
55}
56void StatepointLoweringState::clear() {
57 Locations.clear();
58 RelocLocations.clear();
59 AllocatedStackSlots.clear();
60 assert(PendingGCRelocateCalls.empty() &&
61 "cleared before statepoint sequence completed");
62}
63
64SDValue
65StatepointLoweringState::allocateStackSlot(EVT ValueType,
66 SelectionDAGBuilder &Builder) {
67
68 NumSlotsAllocatedForStatepoints++;
69
70 // The basic scheme here is to first look for a previously created stack slot
71 // which is not in use (accounting for the fact arbitrary slots may already
72 // be reserved), or to create a new stack slot and use it.
73
74 // If this doesn't succeed in 40000 iterations, something is seriously wrong
75 for (int i = 0; i < 40000; i++) {
76 assert(Builder.FuncInfo.StatepointStackSlots.size() ==
77 AllocatedStackSlots.size() &&
78 "broken invariant");
79 const size_t NumSlots = AllocatedStackSlots.size();
80 assert(NextSlotToAllocate <= NumSlots && "broken invariant");
81
82 if (NextSlotToAllocate >= NumSlots) {
83 assert(NextSlotToAllocate == NumSlots);
84 // record stats
85 if (NumSlots + 1 > StatepointMaxSlotsRequired) {
86 StatepointMaxSlotsRequired = NumSlots + 1;
87 }
88
89 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
90 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
91 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
92 AllocatedStackSlots.push_back(true);
93 return SpillSlot;
94 }
95 if (!AllocatedStackSlots[NextSlotToAllocate]) {
96 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
97 AllocatedStackSlots[NextSlotToAllocate] = true;
98 return Builder.DAG.getFrameIndex(FI, ValueType);
99 }
100 // Note: We deliberately choose to advance this only on the failing path.
101 // Doing so on the suceeding path involes a bit of complexity that caused a
102 // minor bug previously. Unless performance shows this matters, please
103 // keep this code as simple as possible.
104 NextSlotToAllocate++;
105 }
106 llvm_unreachable("infinite loop?");
107}
108
109/// Try to find existing copies of the incoming values in stack slots used for
110/// statepoint spilling. If we can find a spill slot for the incoming value,
111/// mark that slot as allocated, and reuse the same slot for this safepoint.
112/// This helps to avoid series of loads and stores that only serve to resuffle
113/// values on the stack between calls.
114static void reservePreviousStackSlotForValue(SDValue Incoming,
115 SelectionDAGBuilder &Builder) {
116
117 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
118 // We won't need to spill this, so no need to check for previously
119 // allocated stack slots
120 return;
121 }
122
123 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
124 if (Loc.getNode()) {
125 // duplicates in input
126 return;
127 }
128
129 // Search back for the load from a stack slot pattern to find the original
130 // slot we allocated for this value. We could extend this to deal with
131 // simple modification patterns, but simple dealing with trivial load/store
132 // sequences helps a lot already.
133 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
134 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
135 const int Index = FI->getIndex();
136 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
137 Builder.FuncInfo.StatepointStackSlots.end(), Index);
138 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
139 // not one of the lowering stack slots, can't reuse!
140 // TODO: Actually, we probably could reuse the stack slot if the value
141 // hasn't changed at all, but we'd need to look for intervening writes
142 return;
143 } else {
144 // This is one of our dedicated lowering slots
145 const int Offset =
146 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
147 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
148 // stack slot already assigned to someone else, can't use it!
149 // TODO: currently we reserve space for gc arguments after doing
150 // normal allocation for deopt arguments. We should reserve for
151 // _all_ deopt and gc arguments, then start allocating. This
152 // will prevent some moves being inserted when vm state changes,
153 // but gc state doesn't between two calls.
154 return;
155 }
156 // Reserve this stack slot
157 Builder.StatepointLowering.reserveStackSlot(Offset);
158 }
159
160 // Cache this slot so we find it when going through the normal
161 // assignment loop.
162 SDValue Loc =
163 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
164
165 Builder.StatepointLowering.setLocation(Incoming, Loc);
166 }
167 }
168
169 // TODO: handle case where a reloaded value flows through a phi to
170 // another safepoint. e.g.
171 // bb1:
172 // a' = relocated...
173 // bb2: % pred: bb1, bb3, bb4, etc.
174 // a_phi = phi(a', ...)
175 // statepoint ... a_phi
176 // NOTE: This will require reasoning about cross basic block values. This is
177 // decidedly non trivial and this might not be the right place to do it. We
178 // don't really have the information we need here...
179
180 // TODO: handle simple updates. If a value is modified and the original
181 // value is no longer live, it would be nice to put the modified value in the
182 // same slot. This allows folding of the memory accesses for some
183 // instructions types (like an increment).
184 // statepoint (i)
185 // i1 = i+1
186 // statepoint (i1)
187}
188
189/// Remove any duplicate (as SDValues) from the derived pointer pairs. This
190/// is not required for correctness. It's purpose is to reduce the size of
191/// StackMap section. It has no effect on the number of spill slots required
192/// or the actual lowering.
193static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
194 SmallVectorImpl<const Value *> &Ptrs,
195 SmallVectorImpl<const Value *> &Relocs,
196 SelectionDAGBuilder &Builder) {
197
198 // This is horribly ineffecient, but I don't care right now
199 SmallSet<SDValue, 64> Seen;
200
201 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
202 for (size_t i = 0; i < Ptrs.size(); i++) {
203 SDValue SD = Builder.getValue(Ptrs[i]);
204 // Only add non-duplicates
205 if (Seen.count(SD) == 0) {
206 NewBases.push_back(Bases[i]);
207 NewPtrs.push_back(Ptrs[i]);
208 NewRelocs.push_back(Relocs[i]);
209 }
210 Seen.insert(SD);
211 }
212 assert(Bases.size() >= NewBases.size());
213 assert(Ptrs.size() >= NewPtrs.size());
214 assert(Relocs.size() >= NewRelocs.size());
215 Bases = NewBases;
216 Ptrs = NewPtrs;
217 Relocs = NewRelocs;
218 assert(Ptrs.size() == Bases.size());
219 assert(Ptrs.size() == Relocs.size());
220}
221
222/// Extract call from statepoint, lower it and return pointer to the
223/// call node. Also update NodeMap so that getValue(statepoint) will
224/// reference lowered call result
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000225static SDNode *
226lowerCallFromStatepoint(ImmutableStatepoint ISP, MachineBasicBlock *LandingPad,
227 SelectionDAGBuilder &Builder,
228 SmallVectorImpl<SDValue> &PendingExports) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000229
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000230 ImmutableCallSite CS(ISP.getCallSite());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000231
Sanjoy Das499d7032015-05-06 02:36:26 +0000232 SDValue ActualCallee = Builder.getValue(ISP.getActualCallee());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000233
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000234 // Handle immediate and symbolic callees.
235 if (auto *ConstCallee = dyn_cast<ConstantSDNode>(ActualCallee.getNode()))
236 ActualCallee = Builder.DAG.getIntPtrConstant(ConstCallee->getZExtValue(),
237 Builder.getCurSDLoc(),
238 /*isTarget=*/true);
239 else if (auto *SymbolicCallee =
240 dyn_cast<GlobalAddressSDNode>(ActualCallee.getNode()))
241 ActualCallee = Builder.DAG.getTargetGlobalAddress(
242 SymbolicCallee->getGlobal(), SDLoc(SymbolicCallee),
243 SymbolicCallee->getValueType(0));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000244
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000245 assert(CS.getCallingConv() != CallingConv::AnyReg &&
246 "anyregcc is not supported on statepoints!");
247
Sanjoy Das499d7032015-05-06 02:36:26 +0000248 Type *DefTy = ISP.getActualReturnType();
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000249 bool HasDef = !DefTy->isVoidTy();
250
251 SDValue ReturnValue, CallEndVal;
252 std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
Sanjoy Das499d7032015-05-06 02:36:26 +0000253 ISP.getCallSite(), ISP.callArgsBeginOffset(), ISP.getNumCallArgs(),
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000254 ActualCallee, DefTy, LandingPad, false /* IsPatchPoint */);
255
256 SDNode *CallEnd = CallEndVal.getNode();
257
258 // Get a call instruction from the call sequence chain. Tail calls are not
259 // allowed. The following code is essentially reverse engineering X86's
260 // LowerCallTo.
261 //
262 // We are expecting DAG to have the following form:
263 //
264 // ch = eh_label (only in case of invoke statepoint)
265 // ch, glue = callseq_start ch
266 // ch, glue = X86::Call ch, glue
267 // ch, glue = callseq_end ch, glue
268 // get_return_value ch, glue
269 //
270 // get_return_value can either be a CopyFromReg to grab the return value from
271 // %RAX, or it can be a LOAD to load a value returned by reference via a stack
272 // slot.
273
274 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg ||
275 CallEnd->getOpcode() == ISD::LOAD))
276 CallEnd = CallEnd->getOperand(0).getNode();
277
278 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
279
Philip Reames1a1bdb22014-12-02 18:50:36 +0000280 if (HasDef) {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000281 if (CS.isInvoke()) {
282 // Result value will be used in different basic block for invokes
283 // so we need to export it now. But statepoint call has a different type
284 // than the actuall call. It means that standart exporting mechanism will
285 // create register of the wrong type. So instead we need to create
286 // register with correct type and save value into it manually.
287 // TODO: To eliminate this problem we can remove gc.result intrinsics
288 // completelly and make statepoint call to return a tuple.
Sanjoy Das499d7032015-05-06 02:36:26 +0000289 unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000290 RegsForValue RFV(*Builder.DAG.getContext(),
291 Builder.DAG.getTargetLoweringInfo(), Reg,
Sanjoy Das499d7032015-05-06 02:36:26 +0000292 ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000293 SDValue Chain = Builder.DAG.getEntryNode();
294
295 RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
296 nullptr);
297 PendingExports.push_back(Chain);
298 Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000299 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000300 // The value of the statepoint itself will be the value of call itself.
301 // We'll replace the actually call node shortly. gc_result will grab
302 // this value.
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000303 Builder.setValue(CS.getInstruction(), ReturnValue);
Igor Laevsky85f7f722015-03-10 16:26:48 +0000304 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000305 } else {
306 // The token value is never used from here on, just generate a poison value
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000307 Builder.setValue(CS.getInstruction(),
308 Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000309 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000310
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000311 return CallEnd->getOperand(0).getNode();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000312}
313
314/// Callect all gc pointers coming into statepoint intrinsic, clean them up,
315/// and return two arrays:
316/// Bases - base pointers incoming to this statepoint
317/// Ptrs - derived pointers incoming to this statepoint
318/// Relocs - the gc_relocate corresponding to each base/ptr pair
319/// Elements of this arrays should be in one-to-one correspondence with each
320/// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000321static void getIncomingStatepointGCValues(
322 SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
323 SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
324 SelectionDAGBuilder &Builder) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000325 for (GCRelocateOperands relocateOpers :
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000326 StatepointSite.getRelocates(StatepointSite)) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000327 Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
Sanjoy Das499d7032015-05-06 02:36:26 +0000328 Bases.push_back(relocateOpers.getBasePtr());
329 Ptrs.push_back(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000330 }
331
332 // Remove any redundant llvm::Values which map to the same SDValue as another
333 // input. Also has the effect of removing duplicates in the original
334 // llvm::Value input list as well. This is a useful optimization for
335 // reducing the size of the StackMap section. It has no other impact.
336 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
337
338 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
339}
340
341/// Spill a value incoming to the statepoint. It might be either part of
342/// vmstate
343/// or gcstate. In both cases unconditionally spill it on the stack unless it
344/// is a null constant. Return pair with first element being frame index
345/// containing saved value and second element with outgoing chain from the
346/// emitted store
347static std::pair<SDValue, SDValue>
348spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
349 SelectionDAGBuilder &Builder) {
350 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
351
352 // Emit new store if we didn't do it for this ptr before
353 if (!Loc.getNode()) {
354 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
355 Builder);
356 assert(isa<FrameIndexSDNode>(Loc));
357 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
358 // We use TargetFrameIndex so that isel will not select it into LEA
359 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
360
361 // TODO: We can create TokenFactor node instead of
362 // chaining stores one after another, this may allow
363 // a bit more optimal scheduling for them
364 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
365 MachinePointerInfo::getFixedStack(Index),
366 false, false, 0);
367
368 Builder.StatepointLowering.setLocation(Incoming, Loc);
369 }
370
371 assert(Loc.getNode());
372 return std::make_pair(Loc, Chain);
373}
374
375/// Lower a single value incoming to a statepoint node. This value can be
376/// either a deopt value or a gc value, the handling is the same. We special
377/// case constants and allocas, then fall back to spilling if required.
378static void lowerIncomingStatepointValue(SDValue Incoming,
379 SmallVectorImpl<SDValue> &Ops,
380 SelectionDAGBuilder &Builder) {
381 SDValue Chain = Builder.getRoot();
382
383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
384 // If the original value was a constant, make sure it gets recorded as
385 // such in the stackmap. This is required so that the consumer can
386 // parse any internal format to the deopt state. It also handles null
387 // pointers and other constant pointers in GC states
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000388 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp,
389 Builder.getCurSDLoc(),
390 MVT::i64));
391 Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(),
392 Builder.getCurSDLoc(),
393 MVT::i64));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000394 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
Philip Reamesf8f09332015-03-27 04:52:48 +0000395 // This handles allocas as arguments to the statepoint (this is only
396 // really meaningful for a deopt value. For GC, we'd be trying to
397 // relocate the address of the alloca itself?)
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000398 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000399 Incoming.getValueType()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000400 } else {
401 // Otherwise, locate a spill slot and explicitly spill it so it
402 // can be found by the runtime later. We currently do not support
403 // tracking values through callee saved registers to their eventual
404 // spill location. This would be a useful optimization, but would
405 // need to be optional since it requires a lot of complexity on the
406 // runtime side which not all would support.
407 std::pair<SDValue, SDValue> Res =
408 spillIncomingStatepointValue(Incoming, Chain, Builder);
409 Ops.push_back(Res.first);
410 Chain = Res.second;
411 }
412
413 Builder.DAG.setRoot(Chain);
414}
415
416/// Lower deopt state and gc pointer arguments of the statepoint. The actual
417/// lowering is described in lowerIncomingStatepointValue. This function is
418/// responsible for lowering everything in the right position and playing some
419/// tricks to avoid redundant stack manipulation where possible. On
420/// completion, 'Ops' will contain ready to use operands for machine code
421/// statepoint. The chain nodes will have already been created and the DAG root
422/// will be set to the last value spilled (if any were).
423static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000424 ImmutableStatepoint StatepointSite,
Philip Reames1a1bdb22014-12-02 18:50:36 +0000425 SelectionDAGBuilder &Builder) {
426
427 // Lower the deopt and gc arguments for this statepoint. Layout will
428 // be: deopt argument length, deopt arguments.., gc arguments...
429
430 SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000431 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
432 Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000433
Philip Reames4ac17a32015-01-07 19:07:50 +0000434#ifndef NDEBUG
435 // Check that each of the gc pointer and bases we've gotten out of the
436 // safepoint is something the strategy thinks might be a pointer into the GC
437 // heap. This is basically just here to help catch errors during statepoint
438 // insertion. TODO: This should actually be in the Verifier, but we can't get
439 // to the GCStrategy from there (yet).
Philip Reamese1bf2702015-03-27 05:09:33 +0000440 GCStrategy &S = Builder.GFI->getStrategy();
441 for (const Value *V : Bases) {
442 auto Opt = S.isGCManagedPointer(V);
443 if (Opt.hasValue()) {
444 assert(Opt.getValue() &&
445 "non gc managed base pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000446 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000447 }
448 for (const Value *V : Ptrs) {
449 auto Opt = S.isGCManagedPointer(V);
450 if (Opt.hasValue()) {
451 assert(Opt.getValue() &&
452 "non gc managed derived pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000453 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000454 }
455 for (const Value *V : Relocations) {
456 auto Opt = S.isGCManagedPointer(V);
457 if (Opt.hasValue()) {
458 assert(Opt.getValue() && "non gc managed pointer relocated");
Philip Reames4ac17a32015-01-07 19:07:50 +0000459 }
460 }
461#endif
462
Philip Reames1a1bdb22014-12-02 18:50:36 +0000463 // Before we actually start lowering (and allocating spill slots for values),
464 // reserve any stack slots which we judge to be profitable to reuse for a
465 // particular value. This is purely an optimization over the code below and
466 // doesn't change semantics at all. It is important for performance that we
467 // reserve slots for both deopt and gc values before lowering either.
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000468 for (auto I = StatepointSite.vm_state_begin() + 1,
469 E = StatepointSite.vm_state_end();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000470 I != E; ++I) {
471 Value *V = *I;
472 SDValue Incoming = Builder.getValue(V);
473 reservePreviousStackSlotForValue(Incoming, Builder);
474 }
475 for (unsigned i = 0; i < Bases.size() * 2; ++i) {
476 // Even elements will contain base, odd elements - derived ptr
477 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
478 SDValue Incoming = Builder.getValue(V);
479 reservePreviousStackSlotForValue(Incoming, Builder);
480 }
481
482 // First, prefix the list with the number of unique values to be
483 // lowered. Note that this is the number of *Values* not the
484 // number of SDValues required to lower them.
Sanjoy Das499d7032015-05-06 02:36:26 +0000485 const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000486 Ops.push_back( Builder.DAG.getTargetConstant(StackMaps::ConstantOp,
487 Builder.getCurSDLoc(),
488 MVT::i64));
489 Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, Builder.getCurSDLoc(),
490 MVT::i64));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000491
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000492 assert(NumVMSArgs + 1 == std::distance(StatepointSite.vm_state_begin(),
493 StatepointSite.vm_state_end()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000494
495 // The vm state arguments are lowered in an opaque manner. We do
496 // not know what type of values are contained within. We skip the
497 // first one since that happens to be the total number we lowered
498 // explicitly just above. We could have left it in the loop and
499 // not done it explicitly, but it's far easier to understand this
500 // way.
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000501 for (auto I = StatepointSite.vm_state_begin() + 1,
502 E = StatepointSite.vm_state_end();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000503 I != E; ++I) {
504 const Value *V = *I;
505 SDValue Incoming = Builder.getValue(V);
506 lowerIncomingStatepointValue(Incoming, Ops, Builder);
507 }
508
509 // Finally, go ahead and lower all the gc arguments. There's no prefixed
510 // length for this one. After lowering, we'll have the base and pointer
511 // arrays interwoven with each (lowered) base pointer immediately followed by
512 // it's (lowered) derived pointer. i.e
513 // (base[0], ptr[0], base[1], ptr[1], ...)
514 for (unsigned i = 0; i < Bases.size() * 2; ++i) {
515 // Even elements will contain base, odd elements - derived ptr
516 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
517 SDValue Incoming = Builder.getValue(V);
518 lowerIncomingStatepointValue(Incoming, Ops, Builder);
519 }
Philip Reamesf8f09332015-03-27 04:52:48 +0000520
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000521 // If there are any explicit spill slots passed to the statepoint, record
Philip Reamesf8f09332015-03-27 04:52:48 +0000522 // them, but otherwise do not do anything special. These are user provided
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000523 // allocas and give control over placement to the consumer. In this case,
Philip Reamesf8f09332015-03-27 04:52:48 +0000524 // it is the contents of the slot which may get updated, not the pointer to
525 // the alloca
526 for (Value *V : StatepointSite.gc_args()) {
527 SDValue Incoming = Builder.getValue(V);
528 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
529 // This handles allocas as arguments to the statepoint
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000530 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000531 Incoming.getValueType()));
Philip Reamesf8f09332015-03-27 04:52:48 +0000532 }
533 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000534}
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000535
Philip Reames1a1bdb22014-12-02 18:50:36 +0000536void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000537 // Check some preconditions for sanity
538 assert(isStatepoint(&CI) &&
539 "function called must be the statepoint function");
540
541 LowerStatepoint(ImmutableStatepoint(&CI));
542}
543
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000544void SelectionDAGBuilder::LowerStatepoint(
545 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000546 // The basic scheme here is that information about both the original call and
547 // the safepoint is encoded in the CallInst. We create a temporary call and
548 // lower it, then reverse engineer the calling sequence.
549
Philip Reames1a1bdb22014-12-02 18:50:36 +0000550 NumOfStatepoints++;
551 // Clear state
552 StatepointLowering.startNewStatepoint(*this);
553
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000554 ImmutableCallSite CS(ISP.getCallSite());
555
Philip Reames1a1bdb22014-12-02 18:50:36 +0000556#ifndef NDEBUG
557 // Consistency check
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000558 for (const User *U : CS->users()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000559 const CallInst *Call = cast<CallInst>(U);
560 if (isGCRelocate(Call))
561 StatepointLowering.scheduleRelocCall(*Call);
562 }
563#endif
564
Philip Reames72fbe7a2014-12-02 21:01:48 +0000565#ifndef NDEBUG
566 // If this is a malformed statepoint, report it early to simplify debugging.
567 // This should catch any IR level mistake that's made when constructing or
568 // transforming statepoints.
569 ISP.verify();
Philip Reames4ac17a32015-01-07 19:07:50 +0000570
571 // Check that the associated GCStrategy expects to encounter statepoints.
572 // TODO: This if should become an assert. For now, we allow the GCStrategy
573 // to be optional for backwards compatibility. This will only last a short
574 // period (i.e. a couple of weeks).
Philip Reamese1bf2702015-03-27 05:09:33 +0000575 assert(GFI->getStrategy().useStatepoints() &&
576 "GCStrategy does not expect to encounter statepoints");
Philip Reames72fbe7a2014-12-02 21:01:48 +0000577#endif
578
Philip Reames1a1bdb22014-12-02 18:50:36 +0000579 // Lower statepoint vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000580 SmallVector<SDValue, 10> LoweredMetaArgs;
581 lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000582
583 // Get call node, we will replace it later with statepoint
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000584 SDNode *CallNode =
585 lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000586
587 // Construct the actual STATEPOINT node with all the appropriate arguments
588 // and return values.
589
590 // TODO: Currently, all of these operands are being marked as read/write in
591 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
592 // and flags to be read-only.
593 SmallVector<SDValue, 40> Ops;
594
595 // Calculate and push starting position of vmstate arguments
596 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
597 SDValue Glue;
598 if (CallNode->getGluedNode()) {
599 // Glue is always last operand
600 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
601 }
602 // Get number of arguments incoming directly into call node
603 unsigned NumCallRegArgs =
604 CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000605 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000606
607 // Add call target
608 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
609 Ops.push_back(CallTarget);
610
611 // Add call arguments
612 // Get position of register mask in the call
613 SDNode::op_iterator RegMaskIt;
614 if (Glue.getNode())
615 RegMaskIt = CallNode->op_end() - 2;
616 else
617 RegMaskIt = CallNode->op_end() - 1;
618 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
619
620 // Add a leading constant argument with the Flags and the calling convention
621 // masked together
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000622 CallingConv::ID CallConv = CS.getCallingConv();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000623 int Flags = cast<ConstantInt>(CS.getArgument(2))->getZExtValue();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000624 assert(Flags == 0 && "not expected to be used");
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000625 Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, getCurSDLoc(),
626 MVT::i64));
627 Ops.push_back(DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1),
628 getCurSDLoc(), MVT::i64));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000629
630 // Insert all vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000631 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000632
633 // Add register mask from call node
634 Ops.push_back(*RegMaskIt);
635
636 // Add chain
637 Ops.push_back(CallNode->getOperand(0));
638
639 // Same for the glue, but we add it only if original call had it
640 if (Glue.getNode())
641 Ops.push_back(Glue);
642
Benjamin Kramerea68a942015-02-19 15:26:17 +0000643 // Compute return values. Provide a glue output since we consume one as
644 // input. This allows someone else to chain off us as needed.
645 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000646
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000647 SDNode *StatepointMCNode =
648 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000649
650 // Replace original call
651 DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root
652 // Remove originall call node
653 DAG.DeleteNode(CallNode);
654
655 // DON'T set the root - under the assumption that it's already set past the
656 // inserted node we created.
657
658 // TODO: A better future implementation would be to emit a single variable
659 // argument, variable return value STATEPOINT node here and then hookup the
660 // return value of each gc.relocate to the respective output of the
661 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
662 // to actually be possible today.
663}
664
665void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
666 // The result value of the gc_result is simply the result of the actual
667 // call. We've already emitted this, so just grab the value.
668 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000669 assert(isStatepoint(I) && "first argument must be a statepoint token");
Philip Reames1a1bdb22014-12-02 18:50:36 +0000670
Igor Laevsky85f7f722015-03-10 16:26:48 +0000671 if (isa<InvokeInst>(I)) {
672 // For invokes we should have stored call result in a virtual register.
673 // We can not use default getValue() functionality to copy value from this
674 // register because statepoint and actuall call return types can be
675 // different, and getValue() will use CopyFromReg of the wrong type,
676 // which is always i32 in our case.
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000677 PointerType *CalleeType =
Sanjoy Das499d7032015-05-06 02:36:26 +0000678 cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000679 Type *RetTy =
680 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
Igor Laevsky85f7f722015-03-10 16:26:48 +0000681 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
682
683 assert(CopyFromReg.getNode());
684 setValue(&CI, CopyFromReg);
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000685 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000686 setValue(&CI, getValue(I));
687 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000688}
689
690void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
691#ifndef NDEBUG
692 // Consistency check
693 StatepointLowering.relocCallVisited(CI);
694#endif
695
696 GCRelocateOperands relocateOpers(&CI);
Sanjoy Das499d7032015-05-06 02:36:26 +0000697 SDValue SD = getValue(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000698
699 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
700 // We didn't need to spill these special cases (constants and allocas).
701 // See the handling in spillIncomingValueForStatepoint for detail.
702 setValue(&CI, SD);
703 return;
704 }
705
706 SDValue Loc = StatepointLowering.getRelocLocation(SD);
707 // Emit new load if we did not emit it before
708 if (!Loc.getNode()) {
709 SDValue SpillSlot = StatepointLowering.getLocation(SD);
710 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
711
712 // Be conservative: flush all pending loads
713 // TODO: Probably we can be less restrictive on this,
714 // it may allow more scheduling opprtunities
715 SDValue Chain = getRoot();
716
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000717 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
718 MachinePointerInfo::getFixedStack(FI), false, false,
719 false, 0);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000720
721 StatepointLowering.setRelocLocation(SD, Loc);
722
723 // Again, be conservative, don't emit pending loads
724 DAG.setRoot(Loc.getValue(1));
725 }
726
727 assert(Loc.getNode());
728 setValue(&CI, Loc);
729}