1 //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file includes support code use by SelectionDAGBuilder when lowering a 11 // statepoint sequence in SelectionDAG IR. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "StatepointLowering.h" 16 #include "SelectionDAGBuilder.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/CodeGen/FunctionLoweringInfo.h" 20 #include "llvm/CodeGen/GCStrategy.h" 21 #include "llvm/CodeGen/SelectionDAG.h" 22 #include "llvm/CodeGen/StackMaps.h" 23 #include "llvm/IR/CallingConv.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/Statepoint.h" 28 #include "llvm/Target/TargetLowering.h" 29 #include <algorithm> 30 using namespace llvm; 31 32 #define DEBUG_TYPE "statepoint-lowering" 33 34 STATISTIC(NumSlotsAllocatedForStatepoints, 35 "Number of stack slots allocated for statepoints"); 36 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered"); 37 STATISTIC(StatepointMaxSlotsRequired, 38 "Maximum number of stack slots required for a singe statepoint"); 39 40 void 41 StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) { 42 // Consistency check 43 assert(PendingGCRelocateCalls.empty() && 44 "Trying to visit statepoint before finished processing previous one"); 45 Locations.clear(); 46 RelocLocations.clear(); 47 NextSlotToAllocate = 0; 48 // Need to resize this on each safepoint - we need the two to stay in 49 // sync and the clear patterns of a SelectionDAGBuilder have no relation 50 // to FunctionLoweringInfo. 51 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size()); 52 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) { 53 AllocatedStackSlots[i] = false; 54 } 55 } 56 void StatepointLoweringState::clear() { 57 Locations.clear(); 58 RelocLocations.clear(); 59 AllocatedStackSlots.clear(); 60 assert(PendingGCRelocateCalls.empty() && 61 "cleared before statepoint sequence completed"); 62 } 63 64 SDValue 65 StatepointLoweringState::allocateStackSlot(EVT ValueType, 66 SelectionDAGBuilder &Builder) { 67 68 NumSlotsAllocatedForStatepoints++; 69 70 // The basic scheme here is to first look for a previously created stack slot 71 // which is not in use (accounting for the fact arbitrary slots may already 72 // be reserved), or to create a new stack slot and use it. 73 74 // If this doesn't succeed in 40000 iterations, something is seriously wrong 75 for (int i = 0; i < 40000; i++) { 76 assert(Builder.FuncInfo.StatepointStackSlots.size() == 77 AllocatedStackSlots.size() && 78 "broken invariant"); 79 const size_t NumSlots = AllocatedStackSlots.size(); 80 assert(NextSlotToAllocate <= NumSlots && "broken invariant"); 81 82 if (NextSlotToAllocate >= NumSlots) { 83 assert(NextSlotToAllocate == NumSlots); 84 // record stats 85 if (NumSlots + 1 > StatepointMaxSlotsRequired) { 86 StatepointMaxSlotsRequired = NumSlots + 1; 87 } 88 89 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType); 90 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 91 Builder.FuncInfo.StatepointStackSlots.push_back(FI); 92 AllocatedStackSlots.push_back(true); 93 return SpillSlot; 94 } 95 if (!AllocatedStackSlots[NextSlotToAllocate]) { 96 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate]; 97 AllocatedStackSlots[NextSlotToAllocate] = true; 98 return Builder.DAG.getFrameIndex(FI, ValueType); 99 } 100 // Note: We deliberately choose to advance this only on the failing path. 101 // Doing so on the suceeding path involes a bit of complexity that caused a 102 // minor bug previously. Unless performance shows this matters, please 103 // keep this code as simple as possible. 104 NextSlotToAllocate++; 105 } 106 llvm_unreachable("infinite loop?"); 107 } 108 109 /// Try to find existing copies of the incoming values in stack slots used for 110 /// statepoint spilling. If we can find a spill slot for the incoming value, 111 /// mark that slot as allocated, and reuse the same slot for this safepoint. 112 /// This helps to avoid series of loads and stores that only serve to resuffle 113 /// values on the stack between calls. 114 static void reservePreviousStackSlotForValue(SDValue Incoming, 115 SelectionDAGBuilder &Builder) { 116 117 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) { 118 // We won't need to spill this, so no need to check for previously 119 // allocated stack slots 120 return; 121 } 122 123 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming); 124 if (Loc.getNode()) { 125 // duplicates in input 126 return; 127 } 128 129 // Search back for the load from a stack slot pattern to find the original 130 // slot we allocated for this value. We could extend this to deal with 131 // simple modification patterns, but simple dealing with trivial load/store 132 // sequences helps a lot already. 133 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) { 134 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) { 135 const int Index = FI->getIndex(); 136 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(), 137 Builder.FuncInfo.StatepointStackSlots.end(), Index); 138 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) { 139 // not one of the lowering stack slots, can't reuse! 140 // TODO: Actually, we probably could reuse the stack slot if the value 141 // hasn't changed at all, but we'd need to look for intervening writes 142 return; 143 } else { 144 // This is one of our dedicated lowering slots 145 const int Offset = 146 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr); 147 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) { 148 // stack slot already assigned to someone else, can't use it! 149 // TODO: currently we reserve space for gc arguments after doing 150 // normal allocation for deopt arguments. We should reserve for 151 // _all_ deopt and gc arguments, then start allocating. This 152 // will prevent some moves being inserted when vm state changes, 153 // but gc state doesn't between two calls. 154 return; 155 } 156 // Reserve this stack slot 157 Builder.StatepointLowering.reserveStackSlot(Offset); 158 } 159 160 // Cache this slot so we find it when going through the normal 161 // assignment loop. 162 SDValue Loc = 163 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType()); 164 165 Builder.StatepointLowering.setLocation(Incoming, Loc); 166 } 167 } 168 169 // TODO: handle case where a reloaded value flows through a phi to 170 // another safepoint. e.g. 171 // bb1: 172 // a' = relocated... 173 // bb2: % pred: bb1, bb3, bb4, etc. 174 // a_phi = phi(a', ...) 175 // statepoint ... a_phi 176 // NOTE: This will require reasoning about cross basic block values. This is 177 // decidedly non trivial and this might not be the right place to do it. We 178 // don't really have the information we need here... 179 180 // TODO: handle simple updates. If a value is modified and the original 181 // value is no longer live, it would be nice to put the modified value in the 182 // same slot. This allows folding of the memory accesses for some 183 // instructions types (like an increment). 184 // statepoint (i) 185 // i1 = i+1 186 // statepoint (i1) 187 } 188 189 /// Remove any duplicate (as SDValues) from the derived pointer pairs. This 190 /// is not required for correctness. It's purpose is to reduce the size of 191 /// StackMap section. It has no effect on the number of spill slots required 192 /// or the actual lowering. 193 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases, 194 SmallVectorImpl<const Value *> &Ptrs, 195 SmallVectorImpl<const Value *> &Relocs, 196 SelectionDAGBuilder &Builder) { 197 198 // This is horribly ineffecient, but I don't care right now 199 SmallSet<SDValue, 64> Seen; 200 201 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs; 202 for (size_t i = 0; i < Ptrs.size(); i++) { 203 SDValue SD = Builder.getValue(Ptrs[i]); 204 // Only add non-duplicates 205 if (Seen.count(SD) == 0) { 206 NewBases.push_back(Bases[i]); 207 NewPtrs.push_back(Ptrs[i]); 208 NewRelocs.push_back(Relocs[i]); 209 } 210 Seen.insert(SD); 211 } 212 assert(Bases.size() >= NewBases.size()); 213 assert(Ptrs.size() >= NewPtrs.size()); 214 assert(Relocs.size() >= NewRelocs.size()); 215 Bases = NewBases; 216 Ptrs = NewPtrs; 217 Relocs = NewRelocs; 218 assert(Ptrs.size() == Bases.size()); 219 assert(Ptrs.size() == Relocs.size()); 220 } 221 222 /// Extract call from statepoint, lower it and return pointer to the 223 /// call node. Also update NodeMap so that getValue(statepoint) will 224 /// reference lowered call result 225 static SDNode *lowerCallFromStatepoint(const CallInst &CI, 226 SelectionDAGBuilder &Builder) { 227 228 assert(Intrinsic::experimental_gc_statepoint == 229 dyn_cast<IntrinsicInst>(&CI)->getIntrinsicID() && 230 "function called must be the statepoint function"); 231 232 ImmutableStatepoint StatepointOperands(&CI); 233 234 // Lower the actual call itself - This is a bit of a hack, but we want to 235 // avoid modifying the actual lowering code. This is similiar in intent to 236 // the LowerCallOperands mechanism used by PATCHPOINT, but is structured 237 // differently. Hopefully, this is slightly more robust w.r.t. calling 238 // convention, return values, and other function attributes. 239 Value *ActualCallee = const_cast<Value *>(StatepointOperands.actualCallee()); 240 241 std::vector<Value *> Args; 242 CallInst::const_op_iterator arg_begin = StatepointOperands.call_args_begin(); 243 CallInst::const_op_iterator arg_end = StatepointOperands.call_args_end(); 244 Args.insert(Args.end(), arg_begin, arg_end); 245 // TODO: remove the creation of a new instruction! We should not be 246 // modifying the IR (even temporarily) at this point. 247 CallInst *Tmp = CallInst::Create(ActualCallee, Args); 248 Tmp->setTailCall(CI.isTailCall()); 249 Tmp->setCallingConv(CI.getCallingConv()); 250 Tmp->setAttributes(CI.getAttributes()); 251 Builder.LowerCallTo(Tmp, Builder.getValue(ActualCallee), false); 252 253 // Handle the return value of the call iff any. 254 const bool HasDef = !Tmp->getType()->isVoidTy(); 255 if (HasDef) { 256 // The value of the statepoint itself will be the value of call itself. 257 // We'll replace the actually call node shortly. gc_result will grab 258 // this value. 259 Builder.setValue(&CI, Builder.getValue(Tmp)); 260 } else { 261 // The token value is never used from here on, just generate a poison value 262 Builder.setValue(&CI, Builder.DAG.getIntPtrConstant(-1)); 263 } 264 // Remove the fake entry we created so we don't have a hanging reference 265 // after we delete this node. 266 Builder.removeValue(Tmp); 267 delete Tmp; 268 Tmp = nullptr; 269 270 // Search for the call node 271 // The following code is essentially reverse engineering X86's 272 // LowerCallTo. 273 SDNode *CallNode = nullptr; 274 275 // We just emitted a call, so it should be last thing generated 276 SDValue Chain = Builder.DAG.getRoot(); 277 278 // Find closest CALLSEQ_END walking back through lowered nodes if needed 279 SDNode *CallEnd = Chain.getNode(); 280 int Sanity = 0; 281 while (CallEnd->getOpcode() != ISD::CALLSEQ_END) { 282 CallEnd = CallEnd->getGluedNode(); 283 assert(CallEnd && "Can not find call node"); 284 assert(Sanity < 20 && "should have found call end already"); 285 Sanity++; 286 } 287 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 288 "Expected a callseq node."); 289 assert(CallEnd->getGluedNode()); 290 291 // Step back inside the CALLSEQ 292 CallNode = CallEnd->getGluedNode(); 293 return CallNode; 294 } 295 296 /// Callect all gc pointers coming into statepoint intrinsic, clean them up, 297 /// and return two arrays: 298 /// Bases - base pointers incoming to this statepoint 299 /// Ptrs - derived pointers incoming to this statepoint 300 /// Relocs - the gc_relocate corresponding to each base/ptr pair 301 /// Elements of this arrays should be in one-to-one correspondence with each 302 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call 303 static void 304 getIncomingStatepointGCValues(SmallVectorImpl<const Value *> &Bases, 305 SmallVectorImpl<const Value *> &Ptrs, 306 SmallVectorImpl<const Value *> &Relocs, 307 ImmutableCallSite Statepoint, 308 SelectionDAGBuilder &Builder) { 309 // Search for relocated pointers. Note that working backwards from the 310 // gc_relocates ensures that we only get pairs which are actually relocated 311 // and used after the statepoint. 312 // TODO: This logic should probably become a utility function in Statepoint.h 313 for (const User *U : cast<CallInst>(Statepoint.getInstruction())->users()) { 314 if (!isGCRelocate(U)) { 315 continue; 316 } 317 GCRelocateOperands relocateOpers(U); 318 Relocs.push_back(cast<Value>(U)); 319 Bases.push_back(relocateOpers.basePtr()); 320 Ptrs.push_back(relocateOpers.derivedPtr()); 321 } 322 323 // Remove any redundant llvm::Values which map to the same SDValue as another 324 // input. Also has the effect of removing duplicates in the original 325 // llvm::Value input list as well. This is a useful optimization for 326 // reducing the size of the StackMap section. It has no other impact. 327 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder); 328 329 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size()); 330 } 331 332 /// Spill a value incoming to the statepoint. It might be either part of 333 /// vmstate 334 /// or gcstate. In both cases unconditionally spill it on the stack unless it 335 /// is a null constant. Return pair with first element being frame index 336 /// containing saved value and second element with outgoing chain from the 337 /// emitted store 338 static std::pair<SDValue, SDValue> 339 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain, 340 SelectionDAGBuilder &Builder) { 341 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming); 342 343 // Emit new store if we didn't do it for this ptr before 344 if (!Loc.getNode()) { 345 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(), 346 Builder); 347 assert(isa<FrameIndexSDNode>(Loc)); 348 int Index = cast<FrameIndexSDNode>(Loc)->getIndex(); 349 // We use TargetFrameIndex so that isel will not select it into LEA 350 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType()); 351 352 // TODO: We can create TokenFactor node instead of 353 // chaining stores one after another, this may allow 354 // a bit more optimal scheduling for them 355 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc, 356 MachinePointerInfo::getFixedStack(Index), 357 false, false, 0); 358 359 Builder.StatepointLowering.setLocation(Incoming, Loc); 360 } 361 362 assert(Loc.getNode()); 363 return std::make_pair(Loc, Chain); 364 } 365 366 /// Lower a single value incoming to a statepoint node. This value can be 367 /// either a deopt value or a gc value, the handling is the same. We special 368 /// case constants and allocas, then fall back to spilling if required. 369 static void lowerIncomingStatepointValue(SDValue Incoming, 370 SmallVectorImpl<SDValue> &Ops, 371 SelectionDAGBuilder &Builder) { 372 SDValue Chain = Builder.getRoot(); 373 374 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) { 375 // If the original value was a constant, make sure it gets recorded as 376 // such in the stackmap. This is required so that the consumer can 377 // parse any internal format to the deopt state. It also handles null 378 // pointers and other constant pointers in GC states 379 Ops.push_back( 380 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64)); 381 Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64)); 382 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) { 383 // This handles allocas as arguments to the statepoint 384 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 385 Ops.push_back( 386 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy())); 387 } else { 388 // Otherwise, locate a spill slot and explicitly spill it so it 389 // can be found by the runtime later. We currently do not support 390 // tracking values through callee saved registers to their eventual 391 // spill location. This would be a useful optimization, but would 392 // need to be optional since it requires a lot of complexity on the 393 // runtime side which not all would support. 394 std::pair<SDValue, SDValue> Res = 395 spillIncomingStatepointValue(Incoming, Chain, Builder); 396 Ops.push_back(Res.first); 397 Chain = Res.second; 398 } 399 400 Builder.DAG.setRoot(Chain); 401 } 402 403 /// Lower deopt state and gc pointer arguments of the statepoint. The actual 404 /// lowering is described in lowerIncomingStatepointValue. This function is 405 /// responsible for lowering everything in the right position and playing some 406 /// tricks to avoid redundant stack manipulation where possible. On 407 /// completion, 'Ops' will contain ready to use operands for machine code 408 /// statepoint. The chain nodes will have already been created and the DAG root 409 /// will be set to the last value spilled (if any were). 410 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops, 411 ImmutableStatepoint Statepoint, 412 SelectionDAGBuilder &Builder) { 413 414 // Lower the deopt and gc arguments for this statepoint. Layout will 415 // be: deopt argument length, deopt arguments.., gc arguments... 416 417 SmallVector<const Value *, 64> Bases, Ptrs, Relocations; 418 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, 419 Statepoint.getCallSite(), Builder); 420 421 #ifndef NDEBUG 422 // Check that each of the gc pointer and bases we've gotten out of the 423 // safepoint is something the strategy thinks might be a pointer into the GC 424 // heap. This is basically just here to help catch errors during statepoint 425 // insertion. TODO: This should actually be in the Verifier, but we can't get 426 // to the GCStrategy from there (yet). 427 if (Builder.GFI) { 428 GCStrategy &S = Builder.GFI->getStrategy(); 429 for (const Value *V : Bases) { 430 auto Opt = S.isGCManagedPointer(V); 431 if (Opt.hasValue()) { 432 assert(Opt.getValue() && 433 "non gc managed base pointer found in statepoint"); 434 } 435 } 436 for (const Value *V : Ptrs) { 437 auto Opt = S.isGCManagedPointer(V); 438 if (Opt.hasValue()) { 439 assert(Opt.getValue() && 440 "non gc managed derived pointer found in statepoint"); 441 } 442 } 443 for (const Value *V : Relocations) { 444 auto Opt = S.isGCManagedPointer(V); 445 if (Opt.hasValue()) { 446 assert(Opt.getValue() && "non gc managed pointer relocated"); 447 } 448 } 449 } 450 #endif 451 452 453 454 // Before we actually start lowering (and allocating spill slots for values), 455 // reserve any stack slots which we judge to be profitable to reuse for a 456 // particular value. This is purely an optimization over the code below and 457 // doesn't change semantics at all. It is important for performance that we 458 // reserve slots for both deopt and gc values before lowering either. 459 for (auto I = Statepoint.vm_state_begin() + 1, E = Statepoint.vm_state_end(); 460 I != E; ++I) { 461 Value *V = *I; 462 SDValue Incoming = Builder.getValue(V); 463 reservePreviousStackSlotForValue(Incoming, Builder); 464 } 465 for (unsigned i = 0; i < Bases.size() * 2; ++i) { 466 // Even elements will contain base, odd elements - derived ptr 467 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2]; 468 SDValue Incoming = Builder.getValue(V); 469 reservePreviousStackSlotForValue(Incoming, Builder); 470 } 471 472 // First, prefix the list with the number of unique values to be 473 // lowered. Note that this is the number of *Values* not the 474 // number of SDValues required to lower them. 475 const int NumVMSArgs = Statepoint.numTotalVMSArgs(); 476 Ops.push_back( 477 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64)); 478 Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, MVT::i64)); 479 480 assert(NumVMSArgs + 1 == std::distance(Statepoint.vm_state_begin(), 481 Statepoint.vm_state_end())); 482 483 // The vm state arguments are lowered in an opaque manner. We do 484 // not know what type of values are contained within. We skip the 485 // first one since that happens to be the total number we lowered 486 // explicitly just above. We could have left it in the loop and 487 // not done it explicitly, but it's far easier to understand this 488 // way. 489 for (auto I = Statepoint.vm_state_begin() + 1, E = Statepoint.vm_state_end(); 490 I != E; ++I) { 491 const Value *V = *I; 492 SDValue Incoming = Builder.getValue(V); 493 lowerIncomingStatepointValue(Incoming, Ops, Builder); 494 } 495 496 // Finally, go ahead and lower all the gc arguments. There's no prefixed 497 // length for this one. After lowering, we'll have the base and pointer 498 // arrays interwoven with each (lowered) base pointer immediately followed by 499 // it's (lowered) derived pointer. i.e 500 // (base[0], ptr[0], base[1], ptr[1], ...) 501 for (unsigned i = 0; i < Bases.size() * 2; ++i) { 502 // Even elements will contain base, odd elements - derived ptr 503 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2]; 504 SDValue Incoming = Builder.getValue(V); 505 lowerIncomingStatepointValue(Incoming, Ops, Builder); 506 } 507 } 508 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) { 509 // The basic scheme here is that information about both the original call and 510 // the safepoint is encoded in the CallInst. We create a temporary call and 511 // lower it, then reverse engineer the calling sequence. 512 513 // Check some preconditions for sanity 514 assert(isStatepoint(&CI) && 515 "function called must be the statepoint function"); 516 NumOfStatepoints++; 517 // Clear state 518 StatepointLowering.startNewStatepoint(*this); 519 520 #ifndef NDEBUG 521 // Consistency check 522 for (const User *U : CI.users()) { 523 const CallInst *Call = cast<CallInst>(U); 524 if (isGCRelocate(Call)) 525 StatepointLowering.scheduleRelocCall(*Call); 526 } 527 #endif 528 529 ImmutableStatepoint ISP(&CI); 530 #ifndef NDEBUG 531 // If this is a malformed statepoint, report it early to simplify debugging. 532 // This should catch any IR level mistake that's made when constructing or 533 // transforming statepoints. 534 ISP.verify(); 535 536 // Check that the associated GCStrategy expects to encounter statepoints. 537 // TODO: This if should become an assert. For now, we allow the GCStrategy 538 // to be optional for backwards compatibility. This will only last a short 539 // period (i.e. a couple of weeks). 540 if (GFI) { 541 assert(GFI->getStrategy().useStatepoints() && 542 "GCStrategy does not expect to encounter statepoints"); 543 } 544 #endif 545 546 547 // Lower statepoint vmstate and gcstate arguments 548 SmallVector<SDValue, 10> LoweredArgs; 549 lowerStatepointMetaArgs(LoweredArgs, ISP, *this); 550 551 // Get call node, we will replace it later with statepoint 552 SDNode *CallNode = lowerCallFromStatepoint(CI, *this); 553 554 // Construct the actual STATEPOINT node with all the appropriate arguments 555 // and return values. 556 557 // TODO: Currently, all of these operands are being marked as read/write in 558 // PrologEpilougeInserter.cpp, we should special case the VMState arguments 559 // and flags to be read-only. 560 SmallVector<SDValue, 40> Ops; 561 562 // Calculate and push starting position of vmstate arguments 563 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 564 SDValue Glue; 565 if (CallNode->getGluedNode()) { 566 // Glue is always last operand 567 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1); 568 } 569 // Get number of arguments incoming directly into call node 570 unsigned NumCallRegArgs = 571 CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3); 572 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32)); 573 574 // Add call target 575 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0); 576 Ops.push_back(CallTarget); 577 578 // Add call arguments 579 // Get position of register mask in the call 580 SDNode::op_iterator RegMaskIt; 581 if (Glue.getNode()) 582 RegMaskIt = CallNode->op_end() - 2; 583 else 584 RegMaskIt = CallNode->op_end() - 1; 585 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt); 586 587 // Add a leading constant argument with the Flags and the calling convention 588 // masked together 589 CallingConv::ID CallConv = CI.getCallingConv(); 590 int Flags = dyn_cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 591 assert(Flags == 0 && "not expected to be used"); 592 Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64)); 593 Ops.push_back( 594 DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1), MVT::i64)); 595 596 // Insert all vmstate and gcstate arguments 597 Ops.insert(Ops.end(), LoweredArgs.begin(), LoweredArgs.end()); 598 599 // Add register mask from call node 600 Ops.push_back(*RegMaskIt); 601 602 // Add chain 603 Ops.push_back(CallNode->getOperand(0)); 604 605 // Same for the glue, but we add it only if original call had it 606 if (Glue.getNode()) 607 Ops.push_back(Glue); 608 609 // Compute return values 610 SmallVector<EVT, 21> ValueVTs; 611 ValueVTs.push_back(MVT::Other); 612 ValueVTs.push_back(MVT::Glue); // provide a glue output since we consume one 613 // as input. This allows someone else to chain 614 // off us as needed. 615 SDVTList NodeTys = DAG.getVTList(ValueVTs); 616 617 SDNode *StatepointMCNode = DAG.getMachineNode(TargetOpcode::STATEPOINT, 618 getCurSDLoc(), NodeTys, Ops); 619 620 // Replace original call 621 DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root 622 // Remove originall call node 623 DAG.DeleteNode(CallNode); 624 625 // DON'T set the root - under the assumption that it's already set past the 626 // inserted node we created. 627 628 // TODO: A better future implementation would be to emit a single variable 629 // argument, variable return value STATEPOINT node here and then hookup the 630 // return value of each gc.relocate to the respective output of the 631 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear 632 // to actually be possible today. 633 } 634 635 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) { 636 // The result value of the gc_result is simply the result of the actual 637 // call. We've already emitted this, so just grab the value. 638 Instruction *I = cast<Instruction>(CI.getArgOperand(0)); 639 assert(isStatepoint(I) && 640 "first argument must be a statepoint token"); 641 642 setValue(&CI, getValue(I)); 643 } 644 645 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) { 646 #ifndef NDEBUG 647 // Consistency check 648 StatepointLowering.relocCallVisited(CI); 649 #endif 650 651 GCRelocateOperands relocateOpers(&CI); 652 SDValue SD = getValue(relocateOpers.derivedPtr()); 653 654 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) { 655 // We didn't need to spill these special cases (constants and allocas). 656 // See the handling in spillIncomingValueForStatepoint for detail. 657 setValue(&CI, SD); 658 return; 659 } 660 661 SDValue Loc = StatepointLowering.getRelocLocation(SD); 662 // Emit new load if we did not emit it before 663 if (!Loc.getNode()) { 664 SDValue SpillSlot = StatepointLowering.getLocation(SD); 665 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 666 667 // Be conservative: flush all pending loads 668 // TODO: Probably we can be less restrictive on this, 669 // it may allow more scheduling opprtunities 670 SDValue Chain = getRoot(); 671 672 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, 673 SpillSlot, MachinePointerInfo::getFixedStack(FI), false, 674 false, false, 0); 675 676 StatepointLowering.setRelocLocation(SD, Loc); 677 678 // Again, be conservative, don't emit pending loads 679 DAG.setRoot(Loc.getValue(1)); 680 } 681 682 assert(Loc.getNode()); 683 setValue(&CI, Loc); 684 } 685