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