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