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