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