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