xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
10b57cec5SDimitry Andric //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file includes support code use by SelectionDAGBuilder when lowering a
100b57cec5SDimitry Andric // statepoint sequence in SelectionDAG IR.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "StatepointLowering.h"
150b57cec5SDimitry Andric #include "SelectionDAGBuilder.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/None.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
200b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/GCStrategy.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/RuntimeLibcalls.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
360b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
370b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
390b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
400b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
410b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
420b57cec5SDimitry Andric #include "llvm/IR/Type.h"
430b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
440b57cec5SDimitry Andric #include "llvm/Support/MachineValueType.h"
450b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
460b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
470b57cec5SDimitry Andric #include <cassert>
480b57cec5SDimitry Andric #include <cstddef>
490b57cec5SDimitry Andric #include <cstdint>
500b57cec5SDimitry Andric #include <iterator>
510b57cec5SDimitry Andric #include <tuple>
520b57cec5SDimitry Andric #include <utility>
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric using namespace llvm;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric #define DEBUG_TYPE "statepoint-lowering"
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric STATISTIC(NumSlotsAllocatedForStatepoints,
590b57cec5SDimitry Andric           "Number of stack slots allocated for statepoints");
600b57cec5SDimitry Andric STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
610b57cec5SDimitry Andric STATISTIC(StatepointMaxSlotsRequired,
620b57cec5SDimitry Andric           "Maximum number of stack slots required for a singe statepoint");
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
650b57cec5SDimitry Andric                                  SelectionDAGBuilder &Builder, uint64_t Value) {
660b57cec5SDimitry Andric   SDLoc L = Builder.getCurSDLoc();
670b57cec5SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
680b57cec5SDimitry Andric                                               MVT::i64));
690b57cec5SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
730b57cec5SDimitry Andric   // Consistency check
740b57cec5SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
750b57cec5SDimitry Andric          "Trying to visit statepoint before finished processing previous one");
760b57cec5SDimitry Andric   Locations.clear();
770b57cec5SDimitry Andric   NextSlotToAllocate = 0;
780b57cec5SDimitry Andric   // Need to resize this on each safepoint - we need the two to stay in sync and
790b57cec5SDimitry Andric   // the clear patterns of a SelectionDAGBuilder have no relation to
800b57cec5SDimitry Andric   // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
810b57cec5SDimitry Andric   AllocatedStackSlots.clear();
820b57cec5SDimitry Andric   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric void StatepointLoweringState::clear() {
860b57cec5SDimitry Andric   Locations.clear();
870b57cec5SDimitry Andric   AllocatedStackSlots.clear();
880b57cec5SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
890b57cec5SDimitry Andric          "cleared before statepoint sequence completed");
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric SDValue
930b57cec5SDimitry Andric StatepointLoweringState::allocateStackSlot(EVT ValueType,
940b57cec5SDimitry Andric                                            SelectionDAGBuilder &Builder) {
950b57cec5SDimitry Andric   NumSlotsAllocatedForStatepoints++;
960b57cec5SDimitry Andric   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   unsigned SpillSize = ValueType.getStoreSize();
990b57cec5SDimitry Andric   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric   // First look for a previously created stack slot which is not in
1020b57cec5SDimitry Andric   // use (accounting for the fact arbitrary slots may already be
1030b57cec5SDimitry Andric   // reserved), or to create a new stack slot and use it.
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   const size_t NumSlots = AllocatedStackSlots.size();
1060b57cec5SDimitry Andric   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   assert(AllocatedStackSlots.size() ==
1090b57cec5SDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
1100b57cec5SDimitry Andric          "Broken invariant");
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
1130b57cec5SDimitry Andric     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
1140b57cec5SDimitry Andric       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
1150b57cec5SDimitry Andric       if (MFI.getObjectSize(FI) == SpillSize) {
1160b57cec5SDimitry Andric         AllocatedStackSlots.set(NextSlotToAllocate);
1170b57cec5SDimitry Andric         // TODO: Is ValueType the right thing to use here?
1180b57cec5SDimitry Andric         return Builder.DAG.getFrameIndex(FI, ValueType);
1190b57cec5SDimitry Andric       }
1200b57cec5SDimitry Andric     }
1210b57cec5SDimitry Andric   }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // Couldn't find a free slot, so create a new one:
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
1260b57cec5SDimitry Andric   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1270b57cec5SDimitry Andric   MFI.markAsStatepointSpillSlotObjectIndex(FI);
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
1300b57cec5SDimitry Andric   AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
1310b57cec5SDimitry Andric   assert(AllocatedStackSlots.size() ==
1320b57cec5SDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
1330b57cec5SDimitry Andric          "Broken invariant");
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   StatepointMaxSlotsRequired.updateMax(
1360b57cec5SDimitry Andric       Builder.FuncInfo.StatepointStackSlots.size());
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   return SpillSlot;
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric /// Utility function for reservePreviousStackSlotForValue. Tries to find
1420b57cec5SDimitry Andric /// stack slot index to which we have spilled value for previous statepoints.
1430b57cec5SDimitry Andric /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
1440b57cec5SDimitry Andric static Optional<int> findPreviousSpillSlot(const Value *Val,
1450b57cec5SDimitry Andric                                            SelectionDAGBuilder &Builder,
1460b57cec5SDimitry Andric                                            int LookUpDepth) {
1470b57cec5SDimitry Andric   // Can not look any further - give up now
1480b57cec5SDimitry Andric   if (LookUpDepth <= 0)
1490b57cec5SDimitry Andric     return None;
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   // Spill location is known for gc relocates
1520b57cec5SDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
1530b57cec5SDimitry Andric     const auto &SpillMap =
1540b57cec5SDimitry Andric         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     auto It = SpillMap.find(Relocate->getDerivedPtr());
1570b57cec5SDimitry Andric     if (It == SpillMap.end())
1580b57cec5SDimitry Andric       return None;
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric     return It->second;
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   // Look through bitcast instructions.
1640b57cec5SDimitry Andric   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
1650b57cec5SDimitry Andric     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   // Look through phi nodes
1680b57cec5SDimitry Andric   // All incoming values should have same known stack slot, otherwise result
1690b57cec5SDimitry Andric   // is unknown.
1700b57cec5SDimitry Andric   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
1710b57cec5SDimitry Andric     Optional<int> MergedResult = None;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric     for (auto &IncomingValue : Phi->incoming_values()) {
1740b57cec5SDimitry Andric       Optional<int> SpillSlot =
1750b57cec5SDimitry Andric           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
1760b57cec5SDimitry Andric       if (!SpillSlot.hasValue())
1770b57cec5SDimitry Andric         return None;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
1800b57cec5SDimitry Andric         return None;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric       MergedResult = SpillSlot;
1830b57cec5SDimitry Andric     }
1840b57cec5SDimitry Andric     return MergedResult;
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // TODO: We can do better for PHI nodes. In cases like this:
1880b57cec5SDimitry Andric   //   ptr = phi(relocated_pointer, not_relocated_pointer)
1890b57cec5SDimitry Andric   //   statepoint(ptr)
1900b57cec5SDimitry Andric   // We will return that stack slot for ptr is unknown. And later we might
1910b57cec5SDimitry Andric   // assign different stack slots for ptr and relocated_pointer. This limits
1920b57cec5SDimitry Andric   // llvm's ability to remove redundant stores.
1930b57cec5SDimitry Andric   // Unfortunately it's hard to accomplish in current infrastructure.
1940b57cec5SDimitry Andric   // We use this function to eliminate spill store completely, while
1950b57cec5SDimitry Andric   // in example we still need to emit store, but instead of any location
1960b57cec5SDimitry Andric   // we need to use special "preferred" location.
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   // TODO: handle simple updates.  If a value is modified and the original
1990b57cec5SDimitry Andric   // value is no longer live, it would be nice to put the modified value in the
2000b57cec5SDimitry Andric   // same slot.  This allows folding of the memory accesses for some
2010b57cec5SDimitry Andric   // instructions types (like an increment).
2020b57cec5SDimitry Andric   //   statepoint (i)
2030b57cec5SDimitry Andric   //   i1 = i+1
2040b57cec5SDimitry Andric   //   statepoint (i1)
2050b57cec5SDimitry Andric   // However we need to be careful for cases like this:
2060b57cec5SDimitry Andric   //   statepoint(i)
2070b57cec5SDimitry Andric   //   i1 = i+1
2080b57cec5SDimitry Andric   //   statepoint(i, i1)
2090b57cec5SDimitry Andric   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
2100b57cec5SDimitry Andric   // put handling of simple modifications in this function like it's done
2110b57cec5SDimitry Andric   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
2120b57cec5SDimitry Andric   // which we visit values is unspecified.
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // Don't know any information about this instruction
2150b57cec5SDimitry Andric   return None;
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric /// Try to find existing copies of the incoming values in stack slots used for
2190b57cec5SDimitry Andric /// statepoint spilling.  If we can find a spill slot for the incoming value,
2200b57cec5SDimitry Andric /// mark that slot as allocated, and reuse the same slot for this safepoint.
2210b57cec5SDimitry Andric /// This helps to avoid series of loads and stores that only serve to reshuffle
2220b57cec5SDimitry Andric /// values on the stack between calls.
2230b57cec5SDimitry Andric static void reservePreviousStackSlotForValue(const Value *IncomingValue,
2240b57cec5SDimitry Andric                                              SelectionDAGBuilder &Builder) {
2250b57cec5SDimitry Andric   SDValue Incoming = Builder.getValue(IncomingValue);
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
2280b57cec5SDimitry Andric     // We won't need to spill this, so no need to check for previously
2290b57cec5SDimitry Andric     // allocated stack slots
2300b57cec5SDimitry Andric     return;
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
2340b57cec5SDimitry Andric   if (OldLocation.getNode())
2350b57cec5SDimitry Andric     // Duplicates in input
2360b57cec5SDimitry Andric     return;
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   const int LookUpDepth = 6;
2390b57cec5SDimitry Andric   Optional<int> Index =
2400b57cec5SDimitry Andric       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
2410b57cec5SDimitry Andric   if (!Index.hasValue())
2420b57cec5SDimitry Andric     return;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   auto SlotIt = find(StatepointSlots, *Index);
2470b57cec5SDimitry Andric   assert(SlotIt != StatepointSlots.end() &&
2480b57cec5SDimitry Andric          "Value spilled to the unknown stack slot");
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   // This is one of our dedicated lowering slots
2510b57cec5SDimitry Andric   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
2520b57cec5SDimitry Andric   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
2530b57cec5SDimitry Andric     // stack slot already assigned to someone else, can't use it!
2540b57cec5SDimitry Andric     // TODO: currently we reserve space for gc arguments after doing
2550b57cec5SDimitry Andric     // normal allocation for deopt arguments.  We should reserve for
2560b57cec5SDimitry Andric     // _all_ deopt and gc arguments, then start allocating.  This
2570b57cec5SDimitry Andric     // will prevent some moves being inserted when vm state changes,
2580b57cec5SDimitry Andric     // but gc state doesn't between two calls.
2590b57cec5SDimitry Andric     return;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric   // Reserve this stack slot
2620b57cec5SDimitry Andric   Builder.StatepointLowering.reserveStackSlot(Offset);
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // Cache this slot so we find it when going through the normal
2650b57cec5SDimitry Andric   // assignment loop.
2660b57cec5SDimitry Andric   SDValue Loc =
2670b57cec5SDimitry Andric       Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
2680b57cec5SDimitry Andric   Builder.StatepointLowering.setLocation(Incoming, Loc);
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
2720b57cec5SDimitry Andric /// is not required for correctness.  It's purpose is to reduce the size of
2730b57cec5SDimitry Andric /// StackMap section.  It has no effect on the number of spill slots required
2740b57cec5SDimitry Andric /// or the actual lowering.
2750b57cec5SDimitry Andric static void
2760b57cec5SDimitry Andric removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
2770b57cec5SDimitry Andric                       SmallVectorImpl<const Value *> &Ptrs,
2780b57cec5SDimitry Andric                       SmallVectorImpl<const GCRelocateInst *> &Relocs,
2790b57cec5SDimitry Andric                       SelectionDAGBuilder &Builder,
2800b57cec5SDimitry Andric                       FunctionLoweringInfo::StatepointSpillMap &SSM) {
2810b57cec5SDimitry Andric   DenseMap<SDValue, const Value *> Seen;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   SmallVector<const Value *, 64> NewBases, NewPtrs;
2840b57cec5SDimitry Andric   SmallVector<const GCRelocateInst *, 64> NewRelocs;
2850b57cec5SDimitry Andric   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
2860b57cec5SDimitry Andric     SDValue SD = Builder.getValue(Ptrs[i]);
2870b57cec5SDimitry Andric     auto SeenIt = Seen.find(SD);
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     if (SeenIt == Seen.end()) {
2900b57cec5SDimitry Andric       // Only add non-duplicates
2910b57cec5SDimitry Andric       NewBases.push_back(Bases[i]);
2920b57cec5SDimitry Andric       NewPtrs.push_back(Ptrs[i]);
2930b57cec5SDimitry Andric       NewRelocs.push_back(Relocs[i]);
2940b57cec5SDimitry Andric       Seen[SD] = Ptrs[i];
2950b57cec5SDimitry Andric     } else {
2960b57cec5SDimitry Andric       // Duplicate pointer found, note in SSM and move on:
2970b57cec5SDimitry Andric       SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
2980b57cec5SDimitry Andric     }
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric   assert(Bases.size() >= NewBases.size());
3010b57cec5SDimitry Andric   assert(Ptrs.size() >= NewPtrs.size());
3020b57cec5SDimitry Andric   assert(Relocs.size() >= NewRelocs.size());
3030b57cec5SDimitry Andric   Bases = NewBases;
3040b57cec5SDimitry Andric   Ptrs = NewPtrs;
3050b57cec5SDimitry Andric   Relocs = NewRelocs;
3060b57cec5SDimitry Andric   assert(Ptrs.size() == Bases.size());
3070b57cec5SDimitry Andric   assert(Ptrs.size() == Relocs.size());
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric /// Extract call from statepoint, lower it and return pointer to the
3110b57cec5SDimitry Andric /// call node. Also update NodeMap so that getValue(statepoint) will
3120b57cec5SDimitry Andric /// reference lowered call result
3130b57cec5SDimitry Andric static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
3140b57cec5SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI,
3150b57cec5SDimitry Andric     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
3160b57cec5SDimitry Andric   SDValue ReturnValue, CallEndVal;
3170b57cec5SDimitry Andric   std::tie(ReturnValue, CallEndVal) =
3180b57cec5SDimitry Andric       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
3190b57cec5SDimitry Andric   SDNode *CallEnd = CallEndVal.getNode();
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   // Get a call instruction from the call sequence chain.  Tail calls are not
3220b57cec5SDimitry Andric   // allowed.  The following code is essentially reverse engineering X86's
3230b57cec5SDimitry Andric   // LowerCallTo.
3240b57cec5SDimitry Andric   //
3250b57cec5SDimitry Andric   // We are expecting DAG to have the following form:
3260b57cec5SDimitry Andric   //
3270b57cec5SDimitry Andric   // ch = eh_label (only in case of invoke statepoint)
3280b57cec5SDimitry Andric   //   ch, glue = callseq_start ch
3290b57cec5SDimitry Andric   //   ch, glue = X86::Call ch, glue
3300b57cec5SDimitry Andric   //   ch, glue = callseq_end ch, glue
3310b57cec5SDimitry Andric   //   get_return_value ch, glue
3320b57cec5SDimitry Andric   //
3330b57cec5SDimitry Andric   // get_return_value can either be a sequence of CopyFromReg instructions
3340b57cec5SDimitry Andric   // to grab the return value from the return register(s), or it can be a LOAD
3350b57cec5SDimitry Andric   // to load a value returned by reference via a stack slot.
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   bool HasDef = !SI.CLI.RetTy->isVoidTy();
3380b57cec5SDimitry Andric   if (HasDef) {
3390b57cec5SDimitry Andric     if (CallEnd->getOpcode() == ISD::LOAD)
3400b57cec5SDimitry Andric       CallEnd = CallEnd->getOperand(0).getNode();
3410b57cec5SDimitry Andric     else
3420b57cec5SDimitry Andric       while (CallEnd->getOpcode() == ISD::CopyFromReg)
3430b57cec5SDimitry Andric         CallEnd = CallEnd->getOperand(0).getNode();
3440b57cec5SDimitry Andric   }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
3470b57cec5SDimitry Andric   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
3480b57cec5SDimitry Andric }
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
3510b57cec5SDimitry Andric                                                FrameIndexSDNode &FI) {
3520b57cec5SDimitry Andric   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
3530b57cec5SDimitry Andric   auto MMOFlags = MachineMemOperand::MOStore |
3540b57cec5SDimitry Andric     MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
3550b57cec5SDimitry Andric   auto &MFI = MF.getFrameInfo();
3560b57cec5SDimitry Andric   return MF.getMachineMemOperand(PtrInfo, MMOFlags,
3570b57cec5SDimitry Andric                                  MFI.getObjectSize(FI.getIndex()),
3580b57cec5SDimitry Andric                                  MFI.getObjectAlignment(FI.getIndex()));
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric /// Spill a value incoming to the statepoint. It might be either part of
3620b57cec5SDimitry Andric /// vmstate
3630b57cec5SDimitry Andric /// or gcstate. In both cases unconditionally spill it on the stack unless it
3640b57cec5SDimitry Andric /// is a null constant. Return pair with first element being frame index
3650b57cec5SDimitry Andric /// containing saved value and second element with outgoing chain from the
3660b57cec5SDimitry Andric /// emitted store
3670b57cec5SDimitry Andric static std::tuple<SDValue, SDValue, MachineMemOperand*>
3680b57cec5SDimitry Andric spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
3690b57cec5SDimitry Andric                              SelectionDAGBuilder &Builder) {
3700b57cec5SDimitry Andric   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
3710b57cec5SDimitry Andric   MachineMemOperand* MMO = nullptr;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Emit new store if we didn't do it for this ptr before
3740b57cec5SDimitry Andric   if (!Loc.getNode()) {
3750b57cec5SDimitry Andric     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
3760b57cec5SDimitry Andric                                                        Builder);
3770b57cec5SDimitry Andric     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
3780b57cec5SDimitry Andric     // We use TargetFrameIndex so that isel will not select it into LEA
3790b57cec5SDimitry Andric     Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     // Right now we always allocate spill slots that are of the same
3820b57cec5SDimitry Andric     // size as the value we're about to spill (the size of spillee can
3830b57cec5SDimitry Andric     // vary since we spill vectors of pointers too).  At some point we
3840b57cec5SDimitry Andric     // can consider allowing spills of smaller values to larger slots
3850b57cec5SDimitry Andric     // (i.e. change the '==' in the assert below to a '>=').
3860b57cec5SDimitry Andric     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
3870b57cec5SDimitry Andric     assert((MFI.getObjectSize(Index) * 8) == Incoming.getValueSizeInBits() &&
3880b57cec5SDimitry Andric            "Bad spill:  stack slot does not match!");
3890b57cec5SDimitry Andric 
390*8bcb0991SDimitry Andric     // Note: Using the alignment of the spill slot (rather than the abi or
391*8bcb0991SDimitry Andric     // preferred alignment) is required for correctness when dealing with spill
392*8bcb0991SDimitry Andric     // slots with preferred alignments larger than frame alignment..
3930b57cec5SDimitry Andric     auto &MF = Builder.DAG.getMachineFunction();
3940b57cec5SDimitry Andric     auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
395*8bcb0991SDimitry Andric     auto *StoreMMO =
396*8bcb0991SDimitry Andric       MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
397*8bcb0991SDimitry Andric                               MFI.getObjectSize(Index),
398*8bcb0991SDimitry Andric                               MFI.getObjectAlignment(Index));
3990b57cec5SDimitry Andric     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
400*8bcb0991SDimitry Andric                                  StoreMMO);
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     Builder.StatepointLowering.setLocation(Incoming, Loc);
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   assert(Loc.getNode());
4080b57cec5SDimitry Andric   return std::make_tuple(Loc, Chain, MMO);
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric /// Lower a single value incoming to a statepoint node.  This value can be
4120b57cec5SDimitry Andric /// either a deopt value or a gc value, the handling is the same.  We special
4130b57cec5SDimitry Andric /// case constants and allocas, then fall back to spilling if required.
4140b57cec5SDimitry Andric static void lowerIncomingStatepointValue(SDValue Incoming, bool LiveInOnly,
4150b57cec5SDimitry Andric                                          SmallVectorImpl<SDValue> &Ops,
4160b57cec5SDimitry Andric                                          SmallVectorImpl<MachineMemOperand*> &MemRefs,
4170b57cec5SDimitry Andric                                          SelectionDAGBuilder &Builder) {
4180b57cec5SDimitry Andric   // Note: We know all of these spills are independent, but don't bother to
4190b57cec5SDimitry Andric   // exploit that chain wise.  DAGCombine will happily do so as needed, so
4200b57cec5SDimitry Andric   // doing it here would be a small compile time win at most.
4210b57cec5SDimitry Andric   SDValue Chain = Builder.getRoot();
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
4240b57cec5SDimitry Andric     // If the original value was a constant, make sure it gets recorded as
4250b57cec5SDimitry Andric     // such in the stackmap.  This is required so that the consumer can
4260b57cec5SDimitry Andric     // parse any internal format to the deopt state.  It also handles null
4270b57cec5SDimitry Andric     // pointers and other constant pointers in GC states.  Note the constant
4280b57cec5SDimitry Andric     // vectors do not appear to actually hit this path and that anything larger
4290b57cec5SDimitry Andric     // than an i64 value (not type!) will fail asserts here.
4300b57cec5SDimitry Andric     pushStackMapConstant(Ops, Builder, C->getSExtValue());
4310b57cec5SDimitry Andric   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
4320b57cec5SDimitry Andric     // This handles allocas as arguments to the statepoint (this is only
4330b57cec5SDimitry Andric     // really meaningful for a deopt value.  For GC, we'd be trying to
4340b57cec5SDimitry Andric     // relocate the address of the alloca itself?)
4350b57cec5SDimitry Andric     assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
4360b57cec5SDimitry Andric            "Incoming value is a frame index!");
4370b57cec5SDimitry Andric     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
4380b57cec5SDimitry Andric                                                   Builder.getFrameIndexTy()));
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     auto &MF = Builder.DAG.getMachineFunction();
4410b57cec5SDimitry Andric     auto *MMO = getMachineMemOperand(MF, *FI);
4420b57cec5SDimitry Andric     MemRefs.push_back(MMO);
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   } else if (LiveInOnly) {
4450b57cec5SDimitry Andric     // If this value is live in (not live-on-return, or live-through), we can
4460b57cec5SDimitry Andric     // treat it the same way patchpoint treats it's "live in" values.  We'll
4470b57cec5SDimitry Andric     // end up folding some of these into stack references, but they'll be
4480b57cec5SDimitry Andric     // handled by the register allocator.  Note that we do not have the notion
4490b57cec5SDimitry Andric     // of a late use so these values might be placed in registers which are
4500b57cec5SDimitry Andric     // clobbered by the call.  This is fine for live-in.
4510b57cec5SDimitry Andric     Ops.push_back(Incoming);
4520b57cec5SDimitry Andric   } else {
4530b57cec5SDimitry Andric     // Otherwise, locate a spill slot and explicitly spill it so it
4540b57cec5SDimitry Andric     // can be found by the runtime later.  We currently do not support
4550b57cec5SDimitry Andric     // tracking values through callee saved registers to their eventual
4560b57cec5SDimitry Andric     // spill location.  This would be a useful optimization, but would
4570b57cec5SDimitry Andric     // need to be optional since it requires a lot of complexity on the
4580b57cec5SDimitry Andric     // runtime side which not all would support.
4590b57cec5SDimitry Andric     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
4600b57cec5SDimitry Andric     Ops.push_back(std::get<0>(Res));
4610b57cec5SDimitry Andric     if (auto *MMO = std::get<2>(Res))
4620b57cec5SDimitry Andric       MemRefs.push_back(MMO);
4630b57cec5SDimitry Andric     Chain = std::get<1>(Res);;
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   Builder.DAG.setRoot(Chain);
4670b57cec5SDimitry Andric }
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
4700b57cec5SDimitry Andric /// lowering is described in lowerIncomingStatepointValue.  This function is
4710b57cec5SDimitry Andric /// responsible for lowering everything in the right position and playing some
4720b57cec5SDimitry Andric /// tricks to avoid redundant stack manipulation where possible.  On
4730b57cec5SDimitry Andric /// completion, 'Ops' will contain ready to use operands for machine code
4740b57cec5SDimitry Andric /// statepoint. The chain nodes will have already been created and the DAG root
4750b57cec5SDimitry Andric /// will be set to the last value spilled (if any were).
4760b57cec5SDimitry Andric static void
4770b57cec5SDimitry Andric lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
4780b57cec5SDimitry Andric                         SmallVectorImpl<MachineMemOperand*> &MemRefs,                                    SelectionDAGBuilder::StatepointLoweringInfo &SI,
4790b57cec5SDimitry Andric                         SelectionDAGBuilder &Builder) {
4800b57cec5SDimitry Andric   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
4810b57cec5SDimitry Andric   // deopt argument length, deopt arguments.., gc arguments...
4820b57cec5SDimitry Andric #ifndef NDEBUG
4830b57cec5SDimitry Andric   if (auto *GFI = Builder.GFI) {
4840b57cec5SDimitry Andric     // Check that each of the gc pointer and bases we've gotten out of the
4850b57cec5SDimitry Andric     // safepoint is something the strategy thinks might be a pointer (or vector
4860b57cec5SDimitry Andric     // of pointers) into the GC heap.  This is basically just here to help catch
4870b57cec5SDimitry Andric     // errors during statepoint insertion. TODO: This should actually be in the
4880b57cec5SDimitry Andric     // Verifier, but we can't get to the GCStrategy from there (yet).
4890b57cec5SDimitry Andric     GCStrategy &S = GFI->getStrategy();
4900b57cec5SDimitry Andric     for (const Value *V : SI.Bases) {
4910b57cec5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
4920b57cec5SDimitry Andric       if (Opt.hasValue()) {
4930b57cec5SDimitry Andric         assert(Opt.getValue() &&
4940b57cec5SDimitry Andric                "non gc managed base pointer found in statepoint");
4950b57cec5SDimitry Andric       }
4960b57cec5SDimitry Andric     }
4970b57cec5SDimitry Andric     for (const Value *V : SI.Ptrs) {
4980b57cec5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
4990b57cec5SDimitry Andric       if (Opt.hasValue()) {
5000b57cec5SDimitry Andric         assert(Opt.getValue() &&
5010b57cec5SDimitry Andric                "non gc managed derived pointer found in statepoint");
5020b57cec5SDimitry Andric       }
5030b57cec5SDimitry Andric     }
5040b57cec5SDimitry Andric     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
5050b57cec5SDimitry Andric   } else {
5060b57cec5SDimitry Andric     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
5070b57cec5SDimitry Andric     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
5080b57cec5SDimitry Andric   }
5090b57cec5SDimitry Andric #endif
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   // Figure out what lowering strategy we're going to use for each part
5120b57cec5SDimitry Andric   // Note: Is is conservatively correct to lower both "live-in" and "live-out"
5130b57cec5SDimitry Andric   // as "live-through". A "live-through" variable is one which is "live-in",
5140b57cec5SDimitry Andric   // "live-out", and live throughout the lifetime of the call (i.e. we can find
5150b57cec5SDimitry Andric   // it from any PC within the transitive callee of the statepoint).  In
5160b57cec5SDimitry Andric   // particular, if the callee spills callee preserved registers we may not
5170b57cec5SDimitry Andric   // be able to find a value placed in that register during the call.  This is
5180b57cec5SDimitry Andric   // fine for live-out, but not for live-through.  If we were willing to make
5190b57cec5SDimitry Andric   // assumptions about the code generator producing the callee, we could
5200b57cec5SDimitry Andric   // potentially allow live-through values in callee saved registers.
5210b57cec5SDimitry Andric   const bool LiveInDeopt =
5220b57cec5SDimitry Andric     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   auto isGCValue =[&](const Value *V) {
5250b57cec5SDimitry Andric     return is_contained(SI.Ptrs, V) || is_contained(SI.Bases, V);
5260b57cec5SDimitry Andric   };
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   // Before we actually start lowering (and allocating spill slots for values),
5290b57cec5SDimitry Andric   // reserve any stack slots which we judge to be profitable to reuse for a
5300b57cec5SDimitry Andric   // particular value.  This is purely an optimization over the code below and
5310b57cec5SDimitry Andric   // doesn't change semantics at all.  It is important for performance that we
5320b57cec5SDimitry Andric   // reserve slots for both deopt and gc values before lowering either.
5330b57cec5SDimitry Andric   for (const Value *V : SI.DeoptState) {
5340b57cec5SDimitry Andric     if (!LiveInDeopt || isGCValue(V))
5350b57cec5SDimitry Andric       reservePreviousStackSlotForValue(V, Builder);
5360b57cec5SDimitry Andric   }
5370b57cec5SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
5380b57cec5SDimitry Andric     reservePreviousStackSlotForValue(SI.Bases[i], Builder);
5390b57cec5SDimitry Andric     reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
5400b57cec5SDimitry Andric   }
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   // First, prefix the list with the number of unique values to be
5430b57cec5SDimitry Andric   // lowered.  Note that this is the number of *Values* not the
5440b57cec5SDimitry Andric   // number of SDValues required to lower them.
5450b57cec5SDimitry Andric   const int NumVMSArgs = SI.DeoptState.size();
5460b57cec5SDimitry Andric   pushStackMapConstant(Ops, Builder, NumVMSArgs);
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   // The vm state arguments are lowered in an opaque manner.  We do not know
5490b57cec5SDimitry Andric   // what type of values are contained within.
5500b57cec5SDimitry Andric   for (const Value *V : SI.DeoptState) {
5510b57cec5SDimitry Andric     SDValue Incoming;
5520b57cec5SDimitry Andric     // If this is a function argument at a static frame index, generate it as
5530b57cec5SDimitry Andric     // the frame index.
5540b57cec5SDimitry Andric     if (const Argument *Arg = dyn_cast<Argument>(V)) {
5550b57cec5SDimitry Andric       int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
5560b57cec5SDimitry Andric       if (FI != INT_MAX)
5570b57cec5SDimitry Andric         Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
5580b57cec5SDimitry Andric     }
5590b57cec5SDimitry Andric     if (!Incoming.getNode())
5600b57cec5SDimitry Andric       Incoming = Builder.getValue(V);
5610b57cec5SDimitry Andric     const bool LiveInValue = LiveInDeopt && !isGCValue(V);
5620b57cec5SDimitry Andric     lowerIncomingStatepointValue(Incoming, LiveInValue, Ops, MemRefs, Builder);
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
5660b57cec5SDimitry Andric   // length for this one.  After lowering, we'll have the base and pointer
5670b57cec5SDimitry Andric   // arrays interwoven with each (lowered) base pointer immediately followed by
5680b57cec5SDimitry Andric   // it's (lowered) derived pointer.  i.e
5690b57cec5SDimitry Andric   // (base[0], ptr[0], base[1], ptr[1], ...)
5700b57cec5SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
5710b57cec5SDimitry Andric     const Value *Base = SI.Bases[i];
5720b57cec5SDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Base), /*LiveInOnly*/ false,
5730b57cec5SDimitry Andric                                  Ops, MemRefs, Builder);
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric     const Value *Ptr = SI.Ptrs[i];
5760b57cec5SDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Ptr), /*LiveInOnly*/ false,
5770b57cec5SDimitry Andric                                  Ops, MemRefs, Builder);
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // If there are any explicit spill slots passed to the statepoint, record
5810b57cec5SDimitry Andric   // them, but otherwise do not do anything special.  These are user provided
5820b57cec5SDimitry Andric   // allocas and give control over placement to the consumer.  In this case,
5830b57cec5SDimitry Andric   // it is the contents of the slot which may get updated, not the pointer to
5840b57cec5SDimitry Andric   // the alloca
5850b57cec5SDimitry Andric   for (Value *V : SI.GCArgs) {
5860b57cec5SDimitry Andric     SDValue Incoming = Builder.getValue(V);
5870b57cec5SDimitry Andric     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
5880b57cec5SDimitry Andric       // This handles allocas as arguments to the statepoint
5890b57cec5SDimitry Andric       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
5900b57cec5SDimitry Andric              "Incoming value is a frame index!");
5910b57cec5SDimitry Andric       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
5920b57cec5SDimitry Andric                                                     Builder.getFrameIndexTy()));
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric       auto &MF = Builder.DAG.getMachineFunction();
5950b57cec5SDimitry Andric       auto *MMO = getMachineMemOperand(MF, *FI);
5960b57cec5SDimitry Andric       MemRefs.push_back(MMO);
5970b57cec5SDimitry Andric     }
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   // Record computed locations for all lowered values.
6010b57cec5SDimitry Andric   // This can not be embedded in lowering loops as we need to record *all*
6020b57cec5SDimitry Andric   // values, while previous loops account only values with unique SDValues.
6030b57cec5SDimitry Andric   const Instruction *StatepointInstr = SI.StatepointInstr;
6040b57cec5SDimitry Andric   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
6070b57cec5SDimitry Andric     const Value *V = Relocate->getDerivedPtr();
6080b57cec5SDimitry Andric     SDValue SDV = Builder.getValue(V);
6090b57cec5SDimitry Andric     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric     if (Loc.getNode()) {
6120b57cec5SDimitry Andric       SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
6130b57cec5SDimitry Andric     } else {
6140b57cec5SDimitry Andric       // Record value as visited, but not spilled. This is case for allocas
6150b57cec5SDimitry Andric       // and constants. For this values we can avoid emitting spill load while
6160b57cec5SDimitry Andric       // visiting corresponding gc_relocate.
6170b57cec5SDimitry Andric       // Actually we do not need to record them in this map at all.
6180b57cec5SDimitry Andric       // We do this only to check that we are not relocating any unvisited
6190b57cec5SDimitry Andric       // value.
6200b57cec5SDimitry Andric       SpillMap.SlotMap[V] = None;
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric       // Default llvm mechanisms for exporting values which are used in
6230b57cec5SDimitry Andric       // different basic blocks does not work for gc relocates.
6240b57cec5SDimitry Andric       // Note that it would be incorrect to teach llvm that all relocates are
6250b57cec5SDimitry Andric       // uses of the corresponding values so that it would automatically
6260b57cec5SDimitry Andric       // export them. Relocates of the spilled values does not use original
6270b57cec5SDimitry Andric       // value.
6280b57cec5SDimitry Andric       if (Relocate->getParent() != StatepointInstr->getParent())
6290b57cec5SDimitry Andric         Builder.ExportFromCurrentBlock(V);
6300b57cec5SDimitry Andric     }
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
6350b57cec5SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
6360b57cec5SDimitry Andric   // The basic scheme here is that information about both the original call and
6370b57cec5SDimitry Andric   // the safepoint is encoded in the CallInst.  We create a temporary call and
6380b57cec5SDimitry Andric   // lower it, then reverse engineer the calling sequence.
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   NumOfStatepoints++;
6410b57cec5SDimitry Andric   // Clear state
6420b57cec5SDimitry Andric   StatepointLowering.startNewStatepoint(*this);
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric #ifndef NDEBUG
6450b57cec5SDimitry Andric   // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
6460b57cec5SDimitry Andric   // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
6470b57cec5SDimitry Andric   for (auto *Reloc : SI.GCRelocates)
6480b57cec5SDimitry Andric     if (Reloc->getParent() == SI.StatepointInstr->getParent())
6490b57cec5SDimitry Andric       StatepointLowering.scheduleRelocCall(*Reloc);
6500b57cec5SDimitry Andric #endif
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   // Remove any redundant llvm::Values which map to the same SDValue as another
6530b57cec5SDimitry Andric   // input.  Also has the effect of removing duplicates in the original
6540b57cec5SDimitry Andric   // llvm::Value input list as well.  This is a useful optimization for
6550b57cec5SDimitry Andric   // reducing the size of the StackMap section.  It has no other impact.
6560b57cec5SDimitry Andric   removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
6570b57cec5SDimitry Andric                         FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
6580b57cec5SDimitry Andric   assert(SI.Bases.size() == SI.Ptrs.size() &&
6590b57cec5SDimitry Andric          SI.Ptrs.size() == SI.GCRelocates.size());
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // Lower statepoint vmstate and gcstate arguments
6620b57cec5SDimitry Andric   SmallVector<SDValue, 10> LoweredMetaArgs;
6630b57cec5SDimitry Andric   SmallVector<MachineMemOperand*, 16> MemRefs;
6640b57cec5SDimitry Andric   lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, SI, *this);
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   // Now that we've emitted the spills, we need to update the root so that the
6670b57cec5SDimitry Andric   // call sequence is ordered correctly.
6680b57cec5SDimitry Andric   SI.CLI.setChain(getRoot());
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   // Get call node, we will replace it later with statepoint
6710b57cec5SDimitry Andric   SDValue ReturnVal;
6720b57cec5SDimitry Andric   SDNode *CallNode;
6730b57cec5SDimitry Andric   std::tie(ReturnVal, CallNode) =
6740b57cec5SDimitry Andric       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
6770b57cec5SDimitry Andric   // nodes with all the appropriate arguments and return values.
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6800b57cec5SDimitry Andric   SDValue Chain = CallNode->getOperand(0);
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   SDValue Glue;
6830b57cec5SDimitry Andric   bool CallHasIncomingGlue = CallNode->getGluedNode();
6840b57cec5SDimitry Andric   if (CallHasIncomingGlue) {
6850b57cec5SDimitry Andric     // Glue is always last operand
6860b57cec5SDimitry Andric     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
6870b57cec5SDimitry Andric   }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   // Build the GC_TRANSITION_START node if necessary.
6900b57cec5SDimitry Andric   //
6910b57cec5SDimitry Andric   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
6920b57cec5SDimitry Andric   // order in which they appear in the call to the statepoint intrinsic. If
6930b57cec5SDimitry Andric   // any of the operands is a pointer-typed, that operand is immediately
6940b57cec5SDimitry Andric   // followed by a SRCVALUE for the pointer that may be used during lowering
6950b57cec5SDimitry Andric   // (e.g. to form MachinePointerInfo values for loads/stores).
6960b57cec5SDimitry Andric   const bool IsGCTransition =
6970b57cec5SDimitry Andric       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
6980b57cec5SDimitry Andric       (uint64_t)StatepointFlags::GCTransition;
6990b57cec5SDimitry Andric   if (IsGCTransition) {
7000b57cec5SDimitry Andric     SmallVector<SDValue, 8> TSOps;
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     // Add chain
7030b57cec5SDimitry Andric     TSOps.push_back(Chain);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric     // Add GC transition arguments
7060b57cec5SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
7070b57cec5SDimitry Andric       TSOps.push_back(getValue(V));
7080b57cec5SDimitry Andric       if (V->getType()->isPointerTy())
7090b57cec5SDimitry Andric         TSOps.push_back(DAG.getSrcValue(V));
7100b57cec5SDimitry Andric     }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric     // Add glue if necessary
7130b57cec5SDimitry Andric     if (CallHasIncomingGlue)
7140b57cec5SDimitry Andric       TSOps.push_back(Glue);
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric     SDValue GCTransitionStart =
7190b57cec5SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric     Chain = GCTransitionStart.getValue(0);
7220b57cec5SDimitry Andric     Glue = GCTransitionStart.getValue(1);
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   // TODO: Currently, all of these operands are being marked as read/write in
7260b57cec5SDimitry Andric   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
7270b57cec5SDimitry Andric   // and flags to be read-only.
7280b57cec5SDimitry Andric   SmallVector<SDValue, 40> Ops;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   // Add the <id> and <numBytes> constants.
7310b57cec5SDimitry Andric   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
7320b57cec5SDimitry Andric   Ops.push_back(
7330b57cec5SDimitry Andric       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   // Calculate and push starting position of vmstate arguments
7360b57cec5SDimitry Andric   // Get number of arguments incoming directly into call node
7370b57cec5SDimitry Andric   unsigned NumCallRegArgs =
7380b57cec5SDimitry Andric       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
7390b57cec5SDimitry Andric   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   // Add call target
7420b57cec5SDimitry Andric   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
7430b57cec5SDimitry Andric   Ops.push_back(CallTarget);
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   // Add call arguments
7460b57cec5SDimitry Andric   // Get position of register mask in the call
7470b57cec5SDimitry Andric   SDNode::op_iterator RegMaskIt;
7480b57cec5SDimitry Andric   if (CallHasIncomingGlue)
7490b57cec5SDimitry Andric     RegMaskIt = CallNode->op_end() - 2;
7500b57cec5SDimitry Andric   else
7510b57cec5SDimitry Andric     RegMaskIt = CallNode->op_end() - 1;
7520b57cec5SDimitry Andric   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric   // Add a constant argument for the calling convention
7550b57cec5SDimitry Andric   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   // Add a constant argument for the flags
7580b57cec5SDimitry Andric   uint64_t Flags = SI.StatepointFlags;
7590b57cec5SDimitry Andric   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
7600b57cec5SDimitry Andric          "Unknown flag used");
7610b57cec5SDimitry Andric   pushStackMapConstant(Ops, *this, Flags);
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   // Insert all vmstate and gcstate arguments
7640b57cec5SDimitry Andric   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   // Add register mask from call node
7670b57cec5SDimitry Andric   Ops.push_back(*RegMaskIt);
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   // Add chain
7700b57cec5SDimitry Andric   Ops.push_back(Chain);
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   // Same for the glue, but we add it only if original call had it
7730b57cec5SDimitry Andric   if (Glue.getNode())
7740b57cec5SDimitry Andric     Ops.push_back(Glue);
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   // Compute return values.  Provide a glue output since we consume one as
7770b57cec5SDimitry Andric   // input.  This allows someone else to chain off us as needed.
7780b57cec5SDimitry Andric   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   MachineSDNode *StatepointMCNode =
7810b57cec5SDimitry Andric     DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
7820b57cec5SDimitry Andric   DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   SDNode *SinkNode = StatepointMCNode;
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   // Build the GC_TRANSITION_END node if necessary.
7870b57cec5SDimitry Andric   //
7880b57cec5SDimitry Andric   // See the comment above regarding GC_TRANSITION_START for the layout of
7890b57cec5SDimitry Andric   // the operands to the GC_TRANSITION_END node.
7900b57cec5SDimitry Andric   if (IsGCTransition) {
7910b57cec5SDimitry Andric     SmallVector<SDValue, 8> TEOps;
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric     // Add chain
7940b57cec5SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 0));
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric     // Add GC transition arguments
7970b57cec5SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
7980b57cec5SDimitry Andric       TEOps.push_back(getValue(V));
7990b57cec5SDimitry Andric       if (V->getType()->isPointerTy())
8000b57cec5SDimitry Andric         TEOps.push_back(DAG.getSrcValue(V));
8010b57cec5SDimitry Andric     }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     // Add glue
8040b57cec5SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 1));
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric     SDValue GCTransitionStart =
8090b57cec5SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric     SinkNode = GCTransitionStart.getNode();
8120b57cec5SDimitry Andric   }
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   // Replace original call
8150b57cec5SDimitry Andric   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
8160b57cec5SDimitry Andric   // Remove original call node
8170b57cec5SDimitry Andric   DAG.DeleteNode(CallNode);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // DON'T set the root - under the assumption that it's already set past the
8200b57cec5SDimitry Andric   // inserted node we created.
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   // TODO: A better future implementation would be to emit a single variable
8230b57cec5SDimitry Andric   // argument, variable return value STATEPOINT node here and then hookup the
8240b57cec5SDimitry Andric   // return value of each gc.relocate to the respective output of the
8250b57cec5SDimitry Andric   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
8260b57cec5SDimitry Andric   // to actually be possible today.
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   return ReturnVal;
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric void
8320b57cec5SDimitry Andric SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
8330b57cec5SDimitry Andric                                      const BasicBlock *EHPadBB /*= nullptr*/) {
8340b57cec5SDimitry Andric   assert(ISP.getCall()->getCallingConv() != CallingConv::AnyReg &&
8350b57cec5SDimitry Andric          "anyregcc is not supported on statepoints!");
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric #ifndef NDEBUG
8380b57cec5SDimitry Andric   // If this is a malformed statepoint, report it early to simplify debugging.
8390b57cec5SDimitry Andric   // This should catch any IR level mistake that's made when constructing or
8400b57cec5SDimitry Andric   // transforming statepoints.
8410b57cec5SDimitry Andric   ISP.verify();
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric   // Check that the associated GCStrategy expects to encounter statepoints.
8440b57cec5SDimitry Andric   assert(GFI->getStrategy().useStatepoints() &&
8450b57cec5SDimitry Andric          "GCStrategy does not expect to encounter statepoints");
8460b57cec5SDimitry Andric #endif
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   SDValue ActualCallee;
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   if (ISP.getNumPatchBytes() > 0) {
8510b57cec5SDimitry Andric     // If we've been asked to emit a nop sequence instead of a call instruction
8520b57cec5SDimitry Andric     // for this statepoint then don't lower the call target, but use a constant
8530b57cec5SDimitry Andric     // `null` instead.  Not lowering the call target lets statepoint clients get
8540b57cec5SDimitry Andric     // away without providing a physical address for the symbolic call target at
8550b57cec5SDimitry Andric     // link time.
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric     const auto &TLI = DAG.getTargetLoweringInfo();
8580b57cec5SDimitry Andric     const auto &DL = DAG.getDataLayout();
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
8610b57cec5SDimitry Andric     ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
8620b57cec5SDimitry Andric   } else {
8630b57cec5SDimitry Andric     ActualCallee = getValue(ISP.getCalledValue());
8640b57cec5SDimitry Andric   }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   StatepointLoweringInfo SI(DAG);
8670b57cec5SDimitry Andric   populateCallLoweringInfo(SI.CLI, ISP.getCall(),
8680b57cec5SDimitry Andric                            ImmutableStatepoint::CallArgsBeginPos,
8690b57cec5SDimitry Andric                            ISP.getNumCallArgs(), ActualCallee,
8700b57cec5SDimitry Andric                            ISP.getActualReturnType(), false /* IsPatchPoint */);
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
8730b57cec5SDimitry Andric     SI.GCRelocates.push_back(Relocate);
8740b57cec5SDimitry Andric     SI.Bases.push_back(Relocate->getBasePtr());
8750b57cec5SDimitry Andric     SI.Ptrs.push_back(Relocate->getDerivedPtr());
8760b57cec5SDimitry Andric   }
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
8790b57cec5SDimitry Andric   SI.StatepointInstr = ISP.getInstruction();
8800b57cec5SDimitry Andric   SI.GCTransitionArgs =
8810b57cec5SDimitry Andric       ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
8820b57cec5SDimitry Andric   SI.ID = ISP.getID();
8830b57cec5SDimitry Andric   SI.DeoptState = ArrayRef<const Use>(ISP.deopt_begin(), ISP.deopt_end());
8840b57cec5SDimitry Andric   SI.StatepointFlags = ISP.getFlags();
8850b57cec5SDimitry Andric   SI.NumPatchBytes = ISP.getNumPatchBytes();
8860b57cec5SDimitry Andric   SI.EHPadBB = EHPadBB;
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   // Export the result value if needed
8910b57cec5SDimitry Andric   const GCResultInst *GCResult = ISP.getGCResult();
8920b57cec5SDimitry Andric   Type *RetTy = ISP.getActualReturnType();
8930b57cec5SDimitry Andric   if (!RetTy->isVoidTy() && GCResult) {
8940b57cec5SDimitry Andric     if (GCResult->getParent() != ISP.getCall()->getParent()) {
8950b57cec5SDimitry Andric       // Result value will be used in a different basic block so we need to
8960b57cec5SDimitry Andric       // export it now.  Default exporting mechanism will not work here because
8970b57cec5SDimitry Andric       // statepoint call has a different type than the actual call. It means
8980b57cec5SDimitry Andric       // that by default llvm will create export register of the wrong type
8990b57cec5SDimitry Andric       // (always i32 in our case). So instead we need to create export register
9000b57cec5SDimitry Andric       // with correct type manually.
9010b57cec5SDimitry Andric       // TODO: To eliminate this problem we can remove gc.result intrinsics
9020b57cec5SDimitry Andric       //       completely and make statepoint call to return a tuple.
9030b57cec5SDimitry Andric       unsigned Reg = FuncInfo.CreateRegs(RetTy);
9040b57cec5SDimitry Andric       RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
9050b57cec5SDimitry Andric                        DAG.getDataLayout(), Reg, RetTy,
9060b57cec5SDimitry Andric                        ISP.getCall()->getCallingConv());
9070b57cec5SDimitry Andric       SDValue Chain = DAG.getEntryNode();
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric       RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
9100b57cec5SDimitry Andric       PendingExports.push_back(Chain);
9110b57cec5SDimitry Andric       FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
9120b57cec5SDimitry Andric     } else {
9130b57cec5SDimitry Andric       // Result value will be used in a same basic block. Don't export it or
9140b57cec5SDimitry Andric       // perform any explicit register copies.
9150b57cec5SDimitry Andric       // We'll replace the actuall call node shortly. gc_result will grab
9160b57cec5SDimitry Andric       // this value.
9170b57cec5SDimitry Andric       setValue(ISP.getInstruction(), ReturnValue);
9180b57cec5SDimitry Andric     }
9190b57cec5SDimitry Andric   } else {
9200b57cec5SDimitry Andric     // The token value is never used from here on, just generate a poison value
9210b57cec5SDimitry Andric     setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
9220b57cec5SDimitry Andric   }
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
9260b57cec5SDimitry Andric     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
9270b57cec5SDimitry Andric     bool VarArgDisallowed, bool ForceVoidReturnTy) {
9280b57cec5SDimitry Andric   StatepointLoweringInfo SI(DAG);
9290b57cec5SDimitry Andric   unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
9300b57cec5SDimitry Andric   populateCallLoweringInfo(
9310b57cec5SDimitry Andric       SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
9320b57cec5SDimitry Andric       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
9330b57cec5SDimitry Andric       false);
9340b57cec5SDimitry Andric   if (!VarArgDisallowed)
9350b57cec5SDimitry Andric     SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
9420b57cec5SDimitry Andric   SI.ID = SD.StatepointID.getValueOr(DefaultID);
9430b57cec5SDimitry Andric   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   SI.DeoptState =
9460b57cec5SDimitry Andric       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
9470b57cec5SDimitry Andric   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
9480b57cec5SDimitry Andric   SI.EHPadBB = EHPadBB;
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // NB! The GC arguments are deliberately left empty.
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
9530b57cec5SDimitry Andric     ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
9540b57cec5SDimitry Andric     setValue(Call, ReturnVal);
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
9590b57cec5SDimitry Andric     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
9600b57cec5SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
9610b57cec5SDimitry Andric                                    /* VarArgDisallowed = */ false,
9620b57cec5SDimitry Andric                                    /* ForceVoidReturnTy  = */ false);
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
9660b57cec5SDimitry Andric   // The result value of the gc_result is simply the result of the actual
9670b57cec5SDimitry Andric   // call.  We've already emitted this, so just grab the value.
9680b57cec5SDimitry Andric   const Instruction *I = CI.getStatepoint();
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   if (I->getParent() != CI.getParent()) {
9710b57cec5SDimitry Andric     // Statepoint is in different basic block so we should have stored call
9720b57cec5SDimitry Andric     // result in a virtual register.
9730b57cec5SDimitry Andric     // We can not use default getValue() functionality to copy value from this
9740b57cec5SDimitry Andric     // register because statepoint and actual call return types can be
9750b57cec5SDimitry Andric     // different, and getValue() will use CopyFromReg of the wrong type,
9760b57cec5SDimitry Andric     // which is always i32 in our case.
9770b57cec5SDimitry Andric     PointerType *CalleeType = cast<PointerType>(
9780b57cec5SDimitry Andric         ImmutableStatepoint(I).getCalledValue()->getType());
9790b57cec5SDimitry Andric     Type *RetTy =
9800b57cec5SDimitry Andric         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
9810b57cec5SDimitry Andric     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     assert(CopyFromReg.getNode());
9840b57cec5SDimitry Andric     setValue(&CI, CopyFromReg);
9850b57cec5SDimitry Andric   } else {
9860b57cec5SDimitry Andric     setValue(&CI, getValue(I));
9870b57cec5SDimitry Andric   }
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
9910b57cec5SDimitry Andric #ifndef NDEBUG
9920b57cec5SDimitry Andric   // Consistency check
9930b57cec5SDimitry Andric   // We skip this check for relocates not in the same basic block as their
9940b57cec5SDimitry Andric   // statepoint. It would be too expensive to preserve validation info through
9950b57cec5SDimitry Andric   // different basic blocks.
9960b57cec5SDimitry Andric   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
9970b57cec5SDimitry Andric     StatepointLowering.relocCallVisited(Relocate);
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   auto *Ty = Relocate.getType()->getScalarType();
10000b57cec5SDimitry Andric   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
10010b57cec5SDimitry Andric     assert(*IsManaged && "Non gc managed pointer relocated!");
10020b57cec5SDimitry Andric #endif
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   const Value *DerivedPtr = Relocate.getDerivedPtr();
10050b57cec5SDimitry Andric   SDValue SD = getValue(DerivedPtr);
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
10080b57cec5SDimitry Andric   auto SlotIt = SpillMap.find(DerivedPtr);
10090b57cec5SDimitry Andric   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
10100b57cec5SDimitry Andric   Optional<int> DerivedPtrLocation = SlotIt->second;
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   // We didn't need to spill these special cases (constants and allocas).
10130b57cec5SDimitry Andric   // See the handling in spillIncomingValueForStatepoint for detail.
10140b57cec5SDimitry Andric   if (!DerivedPtrLocation) {
10150b57cec5SDimitry Andric     setValue(&Relocate, SD);
10160b57cec5SDimitry Andric     return;
10170b57cec5SDimitry Andric   }
10180b57cec5SDimitry Andric 
1019*8bcb0991SDimitry Andric   unsigned Index = *DerivedPtrLocation;
1020*8bcb0991SDimitry Andric   SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   // Note: We know all of these reloads are independent, but don't bother to
10230b57cec5SDimitry Andric   // exploit that chain wise.  DAGCombine will happily do so as needed, so
10240b57cec5SDimitry Andric   // doing it here would be a small compile time win at most.
10250b57cec5SDimitry Andric   SDValue Chain = getRoot();
10260b57cec5SDimitry Andric 
1027*8bcb0991SDimitry Andric   auto &MF = DAG.getMachineFunction();
1028*8bcb0991SDimitry Andric   auto &MFI = MF.getFrameInfo();
1029*8bcb0991SDimitry Andric   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1030*8bcb0991SDimitry Andric   auto *LoadMMO =
1031*8bcb0991SDimitry Andric     MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1032*8bcb0991SDimitry Andric                             MFI.getObjectSize(Index),
1033*8bcb0991SDimitry Andric                             MFI.getObjectAlignment(Index));
1034*8bcb0991SDimitry Andric 
1035*8bcb0991SDimitry Andric   auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1036*8bcb0991SDimitry Andric                                                          Relocate.getType());
1037*8bcb0991SDimitry Andric 
1038*8bcb0991SDimitry Andric   SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1039*8bcb0991SDimitry Andric                                   SpillSlot, LoadMMO);
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   DAG.setRoot(SpillLoad.getValue(1));
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   assert(SpillLoad.getNode());
10440b57cec5SDimitry Andric   setValue(&Relocate, SpillLoad);
10450b57cec5SDimitry Andric }
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
10480b57cec5SDimitry Andric   const auto &TLI = DAG.getTargetLoweringInfo();
10490b57cec5SDimitry Andric   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
10500b57cec5SDimitry Andric                                          TLI.getPointerTy(DAG.getDataLayout()));
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
10530b57cec5SDimitry Andric   // call.  We also do not lower the return value to any virtual register, and
10540b57cec5SDimitry Andric   // change the immediately following return to a trap instruction.
10550b57cec5SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
10560b57cec5SDimitry Andric                                    /* VarArgDisallowed = */ true,
10570b57cec5SDimitry Andric                                    /* ForceVoidReturnTy = */ true);
10580b57cec5SDimitry Andric }
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizingReturn() {
10610b57cec5SDimitry Andric   // We do not lower the return value from llvm.deoptimize to any virtual
10620b57cec5SDimitry Andric   // register, and change the immediately following return to a trap
10630b57cec5SDimitry Andric   // instruction.
10640b57cec5SDimitry Andric   if (DAG.getTarget().Options.TrapUnreachable)
10650b57cec5SDimitry Andric     DAG.setRoot(
10660b57cec5SDimitry Andric         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
10670b57cec5SDimitry Andric }
1068