Restructure some assertion checking based on post commit feedback by Aaron and Tom.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / StatepointLowering.cpp
1 //===-- 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"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/StackMaps.h"
22 #include "llvm/IR/CallingConv.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Statepoint.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 #define DEBUG_TYPE "statepoint-lowering"
32
33 STATISTIC(NumSlotsAllocatedForStatepoints,
34           "Number of stack slots allocated for statepoints");
35 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
36 STATISTIC(StatepointMaxSlotsRequired,
37           "Maximum number of stack slots required for a singe statepoint");
38
39 void
40 StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
41   // Consistency check
42   assert(PendingGCRelocateCalls.empty() &&
43          "Trying to visit statepoint before finished processing previous one");
44   Locations.clear();
45   RelocLocations.clear();
46   NextSlotToAllocate = 0;
47   // Need to resize this on each safepoint - we need the two to stay in
48   // sync and the clear patterns of a SelectionDAGBuilder have no relation
49   // to FunctionLoweringInfo.
50   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
51   for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
52     AllocatedStackSlots[i] = false;
53   }
54 }
55 void StatepointLoweringState::clear() {
56   Locations.clear();
57   RelocLocations.clear();
58   AllocatedStackSlots.clear();
59   assert(PendingGCRelocateCalls.empty() &&
60          "cleared before statepoint sequence completed");
61 }
62
63 SDValue
64 StatepointLoweringState::allocateStackSlot(EVT ValueType,
65                                            SelectionDAGBuilder &Builder) {
66
67   NumSlotsAllocatedForStatepoints++;
68
69   // The basic scheme here is to first look for a previously created stack slot
70   // which is not in use (accounting for the fact arbitrary slots may already
71   // be reserved), or to create a new stack slot and use it.
72
73   // If this doesn't succeed in 40000 iterations, something is seriously wrong
74   for (int i = 0; i < 40000; i++) {
75     assert(Builder.FuncInfo.StatepointStackSlots.size() ==
76                AllocatedStackSlots.size() &&
77            "broken invariant");
78     const size_t NumSlots = AllocatedStackSlots.size();
79     assert(NextSlotToAllocate <= NumSlots && "broken invariant");
80
81     if (NextSlotToAllocate >= NumSlots) {
82       assert(NextSlotToAllocate == NumSlots);
83       // record stats
84       if (NumSlots + 1 > StatepointMaxSlotsRequired) {
85         StatepointMaxSlotsRequired = NumSlots + 1;
86       }
87
88       SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
89       const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
90       Builder.FuncInfo.StatepointStackSlots.push_back(FI);
91       AllocatedStackSlots.push_back(true);
92       return SpillSlot;
93     }
94     if (!AllocatedStackSlots[NextSlotToAllocate]) {
95       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
96       AllocatedStackSlots[NextSlotToAllocate] = true;
97       return Builder.DAG.getFrameIndex(FI, ValueType);
98     }
99     // Note: We deliberately choose to advance this only on the failing path.
100     // Doing so on the suceeding path involes a bit of complexity that caused a
101     // minor bug previously.  Unless performance shows this matters, please
102     // keep this code as simple as possible.
103     NextSlotToAllocate++;
104   }
105   llvm_unreachable("infinite loop?");
106 }
107
108 /// Try to find existing copies of the incoming values in stack slots used for
109 /// statepoint spilling.  If we can find a spill slot for the incoming value,
110 /// mark that slot as allocated, and reuse the same slot for this safepoint.
111 /// This helps to avoid series of loads and stores that only serve to resuffle
112 /// values on the stack between calls.
113 static void reservePreviousStackSlotForValue(SDValue Incoming,
114                                              SelectionDAGBuilder &Builder) {
115
116   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
117     // We won't need to spill this, so no need to check for previously
118     // allocated stack slots
119     return;
120   }
121
122   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
123   if (Loc.getNode()) {
124     // duplicates in input
125     return;
126   }
127
128   // Search back for the load from a stack slot pattern to find the original
129   // slot we allocated for this value.  We could extend this to deal with
130   // simple modification patterns, but simple dealing with trivial load/store
131   // sequences helps a lot already.
132   if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
133     if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
134       const int Index = FI->getIndex();
135       auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
136                            Builder.FuncInfo.StatepointStackSlots.end(), Index);
137       if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
138         // not one of the lowering stack slots, can't reuse!
139         // TODO: Actually, we probably could reuse the stack slot if the value
140         // hasn't changed at all, but we'd need to look for intervening writes
141         return;
142       } else {
143         // This is one of our dedicated lowering slots
144         const int Offset =
145             std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
146         if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
147           // stack slot already assigned to someone else, can't use it!
148           // TODO: currently we reserve space for gc arguments after doing
149           // normal allocation for deopt arguments.  We should reserve for
150           // _all_ deopt and gc arguments, then start allocating.  This
151           // will prevent some moves being inserted when vm state changes,
152           // but gc state doesn't between two calls.
153           return;
154         }
155         // Reserve this stack slot
156         Builder.StatepointLowering.reserveStackSlot(Offset);
157       }
158
159       // Cache this slot so we find it when going through the normal
160       // assignment loop.
161       SDValue Loc =
162           Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
163
164       Builder.StatepointLowering.setLocation(Incoming, Loc);
165     }
166   }
167
168   // TODO: handle case where a reloaded value flows through a phi to
169   // another safepoint.  e.g.
170   // bb1:
171   //  a' = relocated...
172   // bb2: % pred: bb1, bb3, bb4, etc.
173   //  a_phi = phi(a', ...)
174   // statepoint ... a_phi
175   // NOTE: This will require reasoning about cross basic block values.  This is
176   // decidedly non trivial and this might not be the right place to do it.  We
177   // don't really have the information we need here...
178
179   // TODO: handle simple updates.  If a value is modified and the original
180   // value is no longer live, it would be nice to put the modified value in the
181   // same slot.  This allows folding of the memory accesses for some
182   // instructions types (like an increment).
183   // statepoint (i)
184   // i1 = i+1
185   // statepoint (i1)
186 }
187
188 /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
189 /// is not required for correctness.  It's purpose is to reduce the size of
190 /// StackMap section.  It has no effect on the number of spill slots required
191 /// or the actual lowering.
192 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
193                                    SmallVectorImpl<const Value *> &Ptrs,
194                                    SmallVectorImpl<const Value *> &Relocs,
195                                    SelectionDAGBuilder &Builder) {
196
197   // This is horribly ineffecient, but I don't care right now
198   SmallSet<SDValue, 64> Seen;
199
200   SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
201   for (size_t i = 0; i < Ptrs.size(); i++) {
202     SDValue SD = Builder.getValue(Ptrs[i]);
203     // Only add non-duplicates
204     if (Seen.count(SD) == 0) {
205       NewBases.push_back(Bases[i]);
206       NewPtrs.push_back(Ptrs[i]);
207       NewRelocs.push_back(Relocs[i]);
208     }
209     Seen.insert(SD);
210   }
211   assert(Bases.size() >= NewBases.size());
212   assert(Ptrs.size() >= NewPtrs.size());
213   assert(Relocs.size() >= NewRelocs.size());
214   Bases = NewBases;
215   Ptrs = NewPtrs;
216   Relocs = NewRelocs;
217   assert(Ptrs.size() == Bases.size());
218   assert(Ptrs.size() == Relocs.size());
219 }
220
221 /// Extract call from statepoint, lower it and return pointer to the
222 /// call node. Also update NodeMap so that getValue(statepoint) will
223 /// reference lowered call result
224 static SDNode *lowerCallFromStatepoint(const CallInst &CI,
225                                        SelectionDAGBuilder &Builder) {
226
227   assert(Intrinsic::experimental_gc_statepoint ==
228              dyn_cast<IntrinsicInst>(&CI)->getIntrinsicID() &&
229          "function called must be the statepoint function");
230
231   ImmutableStatepoint StatepointOperands(&CI);
232
233   // Lower the actual call itself - This is a bit of a hack, but we want to
234   // avoid modifying the actual lowering code.  This is similiar in intent to
235   // the LowerCallOperands mechanism used by PATCHPOINT, but is structured
236   // differently.  Hopefully, this is slightly more robust w.r.t. calling
237   // convention, return values, and other function attributes.
238   Value *ActualCallee = const_cast<Value *>(StatepointOperands.actualCallee());
239
240   std::vector<Value *> Args;
241   CallInst::const_op_iterator arg_begin = StatepointOperands.call_args_begin();
242   CallInst::const_op_iterator arg_end = StatepointOperands.call_args_end();
243   Args.insert(Args.end(), arg_begin, arg_end);
244   // TODO: remove the creation of a new instruction!  We should not be
245   // modifying the IR (even temporarily) at this point.
246   CallInst *Tmp = CallInst::Create(ActualCallee, Args);
247   Tmp->setTailCall(CI.isTailCall());
248   Tmp->setCallingConv(CI.getCallingConv());
249   Tmp->setAttributes(CI.getAttributes());
250   Builder.LowerCallTo(Tmp, Builder.getValue(ActualCallee), false);
251
252   // Handle the return value of the call iff any.
253   const bool HasDef = !Tmp->getType()->isVoidTy();
254   if (HasDef) {
255     // The value of the statepoint itself will be the value of call itself.
256     // We'll replace the actually call node shortly.  gc_result will grab
257     // this value.
258     Builder.setValue(&CI, Builder.getValue(Tmp));
259   } else {
260     // The token value is never used from here on, just generate a poison value
261     Builder.setValue(&CI, Builder.DAG.getIntPtrConstant(-1));
262   }
263   // Remove the fake entry we created so we don't have a hanging reference
264   // after we delete this node.
265   Builder.removeValue(Tmp);
266   delete Tmp;
267   Tmp = nullptr;
268
269   // Search for the call node
270   // The following code is essentially reverse engineering X86's
271   // LowerCallTo.
272   SDNode *CallNode = nullptr;
273
274   // We just emitted a call, so it should be last thing generated
275   SDValue Chain = Builder.DAG.getRoot();
276
277   // Find closest CALLSEQ_END walking back through lowered nodes if needed
278   SDNode *CallEnd = Chain.getNode();
279   int Sanity = 0;
280   while (CallEnd->getOpcode() != ISD::CALLSEQ_END) {
281     CallEnd = CallEnd->getGluedNode();
282     assert(CallEnd && "Can not find call node");
283     assert(Sanity < 20 && "should have found call end already");
284     Sanity++;
285   }
286   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
287          "Expected a callseq node.");
288   assert(CallEnd->getGluedNode());
289
290   // Step back inside the CALLSEQ
291   CallNode = CallEnd->getGluedNode();
292   return CallNode;
293 }
294
295 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
296 /// and return two arrays:
297 ///   Bases - base pointers incoming to this statepoint
298 ///   Ptrs - derived pointers incoming to this statepoint
299 ///   Relocs - the gc_relocate corresponding to each base/ptr pair
300 /// Elements of this arrays should be in one-to-one correspondence with each
301 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
302 static void
303 getIncomingStatepointGCValues(SmallVectorImpl<const Value *> &Bases,
304                               SmallVectorImpl<const Value *> &Ptrs,
305                               SmallVectorImpl<const Value *> &Relocs,
306                               ImmutableCallSite Statepoint,
307                               SelectionDAGBuilder &Builder) {
308   // Search for relocated pointers.  Note that working backwards from the
309   // gc_relocates ensures that we only get pairs which are actually relocated
310   // and used after the statepoint.
311   // TODO: This logic should probably become a utility function in Statepoint.h
312   for (const User *U : cast<CallInst>(Statepoint.getInstruction())->users()) {
313     if (!isGCRelocate(U)) {
314       continue;
315     }
316     GCRelocateOperands relocateOpers(U);
317     Relocs.push_back(cast<Value>(U));
318     Bases.push_back(relocateOpers.basePtr());
319     Ptrs.push_back(relocateOpers.derivedPtr());
320   }
321
322   // Remove any redundant llvm::Values which map to the same SDValue as another
323   // input.  Also has the effect of removing duplicates in the original
324   // llvm::Value input list as well.  This is a useful optimization for
325   // reducing the size of the StackMap section.  It has no other impact.
326   removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
327
328   assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
329 }
330
331 /// Spill a value incoming to the statepoint. It might be either part of
332 /// vmstate
333 /// or gcstate. In both cases unconditionally spill it on the stack unless it
334 /// is a null constant. Return pair with first element being frame index
335 /// containing saved value and second element with outgoing chain from the
336 /// emitted store
337 static std::pair<SDValue, SDValue>
338 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
339                              SelectionDAGBuilder &Builder) {
340   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
341
342   // Emit new store if we didn't do it for this ptr before
343   if (!Loc.getNode()) {
344     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
345                                                        Builder);
346     assert(isa<FrameIndexSDNode>(Loc));
347     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
348     // We use TargetFrameIndex so that isel will not select it into LEA
349     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
350
351     // TODO: We can create TokenFactor node instead of
352     //       chaining stores one after another, this may allow
353     //       a bit more optimal scheduling for them
354     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
355                                  MachinePointerInfo::getFixedStack(Index),
356                                  false, false, 0);
357
358     Builder.StatepointLowering.setLocation(Incoming, Loc);
359   }
360
361   assert(Loc.getNode());
362   return std::make_pair(Loc, Chain);
363 }
364
365 /// Lower a single value incoming to a statepoint node.  This value can be
366 /// either a deopt value or a gc value, the handling is the same.  We special
367 /// case constants and allocas, then fall back to spilling if required.
368 static void lowerIncomingStatepointValue(SDValue Incoming,
369                                          SmallVectorImpl<SDValue> &Ops,
370                                          SelectionDAGBuilder &Builder) {
371   SDValue Chain = Builder.getRoot();
372
373   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
374     // If the original value was a constant, make sure it gets recorded as
375     // such in the stackmap.  This is required so that the consumer can
376     // parse any internal format to the deopt state.  It also handles null
377     // pointers and other constant pointers in GC states
378     Ops.push_back(
379         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
380     Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
381   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
382     // This handles allocas as arguments to the statepoint
383     const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
384     Ops.push_back(
385         Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
386   } else {
387     // Otherwise, locate a spill slot and explicitly spill it so it
388     // can be found by the runtime later.  We currently do not support
389     // tracking values through callee saved registers to their eventual
390     // spill location.  This would be a useful optimization, but would
391     // need to be optional since it requires a lot of complexity on the
392     // runtime side which not all would support.
393     std::pair<SDValue, SDValue> Res =
394         spillIncomingStatepointValue(Incoming, Chain, Builder);
395     Ops.push_back(Res.first);
396     Chain = Res.second;
397   }
398
399   Builder.DAG.setRoot(Chain);
400 }
401
402 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
403 /// lowering is described in lowerIncomingStatepointValue.  This function is
404 /// responsible for lowering everything in the right position and playing some
405 /// tricks to avoid redundant stack manipulation where possible.  On
406 /// completion, 'Ops' will contain ready to use operands for machine code
407 /// statepoint. The chain nodes will have already been created and the DAG root
408 /// will be set to the last value spilled (if any were).
409 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
410                                     ImmutableStatepoint Statepoint,
411                                     SelectionDAGBuilder &Builder) {
412
413   // Lower the deopt and gc arguments for this statepoint.  Layout will
414   // be: deopt argument length, deopt arguments.., gc arguments...
415
416   SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
417   getIncomingStatepointGCValues(Bases, Ptrs, Relocations,
418                                 Statepoint.getCallSite(), Builder);
419
420   // Before we actually start lowering (and allocating spill slots for values),
421   // reserve any stack slots which we judge to be profitable to reuse for a
422   // particular value.  This is purely an optimization over the code below and
423   // doesn't change semantics at all.  It is important for performance that we
424   // reserve slots for both deopt and gc values before lowering either.
425   for (auto I = Statepoint.vm_state_begin() + 1, E = Statepoint.vm_state_end();
426        I != E; ++I) {
427     Value *V = *I;
428     SDValue Incoming = Builder.getValue(V);
429     reservePreviousStackSlotForValue(Incoming, Builder);
430   }
431   for (unsigned i = 0; i < Bases.size() * 2; ++i) {
432     // Even elements will contain base, odd elements - derived ptr
433     const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
434     SDValue Incoming = Builder.getValue(V);
435     reservePreviousStackSlotForValue(Incoming, Builder);
436   }
437
438   // First, prefix the list with the number of unique values to be
439   // lowered.  Note that this is the number of *Values* not the
440   // number of SDValues required to lower them.
441   const int NumVMSArgs = Statepoint.numTotalVMSArgs();
442   Ops.push_back(
443       Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
444   Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, MVT::i64));
445
446   assert(NumVMSArgs + 1 == std::distance(Statepoint.vm_state_begin(),
447                                          Statepoint.vm_state_end()));
448
449   // The vm state arguments are lowered in an opaque manner.  We do
450   // not know what type of values are contained within.  We skip the
451   // first one since that happens to be the total number we lowered
452   // explicitly just above.  We could have left it in the loop and
453   // not done it explicitly, but it's far easier to understand this
454   // way.
455   for (auto I = Statepoint.vm_state_begin() + 1, E = Statepoint.vm_state_end();
456        I != E; ++I) {
457     const Value *V = *I;
458     SDValue Incoming = Builder.getValue(V);
459     lowerIncomingStatepointValue(Incoming, Ops, Builder);
460   }
461
462   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
463   // length for this one.  After lowering, we'll have the base and pointer
464   // arrays interwoven with each (lowered) base pointer immediately followed by
465   // it's (lowered) derived pointer.  i.e
466   // (base[0], ptr[0], base[1], ptr[1], ...)
467   for (unsigned i = 0; i < Bases.size() * 2; ++i) {
468     // Even elements will contain base, odd elements - derived ptr
469     const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
470     SDValue Incoming = Builder.getValue(V);
471     lowerIncomingStatepointValue(Incoming, Ops, Builder);
472   }
473 }
474 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
475   // The basic scheme here is that information about both the original call and
476   // the safepoint is encoded in the CallInst.  We create a temporary call and
477   // lower it, then reverse engineer the calling sequence.
478
479   // Check some preconditions for sanity
480   assert(isStatepoint(&CI) &&
481          "function called must be the statepoint function");
482   NumOfStatepoints++;
483   // Clear state
484   StatepointLowering.startNewStatepoint(*this);
485
486 #ifndef NDEBUG
487   // Consistency check
488   for (const User *U : CI.users()) {
489     const CallInst *Call = cast<CallInst>(U);
490     if (isGCRelocate(Call))
491       StatepointLowering.scheduleRelocCall(*Call);
492   }
493 #endif
494
495   ImmutableStatepoint ISP(&CI);
496 #ifndef NDEBUG
497   // If this is a malformed statepoint, report it early to simplify debugging.
498   // This should catch any IR level mistake that's made when constructing or
499   // transforming statepoints.
500   ISP.verify();
501 #endif
502
503
504   // Lower statepoint vmstate and gcstate arguments
505   SmallVector<SDValue, 10> LoweredArgs;
506   lowerStatepointMetaArgs(LoweredArgs, ISP, *this);
507
508   // Get call node, we will replace it later with statepoint
509   SDNode *CallNode = lowerCallFromStatepoint(CI, *this);
510
511   // Construct the actual STATEPOINT node with all the appropriate arguments
512   // and return values.
513
514   // TODO: Currently, all of these operands are being marked as read/write in
515   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
516   // and flags to be read-only.
517   SmallVector<SDValue, 40> Ops;
518
519   // Calculate and push starting position of vmstate arguments
520   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
521   SDValue Glue;
522   if (CallNode->getGluedNode()) {
523     // Glue is always last operand
524     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
525   }
526   // Get number of arguments incoming directly into call node
527   unsigned NumCallRegArgs =
528       CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3);
529   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
530
531   // Add call target
532   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
533   Ops.push_back(CallTarget);
534
535   // Add call arguments
536   // Get position of register mask in the call
537   SDNode::op_iterator RegMaskIt;
538   if (Glue.getNode())
539     RegMaskIt = CallNode->op_end() - 2;
540   else
541     RegMaskIt = CallNode->op_end() - 1;
542   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
543
544   // Add a leading constant argument with the Flags and the calling convention
545   // masked together
546   CallingConv::ID CallConv = CI.getCallingConv();
547   int Flags = dyn_cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
548   assert(Flags == 0 && "not expected to be used");
549   Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
550   Ops.push_back(
551       DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1), MVT::i64));
552
553   // Insert all vmstate and gcstate arguments
554   Ops.insert(Ops.end(), LoweredArgs.begin(), LoweredArgs.end());
555
556   // Add register mask from call node
557   Ops.push_back(*RegMaskIt);
558
559   // Add chain
560   Ops.push_back(CallNode->getOperand(0));
561
562   // Same for the glue, but we add it only if original call had it
563   if (Glue.getNode())
564     Ops.push_back(Glue);
565
566   // Compute return values
567   SmallVector<EVT, 21> ValueVTs;
568   ValueVTs.push_back(MVT::Other);
569   ValueVTs.push_back(MVT::Glue); // provide a glue output since we consume one
570   // as input.  This allows someone else to chain
571   // off us as needed.
572   SDVTList NodeTys = DAG.getVTList(ValueVTs);
573
574   SDNode *StatepointMCNode = DAG.getMachineNode(TargetOpcode::STATEPOINT,
575                                                 getCurSDLoc(), NodeTys, Ops);
576
577   // Replace original call
578   DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root
579   // Remove originall call node
580   DAG.DeleteNode(CallNode);
581
582   // DON'T set the root - under the assumption that it's already set past the
583   // inserted node we created.
584
585   // TODO: A better future implementation would be to emit a single variable
586   // argument, variable return value STATEPOINT node here and then hookup the
587   // return value of each gc.relocate to the respective output of the
588   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
589   // to actually be possible today.
590 }
591
592 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
593   // The result value of the gc_result is simply the result of the actual
594   // call.  We've already emitted this, so just grab the value.
595   Instruction *I = cast<Instruction>(CI.getArgOperand(0));
596   assert(isStatepoint(I) &&
597          "first argument must be a statepoint token");
598
599   setValue(&CI, getValue(I));
600 }
601
602 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
603 #ifndef NDEBUG
604   // Consistency check
605   StatepointLowering.relocCallVisited(CI);
606 #endif
607
608   GCRelocateOperands relocateOpers(&CI);
609   SDValue SD = getValue(relocateOpers.derivedPtr());
610
611   if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
612     // We didn't need to spill these special cases (constants and allocas).
613     // See the handling in spillIncomingValueForStatepoint for detail.
614     setValue(&CI, SD);
615     return;
616   }
617
618   SDValue Loc = StatepointLowering.getRelocLocation(SD);
619   // Emit new load if we did not emit it before
620   if (!Loc.getNode()) {
621     SDValue SpillSlot = StatepointLowering.getLocation(SD);
622     int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
623
624     // Be conservative: flush all pending loads
625     // TODO: Probably we can be less restrictive on this,
626     // it may allow more scheduling opprtunities
627     SDValue Chain = getRoot();
628
629     Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain,
630                       SpillSlot, MachinePointerInfo::getFixedStack(FI), false,
631                       false, false, 0);
632
633     StatepointLowering.setRelocLocation(SD, Loc);
634
635     // Again, be conservative, don't emit pending loads
636     DAG.setRoot(Loc.getValue(1));
637   }
638
639   assert(Loc.getNode());
640   setValue(&CI, Loc);
641 }