139d628a0SDimitry Andric //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
239d628a0SDimitry Andric //
339d628a0SDimitry Andric //                     The LLVM Compiler Infrastructure
439d628a0SDimitry Andric //
539d628a0SDimitry Andric // This file is distributed under the University of Illinois Open Source
639d628a0SDimitry Andric // License. See LICENSE.TXT for details.
739d628a0SDimitry Andric //
839d628a0SDimitry Andric //===----------------------------------------------------------------------===//
939d628a0SDimitry Andric //
1039d628a0SDimitry Andric // This file includes support code use by SelectionDAGBuilder when lowering a
1139d628a0SDimitry Andric // statepoint sequence in SelectionDAG IR.
1239d628a0SDimitry Andric //
1339d628a0SDimitry Andric //===----------------------------------------------------------------------===//
1439d628a0SDimitry Andric 
1539d628a0SDimitry Andric #include "StatepointLowering.h"
1639d628a0SDimitry Andric #include "SelectionDAGBuilder.h"
1739d628a0SDimitry Andric #include "llvm/ADT/SmallSet.h"
1839d628a0SDimitry Andric #include "llvm/ADT/Statistic.h"
1939d628a0SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
207d523365SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
21ff0cc061SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
2239d628a0SDimitry Andric #include "llvm/CodeGen/GCStrategy.h"
2339d628a0SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
2439d628a0SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
2539d628a0SDimitry Andric #include "llvm/IR/CallingConv.h"
2639d628a0SDimitry Andric #include "llvm/IR/Instructions.h"
2739d628a0SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
2839d628a0SDimitry Andric #include "llvm/IR/Intrinsics.h"
2939d628a0SDimitry Andric #include "llvm/IR/Statepoint.h"
3039d628a0SDimitry Andric #include "llvm/Target/TargetLowering.h"
3139d628a0SDimitry Andric #include <algorithm>
3239d628a0SDimitry Andric using namespace llvm;
3339d628a0SDimitry Andric 
3439d628a0SDimitry Andric #define DEBUG_TYPE "statepoint-lowering"
3539d628a0SDimitry Andric 
3639d628a0SDimitry Andric STATISTIC(NumSlotsAllocatedForStatepoints,
3739d628a0SDimitry Andric           "Number of stack slots allocated for statepoints");
3839d628a0SDimitry Andric STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
3939d628a0SDimitry Andric STATISTIC(StatepointMaxSlotsRequired,
4039d628a0SDimitry Andric           "Maximum number of stack slots required for a singe statepoint");
4139d628a0SDimitry Andric 
42ff0cc061SDimitry Andric static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
43ff0cc061SDimitry Andric                                  SelectionDAGBuilder &Builder, uint64_t Value) {
44ff0cc061SDimitry Andric   SDLoc L = Builder.getCurSDLoc();
45ff0cc061SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
46ff0cc061SDimitry Andric                                               MVT::i64));
47ff0cc061SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
48ff0cc061SDimitry Andric }
49ff0cc061SDimitry Andric 
50ff0cc061SDimitry Andric void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
5139d628a0SDimitry Andric   // Consistency check
5239d628a0SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
5339d628a0SDimitry Andric          "Trying to visit statepoint before finished processing previous one");
5439d628a0SDimitry Andric   Locations.clear();
5539d628a0SDimitry Andric   NextSlotToAllocate = 0;
563ca95b02SDimitry Andric   // Need to resize this on each safepoint - we need the two to stay in sync and
573ca95b02SDimitry Andric   // the clear patterns of a SelectionDAGBuilder have no relation to
583ca95b02SDimitry Andric   // FunctionLoweringInfo.  SmallBitVector::reset initializes all bits to false.
5939d628a0SDimitry Andric   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
6039d628a0SDimitry Andric }
61ff0cc061SDimitry Andric 
6239d628a0SDimitry Andric void StatepointLoweringState::clear() {
6339d628a0SDimitry Andric   Locations.clear();
6439d628a0SDimitry Andric   AllocatedStackSlots.clear();
6539d628a0SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
6639d628a0SDimitry Andric          "cleared before statepoint sequence completed");
6739d628a0SDimitry Andric }
6839d628a0SDimitry Andric 
6939d628a0SDimitry Andric SDValue
7039d628a0SDimitry Andric StatepointLoweringState::allocateStackSlot(EVT ValueType,
7139d628a0SDimitry Andric                                            SelectionDAGBuilder &Builder) {
7239d628a0SDimitry Andric   NumSlotsAllocatedForStatepoints++;
733ca95b02SDimitry Andric   auto *MFI = Builder.DAG.getMachineFunction().getFrameInfo();
7439d628a0SDimitry Andric 
753ca95b02SDimitry Andric   unsigned SpillSize = ValueType.getSizeInBits() / 8;
763ca95b02SDimitry Andric   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
7739d628a0SDimitry Andric 
783ca95b02SDimitry Andric   // First look for a previously created stack slot which is not in
793ca95b02SDimitry Andric   // use (accounting for the fact arbitrary slots may already be
803ca95b02SDimitry Andric   // reserved), or to create a new stack slot and use it.
813ca95b02SDimitry Andric 
8239d628a0SDimitry Andric   const size_t NumSlots = AllocatedStackSlots.size();
833ca95b02SDimitry Andric   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
8439d628a0SDimitry Andric 
853ca95b02SDimitry Andric   // The stack slots in StatepointStackSlots beyond the first NumSlots were
863ca95b02SDimitry Andric   // added in this instance of StatepointLoweringState, and cannot be re-used.
873ca95b02SDimitry Andric   assert(NumSlots <= Builder.FuncInfo.StatepointStackSlots.size() &&
883ca95b02SDimitry Andric          "Broken invariant");
893ca95b02SDimitry Andric 
903ca95b02SDimitry Andric   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
913ca95b02SDimitry Andric     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
923ca95b02SDimitry Andric       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
933ca95b02SDimitry Andric       if (MFI->getObjectSize(FI) == SpillSize) {
943ca95b02SDimitry Andric         AllocatedStackSlots.set(NextSlotToAllocate);
953ca95b02SDimitry Andric         return Builder.DAG.getFrameIndex(FI, ValueType);
9639d628a0SDimitry Andric       }
973ca95b02SDimitry Andric     }
983ca95b02SDimitry Andric   }
993ca95b02SDimitry Andric 
1003ca95b02SDimitry Andric   // Couldn't find a free slot, so create a new one:
10139d628a0SDimitry Andric 
10239d628a0SDimitry Andric   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
10339d628a0SDimitry Andric   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1047d523365SDimitry Andric   MFI->markAsStatepointSpillSlotObjectIndex(FI);
1057d523365SDimitry Andric 
10639d628a0SDimitry Andric   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
1073ca95b02SDimitry Andric 
1083ca95b02SDimitry Andric   StatepointMaxSlotsRequired = std::max<unsigned long>(
1093ca95b02SDimitry Andric       StatepointMaxSlotsRequired, Builder.FuncInfo.StatepointStackSlots.size());
1103ca95b02SDimitry Andric 
11139d628a0SDimitry Andric   return SpillSlot;
11239d628a0SDimitry Andric }
11339d628a0SDimitry Andric 
1148f0fd8f6SDimitry Andric /// Utility function for reservePreviousStackSlotForValue. Tries to find
1158f0fd8f6SDimitry Andric /// stack slot index to which we have spilled value for previous statepoints.
1168f0fd8f6SDimitry Andric /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
1178f0fd8f6SDimitry Andric static Optional<int> findPreviousSpillSlot(const Value *Val,
1188f0fd8f6SDimitry Andric                                            SelectionDAGBuilder &Builder,
1198f0fd8f6SDimitry Andric                                            int LookUpDepth) {
1207d523365SDimitry Andric   // Can not look any further - give up now
1218f0fd8f6SDimitry Andric   if (LookUpDepth <= 0)
1223ca95b02SDimitry Andric     return None;
1238f0fd8f6SDimitry Andric 
1248f0fd8f6SDimitry Andric   // Spill location is known for gc relocates
1254d0b32cdSDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
1263ca95b02SDimitry Andric     const auto &SpillMap =
1273ca95b02SDimitry Andric         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
1288f0fd8f6SDimitry Andric 
1294d0b32cdSDimitry Andric     auto It = SpillMap.find(Relocate->getDerivedPtr());
1308f0fd8f6SDimitry Andric     if (It == SpillMap.end())
1313ca95b02SDimitry Andric       return None;
1328f0fd8f6SDimitry Andric 
1338f0fd8f6SDimitry Andric     return It->second;
1348f0fd8f6SDimitry Andric   }
1358f0fd8f6SDimitry Andric 
1368f0fd8f6SDimitry Andric   // Look through bitcast instructions.
1373ca95b02SDimitry Andric   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
1388f0fd8f6SDimitry Andric     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
1398f0fd8f6SDimitry Andric 
1408f0fd8f6SDimitry Andric   // Look through phi nodes
1418f0fd8f6SDimitry Andric   // All incoming values should have same known stack slot, otherwise result
1428f0fd8f6SDimitry Andric   // is unknown.
1438f0fd8f6SDimitry Andric   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
1448f0fd8f6SDimitry Andric     Optional<int> MergedResult = None;
1458f0fd8f6SDimitry Andric 
1468f0fd8f6SDimitry Andric     for (auto &IncomingValue : Phi->incoming_values()) {
1478f0fd8f6SDimitry Andric       Optional<int> SpillSlot =
1488f0fd8f6SDimitry Andric           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
1498f0fd8f6SDimitry Andric       if (!SpillSlot.hasValue())
1503ca95b02SDimitry Andric         return None;
1518f0fd8f6SDimitry Andric 
1528f0fd8f6SDimitry Andric       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
1533ca95b02SDimitry Andric         return None;
1548f0fd8f6SDimitry Andric 
1558f0fd8f6SDimitry Andric       MergedResult = SpillSlot;
1568f0fd8f6SDimitry Andric     }
1578f0fd8f6SDimitry Andric     return MergedResult;
1588f0fd8f6SDimitry Andric   }
1598f0fd8f6SDimitry Andric 
1608f0fd8f6SDimitry Andric   // TODO: We can do better for PHI nodes. In cases like this:
1618f0fd8f6SDimitry Andric   //   ptr = phi(relocated_pointer, not_relocated_pointer)
1628f0fd8f6SDimitry Andric   //   statepoint(ptr)
1638f0fd8f6SDimitry Andric   // We will return that stack slot for ptr is unknown. And later we might
1648f0fd8f6SDimitry Andric   // assign different stack slots for ptr and relocated_pointer. This limits
1658f0fd8f6SDimitry Andric   // llvm's ability to remove redundant stores.
1668f0fd8f6SDimitry Andric   // Unfortunately it's hard to accomplish in current infrastructure.
1678f0fd8f6SDimitry Andric   // We use this function to eliminate spill store completely, while
1688f0fd8f6SDimitry Andric   // in example we still need to emit store, but instead of any location
1698f0fd8f6SDimitry Andric   // we need to use special "preferred" location.
1708f0fd8f6SDimitry Andric 
1718f0fd8f6SDimitry Andric   // TODO: handle simple updates.  If a value is modified and the original
1728f0fd8f6SDimitry Andric   // value is no longer live, it would be nice to put the modified value in the
1738f0fd8f6SDimitry Andric   // same slot.  This allows folding of the memory accesses for some
1748f0fd8f6SDimitry Andric   // instructions types (like an increment).
1758f0fd8f6SDimitry Andric   //   statepoint (i)
1768f0fd8f6SDimitry Andric   //   i1 = i+1
1778f0fd8f6SDimitry Andric   //   statepoint (i1)
1788f0fd8f6SDimitry Andric   // However we need to be careful for cases like this:
1798f0fd8f6SDimitry Andric   //   statepoint(i)
1808f0fd8f6SDimitry Andric   //   i1 = i+1
1818f0fd8f6SDimitry Andric   //   statepoint(i, i1)
1828f0fd8f6SDimitry Andric   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
1838f0fd8f6SDimitry Andric   // put handling of simple modifications in this function like it's done
1848f0fd8f6SDimitry Andric   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
1858f0fd8f6SDimitry Andric   // which we visit values is unspecified.
1868f0fd8f6SDimitry Andric 
1878f0fd8f6SDimitry Andric   // Don't know any information about this instruction
1883ca95b02SDimitry Andric   return None;
1898f0fd8f6SDimitry Andric }
1908f0fd8f6SDimitry Andric 
19139d628a0SDimitry Andric /// Try to find existing copies of the incoming values in stack slots used for
19239d628a0SDimitry Andric /// statepoint spilling.  If we can find a spill slot for the incoming value,
19339d628a0SDimitry Andric /// mark that slot as allocated, and reuse the same slot for this safepoint.
1947d523365SDimitry Andric /// This helps to avoid series of loads and stores that only serve to reshuffle
19539d628a0SDimitry Andric /// values on the stack between calls.
1968f0fd8f6SDimitry Andric static void reservePreviousStackSlotForValue(const Value *IncomingValue,
19739d628a0SDimitry Andric                                              SelectionDAGBuilder &Builder) {
19839d628a0SDimitry Andric 
1998f0fd8f6SDimitry Andric   SDValue Incoming = Builder.getValue(IncomingValue);
2008f0fd8f6SDimitry Andric 
20139d628a0SDimitry Andric   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
20239d628a0SDimitry Andric     // We won't need to spill this, so no need to check for previously
20339d628a0SDimitry Andric     // allocated stack slots
20439d628a0SDimitry Andric     return;
20539d628a0SDimitry Andric   }
20639d628a0SDimitry Andric 
2078f0fd8f6SDimitry Andric   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
2088f0fd8f6SDimitry Andric   if (OldLocation.getNode())
2093ca95b02SDimitry Andric     // Duplicates in input
21039d628a0SDimitry Andric     return;
21139d628a0SDimitry Andric 
2128f0fd8f6SDimitry Andric   const int LookUpDepth = 6;
2138f0fd8f6SDimitry Andric   Optional<int> Index =
2148f0fd8f6SDimitry Andric       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
2158f0fd8f6SDimitry Andric   if (!Index.hasValue())
21639d628a0SDimitry Andric     return;
2178f0fd8f6SDimitry Andric 
2183ca95b02SDimitry Andric   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
2193ca95b02SDimitry Andric 
2203ca95b02SDimitry Andric   auto SlotIt = find(StatepointSlots, *Index);
2213ca95b02SDimitry Andric   assert(SlotIt != StatepointSlots.end() &&
2223ca95b02SDimitry Andric          "Value spilled to the unknown stack slot");
2238f0fd8f6SDimitry Andric 
22439d628a0SDimitry Andric   // This is one of our dedicated lowering slots
2253ca95b02SDimitry Andric   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
22639d628a0SDimitry Andric   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
22739d628a0SDimitry Andric     // stack slot already assigned to someone else, can't use it!
22839d628a0SDimitry Andric     // TODO: currently we reserve space for gc arguments after doing
22939d628a0SDimitry Andric     // normal allocation for deopt arguments.  We should reserve for
23039d628a0SDimitry Andric     // _all_ deopt and gc arguments, then start allocating.  This
23139d628a0SDimitry Andric     // will prevent some moves being inserted when vm state changes,
23239d628a0SDimitry Andric     // but gc state doesn't between two calls.
23339d628a0SDimitry Andric     return;
23439d628a0SDimitry Andric   }
23539d628a0SDimitry Andric   // Reserve this stack slot
23639d628a0SDimitry Andric   Builder.StatepointLowering.reserveStackSlot(Offset);
23739d628a0SDimitry Andric 
23839d628a0SDimitry Andric   // Cache this slot so we find it when going through the normal
23939d628a0SDimitry Andric   // assignment loop.
2408f0fd8f6SDimitry Andric   SDValue Loc = Builder.DAG.getTargetFrameIndex(*Index, Incoming.getValueType());
24139d628a0SDimitry Andric   Builder.StatepointLowering.setLocation(Incoming, Loc);
24239d628a0SDimitry Andric }
24339d628a0SDimitry Andric 
24439d628a0SDimitry Andric /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
24539d628a0SDimitry Andric /// is not required for correctness.  It's purpose is to reduce the size of
24639d628a0SDimitry Andric /// StackMap section.  It has no effect on the number of spill slots required
24739d628a0SDimitry Andric /// or the actual lowering.
2483ca95b02SDimitry Andric static void
2493ca95b02SDimitry Andric removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
25039d628a0SDimitry Andric                       SmallVectorImpl<const Value *> &Ptrs,
2513ca95b02SDimitry Andric                       SmallVectorImpl<const GCRelocateInst *> &Relocs,
2523ca95b02SDimitry Andric                       SelectionDAGBuilder &Builder,
2533ca95b02SDimitry Andric                       FunctionLoweringInfo::StatepointSpillMap &SSM) {
2543ca95b02SDimitry Andric   DenseMap<SDValue, const Value *> Seen;
25539d628a0SDimitry Andric 
2563ca95b02SDimitry Andric   SmallVector<const Value *, 64> NewBases, NewPtrs;
2573ca95b02SDimitry Andric   SmallVector<const GCRelocateInst *, 64> NewRelocs;
2583ca95b02SDimitry Andric   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
25939d628a0SDimitry Andric     SDValue SD = Builder.getValue(Ptrs[i]);
2603ca95b02SDimitry Andric     auto SeenIt = Seen.find(SD);
2613ca95b02SDimitry Andric 
2623ca95b02SDimitry Andric     if (SeenIt == Seen.end()) {
26339d628a0SDimitry Andric       // Only add non-duplicates
26439d628a0SDimitry Andric       NewBases.push_back(Bases[i]);
26539d628a0SDimitry Andric       NewPtrs.push_back(Ptrs[i]);
26639d628a0SDimitry Andric       NewRelocs.push_back(Relocs[i]);
2673ca95b02SDimitry Andric       Seen[SD] = Ptrs[i];
2683ca95b02SDimitry Andric     } else {
2693ca95b02SDimitry Andric       // Duplicate pointer found, note in SSM and move on:
2703ca95b02SDimitry Andric       SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
27139d628a0SDimitry Andric     }
27239d628a0SDimitry Andric   }
27339d628a0SDimitry Andric   assert(Bases.size() >= NewBases.size());
27439d628a0SDimitry Andric   assert(Ptrs.size() >= NewPtrs.size());
27539d628a0SDimitry Andric   assert(Relocs.size() >= NewRelocs.size());
27639d628a0SDimitry Andric   Bases = NewBases;
27739d628a0SDimitry Andric   Ptrs = NewPtrs;
27839d628a0SDimitry Andric   Relocs = NewRelocs;
27939d628a0SDimitry Andric   assert(Ptrs.size() == Bases.size());
28039d628a0SDimitry Andric   assert(Ptrs.size() == Relocs.size());
28139d628a0SDimitry Andric }
28239d628a0SDimitry Andric 
28339d628a0SDimitry Andric /// Extract call from statepoint, lower it and return pointer to the
28439d628a0SDimitry Andric /// call node. Also update NodeMap so that getValue(statepoint) will
28539d628a0SDimitry Andric /// reference lowered call result
2863ca95b02SDimitry Andric static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
2873ca95b02SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI,
2883ca95b02SDimitry Andric     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
289ff0cc061SDimitry Andric 
290ff0cc061SDimitry Andric   SDValue ReturnValue, CallEndVal;
2913ca95b02SDimitry Andric   std::tie(ReturnValue, CallEndVal) =
2923ca95b02SDimitry Andric       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
293ff0cc061SDimitry Andric   SDNode *CallEnd = CallEndVal.getNode();
294ff0cc061SDimitry Andric 
295ff0cc061SDimitry Andric   // Get a call instruction from the call sequence chain.  Tail calls are not
296ff0cc061SDimitry Andric   // allowed.  The following code is essentially reverse engineering X86's
297ff0cc061SDimitry Andric   // LowerCallTo.
298ff0cc061SDimitry Andric   //
299ff0cc061SDimitry Andric   // We are expecting DAG to have the following form:
300ff0cc061SDimitry Andric   //
301ff0cc061SDimitry Andric   // ch = eh_label (only in case of invoke statepoint)
302ff0cc061SDimitry Andric   //   ch, glue = callseq_start ch
303ff0cc061SDimitry Andric   //   ch, glue = X86::Call ch, glue
304ff0cc061SDimitry Andric   //   ch, glue = callseq_end ch, glue
305ff0cc061SDimitry Andric   //   get_return_value ch, glue
306ff0cc061SDimitry Andric   //
3077d523365SDimitry Andric   // get_return_value can either be a sequence of CopyFromReg instructions
3087d523365SDimitry Andric   // to grab the return value from the return register(s), or it can be a LOAD
3097d523365SDimitry Andric   // to load a value returned by reference via a stack slot.
310ff0cc061SDimitry Andric 
3113ca95b02SDimitry Andric   bool HasDef = !SI.CLI.RetTy->isVoidTy();
3127d523365SDimitry Andric   if (HasDef) {
3137d523365SDimitry Andric     if (CallEnd->getOpcode() == ISD::LOAD)
314ff0cc061SDimitry Andric       CallEnd = CallEnd->getOperand(0).getNode();
3157d523365SDimitry Andric     else
3167d523365SDimitry Andric       while (CallEnd->getOpcode() == ISD::CopyFromReg)
3177d523365SDimitry Andric         CallEnd = CallEnd->getOperand(0).getNode();
3187d523365SDimitry Andric   }
319ff0cc061SDimitry Andric 
320ff0cc061SDimitry Andric   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
3213ca95b02SDimitry Andric   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
32239d628a0SDimitry Andric }
32339d628a0SDimitry Andric 
32439d628a0SDimitry Andric /// Spill a value incoming to the statepoint. It might be either part of
32539d628a0SDimitry Andric /// vmstate
32639d628a0SDimitry Andric /// or gcstate. In both cases unconditionally spill it on the stack unless it
32739d628a0SDimitry Andric /// is a null constant. Return pair with first element being frame index
32839d628a0SDimitry Andric /// containing saved value and second element with outgoing chain from the
32939d628a0SDimitry Andric /// emitted store
33039d628a0SDimitry Andric static std::pair<SDValue, SDValue>
33139d628a0SDimitry Andric spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
33239d628a0SDimitry Andric                              SelectionDAGBuilder &Builder) {
33339d628a0SDimitry Andric   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
33439d628a0SDimitry Andric 
33539d628a0SDimitry Andric   // Emit new store if we didn't do it for this ptr before
33639d628a0SDimitry Andric   if (!Loc.getNode()) {
33739d628a0SDimitry Andric     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
33839d628a0SDimitry Andric                                                        Builder);
33939d628a0SDimitry Andric     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
34039d628a0SDimitry Andric     // We use TargetFrameIndex so that isel will not select it into LEA
34139d628a0SDimitry Andric     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
34239d628a0SDimitry Andric 
34339d628a0SDimitry Andric     // TODO: We can create TokenFactor node instead of
34439d628a0SDimitry Andric     //       chaining stores one after another, this may allow
34539d628a0SDimitry Andric     //       a bit more optimal scheduling for them
3463ca95b02SDimitry Andric 
3473ca95b02SDimitry Andric #ifndef NDEBUG
3483ca95b02SDimitry Andric     // Right now we always allocate spill slots that are of the same
3493ca95b02SDimitry Andric     // size as the value we're about to spill (the size of spillee can
3503ca95b02SDimitry Andric     // vary since we spill vectors of pointers too).  At some point we
3513ca95b02SDimitry Andric     // can consider allowing spills of smaller values to larger slots
3523ca95b02SDimitry Andric     // (i.e. change the '==' in the assert below to a '>=').
3533ca95b02SDimitry Andric     auto *MFI = Builder.DAG.getMachineFunction().getFrameInfo();
3543ca95b02SDimitry Andric     assert((MFI->getObjectSize(Index) * 8) ==
3553ca95b02SDimitry Andric                Incoming.getValueType().getSizeInBits() &&
3563ca95b02SDimitry Andric            "Bad spill:  stack slot does not match!");
3573ca95b02SDimitry Andric #endif
3583ca95b02SDimitry Andric 
35939d628a0SDimitry Andric     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
3607d523365SDimitry Andric                                  MachinePointerInfo::getFixedStack(
3613ca95b02SDimitry Andric                                      Builder.DAG.getMachineFunction(), Index));
36239d628a0SDimitry Andric 
36339d628a0SDimitry Andric     Builder.StatepointLowering.setLocation(Incoming, Loc);
36439d628a0SDimitry Andric   }
36539d628a0SDimitry Andric 
36639d628a0SDimitry Andric   assert(Loc.getNode());
36739d628a0SDimitry Andric   return std::make_pair(Loc, Chain);
36839d628a0SDimitry Andric }
36939d628a0SDimitry Andric 
37039d628a0SDimitry Andric /// Lower a single value incoming to a statepoint node.  This value can be
37139d628a0SDimitry Andric /// either a deopt value or a gc value, the handling is the same.  We special
37239d628a0SDimitry Andric /// case constants and allocas, then fall back to spilling if required.
37339d628a0SDimitry Andric static void lowerIncomingStatepointValue(SDValue Incoming,
37439d628a0SDimitry Andric                                          SmallVectorImpl<SDValue> &Ops,
37539d628a0SDimitry Andric                                          SelectionDAGBuilder &Builder) {
37639d628a0SDimitry Andric   SDValue Chain = Builder.getRoot();
37739d628a0SDimitry Andric 
37839d628a0SDimitry Andric   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
37939d628a0SDimitry Andric     // If the original value was a constant, make sure it gets recorded as
38039d628a0SDimitry Andric     // such in the stackmap.  This is required so that the consumer can
38139d628a0SDimitry Andric     // parse any internal format to the deopt state.  It also handles null
382444ed5c5SDimitry Andric     // pointers and other constant pointers in GC states.  Note the constant
383444ed5c5SDimitry Andric     // vectors do not appear to actually hit this path and that anything larger
384444ed5c5SDimitry Andric     // than an i64 value (not type!) will fail asserts here.
385ff0cc061SDimitry Andric     pushStackMapConstant(Ops, Builder, C->getSExtValue());
38639d628a0SDimitry Andric   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
387ff0cc061SDimitry Andric     // This handles allocas as arguments to the statepoint (this is only
388ff0cc061SDimitry Andric     // really meaningful for a deopt value.  For GC, we'd be trying to
389ff0cc061SDimitry Andric     // relocate the address of the alloca itself?)
390ff0cc061SDimitry Andric     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
391ff0cc061SDimitry Andric                                                   Incoming.getValueType()));
39239d628a0SDimitry Andric   } else {
39339d628a0SDimitry Andric     // Otherwise, locate a spill slot and explicitly spill it so it
39439d628a0SDimitry Andric     // can be found by the runtime later.  We currently do not support
39539d628a0SDimitry Andric     // tracking values through callee saved registers to their eventual
39639d628a0SDimitry Andric     // spill location.  This would be a useful optimization, but would
39739d628a0SDimitry Andric     // need to be optional since it requires a lot of complexity on the
39839d628a0SDimitry Andric     // runtime side which not all would support.
3993ca95b02SDimitry Andric     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
40039d628a0SDimitry Andric     Ops.push_back(Res.first);
40139d628a0SDimitry Andric     Chain = Res.second;
40239d628a0SDimitry Andric   }
40339d628a0SDimitry Andric 
40439d628a0SDimitry Andric   Builder.DAG.setRoot(Chain);
40539d628a0SDimitry Andric }
40639d628a0SDimitry Andric 
40739d628a0SDimitry Andric /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
40839d628a0SDimitry Andric /// lowering is described in lowerIncomingStatepointValue.  This function is
40939d628a0SDimitry Andric /// responsible for lowering everything in the right position and playing some
41039d628a0SDimitry Andric /// tricks to avoid redundant stack manipulation where possible.  On
41139d628a0SDimitry Andric /// completion, 'Ops' will contain ready to use operands for machine code
41239d628a0SDimitry Andric /// statepoint. The chain nodes will have already been created and the DAG root
41339d628a0SDimitry Andric /// will be set to the last value spilled (if any were).
4143ca95b02SDimitry Andric static void
4153ca95b02SDimitry Andric lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
4163ca95b02SDimitry Andric                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
41739d628a0SDimitry Andric                         SelectionDAGBuilder &Builder) {
4183ca95b02SDimitry Andric   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
4193ca95b02SDimitry Andric   // deopt argument length, deopt arguments.., gc arguments...
42039d628a0SDimitry Andric #ifndef NDEBUG
4213ca95b02SDimitry Andric   if (auto *GFI = Builder.GFI) {
42239d628a0SDimitry Andric     // Check that each of the gc pointer and bases we've gotten out of the
423444ed5c5SDimitry Andric     // safepoint is something the strategy thinks might be a pointer (or vector
424444ed5c5SDimitry Andric     // of pointers) into the GC heap.  This is basically just here to help catch
425444ed5c5SDimitry Andric     // errors during statepoint insertion. TODO: This should actually be in the
426444ed5c5SDimitry Andric     // Verifier, but we can't get to the GCStrategy from there (yet).
4273ca95b02SDimitry Andric     GCStrategy &S = GFI->getStrategy();
4283ca95b02SDimitry Andric     for (const Value *V : SI.Bases) {
429444ed5c5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
43039d628a0SDimitry Andric       if (Opt.hasValue()) {
43139d628a0SDimitry Andric         assert(Opt.getValue() &&
43239d628a0SDimitry Andric                "non gc managed base pointer found in statepoint");
43339d628a0SDimitry Andric       }
43439d628a0SDimitry Andric     }
4353ca95b02SDimitry Andric     for (const Value *V : SI.Ptrs) {
436444ed5c5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
43739d628a0SDimitry Andric       if (Opt.hasValue()) {
43839d628a0SDimitry Andric         assert(Opt.getValue() &&
43939d628a0SDimitry Andric                "non gc managed derived pointer found in statepoint");
44039d628a0SDimitry Andric       }
44139d628a0SDimitry Andric     }
4423ca95b02SDimitry Andric   } else {
4433ca95b02SDimitry Andric     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
4443ca95b02SDimitry Andric     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
44539d628a0SDimitry Andric   }
44639d628a0SDimitry Andric #endif
44739d628a0SDimitry Andric 
44839d628a0SDimitry Andric   // Before we actually start lowering (and allocating spill slots for values),
44939d628a0SDimitry Andric   // reserve any stack slots which we judge to be profitable to reuse for a
45039d628a0SDimitry Andric   // particular value.  This is purely an optimization over the code below and
45139d628a0SDimitry Andric   // doesn't change semantics at all.  It is important for performance that we
45239d628a0SDimitry Andric   // reserve slots for both deopt and gc values before lowering either.
4533ca95b02SDimitry Andric   for (const Value *V : SI.DeoptState) {
4548f0fd8f6SDimitry Andric     reservePreviousStackSlotForValue(V, Builder);
45539d628a0SDimitry Andric   }
4563ca95b02SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
4573ca95b02SDimitry Andric     reservePreviousStackSlotForValue(SI.Bases[i], Builder);
4583ca95b02SDimitry Andric     reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
45939d628a0SDimitry Andric   }
46039d628a0SDimitry Andric 
46139d628a0SDimitry Andric   // First, prefix the list with the number of unique values to be
46239d628a0SDimitry Andric   // lowered.  Note that this is the number of *Values* not the
46339d628a0SDimitry Andric   // number of SDValues required to lower them.
4643ca95b02SDimitry Andric   const int NumVMSArgs = SI.DeoptState.size();
465ff0cc061SDimitry Andric   pushStackMapConstant(Ops, Builder, NumVMSArgs);
46639d628a0SDimitry Andric 
4673ca95b02SDimitry Andric   // The vm state arguments are lowered in an opaque manner.  We do not know
4683ca95b02SDimitry Andric   // what type of values are contained within.
4693ca95b02SDimitry Andric   for (const Value *V : SI.DeoptState) {
47039d628a0SDimitry Andric     SDValue Incoming = Builder.getValue(V);
47139d628a0SDimitry Andric     lowerIncomingStatepointValue(Incoming, Ops, Builder);
47239d628a0SDimitry Andric   }
47339d628a0SDimitry Andric 
47439d628a0SDimitry Andric   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
47539d628a0SDimitry Andric   // length for this one.  After lowering, we'll have the base and pointer
47639d628a0SDimitry Andric   // arrays interwoven with each (lowered) base pointer immediately followed by
47739d628a0SDimitry Andric   // it's (lowered) derived pointer.  i.e
47839d628a0SDimitry Andric   // (base[0], ptr[0], base[1], ptr[1], ...)
4793ca95b02SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
4803ca95b02SDimitry Andric     const Value *Base = SI.Bases[i];
481ff0cc061SDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
482ff0cc061SDimitry Andric 
4833ca95b02SDimitry Andric     const Value *Ptr = SI.Ptrs[i];
484ff0cc061SDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
485ff0cc061SDimitry Andric   }
486ff0cc061SDimitry Andric 
487ff0cc061SDimitry Andric   // If there are any explicit spill slots passed to the statepoint, record
488ff0cc061SDimitry Andric   // them, but otherwise do not do anything special.  These are user provided
489ff0cc061SDimitry Andric   // allocas and give control over placement to the consumer.  In this case,
490ff0cc061SDimitry Andric   // it is the contents of the slot which may get updated, not the pointer to
491ff0cc061SDimitry Andric   // the alloca
4923ca95b02SDimitry Andric   for (Value *V : SI.GCArgs) {
49339d628a0SDimitry Andric     SDValue Incoming = Builder.getValue(V);
494ff0cc061SDimitry Andric     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
495ff0cc061SDimitry Andric       // This handles allocas as arguments to the statepoint
496ff0cc061SDimitry Andric       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
497ff0cc061SDimitry Andric                                                     Incoming.getValueType()));
49839d628a0SDimitry Andric     }
49939d628a0SDimitry Andric   }
500ff0cc061SDimitry Andric 
501ff0cc061SDimitry Andric   // Record computed locations for all lowered values.
502ff0cc061SDimitry Andric   // This can not be embedded in lowering loops as we need to record *all*
503ff0cc061SDimitry Andric   // values, while previous loops account only values with unique SDValues.
5043ca95b02SDimitry Andric   const Instruction *StatepointInstr = SI.StatepointInstr;
5053ca95b02SDimitry Andric   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
506ff0cc061SDimitry Andric 
5073ca95b02SDimitry Andric   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
5084d0b32cdSDimitry Andric     const Value *V = Relocate->getDerivedPtr();
509ff0cc061SDimitry Andric     SDValue SDV = Builder.getValue(V);
510ff0cc061SDimitry Andric     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
511ff0cc061SDimitry Andric 
512ff0cc061SDimitry Andric     if (Loc.getNode()) {
5133ca95b02SDimitry Andric       SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
514ff0cc061SDimitry Andric     } else {
515ff0cc061SDimitry Andric       // Record value as visited, but not spilled. This is case for allocas
5167d523365SDimitry Andric       // and constants. For this values we can avoid emitting spill load while
517ff0cc061SDimitry Andric       // visiting corresponding gc_relocate.
518ff0cc061SDimitry Andric       // Actually we do not need to record them in this map at all.
5197d523365SDimitry Andric       // We do this only to check that we are not relocating any unvisited
5207d523365SDimitry Andric       // value.
5213ca95b02SDimitry Andric       SpillMap.SlotMap[V] = None;
522ff0cc061SDimitry Andric 
523ff0cc061SDimitry Andric       // Default llvm mechanisms for exporting values which are used in
524ff0cc061SDimitry Andric       // different basic blocks does not work for gc relocates.
525ff0cc061SDimitry Andric       // Note that it would be incorrect to teach llvm that all relocates are
5267d523365SDimitry Andric       // uses of the corresponding values so that it would automatically
527ff0cc061SDimitry Andric       // export them. Relocates of the spilled values does not use original
528ff0cc061SDimitry Andric       // value.
5294d0b32cdSDimitry Andric       if (Relocate->getParent() != StatepointInstr->getParent())
530ff0cc061SDimitry Andric         Builder.ExportFromCurrentBlock(V);
531ff0cc061SDimitry Andric     }
532ff0cc061SDimitry Andric   }
533ff0cc061SDimitry Andric }
534ff0cc061SDimitry Andric 
5353ca95b02SDimitry Andric SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
5363ca95b02SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
53739d628a0SDimitry Andric   // The basic scheme here is that information about both the original call and
53839d628a0SDimitry Andric   // the safepoint is encoded in the CallInst.  We create a temporary call and
53939d628a0SDimitry Andric   // lower it, then reverse engineer the calling sequence.
54039d628a0SDimitry Andric 
54139d628a0SDimitry Andric   NumOfStatepoints++;
54239d628a0SDimitry Andric   // Clear state
54339d628a0SDimitry Andric   StatepointLowering.startNewStatepoint(*this);
54439d628a0SDimitry Andric 
54539d628a0SDimitry Andric #ifndef NDEBUG
5463ca95b02SDimitry Andric   // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
5473ca95b02SDimitry Andric   // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
5483ca95b02SDimitry Andric   for (auto *Reloc : SI.GCRelocates)
5493ca95b02SDimitry Andric     if (Reloc->getParent() == SI.StatepointInstr->getParent())
5503ca95b02SDimitry Andric       StatepointLowering.scheduleRelocCall(*Reloc);
55139d628a0SDimitry Andric #endif
55239d628a0SDimitry Andric 
5533ca95b02SDimitry Andric   // Remove any redundant llvm::Values which map to the same SDValue as another
5543ca95b02SDimitry Andric   // input.  Also has the effect of removing duplicates in the original
5553ca95b02SDimitry Andric   // llvm::Value input list as well.  This is a useful optimization for
5563ca95b02SDimitry Andric   // reducing the size of the StackMap section.  It has no other impact.
5573ca95b02SDimitry Andric   removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
5583ca95b02SDimitry Andric                         FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
5593ca95b02SDimitry Andric   assert(SI.Bases.size() == SI.Ptrs.size() &&
5603ca95b02SDimitry Andric          SI.Ptrs.size() == SI.GCRelocates.size());
56139d628a0SDimitry Andric 
56239d628a0SDimitry Andric   // Lower statepoint vmstate and gcstate arguments
563ff0cc061SDimitry Andric   SmallVector<SDValue, 10> LoweredMetaArgs;
5643ca95b02SDimitry Andric   lowerStatepointMetaArgs(LoweredMetaArgs, SI, *this);
5653ca95b02SDimitry Andric 
5663ca95b02SDimitry Andric   // Now that we've emitted the spills, we need to update the root so that the
5673ca95b02SDimitry Andric   // call sequence is ordered correctly.
5683ca95b02SDimitry Andric   SI.CLI.setChain(getRoot());
56939d628a0SDimitry Andric 
57039d628a0SDimitry Andric   // Get call node, we will replace it later with statepoint
5713ca95b02SDimitry Andric   SDValue ReturnVal;
5723ca95b02SDimitry Andric   SDNode *CallNode;
5733ca95b02SDimitry Andric   std::tie(ReturnVal, CallNode) =
5743ca95b02SDimitry Andric       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
57539d628a0SDimitry Andric 
576ff0cc061SDimitry Andric   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
577ff0cc061SDimitry Andric   // nodes with all the appropriate arguments and return values.
578ff0cc061SDimitry Andric 
579ff0cc061SDimitry Andric   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
580ff0cc061SDimitry Andric   SDValue Chain = CallNode->getOperand(0);
581ff0cc061SDimitry Andric 
582ff0cc061SDimitry Andric   SDValue Glue;
583ff0cc061SDimitry Andric   bool CallHasIncomingGlue = CallNode->getGluedNode();
584ff0cc061SDimitry Andric   if (CallHasIncomingGlue) {
585ff0cc061SDimitry Andric     // Glue is always last operand
586ff0cc061SDimitry Andric     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
587ff0cc061SDimitry Andric   }
588ff0cc061SDimitry Andric 
589ff0cc061SDimitry Andric   // Build the GC_TRANSITION_START node if necessary.
590ff0cc061SDimitry Andric   //
591ff0cc061SDimitry Andric   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
592ff0cc061SDimitry Andric   // order in which they appear in the call to the statepoint intrinsic. If
593ff0cc061SDimitry Andric   // any of the operands is a pointer-typed, that operand is immediately
594ff0cc061SDimitry Andric   // followed by a SRCVALUE for the pointer that may be used during lowering
595ff0cc061SDimitry Andric   // (e.g. to form MachinePointerInfo values for loads/stores).
596ff0cc061SDimitry Andric   const bool IsGCTransition =
5973ca95b02SDimitry Andric       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
598ff0cc061SDimitry Andric       (uint64_t)StatepointFlags::GCTransition;
599ff0cc061SDimitry Andric   if (IsGCTransition) {
600ff0cc061SDimitry Andric     SmallVector<SDValue, 8> TSOps;
601ff0cc061SDimitry Andric 
602ff0cc061SDimitry Andric     // Add chain
603ff0cc061SDimitry Andric     TSOps.push_back(Chain);
604ff0cc061SDimitry Andric 
605ff0cc061SDimitry Andric     // Add GC transition arguments
6063ca95b02SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
607ff0cc061SDimitry Andric       TSOps.push_back(getValue(V));
608ff0cc061SDimitry Andric       if (V->getType()->isPointerTy())
609ff0cc061SDimitry Andric         TSOps.push_back(DAG.getSrcValue(V));
610ff0cc061SDimitry Andric     }
611ff0cc061SDimitry Andric 
612ff0cc061SDimitry Andric     // Add glue if necessary
613ff0cc061SDimitry Andric     if (CallHasIncomingGlue)
614ff0cc061SDimitry Andric       TSOps.push_back(Glue);
615ff0cc061SDimitry Andric 
616ff0cc061SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
617ff0cc061SDimitry Andric 
618ff0cc061SDimitry Andric     SDValue GCTransitionStart =
619ff0cc061SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
620ff0cc061SDimitry Andric 
621ff0cc061SDimitry Andric     Chain = GCTransitionStart.getValue(0);
622ff0cc061SDimitry Andric     Glue = GCTransitionStart.getValue(1);
623ff0cc061SDimitry Andric   }
62439d628a0SDimitry Andric 
62539d628a0SDimitry Andric   // TODO: Currently, all of these operands are being marked as read/write in
62639d628a0SDimitry Andric   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
62739d628a0SDimitry Andric   // and flags to be read-only.
62839d628a0SDimitry Andric   SmallVector<SDValue, 40> Ops;
62939d628a0SDimitry Andric 
630ff0cc061SDimitry Andric   // Add the <id> and <numBytes> constants.
6313ca95b02SDimitry Andric   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
632ff0cc061SDimitry Andric   Ops.push_back(
6333ca95b02SDimitry Andric       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
634ff0cc061SDimitry Andric 
63539d628a0SDimitry Andric   // Calculate and push starting position of vmstate arguments
63639d628a0SDimitry Andric   // Get number of arguments incoming directly into call node
63739d628a0SDimitry Andric   unsigned NumCallRegArgs =
638ff0cc061SDimitry Andric       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
639ff0cc061SDimitry Andric   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
64039d628a0SDimitry Andric 
64139d628a0SDimitry Andric   // Add call target
64239d628a0SDimitry Andric   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
64339d628a0SDimitry Andric   Ops.push_back(CallTarget);
64439d628a0SDimitry Andric 
64539d628a0SDimitry Andric   // Add call arguments
64639d628a0SDimitry Andric   // Get position of register mask in the call
64739d628a0SDimitry Andric   SDNode::op_iterator RegMaskIt;
648ff0cc061SDimitry Andric   if (CallHasIncomingGlue)
64939d628a0SDimitry Andric     RegMaskIt = CallNode->op_end() - 2;
65039d628a0SDimitry Andric   else
65139d628a0SDimitry Andric     RegMaskIt = CallNode->op_end() - 1;
65239d628a0SDimitry Andric   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
65339d628a0SDimitry Andric 
654ff0cc061SDimitry Andric   // Add a constant argument for the calling convention
6553ca95b02SDimitry Andric   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
656ff0cc061SDimitry Andric 
657ff0cc061SDimitry Andric   // Add a constant argument for the flags
6583ca95b02SDimitry Andric   uint64_t Flags = SI.StatepointFlags;
6593ca95b02SDimitry Andric   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
6603ca95b02SDimitry Andric          "Unknown flag used");
661ff0cc061SDimitry Andric   pushStackMapConstant(Ops, *this, Flags);
66239d628a0SDimitry Andric 
66339d628a0SDimitry Andric   // Insert all vmstate and gcstate arguments
664ff0cc061SDimitry Andric   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
66539d628a0SDimitry Andric 
66639d628a0SDimitry Andric   // Add register mask from call node
66739d628a0SDimitry Andric   Ops.push_back(*RegMaskIt);
66839d628a0SDimitry Andric 
66939d628a0SDimitry Andric   // Add chain
670ff0cc061SDimitry Andric   Ops.push_back(Chain);
67139d628a0SDimitry Andric 
67239d628a0SDimitry Andric   // Same for the glue, but we add it only if original call had it
67339d628a0SDimitry Andric   if (Glue.getNode())
67439d628a0SDimitry Andric     Ops.push_back(Glue);
67539d628a0SDimitry Andric 
676ff0cc061SDimitry Andric   // Compute return values.  Provide a glue output since we consume one as
677ff0cc061SDimitry Andric   // input.  This allows someone else to chain off us as needed.
678ff0cc061SDimitry Andric   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
67939d628a0SDimitry Andric 
680ff0cc061SDimitry Andric   SDNode *StatepointMCNode =
681ff0cc061SDimitry Andric       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
682ff0cc061SDimitry Andric 
683ff0cc061SDimitry Andric   SDNode *SinkNode = StatepointMCNode;
684ff0cc061SDimitry Andric 
685ff0cc061SDimitry Andric   // Build the GC_TRANSITION_END node if necessary.
686ff0cc061SDimitry Andric   //
687ff0cc061SDimitry Andric   // See the comment above regarding GC_TRANSITION_START for the layout of
688ff0cc061SDimitry Andric   // the operands to the GC_TRANSITION_END node.
689ff0cc061SDimitry Andric   if (IsGCTransition) {
690ff0cc061SDimitry Andric     SmallVector<SDValue, 8> TEOps;
691ff0cc061SDimitry Andric 
692ff0cc061SDimitry Andric     // Add chain
693ff0cc061SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 0));
694ff0cc061SDimitry Andric 
695ff0cc061SDimitry Andric     // Add GC transition arguments
6963ca95b02SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
697ff0cc061SDimitry Andric       TEOps.push_back(getValue(V));
698ff0cc061SDimitry Andric       if (V->getType()->isPointerTy())
699ff0cc061SDimitry Andric         TEOps.push_back(DAG.getSrcValue(V));
700ff0cc061SDimitry Andric     }
701ff0cc061SDimitry Andric 
702ff0cc061SDimitry Andric     // Add glue
703ff0cc061SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 1));
704ff0cc061SDimitry Andric 
705ff0cc061SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
706ff0cc061SDimitry Andric 
707ff0cc061SDimitry Andric     SDValue GCTransitionStart =
708ff0cc061SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
709ff0cc061SDimitry Andric 
710ff0cc061SDimitry Andric     SinkNode = GCTransitionStart.getNode();
711ff0cc061SDimitry Andric   }
71239d628a0SDimitry Andric 
71339d628a0SDimitry Andric   // Replace original call
714ff0cc061SDimitry Andric   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
7157d523365SDimitry Andric   // Remove original call node
71639d628a0SDimitry Andric   DAG.DeleteNode(CallNode);
71739d628a0SDimitry Andric 
71839d628a0SDimitry Andric   // DON'T set the root - under the assumption that it's already set past the
71939d628a0SDimitry Andric   // inserted node we created.
72039d628a0SDimitry Andric 
72139d628a0SDimitry Andric   // TODO: A better future implementation would be to emit a single variable
72239d628a0SDimitry Andric   // argument, variable return value STATEPOINT node here and then hookup the
72339d628a0SDimitry Andric   // return value of each gc.relocate to the respective output of the
72439d628a0SDimitry Andric   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
72539d628a0SDimitry Andric   // to actually be possible today.
7263ca95b02SDimitry Andric 
7273ca95b02SDimitry Andric   return ReturnVal;
72839d628a0SDimitry Andric }
72939d628a0SDimitry Andric 
7303ca95b02SDimitry Andric void
7313ca95b02SDimitry Andric SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
7323ca95b02SDimitry Andric                                      const BasicBlock *EHPadBB /*= nullptr*/) {
7333ca95b02SDimitry Andric   assert(ISP.getCallSite().getCallingConv() != CallingConv::AnyReg &&
7343ca95b02SDimitry Andric          "anyregcc is not supported on statepoints!");
7353ca95b02SDimitry Andric 
7363ca95b02SDimitry Andric #ifndef NDEBUG
7373ca95b02SDimitry Andric   // If this is a malformed statepoint, report it early to simplify debugging.
7383ca95b02SDimitry Andric   // This should catch any IR level mistake that's made when constructing or
7393ca95b02SDimitry Andric   // transforming statepoints.
7403ca95b02SDimitry Andric   ISP.verify();
7413ca95b02SDimitry Andric 
7423ca95b02SDimitry Andric   // Check that the associated GCStrategy expects to encounter statepoints.
7433ca95b02SDimitry Andric   assert(GFI->getStrategy().useStatepoints() &&
7443ca95b02SDimitry Andric          "GCStrategy does not expect to encounter statepoints");
7453ca95b02SDimitry Andric #endif
7463ca95b02SDimitry Andric 
7473ca95b02SDimitry Andric   SDValue ActualCallee;
7483ca95b02SDimitry Andric 
7493ca95b02SDimitry Andric   if (ISP.getNumPatchBytes() > 0) {
7503ca95b02SDimitry Andric     // If we've been asked to emit a nop sequence instead of a call instruction
7513ca95b02SDimitry Andric     // for this statepoint then don't lower the call target, but use a constant
7523ca95b02SDimitry Andric     // `null` instead.  Not lowering the call target lets statepoint clients get
7533ca95b02SDimitry Andric     // away without providing a physical address for the symbolic call target at
7543ca95b02SDimitry Andric     // link time.
7553ca95b02SDimitry Andric 
7563ca95b02SDimitry Andric     const auto &TLI = DAG.getTargetLoweringInfo();
7573ca95b02SDimitry Andric     const auto &DL = DAG.getDataLayout();
7583ca95b02SDimitry Andric 
7593ca95b02SDimitry Andric     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
7603ca95b02SDimitry Andric     ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
7613ca95b02SDimitry Andric   } else {
7623ca95b02SDimitry Andric     ActualCallee = getValue(ISP.getCalledValue());
7633ca95b02SDimitry Andric   }
7643ca95b02SDimitry Andric 
7653ca95b02SDimitry Andric   StatepointLoweringInfo SI(DAG);
7663ca95b02SDimitry Andric   populateCallLoweringInfo(SI.CLI, ISP.getCallSite(),
7673ca95b02SDimitry Andric                            ImmutableStatepoint::CallArgsBeginPos,
7683ca95b02SDimitry Andric                            ISP.getNumCallArgs(), ActualCallee,
7693ca95b02SDimitry Andric                            ISP.getActualReturnType(), false /* IsPatchPoint */);
7703ca95b02SDimitry Andric 
7713ca95b02SDimitry Andric   for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
7723ca95b02SDimitry Andric     SI.GCRelocates.push_back(Relocate);
7733ca95b02SDimitry Andric     SI.Bases.push_back(Relocate->getBasePtr());
7743ca95b02SDimitry Andric     SI.Ptrs.push_back(Relocate->getDerivedPtr());
7753ca95b02SDimitry Andric   }
7763ca95b02SDimitry Andric 
7773ca95b02SDimitry Andric   SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
7783ca95b02SDimitry Andric   SI.StatepointInstr = ISP.getInstruction();
7793ca95b02SDimitry Andric   SI.GCTransitionArgs =
7803ca95b02SDimitry Andric       ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
7813ca95b02SDimitry Andric   SI.ID = ISP.getID();
7823ca95b02SDimitry Andric   SI.DeoptState = ArrayRef<const Use>(ISP.vm_state_begin(), ISP.vm_state_end());
7833ca95b02SDimitry Andric   SI.StatepointFlags = ISP.getFlags();
7843ca95b02SDimitry Andric   SI.NumPatchBytes = ISP.getNumPatchBytes();
7853ca95b02SDimitry Andric   SI.EHPadBB = EHPadBB;
7863ca95b02SDimitry Andric 
7873ca95b02SDimitry Andric   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
7883ca95b02SDimitry Andric 
7893ca95b02SDimitry Andric   // Export the result value if needed
7903ca95b02SDimitry Andric   const GCResultInst *GCResult = ISP.getGCResult();
7913ca95b02SDimitry Andric   Type *RetTy = ISP.getActualReturnType();
7923ca95b02SDimitry Andric   if (!RetTy->isVoidTy() && GCResult) {
7933ca95b02SDimitry Andric     if (GCResult->getParent() != ISP.getCallSite().getParent()) {
7943ca95b02SDimitry Andric       // Result value will be used in a different basic block so we need to
7953ca95b02SDimitry Andric       // export it now.  Default exporting mechanism will not work here because
7963ca95b02SDimitry Andric       // statepoint call has a different type than the actual call. It means
7973ca95b02SDimitry Andric       // that by default llvm will create export register of the wrong type
7983ca95b02SDimitry Andric       // (always i32 in our case). So instead we need to create export register
7993ca95b02SDimitry Andric       // with correct type manually.
8003ca95b02SDimitry Andric       // TODO: To eliminate this problem we can remove gc.result intrinsics
8013ca95b02SDimitry Andric       //       completely and make statepoint call to return a tuple.
8023ca95b02SDimitry Andric       unsigned Reg = FuncInfo.CreateRegs(RetTy);
8033ca95b02SDimitry Andric       RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
8043ca95b02SDimitry Andric                        DAG.getDataLayout(), Reg, RetTy);
8053ca95b02SDimitry Andric       SDValue Chain = DAG.getEntryNode();
8063ca95b02SDimitry Andric 
8073ca95b02SDimitry Andric       RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
8083ca95b02SDimitry Andric       PendingExports.push_back(Chain);
8093ca95b02SDimitry Andric       FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
8103ca95b02SDimitry Andric     } else {
8113ca95b02SDimitry Andric       // Result value will be used in a same basic block. Don't export it or
8123ca95b02SDimitry Andric       // perform any explicit register copies.
8133ca95b02SDimitry Andric       // We'll replace the actuall call node shortly. gc_result will grab
8143ca95b02SDimitry Andric       // this value.
8153ca95b02SDimitry Andric       setValue(ISP.getInstruction(), ReturnValue);
8163ca95b02SDimitry Andric     }
8173ca95b02SDimitry Andric   } else {
8183ca95b02SDimitry Andric     // The token value is never used from here on, just generate a poison value
8193ca95b02SDimitry Andric     setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
8203ca95b02SDimitry Andric   }
8213ca95b02SDimitry Andric }
8223ca95b02SDimitry Andric 
8233ca95b02SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
8243ca95b02SDimitry Andric     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB,
8253ca95b02SDimitry Andric     bool VarArgDisallowed, bool ForceVoidReturnTy) {
8263ca95b02SDimitry Andric   StatepointLoweringInfo SI(DAG);
8273ca95b02SDimitry Andric   unsigned ArgBeginIndex = CS.arg_begin() - CS.getInstruction()->op_begin();
8283ca95b02SDimitry Andric   populateCallLoweringInfo(
8293ca95b02SDimitry Andric       SI.CLI, CS, ArgBeginIndex, CS.getNumArgOperands(), Callee,
8303ca95b02SDimitry Andric       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : CS.getType(),
8313ca95b02SDimitry Andric       false);
8323ca95b02SDimitry Andric   if (!VarArgDisallowed)
8333ca95b02SDimitry Andric     SI.CLI.IsVarArg = CS.getFunctionType()->isVarArg();
8343ca95b02SDimitry Andric 
8353ca95b02SDimitry Andric   auto DeoptBundle = *CS.getOperandBundle(LLVMContext::OB_deopt);
8363ca95b02SDimitry Andric 
8373ca95b02SDimitry Andric   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
8383ca95b02SDimitry Andric 
8393ca95b02SDimitry Andric   auto SD = parseStatepointDirectivesFromAttrs(CS.getAttributes());
8403ca95b02SDimitry Andric   SI.ID = SD.StatepointID.getValueOr(DefaultID);
8413ca95b02SDimitry Andric   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
8423ca95b02SDimitry Andric 
8433ca95b02SDimitry Andric   SI.DeoptState =
8443ca95b02SDimitry Andric       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
8453ca95b02SDimitry Andric   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
8463ca95b02SDimitry Andric   SI.EHPadBB = EHPadBB;
8473ca95b02SDimitry Andric 
8483ca95b02SDimitry Andric   // NB! The GC arguments are deliberately left empty.
8493ca95b02SDimitry Andric 
8503ca95b02SDimitry Andric   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
8513ca95b02SDimitry Andric     const Instruction *Inst = CS.getInstruction();
8523ca95b02SDimitry Andric     ReturnVal = lowerRangeToAssertZExt(DAG, *Inst, ReturnVal);
8533ca95b02SDimitry Andric     setValue(Inst, ReturnVal);
8543ca95b02SDimitry Andric   }
8553ca95b02SDimitry Andric }
8563ca95b02SDimitry Andric 
8573ca95b02SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
8583ca95b02SDimitry Andric     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB) {
8593ca95b02SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CS, Callee, EHPadBB,
8603ca95b02SDimitry Andric                                    /* VarArgDisallowed = */ false,
8613ca95b02SDimitry Andric                                    /* ForceVoidReturnTy  = */ false);
8623ca95b02SDimitry Andric }
8633ca95b02SDimitry Andric 
8643ca95b02SDimitry Andric void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
86539d628a0SDimitry Andric   // The result value of the gc_result is simply the result of the actual
86639d628a0SDimitry Andric   // call.  We've already emitted this, so just grab the value.
8673ca95b02SDimitry Andric   const Instruction *I = CI.getStatepoint();
86839d628a0SDimitry Andric 
8697d523365SDimitry Andric   if (I->getParent() != CI.getParent()) {
8707d523365SDimitry Andric     // Statepoint is in different basic block so we should have stored call
8717d523365SDimitry Andric     // result in a virtual register.
872ff0cc061SDimitry Andric     // We can not use default getValue() functionality to copy value from this
8733ca95b02SDimitry Andric     // register because statepoint and actual call return types can be
874ff0cc061SDimitry Andric     // different, and getValue() will use CopyFromReg of the wrong type,
875ff0cc061SDimitry Andric     // which is always i32 in our case.
8763dac3a9bSDimitry Andric     PointerType *CalleeType = cast<PointerType>(
8773dac3a9bSDimitry Andric         ImmutableStatepoint(I).getCalledValue()->getType());
878ff0cc061SDimitry Andric     Type *RetTy =
879ff0cc061SDimitry Andric         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
880ff0cc061SDimitry Andric     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
881ff0cc061SDimitry Andric 
882ff0cc061SDimitry Andric     assert(CopyFromReg.getNode());
883ff0cc061SDimitry Andric     setValue(&CI, CopyFromReg);
884ff0cc061SDimitry Andric   } else {
88539d628a0SDimitry Andric     setValue(&CI, getValue(I));
88639d628a0SDimitry Andric   }
887ff0cc061SDimitry Andric }
88839d628a0SDimitry Andric 
8894d0b32cdSDimitry Andric void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
89039d628a0SDimitry Andric #ifndef NDEBUG
89139d628a0SDimitry Andric   // Consistency check
8927d523365SDimitry Andric   // We skip this check for relocates not in the same basic block as thier
8937d523365SDimitry Andric   // statepoint. It would be too expensive to preserve validation info through
8947d523365SDimitry Andric   // different basic blocks.
8953ca95b02SDimitry Andric   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
8964d0b32cdSDimitry Andric     StatepointLowering.relocCallVisited(Relocate);
8973ca95b02SDimitry Andric 
8983ca95b02SDimitry Andric   auto *Ty = Relocate.getType()->getScalarType();
8993ca95b02SDimitry Andric   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
9003ca95b02SDimitry Andric     assert(*IsManaged && "Non gc managed pointer relocated!");
90139d628a0SDimitry Andric #endif
90239d628a0SDimitry Andric 
9034d0b32cdSDimitry Andric   const Value *DerivedPtr = Relocate.getDerivedPtr();
904ff0cc061SDimitry Andric   SDValue SD = getValue(DerivedPtr);
90539d628a0SDimitry Andric 
9063ca95b02SDimitry Andric   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
9073ca95b02SDimitry Andric   auto SlotIt = SpillMap.find(DerivedPtr);
9083ca95b02SDimitry Andric   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
9093ca95b02SDimitry Andric   Optional<int> DerivedPtrLocation = SlotIt->second;
910ff0cc061SDimitry Andric 
91139d628a0SDimitry Andric   // We didn't need to spill these special cases (constants and allocas).
91239d628a0SDimitry Andric   // See the handling in spillIncomingValueForStatepoint for detail.
913ff0cc061SDimitry Andric   if (!DerivedPtrLocation) {
9144d0b32cdSDimitry Andric     setValue(&Relocate, SD);
91539d628a0SDimitry Andric     return;
91639d628a0SDimitry Andric   }
91739d628a0SDimitry Andric 
918ff0cc061SDimitry Andric   SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
919ff0cc061SDimitry Andric                                               SD.getValueType());
92039d628a0SDimitry Andric 
92139d628a0SDimitry Andric   // Be conservative: flush all pending loads
92239d628a0SDimitry Andric   // TODO: Probably we can be less restrictive on this,
9237d523365SDimitry Andric   // it may allow more scheduling opportunities.
92439d628a0SDimitry Andric   SDValue Chain = getRoot();
92539d628a0SDimitry Andric 
926ff0cc061SDimitry Andric   SDValue SpillLoad =
927ff0cc061SDimitry Andric       DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
9287d523365SDimitry Andric                   MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
9293ca95b02SDimitry Andric                                                     *DerivedPtrLocation));
93039d628a0SDimitry Andric 
93139d628a0SDimitry Andric   // Again, be conservative, don't emit pending loads
932ff0cc061SDimitry Andric   DAG.setRoot(SpillLoad.getValue(1));
93339d628a0SDimitry Andric 
934ff0cc061SDimitry Andric   assert(SpillLoad.getNode());
9354d0b32cdSDimitry Andric   setValue(&Relocate, SpillLoad);
93639d628a0SDimitry Andric }
9373ca95b02SDimitry Andric 
9383ca95b02SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
9393ca95b02SDimitry Andric   const auto &TLI = DAG.getTargetLoweringInfo();
9403ca95b02SDimitry Andric   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
9413ca95b02SDimitry Andric                                          TLI.getPointerTy(DAG.getDataLayout()));
9423ca95b02SDimitry Andric 
9433ca95b02SDimitry Andric   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
9443ca95b02SDimitry Andric   // call.  We also do not lower the return value to any virtual register, and
9453ca95b02SDimitry Andric   // change the immediately following return to a trap instruction.
9463ca95b02SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
9473ca95b02SDimitry Andric                                    /* VarArgDisallowed = */ true,
9483ca95b02SDimitry Andric                                    /* ForceVoidReturnTy = */ true);
9493ca95b02SDimitry Andric }
9503ca95b02SDimitry Andric 
9513ca95b02SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizingReturn() {
9523ca95b02SDimitry Andric   // We do not lower the return value from llvm.deoptimize to any virtual
9533ca95b02SDimitry Andric   // register, and change the immediately following return to a trap
9543ca95b02SDimitry Andric   // instruction.
9553ca95b02SDimitry Andric   if (DAG.getTarget().Options.TrapUnreachable)
9563ca95b02SDimitry Andric     DAG.setRoot(
9573ca95b02SDimitry Andric         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
9583ca95b02SDimitry Andric }
959