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