blob: 2d4ab6c5077a2322a1fcba63f6aa84381322cc47 [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 Gavlinc7dc6d6ee2015-05-12 19:50:19 +000041static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
42 SelectionDAGBuilder &Builder, uint64_t Value) {
43 SDLoc L = Builder.getCurSDLoc();
44 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
45 MVT::i64));
46 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
47}
48
Pat Gavlin022c5ac2015-04-29 21:52:45 +000049void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
Philip Reames1a1bdb22014-12-02 18:50:36 +000050 // Consistency check
51 assert(PendingGCRelocateCalls.empty() &&
52 "Trying to visit statepoint before finished processing previous one");
53 Locations.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +000054 NextSlotToAllocate = 0;
55 // Need to resize this on each safepoint - we need the two to stay in
56 // sync and the clear patterns of a SelectionDAGBuilder have no relation
57 // to FunctionLoweringInfo.
58 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
59 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
60 AllocatedStackSlots[i] = false;
61 }
62}
Igor Laevsky423bc9ec2015-05-20 11:37:25 +000063
Philip Reames1a1bdb22014-12-02 18:50:36 +000064void StatepointLoweringState::clear() {
65 Locations.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +000066 AllocatedStackSlots.clear();
67 assert(PendingGCRelocateCalls.empty() &&
68 "cleared before statepoint sequence completed");
69}
70
71SDValue
72StatepointLoweringState::allocateStackSlot(EVT ValueType,
73 SelectionDAGBuilder &Builder) {
74
75 NumSlotsAllocatedForStatepoints++;
76
77 // The basic scheme here is to first look for a previously created stack slot
78 // which is not in use (accounting for the fact arbitrary slots may already
79 // be reserved), or to create a new stack slot and use it.
80
81 // If this doesn't succeed in 40000 iterations, something is seriously wrong
82 for (int i = 0; i < 40000; i++) {
83 assert(Builder.FuncInfo.StatepointStackSlots.size() ==
84 AllocatedStackSlots.size() &&
85 "broken invariant");
86 const size_t NumSlots = AllocatedStackSlots.size();
87 assert(NextSlotToAllocate <= NumSlots && "broken invariant");
88
89 if (NextSlotToAllocate >= NumSlots) {
90 assert(NextSlotToAllocate == NumSlots);
91 // record stats
92 if (NumSlots + 1 > StatepointMaxSlotsRequired) {
93 StatepointMaxSlotsRequired = NumSlots + 1;
94 }
95
96 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
97 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
98 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
99 AllocatedStackSlots.push_back(true);
100 return SpillSlot;
101 }
102 if (!AllocatedStackSlots[NextSlotToAllocate]) {
103 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
104 AllocatedStackSlots[NextSlotToAllocate] = true;
105 return Builder.DAG.getFrameIndex(FI, ValueType);
106 }
107 // Note: We deliberately choose to advance this only on the failing path.
108 // Doing so on the suceeding path involes a bit of complexity that caused a
109 // minor bug previously. Unless performance shows this matters, please
110 // keep this code as simple as possible.
111 NextSlotToAllocate++;
112 }
113 llvm_unreachable("infinite loop?");
114}
115
116/// Try to find existing copies of the incoming values in stack slots used for
117/// statepoint spilling. If we can find a spill slot for the incoming value,
118/// mark that slot as allocated, and reuse the same slot for this safepoint.
119/// This helps to avoid series of loads and stores that only serve to resuffle
120/// values on the stack between calls.
121static void reservePreviousStackSlotForValue(SDValue Incoming,
122 SelectionDAGBuilder &Builder) {
123
124 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
125 // We won't need to spill this, so no need to check for previously
126 // allocated stack slots
127 return;
128 }
129
130 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
131 if (Loc.getNode()) {
132 // duplicates in input
133 return;
134 }
135
136 // Search back for the load from a stack slot pattern to find the original
137 // slot we allocated for this value. We could extend this to deal with
138 // simple modification patterns, but simple dealing with trivial load/store
139 // sequences helps a lot already.
140 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
141 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
142 const int Index = FI->getIndex();
143 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
144 Builder.FuncInfo.StatepointStackSlots.end(), Index);
145 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
146 // not one of the lowering stack slots, can't reuse!
147 // TODO: Actually, we probably could reuse the stack slot if the value
148 // hasn't changed at all, but we'd need to look for intervening writes
149 return;
150 } else {
151 // This is one of our dedicated lowering slots
152 const int Offset =
153 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
154 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
155 // stack slot already assigned to someone else, can't use it!
156 // TODO: currently we reserve space for gc arguments after doing
157 // normal allocation for deopt arguments. We should reserve for
158 // _all_ deopt and gc arguments, then start allocating. This
159 // will prevent some moves being inserted when vm state changes,
160 // but gc state doesn't between two calls.
161 return;
162 }
163 // Reserve this stack slot
164 Builder.StatepointLowering.reserveStackSlot(Offset);
165 }
166
167 // Cache this slot so we find it when going through the normal
168 // assignment loop.
169 SDValue Loc =
170 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
171
172 Builder.StatepointLowering.setLocation(Incoming, Loc);
173 }
174 }
175
176 // TODO: handle case where a reloaded value flows through a phi to
177 // another safepoint. e.g.
178 // bb1:
179 // a' = relocated...
180 // bb2: % pred: bb1, bb3, bb4, etc.
181 // a_phi = phi(a', ...)
182 // statepoint ... a_phi
183 // NOTE: This will require reasoning about cross basic block values. This is
184 // decidedly non trivial and this might not be the right place to do it. We
185 // don't really have the information we need here...
186
187 // TODO: handle simple updates. If a value is modified and the original
188 // value is no longer live, it would be nice to put the modified value in the
189 // same slot. This allows folding of the memory accesses for some
190 // instructions types (like an increment).
191 // statepoint (i)
192 // i1 = i+1
193 // statepoint (i1)
194}
195
196/// Remove any duplicate (as SDValues) from the derived pointer pairs. This
197/// is not required for correctness. It's purpose is to reduce the size of
198/// StackMap section. It has no effect on the number of spill slots required
199/// or the actual lowering.
200static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
201 SmallVectorImpl<const Value *> &Ptrs,
202 SmallVectorImpl<const Value *> &Relocs,
203 SelectionDAGBuilder &Builder) {
204
205 // This is horribly ineffecient, but I don't care right now
206 SmallSet<SDValue, 64> Seen;
207
208 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
209 for (size_t i = 0; i < Ptrs.size(); i++) {
210 SDValue SD = Builder.getValue(Ptrs[i]);
211 // Only add non-duplicates
212 if (Seen.count(SD) == 0) {
213 NewBases.push_back(Bases[i]);
214 NewPtrs.push_back(Ptrs[i]);
215 NewRelocs.push_back(Relocs[i]);
216 }
217 Seen.insert(SD);
218 }
219 assert(Bases.size() >= NewBases.size());
220 assert(Ptrs.size() >= NewPtrs.size());
221 assert(Relocs.size() >= NewRelocs.size());
222 Bases = NewBases;
223 Ptrs = NewPtrs;
224 Relocs = NewRelocs;
225 assert(Ptrs.size() == Bases.size());
226 assert(Ptrs.size() == Relocs.size());
227}
228
229/// Extract call from statepoint, lower it and return pointer to the
230/// call node. Also update NodeMap so that getValue(statepoint) will
231/// reference lowered call result
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000232static SDNode *
233lowerCallFromStatepoint(ImmutableStatepoint ISP, MachineBasicBlock *LandingPad,
234 SelectionDAGBuilder &Builder,
235 SmallVectorImpl<SDValue> &PendingExports) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000236
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000237 ImmutableCallSite CS(ISP.getCallSite());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000238
Sanjoy Das499d7032015-05-06 02:36:26 +0000239 SDValue ActualCallee = Builder.getValue(ISP.getActualCallee());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000240
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000241 // Handle immediate and symbolic callees.
242 if (auto *ConstCallee = dyn_cast<ConstantSDNode>(ActualCallee.getNode()))
243 ActualCallee = Builder.DAG.getIntPtrConstant(ConstCallee->getZExtValue(),
244 Builder.getCurSDLoc(),
245 /*isTarget=*/true);
246 else if (auto *SymbolicCallee =
247 dyn_cast<GlobalAddressSDNode>(ActualCallee.getNode()))
248 ActualCallee = Builder.DAG.getTargetGlobalAddress(
249 SymbolicCallee->getGlobal(), SDLoc(SymbolicCallee),
250 SymbolicCallee->getValueType(0));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000251
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000252 assert(CS.getCallingConv() != CallingConv::AnyReg &&
253 "anyregcc is not supported on statepoints!");
254
Sanjoy Das499d7032015-05-06 02:36:26 +0000255 Type *DefTy = ISP.getActualReturnType();
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000256 bool HasDef = !DefTy->isVoidTy();
257
258 SDValue ReturnValue, CallEndVal;
259 std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
Sanjoy Das4bfb4722015-05-06 02:36:31 +0000260 ISP.getCallSite(), ImmutableStatepoint::CallArgsBeginPos,
261 ISP.getNumCallArgs(), ActualCallee, DefTy, LandingPad,
262 false /* IsPatchPoint */);
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000263
264 SDNode *CallEnd = CallEndVal.getNode();
265
266 // Get a call instruction from the call sequence chain. Tail calls are not
267 // allowed. The following code is essentially reverse engineering X86's
268 // LowerCallTo.
269 //
270 // We are expecting DAG to have the following form:
271 //
272 // ch = eh_label (only in case of invoke statepoint)
273 // ch, glue = callseq_start ch
274 // ch, glue = X86::Call ch, glue
275 // ch, glue = callseq_end ch, glue
276 // get_return_value ch, glue
277 //
278 // get_return_value can either be a CopyFromReg to grab the return value from
279 // %RAX, or it can be a LOAD to load a value returned by reference via a stack
280 // slot.
281
282 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg ||
283 CallEnd->getOpcode() == ISD::LOAD))
284 CallEnd = CallEnd->getOperand(0).getNode();
285
286 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
287
Philip Reames1a1bdb22014-12-02 18:50:36 +0000288 if (HasDef) {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000289 if (CS.isInvoke()) {
290 // Result value will be used in different basic block for invokes
291 // so we need to export it now. But statepoint call has a different type
292 // than the actuall call. It means that standart exporting mechanism will
293 // create register of the wrong type. So instead we need to create
294 // register with correct type and save value into it manually.
295 // TODO: To eliminate this problem we can remove gc.result intrinsics
296 // completelly and make statepoint call to return a tuple.
Sanjoy Das499d7032015-05-06 02:36:26 +0000297 unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000298 RegsForValue RFV(*Builder.DAG.getContext(),
299 Builder.DAG.getTargetLoweringInfo(), Reg,
Sanjoy Das499d7032015-05-06 02:36:26 +0000300 ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000301 SDValue Chain = Builder.DAG.getEntryNode();
302
303 RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
304 nullptr);
305 PendingExports.push_back(Chain);
306 Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000307 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000308 // The value of the statepoint itself will be the value of call itself.
309 // We'll replace the actually call node shortly. gc_result will grab
310 // this value.
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000311 Builder.setValue(CS.getInstruction(), ReturnValue);
Igor Laevsky85f7f722015-03-10 16:26:48 +0000312 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000313 } else {
314 // The token value is never used from here on, just generate a poison value
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000315 Builder.setValue(CS.getInstruction(),
316 Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000317 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000318
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000319 return CallEnd->getOperand(0).getNode();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000320}
321
322/// Callect all gc pointers coming into statepoint intrinsic, clean them up,
323/// and return two arrays:
324/// Bases - base pointers incoming to this statepoint
325/// Ptrs - derived pointers incoming to this statepoint
326/// Relocs - the gc_relocate corresponding to each base/ptr pair
327/// Elements of this arrays should be in one-to-one correspondence with each
328/// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000329static void getIncomingStatepointGCValues(
330 SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
331 SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
332 SelectionDAGBuilder &Builder) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000333 for (GCRelocateOperands relocateOpers :
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000334 StatepointSite.getRelocates(StatepointSite)) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000335 Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
Sanjoy Das499d7032015-05-06 02:36:26 +0000336 Bases.push_back(relocateOpers.getBasePtr());
337 Ptrs.push_back(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000338 }
339
340 // Remove any redundant llvm::Values which map to the same SDValue as another
341 // input. Also has the effect of removing duplicates in the original
342 // llvm::Value input list as well. This is a useful optimization for
343 // reducing the size of the StackMap section. It has no other impact.
344 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
345
346 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
347}
348
349/// Spill a value incoming to the statepoint. It might be either part of
350/// vmstate
351/// or gcstate. In both cases unconditionally spill it on the stack unless it
352/// is a null constant. Return pair with first element being frame index
353/// containing saved value and second element with outgoing chain from the
354/// emitted store
355static std::pair<SDValue, SDValue>
356spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
357 SelectionDAGBuilder &Builder) {
358 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
359
360 // Emit new store if we didn't do it for this ptr before
361 if (!Loc.getNode()) {
362 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
363 Builder);
364 assert(isa<FrameIndexSDNode>(Loc));
365 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
366 // We use TargetFrameIndex so that isel will not select it into LEA
367 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
368
369 // TODO: We can create TokenFactor node instead of
370 // chaining stores one after another, this may allow
371 // a bit more optimal scheduling for them
372 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
373 MachinePointerInfo::getFixedStack(Index),
374 false, false, 0);
375
376 Builder.StatepointLowering.setLocation(Incoming, Loc);
377 }
378
379 assert(Loc.getNode());
380 return std::make_pair(Loc, Chain);
381}
382
383/// Lower a single value incoming to a statepoint node. This value can be
384/// either a deopt value or a gc value, the handling is the same. We special
385/// case constants and allocas, then fall back to spilling if required.
386static void lowerIncomingStatepointValue(SDValue Incoming,
387 SmallVectorImpl<SDValue> &Ops,
388 SelectionDAGBuilder &Builder) {
389 SDValue Chain = Builder.getRoot();
390
391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
392 // If the original value was a constant, make sure it gets recorded as
393 // such in the stackmap. This is required so that the consumer can
394 // parse any internal format to the deopt state. It also handles null
395 // pointers and other constant pointers in GC states
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000396 pushStackMapConstant(Ops, Builder, C->getSExtValue());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000397 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
Philip Reamesf8f09332015-03-27 04:52:48 +0000398 // This handles allocas as arguments to the statepoint (this is only
399 // really meaningful for a deopt value. For GC, we'd be trying to
400 // relocate the address of the alloca itself?)
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000401 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000402 Incoming.getValueType()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000403 } else {
404 // Otherwise, locate a spill slot and explicitly spill it so it
405 // can be found by the runtime later. We currently do not support
406 // tracking values through callee saved registers to their eventual
407 // spill location. This would be a useful optimization, but would
408 // need to be optional since it requires a lot of complexity on the
409 // runtime side which not all would support.
410 std::pair<SDValue, SDValue> Res =
411 spillIncomingStatepointValue(Incoming, Chain, Builder);
412 Ops.push_back(Res.first);
413 Chain = Res.second;
414 }
415
416 Builder.DAG.setRoot(Chain);
417}
418
419/// Lower deopt state and gc pointer arguments of the statepoint. The actual
420/// lowering is described in lowerIncomingStatepointValue. This function is
421/// responsible for lowering everything in the right position and playing some
422/// tricks to avoid redundant stack manipulation where possible. On
423/// completion, 'Ops' will contain ready to use operands for machine code
424/// statepoint. The chain nodes will have already been created and the DAG root
425/// will be set to the last value spilled (if any were).
426static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000427 ImmutableStatepoint StatepointSite,
Philip Reames1a1bdb22014-12-02 18:50:36 +0000428 SelectionDAGBuilder &Builder) {
429
430 // Lower the deopt and gc arguments for this statepoint. Layout will
431 // be: deopt argument length, deopt arguments.., gc arguments...
432
433 SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000434 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
435 Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000436
Philip Reames4ac17a32015-01-07 19:07:50 +0000437#ifndef NDEBUG
438 // Check that each of the gc pointer and bases we've gotten out of the
439 // safepoint is something the strategy thinks might be a pointer into the GC
440 // heap. This is basically just here to help catch errors during statepoint
441 // insertion. TODO: This should actually be in the Verifier, but we can't get
442 // to the GCStrategy from there (yet).
Philip Reamese1bf2702015-03-27 05:09:33 +0000443 GCStrategy &S = Builder.GFI->getStrategy();
444 for (const Value *V : Bases) {
445 auto Opt = S.isGCManagedPointer(V);
446 if (Opt.hasValue()) {
447 assert(Opt.getValue() &&
448 "non gc managed base pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000449 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000450 }
451 for (const Value *V : Ptrs) {
452 auto Opt = S.isGCManagedPointer(V);
453 if (Opt.hasValue()) {
454 assert(Opt.getValue() &&
455 "non gc managed derived pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000456 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000457 }
458 for (const Value *V : Relocations) {
459 auto Opt = S.isGCManagedPointer(V);
460 if (Opt.hasValue()) {
461 assert(Opt.getValue() && "non gc managed pointer relocated");
Philip Reames4ac17a32015-01-07 19:07:50 +0000462 }
463 }
464#endif
465
Philip Reames1a1bdb22014-12-02 18:50:36 +0000466 // Before we actually start lowering (and allocating spill slots for values),
467 // reserve any stack slots which we judge to be profitable to reuse for a
468 // particular value. This is purely an optimization over the code below and
469 // doesn't change semantics at all. It is important for performance that we
470 // reserve slots for both deopt and gc values before lowering either.
Pat Gavlin08d70272015-05-12 21:33:48 +0000471 for (const Value *V : StatepointSite.vm_state_args()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000472 SDValue Incoming = Builder.getValue(V);
473 reservePreviousStackSlotForValue(Incoming, Builder);
474 }
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000475 for (unsigned i = 0; i < Bases.size(); ++i) {
476 const Value *Base = Bases[i];
477 reservePreviousStackSlotForValue(Builder.getValue(Base), Builder);
478
479 const Value *Ptr = Ptrs[i];
480 reservePreviousStackSlotForValue(Builder.getValue(Ptr), Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000481 }
482
483 // First, prefix the list with the number of unique values to be
484 // lowered. Note that this is the number of *Values* not the
485 // number of SDValues required to lower them.
Sanjoy Das499d7032015-05-06 02:36:26 +0000486 const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000487 pushStackMapConstant(Ops, Builder, NumVMSArgs);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000488
Pat Gavlin08d70272015-05-12 21:33:48 +0000489 assert(NumVMSArgs == std::distance(StatepointSite.vm_state_begin(),
490 StatepointSite.vm_state_end()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000491
492 // The vm state arguments are lowered in an opaque manner. We do
493 // not know what type of values are contained within. We skip the
494 // first one since that happens to be the total number we lowered
495 // explicitly just above. We could have left it in the loop and
496 // not done it explicitly, but it's far easier to understand this
497 // way.
Pat Gavlin08d70272015-05-12 21:33:48 +0000498 for (const Value *V : StatepointSite.vm_state_args()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000499 SDValue Incoming = Builder.getValue(V);
500 lowerIncomingStatepointValue(Incoming, Ops, Builder);
501 }
502
503 // Finally, go ahead and lower all the gc arguments. There's no prefixed
504 // length for this one. After lowering, we'll have the base and pointer
505 // arrays interwoven with each (lowered) base pointer immediately followed by
506 // it's (lowered) derived pointer. i.e
507 // (base[0], ptr[0], base[1], ptr[1], ...)
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000508 for (unsigned i = 0; i < Bases.size(); ++i) {
509 const Value *Base = Bases[i];
510 lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
511
512 const Value *Ptr = Ptrs[i];
513 lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000514 }
Philip Reamesf8f09332015-03-27 04:52:48 +0000515
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000516 // If there are any explicit spill slots passed to the statepoint, record
Philip Reamesf8f09332015-03-27 04:52:48 +0000517 // them, but otherwise do not do anything special. These are user provided
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000518 // allocas and give control over placement to the consumer. In this case,
Philip Reamesf8f09332015-03-27 04:52:48 +0000519 // it is the contents of the slot which may get updated, not the pointer to
520 // the alloca
521 for (Value *V : StatepointSite.gc_args()) {
522 SDValue Incoming = Builder.getValue(V);
523 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
524 // This handles allocas as arguments to the statepoint
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000525 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000526 Incoming.getValueType()));
Philip Reamesf8f09332015-03-27 04:52:48 +0000527 }
528 }
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000529
530 // Record computed locations for all lowered values.
531 // This can not be embedded in lowering loops as we need to record *all*
532 // values, while previous loops account only values with unique SDValues.
533 const Instruction *StatepointInstr =
534 StatepointSite.getCallSite().getInstruction();
535 FunctionLoweringInfo::StatepointSpilledValueMapTy &SpillMap =
536 Builder.FuncInfo.StatepointRelocatedValues[StatepointInstr];
537
538 for (GCRelocateOperands RelocateOpers :
539 StatepointSite.getRelocates(StatepointSite)) {
540 const Value *V = RelocateOpers.getDerivedPtr();
541 SDValue SDV = Builder.getValue(V);
542 SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
543
544 if (Loc.getNode()) {
545 SpillMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
546 } else {
547 // Record value as visited, but not spilled. This is case for allocas
548 // and constants. For this values we can avoid emiting spill load while
549 // visiting corresponding gc_relocate.
550 // Actually we do not need to record them in this map at all.
551 // We do this only to check that we are not relocating any unvisited value.
552 SpillMap[V] = None;
553
554 // Default llvm mechanisms for exporting values which are used in
555 // different basic blocks does not work for gc relocates.
556 // Note that it would be incorrect to teach llvm that all relocates are
557 // uses of the corresponging values so that it would automatically
558 // export them. Relocates of the spilled values does not use original
559 // value.
560 if (StatepointSite.getCallSite().isInvoke())
561 Builder.ExportFromCurrentBlock(V);
562 }
563 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000564}
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000565
Philip Reames1a1bdb22014-12-02 18:50:36 +0000566void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000567 // Check some preconditions for sanity
568 assert(isStatepoint(&CI) &&
569 "function called must be the statepoint function");
570
571 LowerStatepoint(ImmutableStatepoint(&CI));
572}
573
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000574void SelectionDAGBuilder::LowerStatepoint(
575 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000576 // The basic scheme here is that information about both the original call and
577 // the safepoint is encoded in the CallInst. We create a temporary call and
578 // lower it, then reverse engineer the calling sequence.
579
Philip Reames1a1bdb22014-12-02 18:50:36 +0000580 NumOfStatepoints++;
581 // Clear state
582 StatepointLowering.startNewStatepoint(*this);
583
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000584 ImmutableCallSite CS(ISP.getCallSite());
585
Philip Reames1a1bdb22014-12-02 18:50:36 +0000586#ifndef NDEBUG
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000587 // Consistency check. Don't do this for invokes. It would be too
588 // expensive to preserve this information across different basic blocks
589 if (!CS.isInvoke()) {
590 for (const User *U : CS->users()) {
591 const CallInst *Call = cast<CallInst>(U);
592 if (isGCRelocate(Call))
593 StatepointLowering.scheduleRelocCall(*Call);
594 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000595 }
596#endif
597
Philip Reames72fbe7a2014-12-02 21:01:48 +0000598#ifndef NDEBUG
599 // If this is a malformed statepoint, report it early to simplify debugging.
600 // This should catch any IR level mistake that's made when constructing or
601 // transforming statepoints.
602 ISP.verify();
Philip Reames4ac17a32015-01-07 19:07:50 +0000603
604 // Check that the associated GCStrategy expects to encounter statepoints.
Philip Reamese1bf2702015-03-27 05:09:33 +0000605 assert(GFI->getStrategy().useStatepoints() &&
606 "GCStrategy does not expect to encounter statepoints");
Philip Reames72fbe7a2014-12-02 21:01:48 +0000607#endif
608
Philip Reames1a1bdb22014-12-02 18:50:36 +0000609 // Lower statepoint vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000610 SmallVector<SDValue, 10> LoweredMetaArgs;
611 lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000612
613 // Get call node, we will replace it later with statepoint
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000614 SDNode *CallNode =
615 lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000616
Pat Gavlincc0431d2015-05-08 18:07:42 +0000617 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
618 // nodes with all the appropriate arguments and return values.
Philip Reames1a1bdb22014-12-02 18:50:36 +0000619
Philip Reames1a1bdb22014-12-02 18:50:36 +0000620 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Pat Gavlincc0431d2015-05-08 18:07:42 +0000621 SDValue Chain = CallNode->getOperand(0);
622
Philip Reames1a1bdb22014-12-02 18:50:36 +0000623 SDValue Glue;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000624 bool CallHasIncomingGlue = CallNode->getGluedNode();
625 if (CallHasIncomingGlue) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000626 // Glue is always last operand
627 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
628 }
Pat Gavlincc0431d2015-05-08 18:07:42 +0000629
630 // Build the GC_TRANSITION_START node if necessary.
631 //
632 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
633 // order in which they appear in the call to the statepoint intrinsic. If
634 // any of the operands is a pointer-typed, that operand is immediately
635 // followed by a SRCVALUE for the pointer that may be used during lowering
636 // (e.g. to form MachinePointerInfo values for loads/stores).
637 const bool IsGCTransition =
638 (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
639 (uint64_t)StatepointFlags::GCTransition;
640 if (IsGCTransition) {
641 SmallVector<SDValue, 8> TSOps;
642
643 // Add chain
644 TSOps.push_back(Chain);
645
646 // Add GC transition arguments
Pat Gavlin08d70272015-05-12 21:33:48 +0000647 for (const Value *V : ISP.gc_transition_args()) {
648 TSOps.push_back(getValue(V));
649 if (V->getType()->isPointerTy())
650 TSOps.push_back(DAG.getSrcValue(V));
Pat Gavlincc0431d2015-05-08 18:07:42 +0000651 }
652
653 // Add glue if necessary
654 if (CallHasIncomingGlue)
655 TSOps.push_back(Glue);
656
657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
658
659 SDValue GCTransitionStart =
660 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
661
662 Chain = GCTransitionStart.getValue(0);
663 Glue = GCTransitionStart.getValue(1);
664 }
665
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +0000666 // TODO: Currently, all of these operands are being marked as read/write in
667 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
668 // and flags to be read-only.
669 SmallVector<SDValue, 40> Ops;
670
671 // Add the <id> and <numBytes> constants.
672 Ops.push_back(DAG.getTargetConstant(ISP.getID(), getCurSDLoc(), MVT::i64));
673 Ops.push_back(
674 DAG.getTargetConstant(ISP.getNumPatchBytes(), getCurSDLoc(), MVT::i32));
675
Pat Gavlincc0431d2015-05-08 18:07:42 +0000676 // Calculate and push starting position of vmstate arguments
Philip Reames1a1bdb22014-12-02 18:50:36 +0000677 // Get number of arguments incoming directly into call node
678 unsigned NumCallRegArgs =
Pat Gavlincc0431d2015-05-08 18:07:42 +0000679 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000680 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000681
682 // Add call target
683 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
684 Ops.push_back(CallTarget);
685
686 // Add call arguments
687 // Get position of register mask in the call
688 SDNode::op_iterator RegMaskIt;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000689 if (CallHasIncomingGlue)
Philip Reames1a1bdb22014-12-02 18:50:36 +0000690 RegMaskIt = CallNode->op_end() - 2;
691 else
692 RegMaskIt = CallNode->op_end() - 1;
693 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
694
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000695 // Add a constant argument for the calling convention
696 pushStackMapConstant(Ops, *this, CS.getCallingConv());
697
698 // Add a constant argument for the flags
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +0000699 uint64_t Flags = ISP.getFlags();
Pat Gavlincc0431d2015-05-08 18:07:42 +0000700 assert(
701 ((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0)
702 && "unknown flag used");
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000703 pushStackMapConstant(Ops, *this, Flags);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000704
705 // Insert all vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000706 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000707
708 // Add register mask from call node
709 Ops.push_back(*RegMaskIt);
710
711 // Add chain
Pat Gavlincc0431d2015-05-08 18:07:42 +0000712 Ops.push_back(Chain);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000713
714 // Same for the glue, but we add it only if original call had it
715 if (Glue.getNode())
716 Ops.push_back(Glue);
717
Benjamin Kramerea68a942015-02-19 15:26:17 +0000718 // Compute return values. Provide a glue output since we consume one as
719 // input. This allows someone else to chain off us as needed.
720 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000721
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000722 SDNode *StatepointMCNode =
723 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000724
Pat Gavlincc0431d2015-05-08 18:07:42 +0000725 SDNode *SinkNode = StatepointMCNode;
726
727 // Build the GC_TRANSITION_END node if necessary.
728 //
729 // See the comment above regarding GC_TRANSITION_START for the layout of
730 // the operands to the GC_TRANSITION_END node.
731 if (IsGCTransition) {
732 SmallVector<SDValue, 8> TEOps;
733
734 // Add chain
735 TEOps.push_back(SDValue(StatepointMCNode, 0));
736
737 // Add GC transition arguments
Pat Gavlin08d70272015-05-12 21:33:48 +0000738 for (const Value *V : ISP.gc_transition_args()) {
739 TEOps.push_back(getValue(V));
740 if (V->getType()->isPointerTy())
741 TEOps.push_back(DAG.getSrcValue(V));
Pat Gavlincc0431d2015-05-08 18:07:42 +0000742 }
743
744 // Add glue
745 TEOps.push_back(SDValue(StatepointMCNode, 1));
746
747 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
748
749 SDValue GCTransitionStart =
750 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
751
752 SinkNode = GCTransitionStart.getNode();
753 }
754
Philip Reames1a1bdb22014-12-02 18:50:36 +0000755 // Replace original call
Pat Gavlincc0431d2015-05-08 18:07:42 +0000756 DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
Philip Reames1a1bdb22014-12-02 18:50:36 +0000757 // Remove originall call node
758 DAG.DeleteNode(CallNode);
759
760 // DON'T set the root - under the assumption that it's already set past the
761 // inserted node we created.
762
763 // TODO: A better future implementation would be to emit a single variable
764 // argument, variable return value STATEPOINT node here and then hookup the
765 // return value of each gc.relocate to the respective output of the
766 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
767 // to actually be possible today.
768}
769
770void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
771 // The result value of the gc_result is simply the result of the actual
772 // call. We've already emitted this, so just grab the value.
773 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000774 assert(isStatepoint(I) && "first argument must be a statepoint token");
Philip Reames1a1bdb22014-12-02 18:50:36 +0000775
Igor Laevsky85f7f722015-03-10 16:26:48 +0000776 if (isa<InvokeInst>(I)) {
777 // For invokes we should have stored call result in a virtual register.
778 // We can not use default getValue() functionality to copy value from this
779 // register because statepoint and actuall call return types can be
780 // different, and getValue() will use CopyFromReg of the wrong type,
781 // which is always i32 in our case.
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000782 PointerType *CalleeType =
Sanjoy Das499d7032015-05-06 02:36:26 +0000783 cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000784 Type *RetTy =
785 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
Igor Laevsky85f7f722015-03-10 16:26:48 +0000786 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
787
788 assert(CopyFromReg.getNode());
789 setValue(&CI, CopyFromReg);
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000790 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000791 setValue(&CI, getValue(I));
792 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000793}
794
795void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000796 GCRelocateOperands RelocateOpers(&CI);
797
Philip Reames1a1bdb22014-12-02 18:50:36 +0000798#ifndef NDEBUG
799 // Consistency check
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000800 // We skip this check for invoke statepoints. It would be too expensive to
801 // preserve validation info through different basic blocks.
802 if (!RelocateOpers.isTiedToInvoke()) {
803 StatepointLowering.relocCallVisited(CI);
804 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000805#endif
806
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000807 const Value *DerivedPtr = RelocateOpers.getDerivedPtr();
808 SDValue SD = getValue(DerivedPtr);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000809
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000810 FunctionLoweringInfo::StatepointSpilledValueMapTy &SpillMap =
811 FuncInfo.StatepointRelocatedValues[RelocateOpers.getStatepoint()];
812
813 // We should have recorded location for this pointer
814 assert(SpillMap.count(DerivedPtr) && "Relocating not lowered gc value");
815 Optional<int> DerivedPtrLocation = SpillMap[DerivedPtr];
816
817 // We didn't need to spill these special cases (constants and allocas).
818 // See the handling in spillIncomingValueForStatepoint for detail.
819 if (!DerivedPtrLocation) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000820 setValue(&CI, SD);
821 return;
822 }
823
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000824 SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
825 SD.getValueType());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000826
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000827 // Be conservative: flush all pending loads
828 // TODO: Probably we can be less restrictive on this,
829 // it may allow more scheduling opprtunities
830 SDValue Chain = getRoot();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000831
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000832 SDValue SpillLoad =
833 DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
834 MachinePointerInfo::getFixedStack(*DerivedPtrLocation),
835 false, false, false, 0);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000836
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000837 // Again, be conservative, don't emit pending loads
838 DAG.setRoot(SpillLoad.getValue(1));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000839
Igor Laevsky423bc9ec2015-05-20 11:37:25 +0000840 assert(SpillLoad.getNode());
841 setValue(&CI, SpillLoad);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000842}