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