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