SDAG: Merge the meat of two ExpandAtomic implementations.
[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(ImmutableStatepoint StatepointSite,
227                                        SelectionDAGBuilder &Builder) {
228
229   ImmutableCallSite CS(StatepointSite.getCallSite());
230
231   // Lower the actual call itself - This is a bit of a hack, but we want to
232   // avoid modifying the actual lowering code.  This is similiar in intent to
233   // the LowerCallOperands mechanism used by PATCHPOINT, but is structured
234   // differently.  Hopefully, this is slightly more robust w.r.t. calling
235   // convention, return values, and other function attributes.
236   Value *ActualCallee = const_cast<Value *>(StatepointSite.actualCallee());
237
238   std::vector<Value *> Args;
239   CallInst::const_op_iterator arg_begin = StatepointSite.call_args_begin();
240   CallInst::const_op_iterator arg_end = StatepointSite.call_args_end();
241   Args.insert(Args.end(), arg_begin, arg_end);
242   // TODO: remove the creation of a new instruction!  We should not be
243   // modifying the IR (even temporarily) at this point.
244   CallInst *Tmp = CallInst::Create(ActualCallee, Args);
245   Tmp->setTailCall(CS.isTailCall());
246   Tmp->setCallingConv(CS.getCallingConv());
247   Tmp->setAttributes(CS.getAttributes());
248   Builder.LowerCallTo(Tmp, Builder.getValue(ActualCallee), false);
249
250   // Handle the return value of the call iff any.
251   const bool HasDef = !Tmp->getType()->isVoidTy();
252   if (HasDef) {
253     // The value of the statepoint itself will be the value of call itself.
254     // We'll replace the actually call node shortly.  gc_result will grab
255     // this value.
256     Builder.setValue(CS.getInstruction(), Builder.getValue(Tmp));
257   } else {
258     // The token value is never used from here on, just generate a poison value
259     Builder.setValue(CS.getInstruction(), Builder.DAG.getIntPtrConstant(-1));
260   }
261   // Remove the fake entry we created so we don't have a hanging reference
262   // after we delete this node.
263   Builder.removeValue(Tmp);
264   delete Tmp;
265   Tmp = nullptr;
266
267   // Search for the call node
268   // The following code is essentially reverse engineering X86's
269   // LowerCallTo.
270   SDNode *CallNode = nullptr;
271
272   // We just emitted a call, so it should be last thing generated
273   SDValue Chain = Builder.DAG.getRoot();
274
275   // Find closest CALLSEQ_END walking back through lowered nodes if needed
276   SDNode *CallEnd = Chain.getNode();
277   int Sanity = 0;
278   while (CallEnd->getOpcode() != ISD::CALLSEQ_END) {
279     CallEnd = CallEnd->getGluedNode();
280     assert(CallEnd && "Can not find call node");
281     assert(Sanity < 20 && "should have found call end already");
282     Sanity++;
283   }
284   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
285          "Expected a callseq node.");
286   assert(CallEnd->getGluedNode());
287
288   // Step back inside the CALLSEQ
289   CallNode = CallEnd->getGluedNode();
290   return CallNode;
291 }
292
293 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
294 /// and return two arrays:
295 ///   Bases - base pointers incoming to this statepoint
296 ///   Ptrs - derived pointers incoming to this statepoint
297 ///   Relocs - the gc_relocate corresponding to each base/ptr pair
298 /// Elements of this arrays should be in one-to-one correspondence with each
299 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
300 static void
301 getIncomingStatepointGCValues(SmallVectorImpl<const Value *> &Bases,
302                               SmallVectorImpl<const Value *> &Ptrs,
303                               SmallVectorImpl<const Value *> &Relocs,
304                               ImmutableStatepoint StatepointSite,
305                               SelectionDAGBuilder &Builder) {
306   for (GCRelocateOperands relocateOpers :
307          StatepointSite.getRelocates(StatepointSite)) {
308     Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
309     Bases.push_back(relocateOpers.basePtr());
310     Ptrs.push_back(relocateOpers.derivedPtr());
311   }
312
313   // Remove any redundant llvm::Values which map to the same SDValue as another
314   // input.  Also has the effect of removing duplicates in the original
315   // llvm::Value input list as well.  This is a useful optimization for
316   // reducing the size of the StackMap section.  It has no other impact.
317   removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
318
319   assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
320 }
321
322 /// Spill a value incoming to the statepoint. It might be either part of
323 /// vmstate
324 /// or gcstate. In both cases unconditionally spill it on the stack unless it
325 /// is a null constant. Return pair with first element being frame index
326 /// containing saved value and second element with outgoing chain from the
327 /// emitted store
328 static std::pair<SDValue, SDValue>
329 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
330                              SelectionDAGBuilder &Builder) {
331   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
332
333   // Emit new store if we didn't do it for this ptr before
334   if (!Loc.getNode()) {
335     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
336                                                        Builder);
337     assert(isa<FrameIndexSDNode>(Loc));
338     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
339     // We use TargetFrameIndex so that isel will not select it into LEA
340     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
341
342     // TODO: We can create TokenFactor node instead of
343     //       chaining stores one after another, this may allow
344     //       a bit more optimal scheduling for them
345     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
346                                  MachinePointerInfo::getFixedStack(Index),
347                                  false, false, 0);
348
349     Builder.StatepointLowering.setLocation(Incoming, Loc);
350   }
351
352   assert(Loc.getNode());
353   return std::make_pair(Loc, Chain);
354 }
355
356 /// Lower a single value incoming to a statepoint node.  This value can be
357 /// either a deopt value or a gc value, the handling is the same.  We special
358 /// case constants and allocas, then fall back to spilling if required.
359 static void lowerIncomingStatepointValue(SDValue Incoming,
360                                          SmallVectorImpl<SDValue> &Ops,
361                                          SelectionDAGBuilder &Builder) {
362   SDValue Chain = Builder.getRoot();
363
364   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
365     // If the original value was a constant, make sure it gets recorded as
366     // such in the stackmap.  This is required so that the consumer can
367     // parse any internal format to the deopt state.  It also handles null
368     // pointers and other constant pointers in GC states
369     Ops.push_back(
370         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
371     Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
372   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
373     // This handles allocas as arguments to the statepoint
374     const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
375     Ops.push_back(
376         Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
377   } else {
378     // Otherwise, locate a spill slot and explicitly spill it so it
379     // can be found by the runtime later.  We currently do not support
380     // tracking values through callee saved registers to their eventual
381     // spill location.  This would be a useful optimization, but would
382     // need to be optional since it requires a lot of complexity on the
383     // runtime side which not all would support.
384     std::pair<SDValue, SDValue> Res =
385         spillIncomingStatepointValue(Incoming, Chain, Builder);
386     Ops.push_back(Res.first);
387     Chain = Res.second;
388   }
389
390   Builder.DAG.setRoot(Chain);
391 }
392
393 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
394 /// lowering is described in lowerIncomingStatepointValue.  This function is
395 /// responsible for lowering everything in the right position and playing some
396 /// tricks to avoid redundant stack manipulation where possible.  On
397 /// completion, 'Ops' will contain ready to use operands for machine code
398 /// statepoint. The chain nodes will have already been created and the DAG root
399 /// will be set to the last value spilled (if any were).
400 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
401                                     ImmutableStatepoint StatepointSite,
402                                     SelectionDAGBuilder &Builder) {
403
404   // Lower the deopt and gc arguments for this statepoint.  Layout will
405   // be: deopt argument length, deopt arguments.., gc arguments...
406
407   SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
408   getIncomingStatepointGCValues(Bases, Ptrs, Relocations,
409                                 StatepointSite, Builder);
410
411 #ifndef NDEBUG
412   // Check that each of the gc pointer and bases we've gotten out of the
413   // safepoint is something the strategy thinks might be a pointer into the GC
414   // heap.  This is basically just here to help catch errors during statepoint
415   // insertion. TODO: This should actually be in the Verifier, but we can't get
416   // to the GCStrategy from there (yet).
417   if (Builder.GFI) {
418     GCStrategy &S = Builder.GFI->getStrategy();
419     for (const Value *V : Bases) {
420       auto Opt = S.isGCManagedPointer(V);
421       if (Opt.hasValue()) {
422         assert(Opt.getValue() &&
423                "non gc managed base pointer found in statepoint");
424       }
425     }
426     for (const Value *V : Ptrs) {
427       auto Opt = S.isGCManagedPointer(V);
428       if (Opt.hasValue()) {
429         assert(Opt.getValue() &&
430                "non gc managed derived pointer found in statepoint");
431       }
432     }
433     for (const Value *V : Relocations) {
434       auto Opt = S.isGCManagedPointer(V);
435       if (Opt.hasValue()) {
436         assert(Opt.getValue() && "non gc managed pointer relocated");
437       }
438     }
439   }
440 #endif
441
442
443
444   // Before we actually start lowering (and allocating spill slots for values),
445   // reserve any stack slots which we judge to be profitable to reuse for a
446   // particular value.  This is purely an optimization over the code below and
447   // doesn't change semantics at all.  It is important for performance that we
448   // reserve slots for both deopt and gc values before lowering either.
449   for (auto I = StatepointSite.vm_state_begin() + 1,
450             E = StatepointSite.vm_state_end();
451        I != E; ++I) {
452     Value *V = *I;
453     SDValue Incoming = Builder.getValue(V);
454     reservePreviousStackSlotForValue(Incoming, Builder);
455   }
456   for (unsigned i = 0; i < Bases.size() * 2; ++i) {
457     // Even elements will contain base, odd elements - derived ptr
458     const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
459     SDValue Incoming = Builder.getValue(V);
460     reservePreviousStackSlotForValue(Incoming, Builder);
461   }
462
463   // First, prefix the list with the number of unique values to be
464   // lowered.  Note that this is the number of *Values* not the
465   // number of SDValues required to lower them.
466   const int NumVMSArgs = StatepointSite.numTotalVMSArgs();
467   Ops.push_back(
468       Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
469   Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, MVT::i64));
470
471   assert(NumVMSArgs + 1 == std::distance(StatepointSite.vm_state_begin(),
472                                          StatepointSite.vm_state_end()));
473
474   // The vm state arguments are lowered in an opaque manner.  We do
475   // not know what type of values are contained within.  We skip the
476   // first one since that happens to be the total number we lowered
477   // explicitly just above.  We could have left it in the loop and
478   // not done it explicitly, but it's far easier to understand this
479   // way.
480   for (auto I = StatepointSite.vm_state_begin() + 1,
481             E = StatepointSite.vm_state_end();
482        I != E; ++I) {
483     const Value *V = *I;
484     SDValue Incoming = Builder.getValue(V);
485     lowerIncomingStatepointValue(Incoming, Ops, Builder);
486   }
487
488   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
489   // length for this one.  After lowering, we'll have the base and pointer
490   // arrays interwoven with each (lowered) base pointer immediately followed by
491   // it's (lowered) derived pointer.  i.e
492   // (base[0], ptr[0], base[1], ptr[1], ...)
493   for (unsigned i = 0; i < Bases.size() * 2; ++i) {
494     // Even elements will contain base, odd elements - derived ptr
495     const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
496     SDValue Incoming = Builder.getValue(V);
497     lowerIncomingStatepointValue(Incoming, Ops, Builder);
498   }
499 }
500
501 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
502   // Check some preconditions for sanity
503   assert(isStatepoint(&CI) &&
504          "function called must be the statepoint function");
505
506   LowerStatepoint(ImmutableStatepoint(&CI));
507 }
508
509 void SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP) {
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   NumOfStatepoints++;
515   // Clear state
516   StatepointLowering.startNewStatepoint(*this);
517
518   ImmutableCallSite CS(ISP.getCallSite());
519
520 #ifndef NDEBUG
521   // Consistency check
522   for (const User *U : CS->users()) {
523     const CallInst *Call = cast<CallInst>(U);
524     if (isGCRelocate(Call))
525       StatepointLowering.scheduleRelocCall(*Call);
526   }
527 #endif
528
529 #ifndef NDEBUG
530   // If this is a malformed statepoint, report it early to simplify debugging.
531   // This should catch any IR level mistake that's made when constructing or
532   // transforming statepoints.
533   ISP.verify();
534
535   // Check that the associated GCStrategy expects to encounter statepoints.
536   // TODO: This if should become an assert.  For now, we allow the GCStrategy
537   // to be optional for backwards compatibility.  This will only last a short
538   // period (i.e. a couple of weeks).
539   if (GFI) {
540     assert(GFI->getStrategy().useStatepoints() &&
541            "GCStrategy does not expect to encounter statepoints");
542   }
543 #endif
544
545
546   // Lower statepoint vmstate and gcstate arguments
547   SmallVector<SDValue, 10> LoweredArgs;
548   lowerStatepointMetaArgs(LoweredArgs, ISP, *this);
549
550   // Get call node, we will replace it later with statepoint
551   SDNode *CallNode = lowerCallFromStatepoint(ISP, *this);
552
553   // Construct the actual STATEPOINT node with all the appropriate arguments
554   // and return values.
555
556   // TODO: Currently, all of these operands are being marked as read/write in
557   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
558   // and flags to be read-only.
559   SmallVector<SDValue, 40> Ops;
560
561   // Calculate and push starting position of vmstate arguments
562   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
563   SDValue Glue;
564   if (CallNode->getGluedNode()) {
565     // Glue is always last operand
566     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
567   }
568   // Get number of arguments incoming directly into call node
569   unsigned NumCallRegArgs =
570       CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3);
571   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
572
573   // Add call target
574   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
575   Ops.push_back(CallTarget);
576
577   // Add call arguments
578   // Get position of register mask in the call
579   SDNode::op_iterator RegMaskIt;
580   if (Glue.getNode())
581     RegMaskIt = CallNode->op_end() - 2;
582   else
583     RegMaskIt = CallNode->op_end() - 1;
584   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
585
586   // Add a leading constant argument with the Flags and the calling convention
587   // masked together
588   CallingConv::ID CallConv = CS.getCallingConv();
589   int Flags = dyn_cast<ConstantInt>(CS.getArgument(2))->getZExtValue();
590   assert(Flags == 0 && "not expected to be used");
591   Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
592   Ops.push_back(
593       DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1), MVT::i64));
594
595   // Insert all vmstate and gcstate arguments
596   Ops.insert(Ops.end(), LoweredArgs.begin(), LoweredArgs.end());
597
598   // Add register mask from call node
599   Ops.push_back(*RegMaskIt);
600
601   // Add chain
602   Ops.push_back(CallNode->getOperand(0));
603
604   // Same for the glue, but we add it only if original call had it
605   if (Glue.getNode())
606     Ops.push_back(Glue);
607
608   // Compute return values.  Provide a glue output since we consume one as
609   // input.  This allows someone else to chain off us as needed.
610   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
611
612   SDNode *StatepointMCNode = DAG.getMachineNode(TargetOpcode::STATEPOINT,
613                                                 getCurSDLoc(), NodeTys, Ops);
614
615   // Replace original call
616   DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root
617   // Remove originall call node
618   DAG.DeleteNode(CallNode);
619
620   // DON'T set the root - under the assumption that it's already set past the
621   // inserted node we created.
622
623   // TODO: A better future implementation would be to emit a single variable
624   // argument, variable return value STATEPOINT node here and then hookup the
625   // return value of each gc.relocate to the respective output of the
626   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
627   // to actually be possible today.
628 }
629
630 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
631   // The result value of the gc_result is simply the result of the actual
632   // call.  We've already emitted this, so just grab the value.
633   Instruction *I = cast<Instruction>(CI.getArgOperand(0));
634   assert(isStatepoint(I) &&
635          "first argument must be a statepoint token");
636
637   setValue(&CI, getValue(I));
638 }
639
640 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
641 #ifndef NDEBUG
642   // Consistency check
643   StatepointLowering.relocCallVisited(CI);
644 #endif
645
646   GCRelocateOperands relocateOpers(&CI);
647   SDValue SD = getValue(relocateOpers.derivedPtr());
648
649   if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
650     // We didn't need to spill these special cases (constants and allocas).
651     // See the handling in spillIncomingValueForStatepoint for detail.
652     setValue(&CI, SD);
653     return;
654   }
655
656   SDValue Loc = StatepointLowering.getRelocLocation(SD);
657   // Emit new load if we did not emit it before
658   if (!Loc.getNode()) {
659     SDValue SpillSlot = StatepointLowering.getLocation(SD);
660     int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
661
662     // Be conservative: flush all pending loads
663     // TODO: Probably we can be less restrictive on this,
664     // it may allow more scheduling opprtunities
665     SDValue Chain = getRoot();
666
667     Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain,
668                       SpillSlot, MachinePointerInfo::getFixedStack(FI), false,
669                       false, false, 0);
670
671     StatepointLowering.setRelocLocation(SD, Loc);
672
673     // Again, be conservative, don't emit pending loads
674     DAG.setRoot(Loc.getValue(1));
675   }
676
677   assert(Loc.getNode());
678   setValue(&CI, Loc);
679 }