1 //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file includes support code use by SelectionDAGBuilder when lowering a
11 // statepoint sequence in SelectionDAG IR.
13 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/CodeGen/GCMetadata.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #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"
33 #define DEBUG_TYPE "statepoint-lowering"
35 STATISTIC(NumSlotsAllocatedForStatepoints,
36 "Number of stack slots allocated for statepoints");
37 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
38 STATISTIC(StatepointMaxSlotsRequired,
39 "Maximum number of stack slots required for a singe statepoint");
41 static 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,
46 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
49 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
51 assert(PendingGCRelocateCalls.empty() &&
52 "Trying to visit statepoint before finished processing previous one");
54 RelocLocations.clear();
55 NextSlotToAllocate = 0;
56 // Need to resize this on each safepoint - we need the two to stay in
57 // sync and the clear patterns of a SelectionDAGBuilder have no relation
58 // to FunctionLoweringInfo.
59 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
60 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
61 AllocatedStackSlots[i] = false;
64 void StatepointLoweringState::clear() {
66 RelocLocations.clear();
67 AllocatedStackSlots.clear();
68 assert(PendingGCRelocateCalls.empty() &&
69 "cleared before statepoint sequence completed");
73 StatepointLoweringState::allocateStackSlot(EVT ValueType,
74 SelectionDAGBuilder &Builder) {
76 NumSlotsAllocatedForStatepoints++;
78 // The basic scheme here is to first look for a previously created stack slot
79 // which is not in use (accounting for the fact arbitrary slots may already
80 // be reserved), or to create a new stack slot and use it.
82 // If this doesn't succeed in 40000 iterations, something is seriously wrong
83 for (int i = 0; i < 40000; i++) {
84 assert(Builder.FuncInfo.StatepointStackSlots.size() ==
85 AllocatedStackSlots.size() &&
87 const size_t NumSlots = AllocatedStackSlots.size();
88 assert(NextSlotToAllocate <= NumSlots && "broken invariant");
90 if (NextSlotToAllocate >= NumSlots) {
91 assert(NextSlotToAllocate == NumSlots);
93 if (NumSlots + 1 > StatepointMaxSlotsRequired) {
94 StatepointMaxSlotsRequired = NumSlots + 1;
97 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
98 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
99 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
100 AllocatedStackSlots.push_back(true);
103 if (!AllocatedStackSlots[NextSlotToAllocate]) {
104 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
105 AllocatedStackSlots[NextSlotToAllocate] = true;
106 return Builder.DAG.getFrameIndex(FI, ValueType);
108 // Note: We deliberately choose to advance this only on the failing path.
109 // Doing so on the suceeding path involes a bit of complexity that caused a
110 // minor bug previously. Unless performance shows this matters, please
111 // keep this code as simple as possible.
112 NextSlotToAllocate++;
114 llvm_unreachable("infinite loop?");
117 /// Try to find existing copies of the incoming values in stack slots used for
118 /// statepoint spilling. If we can find a spill slot for the incoming value,
119 /// mark that slot as allocated, and reuse the same slot for this safepoint.
120 /// This helps to avoid series of loads and stores that only serve to resuffle
121 /// values on the stack between calls.
122 static void reservePreviousStackSlotForValue(SDValue Incoming,
123 SelectionDAGBuilder &Builder) {
125 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
126 // We won't need to spill this, so no need to check for previously
127 // allocated stack slots
131 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
133 // duplicates in input
137 // Search back for the load from a stack slot pattern to find the original
138 // slot we allocated for this value. We could extend this to deal with
139 // simple modification patterns, but simple dealing with trivial load/store
140 // sequences helps a lot already.
141 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
142 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
143 const int Index = FI->getIndex();
144 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
145 Builder.FuncInfo.StatepointStackSlots.end(), Index);
146 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
147 // not one of the lowering stack slots, can't reuse!
148 // TODO: Actually, we probably could reuse the stack slot if the value
149 // hasn't changed at all, but we'd need to look for intervening writes
152 // This is one of our dedicated lowering slots
154 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
155 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
156 // stack slot already assigned to someone else, can't use it!
157 // TODO: currently we reserve space for gc arguments after doing
158 // normal allocation for deopt arguments. We should reserve for
159 // _all_ deopt and gc arguments, then start allocating. This
160 // will prevent some moves being inserted when vm state changes,
161 // but gc state doesn't between two calls.
164 // Reserve this stack slot
165 Builder.StatepointLowering.reserveStackSlot(Offset);
168 // Cache this slot so we find it when going through the normal
171 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
173 Builder.StatepointLowering.setLocation(Incoming, Loc);
177 // TODO: handle case where a reloaded value flows through a phi to
178 // another safepoint. e.g.
181 // bb2: % pred: bb1, bb3, bb4, etc.
182 // a_phi = phi(a', ...)
183 // statepoint ... a_phi
184 // NOTE: This will require reasoning about cross basic block values. This is
185 // decidedly non trivial and this might not be the right place to do it. We
186 // don't really have the information we need here...
188 // TODO: handle simple updates. If a value is modified and the original
189 // value is no longer live, it would be nice to put the modified value in the
190 // same slot. This allows folding of the memory accesses for some
191 // instructions types (like an increment).
197 /// Remove any duplicate (as SDValues) from the derived pointer pairs. This
198 /// is not required for correctness. It's purpose is to reduce the size of
199 /// StackMap section. It has no effect on the number of spill slots required
200 /// or the actual lowering.
201 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
202 SmallVectorImpl<const Value *> &Ptrs,
203 SmallVectorImpl<const Value *> &Relocs,
204 SelectionDAGBuilder &Builder) {
206 // This is horribly ineffecient, but I don't care right now
207 SmallSet<SDValue, 64> Seen;
209 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
210 for (size_t i = 0; i < Ptrs.size(); i++) {
211 SDValue SD = Builder.getValue(Ptrs[i]);
212 // Only add non-duplicates
213 if (Seen.count(SD) == 0) {
214 NewBases.push_back(Bases[i]);
215 NewPtrs.push_back(Ptrs[i]);
216 NewRelocs.push_back(Relocs[i]);
220 assert(Bases.size() >= NewBases.size());
221 assert(Ptrs.size() >= NewPtrs.size());
222 assert(Relocs.size() >= NewRelocs.size());
226 assert(Ptrs.size() == Bases.size());
227 assert(Ptrs.size() == Relocs.size());
230 /// Extract call from statepoint, lower it and return pointer to the
231 /// call node. Also update NodeMap so that getValue(statepoint) will
232 /// reference lowered call result
234 lowerCallFromStatepoint(ImmutableStatepoint ISP, MachineBasicBlock *LandingPad,
235 SelectionDAGBuilder &Builder,
236 SmallVectorImpl<SDValue> &PendingExports) {
238 ImmutableCallSite CS(ISP.getCallSite());
240 SDValue ActualCallee = Builder.getValue(ISP.getActualCallee());
242 // Handle immediate and symbolic callees.
243 if (auto *ConstCallee = dyn_cast<ConstantSDNode>(ActualCallee.getNode()))
244 ActualCallee = Builder.DAG.getIntPtrConstant(ConstCallee->getZExtValue(),
245 Builder.getCurSDLoc(),
247 else if (auto *SymbolicCallee =
248 dyn_cast<GlobalAddressSDNode>(ActualCallee.getNode()))
249 ActualCallee = Builder.DAG.getTargetGlobalAddress(
250 SymbolicCallee->getGlobal(), SDLoc(SymbolicCallee),
251 SymbolicCallee->getValueType(0));
253 assert(CS.getCallingConv() != CallingConv::AnyReg &&
254 "anyregcc is not supported on statepoints!");
256 Type *DefTy = ISP.getActualReturnType();
257 bool HasDef = !DefTy->isVoidTy();
259 SDValue ReturnValue, CallEndVal;
260 std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
261 ISP.getCallSite(), ImmutableStatepoint::CallArgsBeginPos,
262 ISP.getNumCallArgs(), ActualCallee, DefTy, LandingPad,
263 false /* IsPatchPoint */);
265 SDNode *CallEnd = CallEndVal.getNode();
267 // Get a call instruction from the call sequence chain. Tail calls are not
268 // allowed. The following code is essentially reverse engineering X86's
271 // We are expecting DAG to have the following form:
273 // ch = eh_label (only in case of invoke statepoint)
274 // ch, glue = callseq_start ch
275 // ch, glue = X86::Call ch, glue
276 // ch, glue = callseq_end ch, glue
277 // get_return_value ch, glue
279 // get_return_value can either be a CopyFromReg to grab the return value from
280 // %RAX, or it can be a LOAD to load a value returned by reference via a stack
283 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg ||
284 CallEnd->getOpcode() == ISD::LOAD))
285 CallEnd = CallEnd->getOperand(0).getNode();
287 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
291 // Result value will be used in different basic block for invokes
292 // so we need to export it now. But statepoint call has a different type
293 // than the actuall call. It means that standart exporting mechanism will
294 // create register of the wrong type. So instead we need to create
295 // register with correct type and save value into it manually.
296 // TODO: To eliminate this problem we can remove gc.result intrinsics
297 // completelly and make statepoint call to return a tuple.
298 unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
299 RegsForValue RFV(*Builder.DAG.getContext(),
300 Builder.DAG.getTargetLoweringInfo(), Reg,
301 ISP.getActualReturnType());
302 SDValue Chain = Builder.DAG.getEntryNode();
304 RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
306 PendingExports.push_back(Chain);
307 Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
309 // The value of the statepoint itself will be the value of call itself.
310 // We'll replace the actually call node shortly. gc_result will grab
312 Builder.setValue(CS.getInstruction(), ReturnValue);
315 // The token value is never used from here on, just generate a poison value
316 Builder.setValue(CS.getInstruction(),
317 Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
320 return CallEnd->getOperand(0).getNode();
323 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
324 /// and return two arrays:
325 /// Bases - base pointers incoming to this statepoint
326 /// Ptrs - derived pointers incoming to this statepoint
327 /// Relocs - the gc_relocate corresponding to each base/ptr pair
328 /// Elements of this arrays should be in one-to-one correspondence with each
329 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
330 static void getIncomingStatepointGCValues(
331 SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
332 SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
333 SelectionDAGBuilder &Builder) {
334 for (GCRelocateOperands relocateOpers :
335 StatepointSite.getRelocates(StatepointSite)) {
336 Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
337 Bases.push_back(relocateOpers.getBasePtr());
338 Ptrs.push_back(relocateOpers.getDerivedPtr());
341 // Remove any redundant llvm::Values which map to the same SDValue as another
342 // input. Also has the effect of removing duplicates in the original
343 // llvm::Value input list as well. This is a useful optimization for
344 // reducing the size of the StackMap section. It has no other impact.
345 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
347 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
350 /// Spill a value incoming to the statepoint. It might be either part of
352 /// or gcstate. In both cases unconditionally spill it on the stack unless it
353 /// is a null constant. Return pair with first element being frame index
354 /// containing saved value and second element with outgoing chain from the
356 static std::pair<SDValue, SDValue>
357 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
358 SelectionDAGBuilder &Builder) {
359 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
361 // Emit new store if we didn't do it for this ptr before
362 if (!Loc.getNode()) {
363 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
365 assert(isa<FrameIndexSDNode>(Loc));
366 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
367 // We use TargetFrameIndex so that isel will not select it into LEA
368 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
370 // TODO: We can create TokenFactor node instead of
371 // chaining stores one after another, this may allow
372 // a bit more optimal scheduling for them
373 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
374 MachinePointerInfo::getFixedStack(Index),
377 Builder.StatepointLowering.setLocation(Incoming, Loc);
380 assert(Loc.getNode());
381 return std::make_pair(Loc, Chain);
384 /// Lower a single value incoming to a statepoint node. This value can be
385 /// either a deopt value or a gc value, the handling is the same. We special
386 /// case constants and allocas, then fall back to spilling if required.
387 static void lowerIncomingStatepointValue(SDValue Incoming,
388 SmallVectorImpl<SDValue> &Ops,
389 SelectionDAGBuilder &Builder) {
390 SDValue Chain = Builder.getRoot();
392 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
393 // If the original value was a constant, make sure it gets recorded as
394 // such in the stackmap. This is required so that the consumer can
395 // parse any internal format to the deopt state. It also handles null
396 // pointers and other constant pointers in GC states
397 pushStackMapConstant(Ops, Builder, C->getSExtValue());
398 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
399 // This handles allocas as arguments to the statepoint (this is only
400 // really meaningful for a deopt value. For GC, we'd be trying to
401 // relocate the address of the alloca itself?)
402 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
403 Incoming.getValueType()));
405 // Otherwise, locate a spill slot and explicitly spill it so it
406 // can be found by the runtime later. We currently do not support
407 // tracking values through callee saved registers to their eventual
408 // spill location. This would be a useful optimization, but would
409 // need to be optional since it requires a lot of complexity on the
410 // runtime side which not all would support.
411 std::pair<SDValue, SDValue> Res =
412 spillIncomingStatepointValue(Incoming, Chain, Builder);
413 Ops.push_back(Res.first);
417 Builder.DAG.setRoot(Chain);
420 /// Lower deopt state and gc pointer arguments of the statepoint. The actual
421 /// lowering is described in lowerIncomingStatepointValue. This function is
422 /// responsible for lowering everything in the right position and playing some
423 /// tricks to avoid redundant stack manipulation where possible. On
424 /// completion, 'Ops' will contain ready to use operands for machine code
425 /// statepoint. The chain nodes will have already been created and the DAG root
426 /// will be set to the last value spilled (if any were).
427 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
428 ImmutableStatepoint StatepointSite,
429 SelectionDAGBuilder &Builder) {
431 // Lower the deopt and gc arguments for this statepoint. Layout will
432 // be: deopt argument length, deopt arguments.., gc arguments...
434 SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
435 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
439 // Check that each of the gc pointer and bases we've gotten out of the
440 // safepoint is something the strategy thinks might be a pointer into the GC
441 // heap. This is basically just here to help catch errors during statepoint
442 // insertion. TODO: This should actually be in the Verifier, but we can't get
443 // to the GCStrategy from there (yet).
444 GCStrategy &S = Builder.GFI->getStrategy();
445 for (const Value *V : Bases) {
446 auto Opt = S.isGCManagedPointer(V);
447 if (Opt.hasValue()) {
448 assert(Opt.getValue() &&
449 "non gc managed base pointer found in statepoint");
452 for (const Value *V : Ptrs) {
453 auto Opt = S.isGCManagedPointer(V);
454 if (Opt.hasValue()) {
455 assert(Opt.getValue() &&
456 "non gc managed derived pointer found in statepoint");
459 for (const Value *V : Relocations) {
460 auto Opt = S.isGCManagedPointer(V);
461 if (Opt.hasValue()) {
462 assert(Opt.getValue() && "non gc managed pointer relocated");
467 // Before we actually start lowering (and allocating spill slots for values),
468 // reserve any stack slots which we judge to be profitable to reuse for a
469 // particular value. This is purely an optimization over the code below and
470 // doesn't change semantics at all. It is important for performance that we
471 // reserve slots for both deopt and gc values before lowering either.
472 for (const Value *V : StatepointSite.vm_state_args()) {
473 SDValue Incoming = Builder.getValue(V);
474 reservePreviousStackSlotForValue(Incoming, Builder);
476 for (unsigned i = 0; i < Bases.size(); ++i) {
477 const Value *Base = Bases[i];
478 reservePreviousStackSlotForValue(Builder.getValue(Base), Builder);
480 const Value *Ptr = Ptrs[i];
481 reservePreviousStackSlotForValue(Builder.getValue(Ptr), Builder);
484 // First, prefix the list with the number of unique values to be
485 // lowered. Note that this is the number of *Values* not the
486 // number of SDValues required to lower them.
487 const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
488 pushStackMapConstant(Ops, Builder, NumVMSArgs);
490 assert(NumVMSArgs == std::distance(StatepointSite.vm_state_begin(),
491 StatepointSite.vm_state_end()));
493 // The vm state arguments are lowered in an opaque manner. We do
494 // not know what type of values are contained within. We skip the
495 // first one since that happens to be the total number we lowered
496 // explicitly just above. We could have left it in the loop and
497 // not done it explicitly, but it's far easier to understand this
499 for (const Value *V : StatepointSite.vm_state_args()) {
500 SDValue Incoming = Builder.getValue(V);
501 lowerIncomingStatepointValue(Incoming, Ops, Builder);
504 // Finally, go ahead and lower all the gc arguments. There's no prefixed
505 // length for this one. After lowering, we'll have the base and pointer
506 // arrays interwoven with each (lowered) base pointer immediately followed by
507 // it's (lowered) derived pointer. i.e
508 // (base[0], ptr[0], base[1], ptr[1], ...)
509 for (unsigned i = 0; i < Bases.size(); ++i) {
510 const Value *Base = Bases[i];
511 lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
513 const Value *Ptr = Ptrs[i];
514 lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
517 // If there are any explicit spill slots passed to the statepoint, record
518 // them, but otherwise do not do anything special. These are user provided
519 // allocas and give control over placement to the consumer. In this case,
520 // it is the contents of the slot which may get updated, not the pointer to
522 for (Value *V : StatepointSite.gc_args()) {
523 SDValue Incoming = Builder.getValue(V);
524 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
525 // This handles allocas as arguments to the statepoint
526 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
527 Incoming.getValueType()));
532 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
533 // Check some preconditions for sanity
534 assert(isStatepoint(&CI) &&
535 "function called must be the statepoint function");
537 LowerStatepoint(ImmutableStatepoint(&CI));
540 void SelectionDAGBuilder::LowerStatepoint(
541 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
542 // The basic scheme here is that information about both the original call and
543 // the safepoint is encoded in the CallInst. We create a temporary call and
544 // lower it, then reverse engineer the calling sequence.
548 StatepointLowering.startNewStatepoint(*this);
550 ImmutableCallSite CS(ISP.getCallSite());
554 for (const User *U : CS->users()) {
555 const CallInst *Call = cast<CallInst>(U);
556 if (isGCRelocate(Call))
557 StatepointLowering.scheduleRelocCall(*Call);
562 // If this is a malformed statepoint, report it early to simplify debugging.
563 // This should catch any IR level mistake that's made when constructing or
564 // transforming statepoints.
567 // Check that the associated GCStrategy expects to encounter statepoints.
568 // TODO: This if should become an assert. For now, we allow the GCStrategy
569 // to be optional for backwards compatibility. This will only last a short
570 // period (i.e. a couple of weeks).
571 assert(GFI->getStrategy().useStatepoints() &&
572 "GCStrategy does not expect to encounter statepoints");
575 // Lower statepoint vmstate and gcstate arguments
576 SmallVector<SDValue, 10> LoweredMetaArgs;
577 lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
579 // Get call node, we will replace it later with statepoint
581 lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
583 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
584 // nodes with all the appropriate arguments and return values.
586 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
587 SDValue Chain = CallNode->getOperand(0);
590 bool CallHasIncomingGlue = CallNode->getGluedNode();
591 if (CallHasIncomingGlue) {
592 // Glue is always last operand
593 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
596 // Build the GC_TRANSITION_START node if necessary.
598 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
599 // order in which they appear in the call to the statepoint intrinsic. If
600 // any of the operands is a pointer-typed, that operand is immediately
601 // followed by a SRCVALUE for the pointer that may be used during lowering
602 // (e.g. to form MachinePointerInfo values for loads/stores).
603 const bool IsGCTransition =
604 (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
605 (uint64_t)StatepointFlags::GCTransition;
606 if (IsGCTransition) {
607 SmallVector<SDValue, 8> TSOps;
610 TSOps.push_back(Chain);
612 // Add GC transition arguments
613 for (const Value *V : ISP.gc_transition_args()) {
614 TSOps.push_back(getValue(V));
615 if (V->getType()->isPointerTy())
616 TSOps.push_back(DAG.getSrcValue(V));
619 // Add glue if necessary
620 if (CallHasIncomingGlue)
621 TSOps.push_back(Glue);
623 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
625 SDValue GCTransitionStart =
626 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
628 Chain = GCTransitionStart.getValue(0);
629 Glue = GCTransitionStart.getValue(1);
632 // TODO: Currently, all of these operands are being marked as read/write in
633 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
634 // and flags to be read-only.
635 SmallVector<SDValue, 40> Ops;
637 // Add the <id> and <numBytes> constants.
638 Ops.push_back(DAG.getTargetConstant(ISP.getID(), getCurSDLoc(), MVT::i64));
640 DAG.getTargetConstant(ISP.getNumPatchBytes(), getCurSDLoc(), MVT::i32));
642 // Calculate and push starting position of vmstate arguments
643 // Get number of arguments incoming directly into call node
644 unsigned NumCallRegArgs =
645 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
646 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
649 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
650 Ops.push_back(CallTarget);
652 // Add call arguments
653 // Get position of register mask in the call
654 SDNode::op_iterator RegMaskIt;
655 if (CallHasIncomingGlue)
656 RegMaskIt = CallNode->op_end() - 2;
658 RegMaskIt = CallNode->op_end() - 1;
659 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
661 // Add a constant argument for the calling convention
662 pushStackMapConstant(Ops, *this, CS.getCallingConv());
664 // Add a constant argument for the flags
665 uint64_t Flags = ISP.getFlags();
667 ((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0)
668 && "unknown flag used");
669 pushStackMapConstant(Ops, *this, Flags);
671 // Insert all vmstate and gcstate arguments
672 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
674 // Add register mask from call node
675 Ops.push_back(*RegMaskIt);
678 Ops.push_back(Chain);
680 // Same for the glue, but we add it only if original call had it
684 // Compute return values. Provide a glue output since we consume one as
685 // input. This allows someone else to chain off us as needed.
686 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
688 SDNode *StatepointMCNode =
689 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
691 SDNode *SinkNode = StatepointMCNode;
693 // Build the GC_TRANSITION_END node if necessary.
695 // See the comment above regarding GC_TRANSITION_START for the layout of
696 // the operands to the GC_TRANSITION_END node.
697 if (IsGCTransition) {
698 SmallVector<SDValue, 8> TEOps;
701 TEOps.push_back(SDValue(StatepointMCNode, 0));
703 // Add GC transition arguments
704 for (const Value *V : ISP.gc_transition_args()) {
705 TEOps.push_back(getValue(V));
706 if (V->getType()->isPointerTy())
707 TEOps.push_back(DAG.getSrcValue(V));
711 TEOps.push_back(SDValue(StatepointMCNode, 1));
713 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
715 SDValue GCTransitionStart =
716 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
718 SinkNode = GCTransitionStart.getNode();
721 // Replace original call
722 DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
723 // Remove originall call node
724 DAG.DeleteNode(CallNode);
726 // DON'T set the root - under the assumption that it's already set past the
727 // inserted node we created.
729 // TODO: A better future implementation would be to emit a single variable
730 // argument, variable return value STATEPOINT node here and then hookup the
731 // return value of each gc.relocate to the respective output of the
732 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
733 // to actually be possible today.
736 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
737 // The result value of the gc_result is simply the result of the actual
738 // call. We've already emitted this, so just grab the value.
739 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
740 assert(isStatepoint(I) && "first argument must be a statepoint token");
742 if (isa<InvokeInst>(I)) {
743 // For invokes we should have stored call result in a virtual register.
744 // We can not use default getValue() functionality to copy value from this
745 // register because statepoint and actuall call return types can be
746 // different, and getValue() will use CopyFromReg of the wrong type,
747 // which is always i32 in our case.
748 PointerType *CalleeType =
749 cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
751 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
752 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
754 assert(CopyFromReg.getNode());
755 setValue(&CI, CopyFromReg);
757 setValue(&CI, getValue(I));
761 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
764 StatepointLowering.relocCallVisited(CI);
767 GCRelocateOperands relocateOpers(&CI);
768 SDValue SD = getValue(relocateOpers.getDerivedPtr());
770 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
771 // We didn't need to spill these special cases (constants and allocas).
772 // See the handling in spillIncomingValueForStatepoint for detail.
777 SDValue Loc = StatepointLowering.getRelocLocation(SD);
778 // Emit new load if we did not emit it before
779 if (!Loc.getNode()) {
780 SDValue SpillSlot = StatepointLowering.getLocation(SD);
781 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
783 // Be conservative: flush all pending loads
784 // TODO: Probably we can be less restrictive on this,
785 // it may allow more scheduling opprtunities
786 SDValue Chain = getRoot();
788 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
789 MachinePointerInfo::getFixedStack(FI), false, false,
792 StatepointLowering.setRelocLocation(SD, Loc);
794 // Again, be conservative, don't emit pending loads
795 DAG.setRoot(Loc.getValue(1));
798 assert(Loc.getNode());