1 //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file includes support code use by SelectionDAGBuilder when lowering a
10 // statepoint sequence in SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "StatepointLowering.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GCMetadata.h"
26 #include "llvm/CodeGen/GCStrategy.h"
27 #include "llvm/CodeGen/ISDOpcodes.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/RuntimeLibcalls.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/CodeGen/StackMaps.h"
35 #include "llvm/CodeGen/TargetLowering.h"
36 #include "llvm/CodeGen/TargetOpcodes.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Statepoint.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/MachineValueType.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <cassert>
50 #include <cstddef>
51 #include <cstdint>
52 #include <iterator>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "statepoint-lowering"
59 
60 STATISTIC(NumSlotsAllocatedForStatepoints,
61           "Number of stack slots allocated for statepoints");
62 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
63 STATISTIC(StatepointMaxSlotsRequired,
64           "Maximum number of stack slots required for a singe statepoint");
65 
66 cl::opt<bool> UseRegistersForDeoptValues(
67     "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
68     cl::desc("Allow using registers for non pointer deopt args"));
69 
70 cl::opt<unsigned> MaxRegistersForGCPointers(
71     "max-registers-for-gc-values", cl::Hidden, cl::init(0),
72     cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
73 
74 static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
75                                  SelectionDAGBuilder &Builder, uint64_t Value) {
76   SDLoc L = Builder.getCurSDLoc();
77   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
78                                               MVT::i64));
79   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
80 }
81 
82 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
83   // Consistency check
84   assert(PendingGCRelocateCalls.empty() &&
85          "Trying to visit statepoint before finished processing previous one");
86   Locations.clear();
87   NextSlotToAllocate = 0;
88   // Need to resize this on each safepoint - we need the two to stay in sync and
89   // the clear patterns of a SelectionDAGBuilder have no relation to
90   // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
91   AllocatedStackSlots.clear();
92   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
93   DerivedPtrMap.clear();
94 }
95 
96 void StatepointLoweringState::clear() {
97   Locations.clear();
98   AllocatedStackSlots.clear();
99   DerivedPtrMap.clear();
100   assert(PendingGCRelocateCalls.empty() &&
101          "cleared before statepoint sequence completed");
102 }
103 
104 SDValue
105 StatepointLoweringState::allocateStackSlot(EVT ValueType,
106                                            SelectionDAGBuilder &Builder) {
107   NumSlotsAllocatedForStatepoints++;
108   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
109 
110   unsigned SpillSize = ValueType.getStoreSize();
111   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
112 
113   // First look for a previously created stack slot which is not in
114   // use (accounting for the fact arbitrary slots may already be
115   // reserved), or to create a new stack slot and use it.
116 
117   const size_t NumSlots = AllocatedStackSlots.size();
118   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
119 
120   assert(AllocatedStackSlots.size() ==
121          Builder.FuncInfo.StatepointStackSlots.size() &&
122          "Broken invariant");
123 
124   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
125     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
126       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
127       if (MFI.getObjectSize(FI) == SpillSize) {
128         AllocatedStackSlots.set(NextSlotToAllocate);
129         // TODO: Is ValueType the right thing to use here?
130         return Builder.DAG.getFrameIndex(FI, ValueType);
131       }
132     }
133   }
134 
135   // Couldn't find a free slot, so create a new one:
136 
137   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
138   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
139   MFI.markAsStatepointSpillSlotObjectIndex(FI);
140 
141   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
142   AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
143   assert(AllocatedStackSlots.size() ==
144          Builder.FuncInfo.StatepointStackSlots.size() &&
145          "Broken invariant");
146 
147   StatepointMaxSlotsRequired.updateMax(
148       Builder.FuncInfo.StatepointStackSlots.size());
149 
150   return SpillSlot;
151 }
152 
153 /// Utility function for reservePreviousStackSlotForValue. Tries to find
154 /// stack slot index to which we have spilled value for previous statepoints.
155 /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
156 static Optional<int> findPreviousSpillSlot(const Value *Val,
157                                            SelectionDAGBuilder &Builder,
158                                            int LookUpDepth) {
159   // Can not look any further - give up now
160   if (LookUpDepth <= 0)
161     return None;
162 
163   // Spill location is known for gc relocates
164   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
165     const auto &SpillMap =
166         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
167 
168     auto It = SpillMap.find(Relocate->getDerivedPtr());
169     if (It == SpillMap.end())
170       return None;
171 
172     return It->second;
173   }
174 
175   // Look through bitcast instructions.
176   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
177     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
178 
179   // Look through phi nodes
180   // All incoming values should have same known stack slot, otherwise result
181   // is unknown.
182   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
183     Optional<int> MergedResult = None;
184 
185     for (auto &IncomingValue : Phi->incoming_values()) {
186       Optional<int> SpillSlot =
187           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
188       if (!SpillSlot.hasValue())
189         return None;
190 
191       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
192         return None;
193 
194       MergedResult = SpillSlot;
195     }
196     return MergedResult;
197   }
198 
199   // TODO: We can do better for PHI nodes. In cases like this:
200   //   ptr = phi(relocated_pointer, not_relocated_pointer)
201   //   statepoint(ptr)
202   // We will return that stack slot for ptr is unknown. And later we might
203   // assign different stack slots for ptr and relocated_pointer. This limits
204   // llvm's ability to remove redundant stores.
205   // Unfortunately it's hard to accomplish in current infrastructure.
206   // We use this function to eliminate spill store completely, while
207   // in example we still need to emit store, but instead of any location
208   // we need to use special "preferred" location.
209 
210   // TODO: handle simple updates.  If a value is modified and the original
211   // value is no longer live, it would be nice to put the modified value in the
212   // same slot.  This allows folding of the memory accesses for some
213   // instructions types (like an increment).
214   //   statepoint (i)
215   //   i1 = i+1
216   //   statepoint (i1)
217   // However we need to be careful for cases like this:
218   //   statepoint(i)
219   //   i1 = i+1
220   //   statepoint(i, i1)
221   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
222   // put handling of simple modifications in this function like it's done
223   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
224   // which we visit values is unspecified.
225 
226   // Don't know any information about this instruction
227   return None;
228 }
229 
230 /// Return true if-and-only-if the given SDValue can be lowered as either a
231 /// constant argument or a stack reference.  The key point is that the value
232 /// doesn't need to be spilled or tracked as a vreg use.
233 static bool willLowerDirectly(SDValue Incoming) {
234   // We are making an unchecked assumption that the frame size <= 2^16 as that
235   // is the largest offset which can be encoded in the stackmap format.
236   if (isa<FrameIndexSDNode>(Incoming))
237     return true;
238 
239   // The largest constant describeable in the StackMap format is 64 bits.
240   // Potential Optimization:  Constants values are sign extended by consumer,
241   // and thus there are many constants of static type > 64 bits whose value
242   // happens to be sext(Con64) and could thus be lowered directly.
243   if (Incoming.getValueType().getSizeInBits() > 64)
244     return false;
245 
246   return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
247           Incoming.isUndef());
248 }
249 
250 /// Try to find existing copies of the incoming values in stack slots used for
251 /// statepoint spilling.  If we can find a spill slot for the incoming value,
252 /// mark that slot as allocated, and reuse the same slot for this safepoint.
253 /// This helps to avoid series of loads and stores that only serve to reshuffle
254 /// values on the stack between calls.
255 static void reservePreviousStackSlotForValue(const Value *IncomingValue,
256                                              SelectionDAGBuilder &Builder) {
257   SDValue Incoming = Builder.getValue(IncomingValue);
258 
259   // If we won't spill this, we don't need to check for previously allocated
260   // stack slots.
261   if (willLowerDirectly(Incoming))
262     return;
263 
264   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
265   if (OldLocation.getNode())
266     // Duplicates in input
267     return;
268 
269   const int LookUpDepth = 6;
270   Optional<int> Index =
271       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
272   if (!Index.hasValue())
273     return;
274 
275   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
276 
277   auto SlotIt = find(StatepointSlots, *Index);
278   assert(SlotIt != StatepointSlots.end() &&
279          "Value spilled to the unknown stack slot");
280 
281   // This is one of our dedicated lowering slots
282   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
283   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
284     // stack slot already assigned to someone else, can't use it!
285     // TODO: currently we reserve space for gc arguments after doing
286     // normal allocation for deopt arguments.  We should reserve for
287     // _all_ deopt and gc arguments, then start allocating.  This
288     // will prevent some moves being inserted when vm state changes,
289     // but gc state doesn't between two calls.
290     return;
291   }
292   // Reserve this stack slot
293   Builder.StatepointLowering.reserveStackSlot(Offset);
294 
295   // Cache this slot so we find it when going through the normal
296   // assignment loop.
297   SDValue Loc =
298       Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
299   Builder.StatepointLowering.setLocation(Incoming, Loc);
300 }
301 
302 /// Extract call from statepoint, lower it and return pointer to the
303 /// call node. Also update NodeMap so that getValue(statepoint) will
304 /// reference lowered call result
305 static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
306     SelectionDAGBuilder::StatepointLoweringInfo &SI,
307     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
308   SDValue ReturnValue, CallEndVal;
309   std::tie(ReturnValue, CallEndVal) =
310       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
311   SDNode *CallEnd = CallEndVal.getNode();
312 
313   // Get a call instruction from the call sequence chain.  Tail calls are not
314   // allowed.  The following code is essentially reverse engineering X86's
315   // LowerCallTo.
316   //
317   // We are expecting DAG to have the following form:
318   //
319   // ch = eh_label (only in case of invoke statepoint)
320   //   ch, glue = callseq_start ch
321   //   ch, glue = X86::Call ch, glue
322   //   ch, glue = callseq_end ch, glue
323   //   get_return_value ch, glue
324   //
325   // get_return_value can either be a sequence of CopyFromReg instructions
326   // to grab the return value from the return register(s), or it can be a LOAD
327   // to load a value returned by reference via a stack slot.
328 
329   bool HasDef = !SI.CLI.RetTy->isVoidTy();
330   if (HasDef) {
331     if (CallEnd->getOpcode() == ISD::LOAD)
332       CallEnd = CallEnd->getOperand(0).getNode();
333     else
334       while (CallEnd->getOpcode() == ISD::CopyFromReg)
335         CallEnd = CallEnd->getOperand(0).getNode();
336   }
337 
338   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
339   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
340 }
341 
342 static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
343                                                FrameIndexSDNode &FI) {
344   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
345   auto MMOFlags = MachineMemOperand::MOStore |
346     MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
347   auto &MFI = MF.getFrameInfo();
348   return MF.getMachineMemOperand(PtrInfo, MMOFlags,
349                                  MFI.getObjectSize(FI.getIndex()),
350                                  MFI.getObjectAlign(FI.getIndex()));
351 }
352 
353 /// Spill a value incoming to the statepoint. It might be either part of
354 /// vmstate
355 /// or gcstate. In both cases unconditionally spill it on the stack unless it
356 /// is a null constant. Return pair with first element being frame index
357 /// containing saved value and second element with outgoing chain from the
358 /// emitted store
359 static std::tuple<SDValue, SDValue, MachineMemOperand*>
360 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
361                              SelectionDAGBuilder &Builder) {
362   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
363   MachineMemOperand* MMO = nullptr;
364 
365   // Emit new store if we didn't do it for this ptr before
366   if (!Loc.getNode()) {
367     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
368                                                        Builder);
369     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
370     // We use TargetFrameIndex so that isel will not select it into LEA
371     Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
372 
373     // Right now we always allocate spill slots that are of the same
374     // size as the value we're about to spill (the size of spillee can
375     // vary since we spill vectors of pointers too).  At some point we
376     // can consider allowing spills of smaller values to larger slots
377     // (i.e. change the '==' in the assert below to a '>=').
378     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
379     assert((MFI.getObjectSize(Index) * 8) ==
380            (int64_t)Incoming.getValueSizeInBits() &&
381            "Bad spill:  stack slot does not match!");
382 
383     // Note: Using the alignment of the spill slot (rather than the abi or
384     // preferred alignment) is required for correctness when dealing with spill
385     // slots with preferred alignments larger than frame alignment..
386     auto &MF = Builder.DAG.getMachineFunction();
387     auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
388     auto *StoreMMO = MF.getMachineMemOperand(
389         PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
390         MFI.getObjectAlign(Index));
391     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
392                                  StoreMMO);
393 
394     MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
395 
396     Builder.StatepointLowering.setLocation(Incoming, Loc);
397   }
398 
399   assert(Loc.getNode());
400   return std::make_tuple(Loc, Chain, MMO);
401 }
402 
403 /// Lower a single value incoming to a statepoint node.  This value can be
404 /// either a deopt value or a gc value, the handling is the same.  We special
405 /// case constants and allocas, then fall back to spilling if required.
406 static void
407 lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
408                              SmallVectorImpl<SDValue> &Ops,
409                              SmallVectorImpl<MachineMemOperand *> &MemRefs,
410                              SelectionDAGBuilder &Builder) {
411 
412   if (willLowerDirectly(Incoming)) {
413     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
414       // This handles allocas as arguments to the statepoint (this is only
415       // really meaningful for a deopt value.  For GC, we'd be trying to
416       // relocate the address of the alloca itself?)
417       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
418              "Incoming value is a frame index!");
419       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
420                                                     Builder.getFrameIndexTy()));
421 
422       auto &MF = Builder.DAG.getMachineFunction();
423       auto *MMO = getMachineMemOperand(MF, *FI);
424       MemRefs.push_back(MMO);
425       return;
426     }
427 
428     assert(Incoming.getValueType().getSizeInBits() <= 64);
429 
430     if (Incoming.isUndef()) {
431       // Put an easily recognized constant that's unlikely to be a valid
432       // value so that uses of undef by the consumer of the stackmap is
433       // easily recognized. This is legal since the compiler is always
434       // allowed to chose an arbitrary value for undef.
435       pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
436       return;
437     }
438 
439     // If the original value was a constant, make sure it gets recorded as
440     // such in the stackmap.  This is required so that the consumer can
441     // parse any internal format to the deopt state.  It also handles null
442     // pointers and other constant pointers in GC states.
443     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
444       pushStackMapConstant(Ops, Builder, C->getSExtValue());
445       return;
446     } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
447       pushStackMapConstant(Ops, Builder,
448                            C->getValueAPF().bitcastToAPInt().getZExtValue());
449       return;
450     }
451 
452     llvm_unreachable("unhandled direct lowering case");
453   }
454 
455 
456 
457   if (!RequireSpillSlot) {
458     // If this value is live in (not live-on-return, or live-through), we can
459     // treat it the same way patchpoint treats it's "live in" values.  We'll
460     // end up folding some of these into stack references, but they'll be
461     // handled by the register allocator.  Note that we do not have the notion
462     // of a late use so these values might be placed in registers which are
463     // clobbered by the call.  This is fine for live-in. For live-through
464     // fix-up pass should be executed to force spilling of such registers.
465     Ops.push_back(Incoming);
466   } else {
467     // Otherwise, locate a spill slot and explicitly spill it so it can be
468     // found by the runtime later.  Note: We know all of these spills are
469     // independent, but don't bother to exploit that chain wise.  DAGCombine
470     // will happily do so as needed, so doing it here would be a small compile
471     // time win at most.
472     SDValue Chain = Builder.getRoot();
473     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
474     Ops.push_back(std::get<0>(Res));
475     if (auto *MMO = std::get<2>(Res))
476       MemRefs.push_back(MMO);
477     Chain = std::get<1>(Res);;
478     Builder.DAG.setRoot(Chain);
479   }
480 
481 }
482 
483 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
484 /// lowering is described in lowerIncomingStatepointValue.  This function is
485 /// responsible for lowering everything in the right position and playing some
486 /// tricks to avoid redundant stack manipulation where possible.  On
487 /// completion, 'Ops' will contain ready to use operands for machine code
488 /// statepoint. The chain nodes will have already been created and the DAG root
489 /// will be set to the last value spilled (if any were).
490 static void
491 lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
492                         SmallVectorImpl<MachineMemOperand *> &MemRefs,
493                         DenseMap<SDValue, int> &LowerAsVReg,
494                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
495                         SelectionDAGBuilder &Builder) {
496   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
497   // deopt argument length, deopt arguments.., gc arguments...
498 #ifndef NDEBUG
499   if (auto *GFI = Builder.GFI) {
500     // Check that each of the gc pointer and bases we've gotten out of the
501     // safepoint is something the strategy thinks might be a pointer (or vector
502     // of pointers) into the GC heap.  This is basically just here to help catch
503     // errors during statepoint insertion. TODO: This should actually be in the
504     // Verifier, but we can't get to the GCStrategy from there (yet).
505     GCStrategy &S = GFI->getStrategy();
506     for (const Value *V : SI.Bases) {
507       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
508       if (Opt.hasValue()) {
509         assert(Opt.getValue() &&
510                "non gc managed base pointer found in statepoint");
511       }
512     }
513     for (const Value *V : SI.Ptrs) {
514       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
515       if (Opt.hasValue()) {
516         assert(Opt.getValue() &&
517                "non gc managed derived pointer found in statepoint");
518       }
519     }
520     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
521   } else {
522     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
523     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
524   }
525 #endif
526 
527   // Figure out what lowering strategy we're going to use for each part
528   // Note: Is is conservatively correct to lower both "live-in" and "live-out"
529   // as "live-through". A "live-through" variable is one which is "live-in",
530   // "live-out", and live throughout the lifetime of the call (i.e. we can find
531   // it from any PC within the transitive callee of the statepoint).  In
532   // particular, if the callee spills callee preserved registers we may not
533   // be able to find a value placed in that register during the call.  This is
534   // fine for live-out, but not for live-through.  If we were willing to make
535   // assumptions about the code generator producing the callee, we could
536   // potentially allow live-through values in callee saved registers.
537   const bool LiveInDeopt =
538     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
539 
540   // Decide which deriver pointers will go on VRegs
541   const unsigned MaxTiedRegs = 15; // Max  number of tied regs MI can have.
542   unsigned MaxVRegPtrs =
543       std::min(MaxTiedRegs, MaxRegistersForGCPointers.getValue());
544   // Use old spill scheme for cross-block relocates.
545   if (SI.StatepointInstr) {
546     const BasicBlock *BB = SI.StatepointInstr->getParent();
547     bool NonLocalReloc =
548         llvm::any_of(SI.GCRelocates, [BB](const GCRelocateInst *R) {
549           return R->getParent() != BB;
550         });
551     if (NonLocalReloc)
552       MaxVRegPtrs = 0;
553   }
554 
555   LLVM_DEBUG(dbgs() << "Desiding how to lower GC Pointers:\n");
556   unsigned CurNumVRegs = 0;
557   for (const Value *P : SI.Ptrs) {
558     if (LowerAsVReg.size() == MaxVRegPtrs)
559       break;
560     SDValue PtrSD = Builder.getValue(P);
561     if (willLowerDirectly(PtrSD) || P->getType()->isVectorTy()) {
562       LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
563       continue;
564     }
565     LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
566     LowerAsVReg[PtrSD] = CurNumVRegs++;
567   }
568   LLVM_DEBUG(dbgs() << LowerAsVReg.size()
569                     << " derived pointers will go in vregs\n");
570 
571   auto isGCValue = [&](const Value *V) {
572     auto *Ty = V->getType();
573     if (!Ty->isPtrOrPtrVectorTy())
574       return false;
575     if (auto *GFI = Builder.GFI)
576       if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
577         return *IsManaged;
578     return true; // conservative
579   };
580 
581   auto requireSpillSlot = [&](const Value *V) {
582     if (isGCValue(V))
583       return !LowerAsVReg.count(Builder.getValue(V));
584     return !(LiveInDeopt || UseRegistersForDeoptValues);
585   };
586 
587   // Before we actually start lowering (and allocating spill slots for values),
588   // reserve any stack slots which we judge to be profitable to reuse for a
589   // particular value.  This is purely an optimization over the code below and
590   // doesn't change semantics at all.  It is important for performance that we
591   // reserve slots for both deopt and gc values before lowering either.
592   for (const Value *V : SI.DeoptState) {
593     if (requireSpillSlot(V))
594       reservePreviousStackSlotForValue(V, Builder);
595   }
596 
597   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
598     SDValue SDV = Builder.getValue(SI.Bases[i]);
599     if (!LowerAsVReg.count(SDV))
600       reservePreviousStackSlotForValue(SI.Bases[i], Builder);
601     SDV = Builder.getValue(SI.Ptrs[i]);
602     if (!LowerAsVReg.count(SDV))
603       reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
604   }
605 
606   // First, prefix the list with the number of unique values to be
607   // lowered.  Note that this is the number of *Values* not the
608   // number of SDValues required to lower them.
609   const int NumVMSArgs = SI.DeoptState.size();
610   pushStackMapConstant(Ops, Builder, NumVMSArgs);
611 
612   // The vm state arguments are lowered in an opaque manner.  We do not know
613   // what type of values are contained within.
614   LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
615   for (const Value *V : SI.DeoptState) {
616     SDValue Incoming;
617     // If this is a function argument at a static frame index, generate it as
618     // the frame index.
619     if (const Argument *Arg = dyn_cast<Argument>(V)) {
620       int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
621       if (FI != INT_MAX)
622         Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
623     }
624     if (!Incoming.getNode())
625       Incoming = Builder.getValue(V);
626     LLVM_DEBUG(dbgs() << "Value " << *V
627                       << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
628     lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
629                                  Builder);
630   }
631 
632   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
633   // length for this one.  After lowering, we'll have the base and pointer
634   // arrays interwoven with each (lowered) base pointer immediately followed by
635   // it's (lowered) derived pointer.  i.e
636   // (base[0], ptr[0], base[1], ptr[1], ...)
637   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
638     bool RequireSpillSlot;
639     SDValue Base = Builder.getValue(SI.Bases[i]);
640     RequireSpillSlot = !LowerAsVReg.count(Base);
641     lowerIncomingStatepointValue(Base, RequireSpillSlot, Ops, MemRefs,
642                                  Builder);
643 
644     SDValue Derived = Builder.getValue(SI.Ptrs[i]);
645     RequireSpillSlot = !LowerAsVReg.count(Derived);
646     lowerIncomingStatepointValue(Derived, RequireSpillSlot, Ops, MemRefs,
647                                  Builder);
648   }
649 
650   // If there are any explicit spill slots passed to the statepoint, record
651   // them, but otherwise do not do anything special.  These are user provided
652   // allocas and give control over placement to the consumer.  In this case,
653   // it is the contents of the slot which may get updated, not the pointer to
654   // the alloca
655   for (Value *V : SI.GCArgs) {
656     SDValue Incoming = Builder.getValue(V);
657     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
658       // This handles allocas as arguments to the statepoint
659       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
660              "Incoming value is a frame index!");
661       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
662                                                     Builder.getFrameIndexTy()));
663 
664       auto &MF = Builder.DAG.getMachineFunction();
665       auto *MMO = getMachineMemOperand(MF, *FI);
666       MemRefs.push_back(MMO);
667     }
668   }
669 
670   // Record computed locations for all lowered values.
671   // This can not be embedded in lowering loops as we need to record *all*
672   // values, while previous loops account only values with unique SDValues.
673   const Instruction *StatepointInstr = SI.StatepointInstr;
674   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
675 
676   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
677     const Value *V = Relocate->getDerivedPtr();
678     SDValue SDV = Builder.getValue(V);
679     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
680 
681     if (Loc.getNode()) {
682       // If this is a value we spilled, remember where for when we visit the
683       // gc.relocate corresponding to this gc.statepoint
684       SpillMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
685     } else {
686       // If we didn't spill the value - allocas, constants, and values lowered
687       // as tied vregs - mark them as visited, but not spilled.  Marking them
688       // visited (as opposed to simply missing in the map), allows tighter
689       // assertion checking.
690       SpillMap[V] = None;
691 
692       // Conservatively export all values used by gc.relocates outside this
693       // block.  This is currently only needed for expressions which don't need
694       // relocation, but will likely be extended for vreg case shortly.
695       if (Relocate->getParent() != StatepointInstr->getParent()) {
696         Builder.ExportFromCurrentBlock(V);
697         assert(!LowerAsVReg.count(SDV));
698       }
699     }
700   }
701 }
702 
703 SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
704     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
705   // The basic scheme here is that information about both the original call and
706   // the safepoint is encoded in the CallInst.  We create a temporary call and
707   // lower it, then reverse engineer the calling sequence.
708 
709   NumOfStatepoints++;
710   // Clear state
711   StatepointLowering.startNewStatepoint(*this);
712   assert(SI.Bases.size() == SI.Ptrs.size() &&
713          SI.Ptrs.size() <= SI.GCRelocates.size());
714 
715   LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n");
716 #ifndef NDEBUG
717   for (auto *Reloc : SI.GCRelocates)
718     if (Reloc->getParent() == SI.StatepointInstr->getParent())
719       StatepointLowering.scheduleRelocCall(*Reloc);
720 #endif
721 
722   // Lower statepoint vmstate and gcstate arguments
723   SmallVector<SDValue, 10> LoweredMetaArgs;
724   SmallVector<MachineMemOperand*, 16> MemRefs;
725   // Maps derived pointer SDValue to statepoint result of relocated pointer.
726   DenseMap<SDValue, int> LowerAsVReg;
727   lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LowerAsVReg, SI, *this);
728 
729   // Now that we've emitted the spills, we need to update the root so that the
730   // call sequence is ordered correctly.
731   SI.CLI.setChain(getRoot());
732 
733   // Get call node, we will replace it later with statepoint
734   SDValue ReturnVal;
735   SDNode *CallNode;
736   std::tie(ReturnVal, CallNode) =
737       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
738 
739   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
740   // nodes with all the appropriate arguments and return values.
741 
742   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
743   SDValue Chain = CallNode->getOperand(0);
744 
745   SDValue Glue;
746   bool CallHasIncomingGlue = CallNode->getGluedNode();
747   if (CallHasIncomingGlue) {
748     // Glue is always last operand
749     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
750   }
751 
752   // Build the GC_TRANSITION_START node if necessary.
753   //
754   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
755   // order in which they appear in the call to the statepoint intrinsic. If
756   // any of the operands is a pointer-typed, that operand is immediately
757   // followed by a SRCVALUE for the pointer that may be used during lowering
758   // (e.g. to form MachinePointerInfo values for loads/stores).
759   const bool IsGCTransition =
760       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
761       (uint64_t)StatepointFlags::GCTransition;
762   if (IsGCTransition) {
763     SmallVector<SDValue, 8> TSOps;
764 
765     // Add chain
766     TSOps.push_back(Chain);
767 
768     // Add GC transition arguments
769     for (const Value *V : SI.GCTransitionArgs) {
770       TSOps.push_back(getValue(V));
771       if (V->getType()->isPointerTy())
772         TSOps.push_back(DAG.getSrcValue(V));
773     }
774 
775     // Add glue if necessary
776     if (CallHasIncomingGlue)
777       TSOps.push_back(Glue);
778 
779     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
780 
781     SDValue GCTransitionStart =
782         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
783 
784     Chain = GCTransitionStart.getValue(0);
785     Glue = GCTransitionStart.getValue(1);
786   }
787 
788   // TODO: Currently, all of these operands are being marked as read/write in
789   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
790   // and flags to be read-only.
791   SmallVector<SDValue, 40> Ops;
792 
793   // Add the <id> and <numBytes> constants.
794   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
795   Ops.push_back(
796       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
797 
798   // Calculate and push starting position of vmstate arguments
799   // Get number of arguments incoming directly into call node
800   unsigned NumCallRegArgs =
801       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
802   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
803 
804   // Add call target
805   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
806   Ops.push_back(CallTarget);
807 
808   // Add call arguments
809   // Get position of register mask in the call
810   SDNode::op_iterator RegMaskIt;
811   if (CallHasIncomingGlue)
812     RegMaskIt = CallNode->op_end() - 2;
813   else
814     RegMaskIt = CallNode->op_end() - 1;
815   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
816 
817   // Add a constant argument for the calling convention
818   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
819 
820   // Add a constant argument for the flags
821   uint64_t Flags = SI.StatepointFlags;
822   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
823          "Unknown flag used");
824   pushStackMapConstant(Ops, *this, Flags);
825 
826   // Insert all vmstate and gcstate arguments
827   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
828 
829   // Add register mask from call node
830   Ops.push_back(*RegMaskIt);
831 
832   // Add chain
833   Ops.push_back(Chain);
834 
835   // Same for the glue, but we add it only if original call had it
836   if (Glue.getNode())
837     Ops.push_back(Glue);
838 
839   // Compute return values.  Provide a glue output since we consume one as
840   // input.  This allows someone else to chain off us as needed.
841   SmallVector<EVT, 8> NodeTys;
842   for (auto &Ptr : SI.Ptrs) {
843     SDValue SD = getValue(Ptr);
844     if (!LowerAsVReg.count(SD))
845       continue;
846     NodeTys.push_back(SD.getValueType());
847   }
848   LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
849   assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
850   NodeTys.push_back(MVT::Other);
851   NodeTys.push_back(MVT::Glue);
852 
853   unsigned NumResults = NodeTys.size();
854   MachineSDNode *StatepointMCNode =
855     DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
856   DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
857 
858   SDNode *SinkNode = StatepointMCNode;
859 
860   // Fill mapping from derived pointer to statepoint result denoting its
861   // relocated value.
862   auto &DPtrMap = StatepointLowering.DerivedPtrMap;
863   for (const auto *Relocate : SI.GCRelocates) {
864     Value *Derived = Relocate->getDerivedPtr();
865     SDValue SD = getValue(Derived);
866     if (!LowerAsVReg.count(SD))
867       continue;
868     DPtrMap[Derived] = SDValue(StatepointMCNode, LowerAsVReg[SD]);
869   }
870 
871   // Build the GC_TRANSITION_END node if necessary.
872   //
873   // See the comment above regarding GC_TRANSITION_START for the layout of
874   // the operands to the GC_TRANSITION_END node.
875   if (IsGCTransition) {
876     SmallVector<SDValue, 8> TEOps;
877 
878     // Add chain
879     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
880 
881     // Add GC transition arguments
882     for (const Value *V : SI.GCTransitionArgs) {
883       TEOps.push_back(getValue(V));
884       if (V->getType()->isPointerTy())
885         TEOps.push_back(DAG.getSrcValue(V));
886     }
887 
888     // Add glue
889     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
890 
891     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
892 
893     SDValue GCTransitionStart =
894         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
895 
896     SinkNode = GCTransitionStart.getNode();
897   }
898 
899   // Replace original call
900   // Call: ch,glue = CALL ...
901   // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
902   unsigned NumSinkValues = SinkNode->getNumValues();
903   SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
904                                  SDValue(SinkNode, NumSinkValues - 1)};
905   DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
906   // Remove original call node
907   DAG.DeleteNode(CallNode);
908 
909   // DON'T set the root - under the assumption that it's already set past the
910   // inserted node we created.
911 
912   // TODO: A better future implementation would be to emit a single variable
913   // argument, variable return value STATEPOINT node here and then hookup the
914   // return value of each gc.relocate to the respective output of the
915   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
916   // to actually be possible today.
917 
918   return ReturnVal;
919 }
920 
921 void
922 SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
923                                      const BasicBlock *EHPadBB /*= nullptr*/) {
924   assert(I.getCallingConv() != CallingConv::AnyReg &&
925          "anyregcc is not supported on statepoints!");
926 
927 #ifndef NDEBUG
928   // Check that the associated GCStrategy expects to encounter statepoints.
929   assert(GFI->getStrategy().useStatepoints() &&
930          "GCStrategy does not expect to encounter statepoints");
931 #endif
932 
933   SDValue ActualCallee;
934   SDValue Callee = getValue(I.getActualCalledOperand());
935 
936   if (I.getNumPatchBytes() > 0) {
937     // If we've been asked to emit a nop sequence instead of a call instruction
938     // for this statepoint then don't lower the call target, but use a constant
939     // `undef` instead.  Not lowering the call target lets statepoint clients
940     // get away without providing a physical address for the symbolic call
941     // target at link time.
942     ActualCallee = DAG.getUNDEF(Callee.getValueType());
943   } else {
944     ActualCallee = Callee;
945   }
946 
947   StatepointLoweringInfo SI(DAG);
948   populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
949                            I.getNumCallArgs(), ActualCallee,
950                            I.getActualReturnType(), false /* IsPatchPoint */);
951 
952   // There may be duplication in the gc.relocate list; such as two copies of
953   // each relocation on normal and exceptional path for an invoke.  We only
954   // need to spill once and record one copy in the stackmap, but we need to
955   // reload once per gc.relocate.  (Dedupping gc.relocates is trickier and best
956   // handled as a CSE problem elsewhere.)
957   // TODO: There a couple of major stackmap size optimizations we could do
958   // here if we wished.
959   // 1) If we've encountered a derived pair {B, D}, we don't need to actually
960   // record {B,B} if it's seen later.
961   // 2) Due to rematerialization, actual derived pointers are somewhat rare;
962   // given that, we could change the format to record base pointer relocations
963   // separately with half the space. This would require a format rev and a
964   // fairly major rework of the STATEPOINT node though.
965   SmallSet<SDValue, 8> Seen;
966   for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
967     SI.GCRelocates.push_back(Relocate);
968 
969     SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
970     if (Seen.insert(DerivedSD).second) {
971       SI.Bases.push_back(Relocate->getBasePtr());
972       SI.Ptrs.push_back(Relocate->getDerivedPtr());
973     }
974   }
975 
976   SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
977   SI.StatepointInstr = &I;
978   SI.ID = I.getID();
979 
980   SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
981   SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
982                                             I.gc_transition_args_end());
983 
984   SI.StatepointFlags = I.getFlags();
985   SI.NumPatchBytes = I.getNumPatchBytes();
986   SI.EHPadBB = EHPadBB;
987 
988   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
989 
990   // Export the result value if needed
991   const GCResultInst *GCResult = I.getGCResult();
992   Type *RetTy = I.getActualReturnType();
993 
994   if (RetTy->isVoidTy() || !GCResult) {
995     // The return value is not needed, just generate a poison value.
996     setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
997     return;
998   }
999 
1000   if (GCResult->getParent() == I.getParent()) {
1001     // Result value will be used in a same basic block. Don't export it or
1002     // perform any explicit register copies. The gc_result will simply grab
1003     // this value.
1004     setValue(&I, ReturnValue);
1005     return;
1006   }
1007 
1008   // Result value will be used in a different basic block so we need to export
1009   // it now.  Default exporting mechanism will not work here because statepoint
1010   // call has a different type than the actual call. It means that by default
1011   // llvm will create export register of the wrong type (always i32 in our
1012   // case). So instead we need to create export register with correct type
1013   // manually.
1014   // TODO: To eliminate this problem we can remove gc.result intrinsics
1015   //       completely and make statepoint call to return a tuple.
1016   unsigned Reg = FuncInfo.CreateRegs(RetTy);
1017   RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1018                    DAG.getDataLayout(), Reg, RetTy,
1019                    I.getCallingConv());
1020   SDValue Chain = DAG.getEntryNode();
1021 
1022   RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1023   PendingExports.push_back(Chain);
1024   FuncInfo.ValueMap[&I] = Reg;
1025 }
1026 
1027 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
1028     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1029     bool VarArgDisallowed, bool ForceVoidReturnTy) {
1030   StatepointLoweringInfo SI(DAG);
1031   unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1032   populateCallLoweringInfo(
1033       SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
1034       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1035       false);
1036   if (!VarArgDisallowed)
1037     SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1038 
1039   auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1040 
1041   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
1042 
1043   auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1044   SI.ID = SD.StatepointID.getValueOr(DefaultID);
1045   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
1046 
1047   SI.DeoptState =
1048       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
1049   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
1050   SI.EHPadBB = EHPadBB;
1051 
1052   // NB! The GC arguments are deliberately left empty.
1053 
1054   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
1055     ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
1056     setValue(Call, ReturnVal);
1057   }
1058 }
1059 
1060 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
1061     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
1062   LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
1063                                    /* VarArgDisallowed = */ false,
1064                                    /* ForceVoidReturnTy  = */ false);
1065 }
1066 
1067 void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
1068   // The result value of the gc_result is simply the result of the actual
1069   // call.  We've already emitted this, so just grab the value.
1070   const GCStatepointInst *SI = CI.getStatepoint();
1071 
1072   if (SI->getParent() == CI.getParent()) {
1073     setValue(&CI, getValue(SI));
1074     return;
1075   }
1076   // Statepoint is in different basic block so we should have stored call
1077   // result in a virtual register.
1078   // We can not use default getValue() functionality to copy value from this
1079   // register because statepoint and actual call return types can be
1080   // different, and getValue() will use CopyFromReg of the wrong type,
1081   // which is always i32 in our case.
1082   Type *RetTy = SI->getActualReturnType();
1083   SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
1084 
1085   assert(CopyFromReg.getNode());
1086   setValue(&CI, CopyFromReg);
1087 }
1088 
1089 void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1090 #ifndef NDEBUG
1091   // Consistency check
1092   // We skip this check for relocates not in the same basic block as their
1093   // statepoint. It would be too expensive to preserve validation info through
1094   // different basic blocks.
1095   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
1096     StatepointLowering.relocCallVisited(Relocate);
1097 
1098   auto *Ty = Relocate.getType()->getScalarType();
1099   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1100     assert(*IsManaged && "Non gc managed pointer relocated!");
1101 #endif
1102 
1103   const Value *DerivedPtr = Relocate.getDerivedPtr();
1104   SDValue SD = getValue(DerivedPtr);
1105 
1106   if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1107     // Lowering relocate(undef) as arbitrary constant. Current constant value
1108     // is chosen such that it's unlikely to be a valid pointer.
1109     setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1110     return;
1111   }
1112 
1113   // Relocate is local to statepoint block and its pointer was assigned
1114   // to VReg. Use corresponding statepoint result.
1115   auto &DPtrMap = StatepointLowering.DerivedPtrMap;
1116   auto It = DPtrMap.find(DerivedPtr);
1117   if (It != DPtrMap.end()) {
1118     setValue(&Relocate, It->second);
1119     assert(Relocate.getParent() == Relocate.getStatepoint()->getParent() &&
1120            "unexpected DPtrMap entry");
1121     return;
1122   }
1123 
1124   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
1125   auto SlotIt = SpillMap.find(DerivedPtr);
1126   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
1127   Optional<int> DerivedPtrLocation = SlotIt->second;
1128 
1129   // We didn't need to spill these special cases (constants and allocas).
1130   // See the handling in spillIncomingValueForStatepoint for detail.
1131   if (!DerivedPtrLocation) {
1132     setValue(&Relocate, SD);
1133     return;
1134   }
1135 
1136   unsigned Index = *DerivedPtrLocation;
1137   SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
1138 
1139   // All the reloads are independent and are reading memory only modified by
1140   // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1141   // this this let's CSE kick in for free and allows reordering of instructions
1142   // if possible.  The lowering for statepoint sets the root, so this is
1143   // ordering all reloads with the either a) the statepoint node itself, or b)
1144   // the entry of the current block for an invoke statepoint.
1145   const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
1146 
1147   auto &MF = DAG.getMachineFunction();
1148   auto &MFI = MF.getFrameInfo();
1149   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1150   auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1151                                           MFI.getObjectSize(Index),
1152                                           MFI.getObjectAlign(Index));
1153 
1154   auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1155                                                          Relocate.getType());
1156 
1157   SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1158                                   SpillSlot, LoadMMO);
1159   PendingLoads.push_back(SpillLoad.getValue(1));
1160 
1161   assert(SpillLoad.getNode());
1162   setValue(&Relocate, SpillLoad);
1163 }
1164 
1165 void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1166   const auto &TLI = DAG.getTargetLoweringInfo();
1167   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1168                                          TLI.getPointerTy(DAG.getDataLayout()));
1169 
1170   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1171   // call.  We also do not lower the return value to any virtual register, and
1172   // change the immediately following return to a trap instruction.
1173   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1174                                    /* VarArgDisallowed = */ true,
1175                                    /* ForceVoidReturnTy = */ true);
1176 }
1177 
1178 void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1179   // We do not lower the return value from llvm.deoptimize to any virtual
1180   // register, and change the immediately following return to a trap
1181   // instruction.
1182   if (DAG.getTarget().Options.TrapUnreachable)
1183     DAG.setRoot(
1184         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1185 }
1186