]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
Merge ^/head r284188 through r284643.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
42                                  SelectionDAGBuilder &Builder, uint64_t Value) {
43   SDLoc L = Builder.getCurSDLoc();
44   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
45                                               MVT::i64));
46   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
47 }
48
49 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
50   // Consistency check
51   assert(PendingGCRelocateCalls.empty() &&
52          "Trying to visit statepoint before finished processing previous one");
53   Locations.clear();
54   NextSlotToAllocate = 0;
55   // Need to resize this on each safepoint - we need the two to stay in
56   // sync and the clear patterns of a SelectionDAGBuilder have no relation
57   // to FunctionLoweringInfo.
58   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
59   for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
60     AllocatedStackSlots[i] = false;
61   }
62 }
63
64 void StatepointLoweringState::clear() {
65   Locations.clear();
66   AllocatedStackSlots.clear();
67   assert(PendingGCRelocateCalls.empty() &&
68          "cleared before statepoint sequence completed");
69 }
70
71 SDValue
72 StatepointLoweringState::allocateStackSlot(EVT ValueType,
73                                            SelectionDAGBuilder &Builder) {
74
75   NumSlotsAllocatedForStatepoints++;
76
77   // The basic scheme here is to first look for a previously created stack slot
78   // which is not in use (accounting for the fact arbitrary slots may already
79   // be reserved), or to create a new stack slot and use it.
80
81   // If this doesn't succeed in 40000 iterations, something is seriously wrong
82   for (int i = 0; i < 40000; i++) {
83     assert(Builder.FuncInfo.StatepointStackSlots.size() ==
84                AllocatedStackSlots.size() &&
85            "broken invariant");
86     const size_t NumSlots = AllocatedStackSlots.size();
87     assert(NextSlotToAllocate <= NumSlots && "broken invariant");
88
89     if (NextSlotToAllocate >= NumSlots) {
90       assert(NextSlotToAllocate == NumSlots);
91       // record stats
92       if (NumSlots + 1 > StatepointMaxSlotsRequired) {
93         StatepointMaxSlotsRequired = NumSlots + 1;
94       }
95
96       SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
97       const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
98       Builder.FuncInfo.StatepointStackSlots.push_back(FI);
99       AllocatedStackSlots.push_back(true);
100       return SpillSlot;
101     }
102     if (!AllocatedStackSlots[NextSlotToAllocate]) {
103       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
104       AllocatedStackSlots[NextSlotToAllocate] = true;
105       return Builder.DAG.getFrameIndex(FI, ValueType);
106     }
107     // Note: We deliberately choose to advance this only on the failing path.
108     // Doing so on the suceeding path involes a bit of complexity that caused a
109     // minor bug previously.  Unless performance shows this matters, please
110     // keep this code as simple as possible.
111     NextSlotToAllocate++;
112   }
113   llvm_unreachable("infinite loop?");
114 }
115
116 /// Try to find existing copies of the incoming values in stack slots used for
117 /// statepoint spilling.  If we can find a spill slot for the incoming value,
118 /// mark that slot as allocated, and reuse the same slot for this safepoint.
119 /// This helps to avoid series of loads and stores that only serve to resuffle
120 /// values on the stack between calls.
121 static void reservePreviousStackSlotForValue(SDValue Incoming,
122                                              SelectionDAGBuilder &Builder) {
123
124   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
125     // We won't need to spill this, so no need to check for previously
126     // allocated stack slots
127     return;
128   }
129
130   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
131   if (Loc.getNode()) {
132     // duplicates in input
133     return;
134   }
135
136   // Search back for the load from a stack slot pattern to find the original
137   // slot we allocated for this value.  We could extend this to deal with
138   // simple modification patterns, but simple dealing with trivial load/store
139   // sequences helps a lot already.
140   if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
141     if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
142       const int Index = FI->getIndex();
143       auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
144                            Builder.FuncInfo.StatepointStackSlots.end(), Index);
145       if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
146         // not one of the lowering stack slots, can't reuse!
147         // TODO: Actually, we probably could reuse the stack slot if the value
148         // hasn't changed at all, but we'd need to look for intervening writes
149         return;
150       } else {
151         // This is one of our dedicated lowering slots
152         const int Offset =
153             std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
154         if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
155           // stack slot already assigned to someone else, can't use it!
156           // TODO: currently we reserve space for gc arguments after doing
157           // normal allocation for deopt arguments.  We should reserve for
158           // _all_ deopt and gc arguments, then start allocating.  This
159           // will prevent some moves being inserted when vm state changes,
160           // but gc state doesn't between two calls.
161           return;
162         }
163         // Reserve this stack slot
164         Builder.StatepointLowering.reserveStackSlot(Offset);
165       }
166
167       // Cache this slot so we find it when going through the normal
168       // assignment loop.
169       SDValue Loc =
170           Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
171
172       Builder.StatepointLowering.setLocation(Incoming, Loc);
173     }
174   }
175
176   // TODO: handle case where a reloaded value flows through a phi to
177   // another safepoint.  e.g.
178   // bb1:
179   //  a' = relocated...
180   // bb2: % pred: bb1, bb3, bb4, etc.
181   //  a_phi = phi(a', ...)
182   // statepoint ... a_phi
183   // NOTE: This will require reasoning about cross basic block values.  This is
184   // decidedly non trivial and this might not be the right place to do it.  We
185   // don't really have the information we need here...
186
187   // TODO: handle simple updates.  If a value is modified and the original
188   // value is no longer live, it would be nice to put the modified value in the
189   // same slot.  This allows folding of the memory accesses for some
190   // instructions types (like an increment).
191   // statepoint (i)
192   // i1 = i+1
193   // statepoint (i1)
194 }
195
196 /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
197 /// is not required for correctness.  It's purpose is to reduce the size of
198 /// StackMap section.  It has no effect on the number of spill slots required
199 /// or the actual lowering.
200 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
201                                    SmallVectorImpl<const Value *> &Ptrs,
202                                    SmallVectorImpl<const Value *> &Relocs,
203                                    SelectionDAGBuilder &Builder) {
204
205   // This is horribly ineffecient, but I don't care right now
206   SmallSet<SDValue, 64> Seen;
207
208   SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
209   for (size_t i = 0; i < Ptrs.size(); i++) {
210     SDValue SD = Builder.getValue(Ptrs[i]);
211     // Only add non-duplicates
212     if (Seen.count(SD) == 0) {
213       NewBases.push_back(Bases[i]);
214       NewPtrs.push_back(Ptrs[i]);
215       NewRelocs.push_back(Relocs[i]);
216     }
217     Seen.insert(SD);
218   }
219   assert(Bases.size() >= NewBases.size());
220   assert(Ptrs.size() >= NewPtrs.size());
221   assert(Relocs.size() >= NewRelocs.size());
222   Bases = NewBases;
223   Ptrs = NewPtrs;
224   Relocs = NewRelocs;
225   assert(Ptrs.size() == Bases.size());
226   assert(Ptrs.size() == Relocs.size());
227 }
228
229 /// Extract call from statepoint, lower it and return pointer to the
230 /// call node. Also update NodeMap so that getValue(statepoint) will
231 /// reference lowered call result
232 static SDNode *
233 lowerCallFromStatepoint(ImmutableStatepoint ISP, MachineBasicBlock *LandingPad,
234                         SelectionDAGBuilder &Builder,
235                         SmallVectorImpl<SDValue> &PendingExports) {
236
237   ImmutableCallSite CS(ISP.getCallSite());
238
239   SDValue ActualCallee = Builder.getValue(ISP.getActualCallee());
240
241   assert(CS.getCallingConv() != CallingConv::AnyReg &&
242          "anyregcc is not supported on statepoints!");
243
244   Type *DefTy = ISP.getActualReturnType();
245   bool HasDef = !DefTy->isVoidTy();
246
247   SDValue ReturnValue, CallEndVal;
248   std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
249       ISP.getCallSite(), ImmutableStatepoint::CallArgsBeginPos,
250       ISP.getNumCallArgs(), ActualCallee, DefTy, LandingPad,
251       false /* IsPatchPoint */);
252
253   SDNode *CallEnd = CallEndVal.getNode();
254
255   // Get a call instruction from the call sequence chain.  Tail calls are not
256   // allowed.  The following code is essentially reverse engineering X86's
257   // LowerCallTo.
258   //
259   // We are expecting DAG to have the following form:
260   //
261   // ch = eh_label (only in case of invoke statepoint)
262   //   ch, glue = callseq_start ch
263   //   ch, glue = X86::Call ch, glue
264   //   ch, glue = callseq_end ch, glue
265   //   get_return_value ch, glue
266   //
267   // get_return_value can either be a CopyFromReg to grab the return value from
268   // %RAX, or it can be a LOAD to load a value returned by reference via a stack
269   // slot.
270
271   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg ||
272                  CallEnd->getOpcode() == ISD::LOAD))
273     CallEnd = CallEnd->getOperand(0).getNode();
274
275   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
276
277   if (HasDef) {
278     if (CS.isInvoke()) {
279       // Result value will be used in different basic block for invokes
280       // so we need to export it now. But statepoint call has a different type
281       // than the actuall call. It means that standart exporting mechanism will
282       // create register of the wrong type. So instead we need to create
283       // register with correct type and save value into it manually.
284       // TODO: To eliminate this problem we can remove gc.result intrinsics
285       //       completelly and make statepoint call to return a tuple.
286       unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
287       RegsForValue RFV(*Builder.DAG.getContext(),
288                        Builder.DAG.getTargetLoweringInfo(), Reg,
289                        ISP.getActualReturnType());
290       SDValue Chain = Builder.DAG.getEntryNode();
291
292       RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
293                         nullptr);
294       PendingExports.push_back(Chain);
295       Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
296     } else {
297       // The value of the statepoint itself will be the value of call itself.
298       // We'll replace the actually call node shortly.  gc_result will grab
299       // this value.
300       Builder.setValue(CS.getInstruction(), ReturnValue);
301     }
302   } else {
303     // The token value is never used from here on, just generate a poison value
304     Builder.setValue(CS.getInstruction(),
305                      Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
306   }
307
308   return CallEnd->getOperand(0).getNode();
309 }
310
311 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
312 /// and return two arrays:
313 ///   Bases - base pointers incoming to this statepoint
314 ///   Ptrs - derived pointers incoming to this statepoint
315 ///   Relocs - the gc_relocate corresponding to each base/ptr pair
316 /// Elements of this arrays should be in one-to-one correspondence with each
317 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
318 static void getIncomingStatepointGCValues(
319     SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
320     SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
321     SelectionDAGBuilder &Builder) {
322   for (GCRelocateOperands relocateOpers :
323        StatepointSite.getRelocates(StatepointSite)) {
324     Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
325     Bases.push_back(relocateOpers.getBasePtr());
326     Ptrs.push_back(relocateOpers.getDerivedPtr());
327   }
328
329   // Remove any redundant llvm::Values which map to the same SDValue as another
330   // input.  Also has the effect of removing duplicates in the original
331   // llvm::Value input list as well.  This is a useful optimization for
332   // reducing the size of the StackMap section.  It has no other impact.
333   removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
334
335   assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
336 }
337
338 /// Spill a value incoming to the statepoint. It might be either part of
339 /// vmstate
340 /// or gcstate. In both cases unconditionally spill it on the stack unless it
341 /// is a null constant. Return pair with first element being frame index
342 /// containing saved value and second element with outgoing chain from the
343 /// emitted store
344 static std::pair<SDValue, SDValue>
345 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
346                              SelectionDAGBuilder &Builder) {
347   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
348
349   // Emit new store if we didn't do it for this ptr before
350   if (!Loc.getNode()) {
351     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
352                                                        Builder);
353     assert(isa<FrameIndexSDNode>(Loc));
354     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
355     // We use TargetFrameIndex so that isel will not select it into LEA
356     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
357
358     // TODO: We can create TokenFactor node instead of
359     //       chaining stores one after another, this may allow
360     //       a bit more optimal scheduling for them
361     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
362                                  MachinePointerInfo::getFixedStack(Index),
363                                  false, false, 0);
364
365     Builder.StatepointLowering.setLocation(Incoming, Loc);
366   }
367
368   assert(Loc.getNode());
369   return std::make_pair(Loc, Chain);
370 }
371
372 /// Lower a single value incoming to a statepoint node.  This value can be
373 /// either a deopt value or a gc value, the handling is the same.  We special
374 /// case constants and allocas, then fall back to spilling if required.
375 static void lowerIncomingStatepointValue(SDValue Incoming,
376                                          SmallVectorImpl<SDValue> &Ops,
377                                          SelectionDAGBuilder &Builder) {
378   SDValue Chain = Builder.getRoot();
379
380   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
381     // If the original value was a constant, make sure it gets recorded as
382     // such in the stackmap.  This is required so that the consumer can
383     // parse any internal format to the deopt state.  It also handles null
384     // pointers and other constant pointers in GC states
385     pushStackMapConstant(Ops, Builder, C->getSExtValue());
386   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
387     // This handles allocas as arguments to the statepoint (this is only
388     // really meaningful for a deopt value.  For GC, we'd be trying to
389     // relocate the address of the alloca itself?)
390     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
391                                                   Incoming.getValueType()));
392   } else {
393     // Otherwise, locate a spill slot and explicitly spill it so it
394     // can be found by the runtime later.  We currently do not support
395     // tracking values through callee saved registers to their eventual
396     // spill location.  This would be a useful optimization, but would
397     // need to be optional since it requires a lot of complexity on the
398     // runtime side which not all would support.
399     std::pair<SDValue, SDValue> Res =
400         spillIncomingStatepointValue(Incoming, Chain, Builder);
401     Ops.push_back(Res.first);
402     Chain = Res.second;
403   }
404
405   Builder.DAG.setRoot(Chain);
406 }
407
408 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
409 /// lowering is described in lowerIncomingStatepointValue.  This function is
410 /// responsible for lowering everything in the right position and playing some
411 /// tricks to avoid redundant stack manipulation where possible.  On
412 /// completion, 'Ops' will contain ready to use operands for machine code
413 /// statepoint. The chain nodes will have already been created and the DAG root
414 /// will be set to the last value spilled (if any were).
415 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
416                                     ImmutableStatepoint StatepointSite,
417                                     SelectionDAGBuilder &Builder) {
418
419   // Lower the deopt and gc arguments for this statepoint.  Layout will
420   // be: deopt argument length, deopt arguments.., gc arguments...
421
422   SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
423   getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
424                                 Builder);
425
426 #ifndef NDEBUG
427   // Check that each of the gc pointer and bases we've gotten out of the
428   // safepoint is something the strategy thinks might be a pointer into the GC
429   // heap.  This is basically just here to help catch errors during statepoint
430   // insertion. TODO: This should actually be in the Verifier, but we can't get
431   // to the GCStrategy from there (yet).
432   GCStrategy &S = Builder.GFI->getStrategy();
433   for (const Value *V : Bases) {
434     auto Opt = S.isGCManagedPointer(V);
435     if (Opt.hasValue()) {
436       assert(Opt.getValue() &&
437              "non gc managed base pointer found in statepoint");
438     }
439   }
440   for (const Value *V : Ptrs) {
441     auto Opt = S.isGCManagedPointer(V);
442     if (Opt.hasValue()) {
443       assert(Opt.getValue() &&
444              "non gc managed derived pointer found in statepoint");
445     }
446   }
447   for (const Value *V : Relocations) {
448     auto Opt = S.isGCManagedPointer(V);
449     if (Opt.hasValue()) {
450       assert(Opt.getValue() && "non gc managed pointer relocated");
451     }
452   }
453 #endif
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 (const Value *V : StatepointSite.vm_state_args()) {
461     SDValue Incoming = Builder.getValue(V);
462     reservePreviousStackSlotForValue(Incoming, Builder);
463   }
464   for (unsigned i = 0; i < Bases.size(); ++i) {
465     const Value *Base = Bases[i];
466     reservePreviousStackSlotForValue(Builder.getValue(Base), Builder);
467
468     const Value *Ptr = Ptrs[i];
469     reservePreviousStackSlotForValue(Builder.getValue(Ptr), Builder);
470   }
471
472   // First, prefix the list with the number of unique values to be
473   // lowered.  Note that this is the number of *Values* not the
474   // number of SDValues required to lower them.
475   const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
476   pushStackMapConstant(Ops, Builder, NumVMSArgs);
477
478   assert(NumVMSArgs == std::distance(StatepointSite.vm_state_begin(),
479                                      StatepointSite.vm_state_end()));
480
481   // The vm state arguments are lowered in an opaque manner.  We do
482   // not know what type of values are contained within.  We skip the
483   // first one since that happens to be the total number we lowered
484   // explicitly just above.  We could have left it in the loop and
485   // not done it explicitly, but it's far easier to understand this
486   // way.
487   for (const Value *V : StatepointSite.vm_state_args()) {
488     SDValue Incoming = Builder.getValue(V);
489     lowerIncomingStatepointValue(Incoming, Ops, Builder);
490   }
491
492   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
493   // length for this one.  After lowering, we'll have the base and pointer
494   // arrays interwoven with each (lowered) base pointer immediately followed by
495   // it's (lowered) derived pointer.  i.e
496   // (base[0], ptr[0], base[1], ptr[1], ...)
497   for (unsigned i = 0; i < Bases.size(); ++i) {
498     const Value *Base = Bases[i];
499     lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
500
501     const Value *Ptr = Ptrs[i];
502     lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
503   }
504
505   // If there are any explicit spill slots passed to the statepoint, record
506   // them, but otherwise do not do anything special.  These are user provided
507   // allocas and give control over placement to the consumer.  In this case,
508   // it is the contents of the slot which may get updated, not the pointer to
509   // the alloca
510   for (Value *V : StatepointSite.gc_args()) {
511     SDValue Incoming = Builder.getValue(V);
512     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
513       // This handles allocas as arguments to the statepoint
514       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
515                                                     Incoming.getValueType()));
516     }
517   }
518
519   // Record computed locations for all lowered values.
520   // This can not be embedded in lowering loops as we need to record *all*
521   // values, while previous loops account only values with unique SDValues.
522   const Instruction *StatepointInstr =
523     StatepointSite.getCallSite().getInstruction();
524   FunctionLoweringInfo::StatepointSpilledValueMapTy &SpillMap =
525     Builder.FuncInfo.StatepointRelocatedValues[StatepointInstr];
526
527   for (GCRelocateOperands RelocateOpers :
528        StatepointSite.getRelocates(StatepointSite)) {
529     const Value *V = RelocateOpers.getDerivedPtr();
530     SDValue SDV = Builder.getValue(V);
531     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
532
533     if (Loc.getNode()) {
534       SpillMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
535     } else {
536       // Record value as visited, but not spilled. This is case for allocas
537       // and constants. For this values we can avoid emiting spill load while
538       // visiting corresponding gc_relocate.
539       // Actually we do not need to record them in this map at all.
540       // We do this only to check that we are not relocating any unvisited value.
541       SpillMap[V] = None;
542
543       // Default llvm mechanisms for exporting values which are used in
544       // different basic blocks does not work for gc relocates.
545       // Note that it would be incorrect to teach llvm that all relocates are
546       // uses of the corresponging values so that it would automatically
547       // export them. Relocates of the spilled values does not use original
548       // value.
549       if (StatepointSite.getCallSite().isInvoke())
550         Builder.ExportFromCurrentBlock(V);
551     }
552   }
553 }
554
555 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
556   // Check some preconditions for sanity
557   assert(isStatepoint(&CI) &&
558          "function called must be the statepoint function");
559
560   LowerStatepoint(ImmutableStatepoint(&CI));
561 }
562
563 void SelectionDAGBuilder::LowerStatepoint(
564     ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
565   // The basic scheme here is that information about both the original call and
566   // the safepoint is encoded in the CallInst.  We create a temporary call and
567   // lower it, then reverse engineer the calling sequence.
568
569   NumOfStatepoints++;
570   // Clear state
571   StatepointLowering.startNewStatepoint(*this);
572
573   ImmutableCallSite CS(ISP.getCallSite());
574
575 #ifndef NDEBUG
576   // Consistency check. Don't do this for invokes. It would be too
577   // expensive to preserve this information across different basic blocks
578   if (!CS.isInvoke()) {
579     for (const User *U : CS->users()) {
580       const CallInst *Call = cast<CallInst>(U);
581       if (isGCRelocate(Call))
582         StatepointLowering.scheduleRelocCall(*Call);
583     }
584   }
585 #endif
586
587 #ifndef NDEBUG
588   // If this is a malformed statepoint, report it early to simplify debugging.
589   // This should catch any IR level mistake that's made when constructing or
590   // transforming statepoints.
591   ISP.verify();
592
593   // Check that the associated GCStrategy expects to encounter statepoints.
594   assert(GFI->getStrategy().useStatepoints() &&
595          "GCStrategy does not expect to encounter statepoints");
596 #endif
597
598   // Lower statepoint vmstate and gcstate arguments
599   SmallVector<SDValue, 10> LoweredMetaArgs;
600   lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
601
602   // Get call node, we will replace it later with statepoint
603   SDNode *CallNode =
604       lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
605
606   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
607   // nodes with all the appropriate arguments and return values.
608
609   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
610   SDValue Chain = CallNode->getOperand(0);
611
612   SDValue Glue;
613   bool CallHasIncomingGlue = CallNode->getGluedNode();
614   if (CallHasIncomingGlue) {
615     // Glue is always last operand
616     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
617   }
618
619   // Build the GC_TRANSITION_START node if necessary.
620   //
621   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
622   // order in which they appear in the call to the statepoint intrinsic. If
623   // any of the operands is a pointer-typed, that operand is immediately
624   // followed by a SRCVALUE for the pointer that may be used during lowering
625   // (e.g. to form MachinePointerInfo values for loads/stores).
626   const bool IsGCTransition =
627       (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
628           (uint64_t)StatepointFlags::GCTransition;
629   if (IsGCTransition) {
630     SmallVector<SDValue, 8> TSOps;
631
632     // Add chain
633     TSOps.push_back(Chain);
634
635     // Add GC transition arguments
636     for (const Value *V : ISP.gc_transition_args()) {
637       TSOps.push_back(getValue(V));
638       if (V->getType()->isPointerTy())
639         TSOps.push_back(DAG.getSrcValue(V));
640     }
641
642     // Add glue if necessary
643     if (CallHasIncomingGlue)
644       TSOps.push_back(Glue);
645
646     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
647
648     SDValue GCTransitionStart =
649         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
650
651     Chain = GCTransitionStart.getValue(0);
652     Glue = GCTransitionStart.getValue(1);
653   }
654
655   // TODO: Currently, all of these operands are being marked as read/write in
656   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
657   // and flags to be read-only.
658   SmallVector<SDValue, 40> Ops;
659
660   // Add the <id> and <numBytes> constants.
661   Ops.push_back(DAG.getTargetConstant(ISP.getID(), getCurSDLoc(), MVT::i64));
662   Ops.push_back(
663       DAG.getTargetConstant(ISP.getNumPatchBytes(), getCurSDLoc(), MVT::i32));
664
665   // Calculate and push starting position of vmstate arguments
666   // Get number of arguments incoming directly into call node
667   unsigned NumCallRegArgs =
668       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
669   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
670
671   // Add call target
672   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
673   Ops.push_back(CallTarget);
674
675   // Add call arguments
676   // Get position of register mask in the call
677   SDNode::op_iterator RegMaskIt;
678   if (CallHasIncomingGlue)
679     RegMaskIt = CallNode->op_end() - 2;
680   else
681     RegMaskIt = CallNode->op_end() - 1;
682   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
683
684   // Add a constant argument for the calling convention
685   pushStackMapConstant(Ops, *this, CS.getCallingConv());
686
687   // Add a constant argument for the flags
688   uint64_t Flags = ISP.getFlags();
689   assert(
690       ((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0)
691           && "unknown flag used");
692   pushStackMapConstant(Ops, *this, Flags);
693
694   // Insert all vmstate and gcstate arguments
695   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
696
697   // Add register mask from call node
698   Ops.push_back(*RegMaskIt);
699
700   // Add chain
701   Ops.push_back(Chain);
702
703   // Same for the glue, but we add it only if original call had it
704   if (Glue.getNode())
705     Ops.push_back(Glue);
706
707   // Compute return values.  Provide a glue output since we consume one as
708   // input.  This allows someone else to chain off us as needed.
709   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
710
711   SDNode *StatepointMCNode =
712       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
713
714   SDNode *SinkNode = StatepointMCNode;
715
716   // Build the GC_TRANSITION_END node if necessary.
717   //
718   // See the comment above regarding GC_TRANSITION_START for the layout of
719   // the operands to the GC_TRANSITION_END node.
720   if (IsGCTransition) {
721     SmallVector<SDValue, 8> TEOps;
722
723     // Add chain
724     TEOps.push_back(SDValue(StatepointMCNode, 0));
725
726     // Add GC transition arguments
727     for (const Value *V : ISP.gc_transition_args()) {
728       TEOps.push_back(getValue(V));
729       if (V->getType()->isPointerTy())
730         TEOps.push_back(DAG.getSrcValue(V));
731     }
732
733     // Add glue
734     TEOps.push_back(SDValue(StatepointMCNode, 1));
735
736     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
737
738     SDValue GCTransitionStart =
739         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
740
741     SinkNode = GCTransitionStart.getNode();
742   }
743
744   // Replace original call
745   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
746   // Remove originall call node
747   DAG.DeleteNode(CallNode);
748
749   // DON'T set the root - under the assumption that it's already set past the
750   // inserted node we created.
751
752   // TODO: A better future implementation would be to emit a single variable
753   // argument, variable return value STATEPOINT node here and then hookup the
754   // return value of each gc.relocate to the respective output of the
755   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
756   // to actually be possible today.
757 }
758
759 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
760   // The result value of the gc_result is simply the result of the actual
761   // call.  We've already emitted this, so just grab the value.
762   Instruction *I = cast<Instruction>(CI.getArgOperand(0));
763   assert(isStatepoint(I) && "first argument must be a statepoint token");
764
765   if (isa<InvokeInst>(I)) {
766     // For invokes we should have stored call result in a virtual register.
767     // We can not use default getValue() functionality to copy value from this
768     // register because statepoint and actuall call return types can be
769     // different, and getValue() will use CopyFromReg of the wrong type,
770     // which is always i32 in our case.
771     PointerType *CalleeType =
772         cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
773     Type *RetTy =
774         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
775     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
776
777     assert(CopyFromReg.getNode());
778     setValue(&CI, CopyFromReg);
779   } else {
780     setValue(&CI, getValue(I));
781   }
782 }
783
784 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
785   GCRelocateOperands RelocateOpers(&CI);
786
787 #ifndef NDEBUG
788   // Consistency check
789   // We skip this check for invoke statepoints. It would be too expensive to
790   // preserve validation info through different basic blocks.
791   if (!RelocateOpers.isTiedToInvoke()) {
792     StatepointLowering.relocCallVisited(CI);
793   }
794 #endif
795
796   const Value *DerivedPtr = RelocateOpers.getDerivedPtr();
797   SDValue SD = getValue(DerivedPtr);
798
799   FunctionLoweringInfo::StatepointSpilledValueMapTy &SpillMap =
800     FuncInfo.StatepointRelocatedValues[RelocateOpers.getStatepoint()];
801
802   // We should have recorded location for this pointer
803   assert(SpillMap.count(DerivedPtr) && "Relocating not lowered gc value");
804   Optional<int> DerivedPtrLocation = SpillMap[DerivedPtr];
805
806   // We didn't need to spill these special cases (constants and allocas).
807   // See the handling in spillIncomingValueForStatepoint for detail.
808   if (!DerivedPtrLocation) {
809     setValue(&CI, SD);
810     return;
811   }
812
813   SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
814                                               SD.getValueType());
815
816   // Be conservative: flush all pending loads
817   // TODO: Probably we can be less restrictive on this,
818   // it may allow more scheduling opprtunities
819   SDValue Chain = getRoot();
820
821   SDValue SpillLoad =
822     DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
823                 MachinePointerInfo::getFixedStack(*DerivedPtrLocation),
824                 false, false, false, 0);
825
826   // Again, be conservative, don't emit pending loads
827   DAG.setRoot(SpillLoad.getValue(1));
828
829   assert(SpillLoad.getNode());
830   setValue(&CI, SpillLoad);
831 }