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