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