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