LLVM 24.0.0git
StatepointLowering.cpp
Go to the documentation of this file.
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"
20#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
35#include "llvm/IR/CallingConv.h"
37#include "llvm/IR/GCStrategy.h"
38#include "llvm/IR/Instruction.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Statepoint.h"
42#include "llvm/IR/Type.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
65 "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
66 cl::desc("Allow using registers for non pointer deopt args"));
67
69 "use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false),
70 cl::desc("Allow using registers for gc pointer in landing pad"));
71
73 "max-registers-for-gc-values", cl::Hidden, cl::init(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
81
84 SDLoc L = Builder.getCurSDLoc();
85 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
86 MVT::i64));
87 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
88}
89
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(Builder.FuncInfo.StatepointStackSlots.size());
101}
102
104 Locations.clear();
105 AllocatedStackSlots.clear();
106 assert(PendingGCRelocateCalls.empty() &&
107 "cleared before statepoint sequence completed");
108}
109
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(NextSlotToAllocate)) {
134 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
135 if (MFI.getObjectSize(FI) == SpillSize) {
136 AllocatedStackSlots.set(NextSlotToAllocate);
137 // TODO: Is ValueType the right thing to use here?
138 return Builder.DAG.getFrameIndex(FI, ValueType);
139 }
140 }
141 }
142
143 // Couldn't find a free slot, so create a new one:
144
145 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
146 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
148
149 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
150 AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
151 assert(AllocatedStackSlots.size() ==
152 Builder.FuncInfo.StatepointStackSlots.size() &&
153 "Broken invariant");
154
155 StatepointMaxSlotsRequired.updateMax(
156 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>(Statepoint))
177 return std::nullopt;
178
179 const auto &RelocationMap = Builder.FuncInfo.StatepointRelocationMaps
180 [cast<GCStatepointInst>(Statepoint)];
181
182 auto It = RelocationMap.find(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(Cast->getOperand(0), Builder, 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(IncomingValue, Builder, 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>(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(Incoming) || Incoming.isUndef();
265}
266
268 assert(willLowerDirectly(V) && "not a directly-lowered leaf");
269 if (V.isUndef()) {
270 Kind = Undef;
271 } else if (auto *FI = dyn_cast<FrameIndexSDNode>(V)) {
273 FrameIndexValue = FI->getIndex();
274 } else {
275 Kind = Constant;
276 IntValue = cast<ConstantSDNode>(V)->getAPIntValue();
277 }
278}
279
281 SelectionDAG &DAG, const SDLoc &DL, EVT VT) const {
282 switch (Kind) {
283 case FrameIndex:
284 return DAG.getFrameIndex(FrameIndexValue, VT);
285 case Constant:
286 return DAG.getConstant(IntValue, DL, VT);
287 case Undef:
288 return DAG.getConstant(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(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(Incoming);
308 if (OldLocation.getNode())
309 // Duplicates in input
310 return;
311
312 const int LookUpDepth = 6;
313 std::optional<int> Index =
314 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
315 if (!Index)
316 return;
317
318 const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
319
320 auto SlotIt = find(StatepointSlots, *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(StatepointSlots.begin(), 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(*Index, Builder.getFrameIndexTy());
342 Builder.StatepointLowering.setLocation(Incoming, 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(
350 SelectionDAGBuilder &Builder) {
351 SDValue ReturnValue, CallEndVal;
352 std::tie(ReturnValue, CallEndVal) =
353 Builder.lowerInvokable(SI.CLI, 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(0).getNode();
374
375 bool HasDef = !SI.CLI.RetTy->isVoidTy();
376 if (HasDef) {
377 if (CallEnd->getOpcode() == ISD::LOAD)
378 CallEnd = CallEnd->getOperand(0).getNode();
379 else
380 while (CallEnd->getOpcode() == ISD::CopyFromReg)
381 CallEnd = CallEnd->getOperand(0).getNode();
382 }
383
384 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
385 return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
386}
387
389 FrameIndexSDNode &FI) {
390 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
391 auto MMOFlags = MachineMemOperand::MOStore |
393 auto &MFI = MF.getFrameInfo();
394 return MF.getMachineMemOperand(PtrInfo, MMOFlags,
395 MFI.getObjectSize(FI.getIndex()),
396 MFI.getObjectAlign(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*>
407 SelectionDAGBuilder &Builder) {
408 SDValue Loc = Builder.StatepointLowering.getLocation(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(Incoming.getValueType(),
414 Builder);
415 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
416 // We use TargetFrameIndex so that isel will not select it into LEA
417 Loc = Builder.DAG.getTargetFrameIndex(Index, 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, Index);
435 auto *StoreMMO = MF.getMachineMemOperand(
436 PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
437 MFI.getObjectAlign(Index));
438 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
439 StoreMMO);
440
442
443 Builder.StatepointLowering.setLocation(Incoming, Loc);
444 }
445
446 assert(Loc.getNode());
447 return std::make_tuple(Loc, Chain, 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,
457 SelectionDAGBuilder &Builder) {
458
459 if (willLowerDirectly(Incoming)) {
460 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(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(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
467 Builder.getFrameIndexTy()));
468
469 auto &MF = Builder.DAG.getMachineFunction();
470 auto *MMO = getMachineMemOperand(MF, *FI);
471 MemRefs.push_back(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, 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>(Incoming)) {
491 pushStackMapConstant(Ops, Builder, C->getSExtValue());
492 return;
493 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
494 pushStackMapConstant(Ops, Builder,
495 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(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(std::get<0>(Res));
522 if (auto *MMO = std::get<2>(Res))
523 MemRefs.push_back(MMO);
524 Chain = std::get<1>(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
553 DenseMap<SDValue, int> &LowerAsVReg,
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;
579 if (const auto *StInvoke =
580 dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
581 LandingPadInst *LPI = StInvoke->getLandingPadInst();
582 for (const auto *Relocate : SI.GCRelocates)
583 if (Relocate->getOperand(0) == LPI) {
584 LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
585 LPadPointers.insert(Builder.getValue(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(SD))
602 return false;
603 return !willLowerDirectly(SD);
604 };
605
606 auto processGCPtr = [&](const Value *V) {
607 SDValue PtrSD = Builder.getValue(V);
608 if (!LoweredGCPtrs.insert(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 Builder.getValue(V).getValueType()))
636 return true;
637 if (isGCValue(V, Builder))
638 return !LowerAsVReg.count(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))
650 }
651
652 for (const Value *V : SI.Ptrs) {
653 SDValue SDV = Builder.getValue(V);
654 if (!LowerAsVReg.count(SDV))
656 }
657
658 for (const Value *V : SI.Bases) {
659 SDValue SDV = Builder.getValue(V);
660 if (!LowerAsVReg.count(SDV))
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, 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>(V)) {
678 int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
679 if (FI != INT_MAX)
680 Incoming = Builder.DAG.getFrameIndex(FI, 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(V), Ops, MemRefs,
687 Builder);
688 }
689
690 // Finally, go ahead and lower all the gc arguments.
691 pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
692 for (SDValue SDV : LoweredGCPtrs)
693 lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(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
705 for (Value *V : SI.GCLives) {
706 SDValue Incoming = Builder.getValue(V);
707 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(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(Builder.DAG.getTargetFrameIndex(
712 FI->getIndex(), Builder.getFrameIndexTy()));
713
714 auto &MF = Builder.DAG.getMachineFunction();
715 auto *MMO = getMachineMemOperand(MF, *FI);
716 MemRefs.push_back(MMO);
717 }
718 }
719 pushStackMapConstant(Ops, Builder, Allocas.size());
720 Ops.append(Allocas.begin(), Allocas.end());
721
722 // Now construct GC base/derived map;
723 pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
724 SDLoc L = Builder.getCurSDLoc();
725 for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
726 SDValue Base = Builder.getValue(SI.Bases[i]);
727 assert(GCPtrIndexMap.count(Base) && "base not found in index map");
728 Ops.push_back(
729 Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
730 SDValue Derived = Builder.getValue(SI.Ptrs[i]);
731 assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
732 Ops.push_back(
733 Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
734 }
735}
736
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(*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;
765 // Maps derived pointer SDValue to statepoint result of relocated pointer.
766 DenseMap<SDValue, int> LowerAsVReg;
767 lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
768 SI, *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(ReturnVal, CallNode) = lowerCallFromStatepointLoweringInfo(SI, *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(0);
784
785 SDValue Glue;
786 bool CallHasIncomingGlue = CallNode->getGluedNode();
787 if (CallHasIncomingGlue) {
788 // Glue is always last operand
789 Glue = CallNode->getOperand(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) ==
802 if (IsGCTransition) {
804
805 // Add chain
806 TSOps.push_back(Chain);
807
808 // Add GC transition arguments
809 for (const Value *V : SI.GCTransitionArgs) {
810 TSOps.push_back(getValue(V));
811 if (V->getType()->isPointerTy())
812 TSOps.push_back(DAG.getSrcValue(V));
813 }
814
815 // Add glue if necessary
816 if (CallHasIncomingGlue)
817 TSOps.push_back(Glue);
818
819 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
820
821 SDValue GCTransitionStart =
822 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
823
824 Chain = GCTransitionStart.getValue(0);
825 Glue = GCTransitionStart.getValue(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.
832
833 // Add the <id> and <numBytes> constants.
834 Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
835 Ops.push_back(
836 DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), 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(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
843
844 // Add call target
845 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
846 Ops.push_back(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(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
856
857 // Add a constant argument for the calling convention
858 pushStackMapConstant(Ops, *this, 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, *this, Flags);
865
866 // Insert all vmstate and gcstate arguments
867 llvm::append_range(Ops, LoweredMetaArgs);
868
869 // Add register mask from call node
870 Ops.push_back(*RegMaskIt);
871
872 // Add chain
873 Ops.push_back(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(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(SD))
884 continue;
885 NodeTys.push_back(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(MVT::Other);
890 NodeTys.push_back(MVT::Glue);
891
892 unsigned NumResults = NodeTys.size();
893 MachineSDNode *StatepointMCNode =
894 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
895 DAG.setNodeMemRefs(StatepointMCNode, 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.
901 for (const auto *Relocate : SI.GCRelocates) {
902 Value *Derived = Relocate->getDerivedPtr();
903 SDValue SD = getValue(Derived);
904 auto It = LowerAsVReg.find(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(SD);
914 if (Res)
915 assert(Res == Relocated);
916 else
917 StatepointLowering.setLocation(SD, Relocated);
918 continue;
919 }
920
921 // Handle multiple gc.relocates of the same input efficiently.
922 auto [VRegIt, Inserted] = VirtRegs.try_emplace(SD);
923 if (!Inserted)
924 continue;
925
926 auto *RetTy = Relocate->getType();
927 Register Reg = FuncInfo.CreateRegs(RetTy);
928 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
929 DAG.getDataLayout(), Reg, RetTy, std::nullopt);
930 SDValue Chain = DAG.getRoot();
931 RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
932 PendingExports.push_back(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(SDV);
945
946 bool IsLocal = (Relocate->getParent() == StatepointInstr->getParent());
947
949 if (LowerAsVReg.count(SDV)) {
950 if (IsLocal) {
951 // Result is already stored in StatepointLowering
953 } else {
955 auto It = VirtRegs.find(SDV);
956 assert(It != VirtRegs.end());
957 Record.payload.Reg = It->second;
958 }
959 } else if (Loc.getNode()) {
961 Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
962 } else {
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(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) {
984
985 // Add chain
986 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
987
988 // Add GC transition arguments
989 for (const Value *V : SI.GCTransitionArgs) {
990 TEOps.push_back(getValue(V));
991 if (V->getType()->isPointerTy())
992 TEOps.push_back(DAG.getSrcValue(V));
993 }
994
995 // Add glue
996 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
997
998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
999
1000 SDValue GCTransitionStart =
1001 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, 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(CallNode, StatepointValues);
1013 // Remove original call node
1014 DAG.DeleteNode(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*>
1034 std::pair<const GCResultInst *, const GCResultInst*> Res(nullptr, nullptr);
1035 for (const auto *U : S.users()) {
1036 auto *GRI = dyn_cast<GCResultInst>(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
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(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(Callee.getValueType());
1069 } else {
1070 ActualCallee = Callee;
1071 }
1072
1073 const auto GCResultLocality = getGCResultLocality(I);
1074 AttributeSet retAttrs;
1075 if (GCResultLocality.first)
1076 retAttrs = GCResultLocality.first->getAttributes().getRetAttrs();
1077
1080 I.getNumCallArgs(), ActualCallee,
1081 I.getActualReturnType(), 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.
1098 for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
1099 SI.GCRelocates.push_back(Relocate);
1100
1101 SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1102 if (Seen.insert(DerivedSD).second) {
1103 SI.Bases.push_back(Relocate->getBasePtr());
1104 SI.Ptrs.push_back(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, *this))
1116 continue;
1117 if (Seen.insert(getValue(V)).second) {
1118 SI.Bases.push_back(V);
1119 SI.Ptrs.push_back(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(&I, DAG.getIntPtrConstant(-1, 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(&I, 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(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(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1170 PendingExports.push_back(Chain);
1171 FuncInfo.ValueMap[&I] = Reg;
1172}
1173
1175 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1176 bool VarArgDisallowed, bool ForceVoidReturnTy) {
1178 SI.CLI.CB = Call;
1179
1180 unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1182 SI.CLI, Call, ArgBeginIndex, Call->arg_size(), Callee,
1183 ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1184 Call->getAttributes().getRetAttrs(), /*IsPatchPoint=*/false);
1185 if (!VarArgDisallowed)
1186 SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1187
1188 auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1189
1191
1192 auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1193 SI.ID = SD.StatepointID.value_or(DefaultID);
1194 SI.NumPatchBytes = SD.NumPatchBytes.value_or(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, *Call, ReturnVal);
1206 setValue(Call, ReturnVal);
1207 }
1208}
1209
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();
1222 "GetStatepoint must return one of two types");
1223 if (isa<UndefValue>(SI))
1224 return;
1225
1226 if (cast<GCStatepointInst>(SI)->getParent() == CI.getParent()) {
1227 setValue(&CI, getValue(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(SI, RetTy);
1238
1239 assert(CopyFromReg.getNode());
1240 setValue(&CI, 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>(Statepoint)];
1262 auto SlotIt = RelocationMap.find(&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(getValue(DerivedPtr));
1272 assert(SDV.getNode() && "empty SDValue");
1273 setValue(&Relocate, 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, getCurSDLoc(),
1286 Chain, nullptr, nullptr);
1287 setValue(&Relocate, Relocation);
1288 return;
1289 }
1290
1291 if (Record.type == RecordType::Spill) {
1292 unsigned Index = Record.payload.FI;
1293 SDValue SpillSlot = DAG.getFrameIndex(Index, 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, Index);
1307 auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1308 MFI.getObjectSize(Index),
1309 MFI.getObjectAlign(Index));
1310
1311 auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1312 Relocate.getType());
1313
1314 SDValue SpillLoad =
1315 DAG.getLoad(LoadVT, getCurSDLoc(), Chain, SpillSlot, LoadMMO);
1316 PendingLoads.push_back(SpillLoad.getValue(1));
1317
1318 assert(SpillLoad.getNode());
1319 setValue(&Relocate, SpillLoad);
1320 return;
1321 }
1322
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(DAG.getDataLayout(),
1329 Relocate.getType());
1330 setValue(&Relocate,
1331 Record.RematLeaf->rematerialize(DAG, getCurSDLoc(), VT));
1332 return;
1333 }
1334
1335 SDValue SD = getValue(DerivedPtr);
1336
1337 if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1338 setValue(&Relocate,
1339 DAG.getConstant(UndefStackMapValue, SDLoc(SD), 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(&Relocate, SD);
1346}
1347
1349 const auto &TLI = DAG.getTargetLoweringInfo();
1350
1351 RTLIB::LibcallImpl DeoptImpl =
1352 DAG.getLibcalls().getLibcallImpl(RTLIB::DEOPTIMIZE);
1353 if (DeoptImpl == RTLIB::Unsupported) {
1354 DAG.getContext()->emitError("no deoptimize libcall available");
1355 return;
1356 }
1357
1358 SDValue Callee =
1359 DAG.getExternalSymbol(DeoptImpl, TLI.getPointerTy(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(CI, Callee, /* EHPadBB = */ nullptr,
1366 /* VarArgDisallowed = */ true,
1367 /* ForceVoidReturnTy = */ true);
1368}
1369
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(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1377}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static DeltaTreeNode * getRoot(void *Root)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file implements the SmallBitVector class.
This file defines the SmallSet class.
This file defines the SmallVector class.
static cl::opt< bool > UseRegistersForGCPointersInLandingPad("use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false), cl::desc("Allow using registers for gc pointer in landing pad"))
static void lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot, SmallVectorImpl< SDValue > &Ops, SmallVectorImpl< MachineMemOperand * > &MemRefs, SelectionDAGBuilder &Builder)
Lower a single value incoming to a statepoint node.
static constexpr uint32_t UndefStackMapValue
static std::optional< int > findPreviousSpillSlot(const Value *Val, SelectionDAGBuilder &Builder, int LookUpDepth)
Utility function for reservePreviousStackSlotForValue.
static void pushStackMapConstant(SmallVectorImpl< SDValue > &Ops, SelectionDAGBuilder &Builder, uint64_t Value)
static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder)
Return true if value V represents the GC value.
static bool willLowerDirectly(SDValue Incoming)
Return true if-and-only-if the given SDValue can be lowered as either a constant argument or a stack ...
static void lowerStatepointMetaArgs(SmallVectorImpl< SDValue > &Ops, SmallVectorImpl< MachineMemOperand * > &MemRefs, SmallVectorImpl< SDValue > &GCPtrs, DenseMap< SDValue, int > &LowerAsVReg, SelectionDAGBuilder::StatepointLoweringInfo &SI, SelectionDAGBuilder &Builder)
Lower deopt state and gc pointer arguments of the statepoint.
static std::pair< const GCResultInst *, const GCResultInst * > getGCResultLocality(const GCStatepointInst &S)
Return two gc.results if present.
static cl::opt< bool > UseRegistersForDeoptValues("use-registers-for-deopt-values", cl::Hidden, cl::init(false), cl::desc("Allow using registers for non pointer deopt args"))
static cl::opt< unsigned > MaxRegistersForGCPointers("max-registers-for-gc-values", cl::Hidden, cl::init(0), cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"))
static void reservePreviousStackSlotForValue(const Value *IncomingValue, SelectionDAGBuilder &Builder)
Try to find existing copies of the incoming values in stack slots used for statepoint spilling.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static MachineMemOperand * getMachineMemOperand(MachineFunction &MF, FrameIndexSDNode &FI)
static std::pair< SDValue, SDNode * > lowerCallFromStatepointLoweringInfo(SelectionDAGBuilder::StatepointLoweringInfo &SI, SelectionDAGBuilder &Builder)
Extract call from statepoint, lower it and return pointer to the call node.
static std::tuple< SDValue, SDValue, MachineMemOperand * > spillIncomingStatepointValue(SDValue Incoming, SDValue Chain, SelectionDAGBuilder &Builder)
Spill a value incoming to the statepoint.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM Basic Block Representation.
Definition BasicBlock.h:62
This class represents a no-op cast from one type to another.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:348
unsigned size() const
Definition DenseMap.h:207
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:254
iterator end()
Definition DenseMap.h:176
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
LLVM_ABI Value * getDerivedPtr() const
Represents calls to the gc.result intrinsic.
Represents a gc.statepoint intrinsic call.
Definition Statepoint.h:61
iterator_range< user_iterator > users()
The landingpad instruction holds all of the information necessary to generate correct exception handl...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void markAsStatepointSpillSlotObjectIndex(int ObjectIdx)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
A description of a memory reference used in the backend.
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
An SDNode that represents everything that will be needed to construct a MachineInstr.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
SDNode * getGluedNode() const
If this node has a glue operand, return the node to which the glue operand points.
op_iterator op_end() const
op_iterator op_begin() const
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB, bool VarArgDisallowed, bool ForceVoidReturnTy)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI)
Lower SLI into a STATEPOINT instruction.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition SetVector.h:94
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void clear()
Clear the memory usage of this object.
SDValue allocateStackSlot(EVT ValueType, SelectionDAGBuilder &Builder)
Get a stack slot we can use to store an value of type ValueType.
void startNewStatepoint(SelectionDAGBuilder &Builder)
Reset all state tracking for a newly encountered safepoint.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ GC_TRANSITION_START
GC_TRANSITION_START/GC_TRANSITION_END - These operators mark the beginning and end of GC transition s...
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ TRAP
TRAP - Trapping instruction.
@ GC_TRANSITION_END
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI StatepointDirectives parseStatepointDirectivesFromAttrs(AttributeList AS)
Parse out statepoint directives from the function attributes present in AS.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ MaskAll
A bitmask that includes all valid flags.
Definition Statepoint.h:51
@ DeoptLiveIn
Mark the deopt arguments associated with the statepoint as only being "live-in".
Definition Statepoint.h:49
@ GCTransition
Indicates that this statepoint is a transition from GC-aware code to code that is not GC-aware.
Definition Statepoint.h:41
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
LLVM_ABI SDValue rematerialize(SelectionDAG &DAG, const SDLoc &DL, EVT VT) const
Rebuild the captured leaf as a fresh SDValue of type VT.
LLVM_ABI StatepointDirectLeaf(SDValue V)
Capture the leaf V, which must be a directly-lowered value.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Describes a gc.statepoint or a gc.statepoint like thing for the purposes of lowering into a STATEPOIN...
static const uint64_t DeoptBundleStatepointID
Definition Statepoint.h:240