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