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