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