1 //===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===// 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 // This file contains classes used to discover if for a particular value 9 // there from sue to definition that crosses a suspend block. 10 // 11 // Using the information discovered we form a Coroutine Frame structure to 12 // contain those values. All uses of those values are replaced with appropriate 13 // GEP + load from the coroutine frame. At the point of the definition we spill 14 // the value into the coroutine frame. 15 // 16 // TODO: pack values tightly using liveness info. 17 //===----------------------------------------------------------------------===// 18 19 #include "CoroInternal.h" 20 #include "llvm/ADT/BitVector.h" 21 #include "llvm/Transforms/Utils/Local.h" 22 #include "llvm/Config/llvm-config.h" 23 #include "llvm/IR/CFG.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/InstIterator.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/Support/circular_raw_ostream.h" 30 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 31 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 32 33 using namespace llvm; 34 35 // The "coro-suspend-crossing" flag is very noisy. There is another debug type, 36 // "coro-frame", which results in leaner debug spew. 37 #define DEBUG_TYPE "coro-suspend-crossing" 38 39 enum { SmallVectorThreshold = 32 }; 40 41 // Provides two way mapping between the blocks and numbers. 42 namespace { 43 class BlockToIndexMapping { 44 SmallVector<BasicBlock *, SmallVectorThreshold> V; 45 46 public: 47 size_t size() const { return V.size(); } 48 49 BlockToIndexMapping(Function &F) { 50 for (BasicBlock &BB : F) 51 V.push_back(&BB); 52 llvm::sort(V); 53 } 54 55 size_t blockToIndex(BasicBlock *BB) const { 56 auto *I = llvm::lower_bound(V, BB); 57 assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block"); 58 return I - V.begin(); 59 } 60 61 BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; } 62 }; 63 } // end anonymous namespace 64 65 // The SuspendCrossingInfo maintains data that allows to answer a question 66 // whether given two BasicBlocks A and B there is a path from A to B that 67 // passes through a suspend point. 68 // 69 // For every basic block 'i' it maintains a BlockData that consists of: 70 // Consumes: a bit vector which contains a set of indices of blocks that can 71 // reach block 'i' 72 // Kills: a bit vector which contains a set of indices of blocks that can 73 // reach block 'i', but one of the path will cross a suspend point 74 // Suspend: a boolean indicating whether block 'i' contains a suspend point. 75 // End: a boolean indicating whether block 'i' contains a coro.end intrinsic. 76 // 77 namespace { 78 struct SuspendCrossingInfo { 79 BlockToIndexMapping Mapping; 80 81 struct BlockData { 82 BitVector Consumes; 83 BitVector Kills; 84 bool Suspend = false; 85 bool End = false; 86 }; 87 SmallVector<BlockData, SmallVectorThreshold> Block; 88 89 iterator_range<succ_iterator> successors(BlockData const &BD) const { 90 BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]); 91 return llvm::successors(BB); 92 } 93 94 BlockData &getBlockData(BasicBlock *BB) { 95 return Block[Mapping.blockToIndex(BB)]; 96 } 97 98 void dump() const; 99 void dump(StringRef Label, BitVector const &BV) const; 100 101 SuspendCrossingInfo(Function &F, coro::Shape &Shape); 102 103 bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const { 104 size_t const DefIndex = Mapping.blockToIndex(DefBB); 105 size_t const UseIndex = Mapping.blockToIndex(UseBB); 106 107 assert(Block[UseIndex].Consumes[DefIndex] && "use must consume def"); 108 bool const Result = Block[UseIndex].Kills[DefIndex]; 109 LLVM_DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName() 110 << " answer is " << Result << "\n"); 111 return Result; 112 } 113 114 bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const { 115 auto *I = cast<Instruction>(U); 116 117 // We rewrote PHINodes, so that only the ones with exactly one incoming 118 // value need to be analyzed. 119 if (auto *PN = dyn_cast<PHINode>(I)) 120 if (PN->getNumIncomingValues() > 1) 121 return false; 122 123 BasicBlock *UseBB = I->getParent(); 124 125 // As a special case, treat uses by an llvm.coro.suspend.retcon 126 // as if they were uses in the suspend's single predecessor: the 127 // uses conceptually occur before the suspend. 128 if (isa<CoroSuspendRetconInst>(I)) { 129 UseBB = UseBB->getSinglePredecessor(); 130 assert(UseBB && "should have split coro.suspend into its own block"); 131 } 132 133 return hasPathCrossingSuspendPoint(DefBB, UseBB); 134 } 135 136 bool isDefinitionAcrossSuspend(Argument &A, User *U) const { 137 return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U); 138 } 139 140 bool isDefinitionAcrossSuspend(Instruction &I, User *U) const { 141 auto *DefBB = I.getParent(); 142 143 // As a special case, treat values produced by an llvm.coro.suspend.* 144 // as if they were defined in the single successor: the uses 145 // conceptually occur after the suspend. 146 if (isa<AnyCoroSuspendInst>(I)) { 147 DefBB = DefBB->getSingleSuccessor(); 148 assert(DefBB && "should have split coro.suspend into its own block"); 149 } 150 151 return isDefinitionAcrossSuspend(DefBB, U); 152 } 153 }; 154 } // end anonymous namespace 155 156 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 157 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label, 158 BitVector const &BV) const { 159 dbgs() << Label << ":"; 160 for (size_t I = 0, N = BV.size(); I < N; ++I) 161 if (BV[I]) 162 dbgs() << " " << Mapping.indexToBlock(I)->getName(); 163 dbgs() << "\n"; 164 } 165 166 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const { 167 for (size_t I = 0, N = Block.size(); I < N; ++I) { 168 BasicBlock *const B = Mapping.indexToBlock(I); 169 dbgs() << B->getName() << ":\n"; 170 dump(" Consumes", Block[I].Consumes); 171 dump(" Kills", Block[I].Kills); 172 } 173 dbgs() << "\n"; 174 } 175 #endif 176 177 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape) 178 : Mapping(F) { 179 const size_t N = Mapping.size(); 180 Block.resize(N); 181 182 // Initialize every block so that it consumes itself 183 for (size_t I = 0; I < N; ++I) { 184 auto &B = Block[I]; 185 B.Consumes.resize(N); 186 B.Kills.resize(N); 187 B.Consumes.set(I); 188 } 189 190 // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as 191 // the code beyond coro.end is reachable during initial invocation of the 192 // coroutine. 193 for (auto *CE : Shape.CoroEnds) 194 getBlockData(CE->getParent()).End = true; 195 196 // Mark all suspend blocks and indicate that they kill everything they 197 // consume. Note, that crossing coro.save also requires a spill, as any code 198 // between coro.save and coro.suspend may resume the coroutine and all of the 199 // state needs to be saved by that time. 200 auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) { 201 BasicBlock *SuspendBlock = BarrierInst->getParent(); 202 auto &B = getBlockData(SuspendBlock); 203 B.Suspend = true; 204 B.Kills |= B.Consumes; 205 }; 206 for (auto *CSI : Shape.CoroSuspends) { 207 markSuspendBlock(CSI); 208 if (auto *Save = CSI->getCoroSave()) 209 markSuspendBlock(Save); 210 } 211 212 // Iterate propagating consumes and kills until they stop changing. 213 int Iteration = 0; 214 (void)Iteration; 215 216 bool Changed; 217 do { 218 LLVM_DEBUG(dbgs() << "iteration " << ++Iteration); 219 LLVM_DEBUG(dbgs() << "==============\n"); 220 221 Changed = false; 222 for (size_t I = 0; I < N; ++I) { 223 auto &B = Block[I]; 224 for (BasicBlock *SI : successors(B)) { 225 226 auto SuccNo = Mapping.blockToIndex(SI); 227 228 // Saved Consumes and Kills bitsets so that it is easy to see 229 // if anything changed after propagation. 230 auto &S = Block[SuccNo]; 231 auto SavedConsumes = S.Consumes; 232 auto SavedKills = S.Kills; 233 234 // Propagate Kills and Consumes from block B into its successor S. 235 S.Consumes |= B.Consumes; 236 S.Kills |= B.Kills; 237 238 // If block B is a suspend block, it should propagate kills into the 239 // its successor for every block B consumes. 240 if (B.Suspend) { 241 S.Kills |= B.Consumes; 242 } 243 if (S.Suspend) { 244 // If block S is a suspend block, it should kill all of the blocks it 245 // consumes. 246 S.Kills |= S.Consumes; 247 } else if (S.End) { 248 // If block S is an end block, it should not propagate kills as the 249 // blocks following coro.end() are reached during initial invocation 250 // of the coroutine while all the data are still available on the 251 // stack or in the registers. 252 S.Kills.reset(); 253 } else { 254 // This is reached when S block it not Suspend nor coro.end and it 255 // need to make sure that it is not in the kill set. 256 S.Kills.reset(SuccNo); 257 } 258 259 // See if anything changed. 260 Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes); 261 262 if (S.Kills != SavedKills) { 263 LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName() 264 << "\n"); 265 LLVM_DEBUG(dump("S.Kills", S.Kills)); 266 LLVM_DEBUG(dump("SavedKills", SavedKills)); 267 } 268 if (S.Consumes != SavedConsumes) { 269 LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n"); 270 LLVM_DEBUG(dump("S.Consume", S.Consumes)); 271 LLVM_DEBUG(dump("SavedCons", SavedConsumes)); 272 } 273 } 274 } 275 } while (Changed); 276 LLVM_DEBUG(dump()); 277 } 278 279 #undef DEBUG_TYPE // "coro-suspend-crossing" 280 #define DEBUG_TYPE "coro-frame" 281 282 // We build up the list of spills for every case where a use is separated 283 // from the definition by a suspend point. 284 285 static const unsigned InvalidFieldIndex = ~0U; 286 287 namespace { 288 class Spill { 289 Value *Def = nullptr; 290 Instruction *User = nullptr; 291 unsigned FieldNo = InvalidFieldIndex; 292 293 public: 294 Spill(Value *Def, llvm::User *U) : Def(Def), User(cast<Instruction>(U)) {} 295 296 Value *def() const { return Def; } 297 Instruction *user() const { return User; } 298 BasicBlock *userBlock() const { return User->getParent(); } 299 300 // Note that field index is stored in the first SpillEntry for a particular 301 // definition. Subsequent mentions of a defintion do not have fieldNo 302 // assigned. This works out fine as the users of Spills capture the info about 303 // the definition the first time they encounter it. Consider refactoring 304 // SpillInfo into two arrays to normalize the spill representation. 305 unsigned fieldIndex() const { 306 assert(FieldNo != InvalidFieldIndex && "Accessing unassigned field"); 307 return FieldNo; 308 } 309 void setFieldIndex(unsigned FieldNumber) { 310 assert(FieldNo == InvalidFieldIndex && "Reassigning field number"); 311 FieldNo = FieldNumber; 312 } 313 }; 314 } // namespace 315 316 // Note that there may be more than one record with the same value of Def in 317 // the SpillInfo vector. 318 using SpillInfo = SmallVector<Spill, 8>; 319 320 #ifndef NDEBUG 321 static void dump(StringRef Title, SpillInfo const &Spills) { 322 dbgs() << "------------- " << Title << "--------------\n"; 323 Value *CurrentValue = nullptr; 324 for (auto const &E : Spills) { 325 if (CurrentValue != E.def()) { 326 CurrentValue = E.def(); 327 CurrentValue->dump(); 328 } 329 dbgs() << " user: "; 330 E.user()->dump(); 331 } 332 } 333 #endif 334 335 namespace { 336 // We cannot rely solely on natural alignment of a type when building a 337 // coroutine frame and if the alignment specified on the Alloca instruction 338 // differs from the natural alignment of the alloca type we will need to insert 339 // padding. 340 struct PaddingCalculator { 341 const DataLayout &DL; 342 LLVMContext &Context; 343 unsigned StructSize = 0; 344 345 PaddingCalculator(LLVMContext &Context, DataLayout const &DL) 346 : DL(DL), Context(Context) {} 347 348 // Replicate the logic from IR/DataLayout.cpp to match field offset 349 // computation for LLVM structs. 350 void addType(Type *Ty) { 351 unsigned TyAlign = DL.getABITypeAlignment(Ty); 352 if ((StructSize & (TyAlign - 1)) != 0) 353 StructSize = alignTo(StructSize, TyAlign); 354 355 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item. 356 } 357 358 void addTypes(SmallVectorImpl<Type *> const &Types) { 359 for (auto *Ty : Types) 360 addType(Ty); 361 } 362 363 unsigned computePadding(Type *Ty, unsigned ForcedAlignment) { 364 unsigned TyAlign = DL.getABITypeAlignment(Ty); 365 auto Natural = alignTo(StructSize, TyAlign); 366 auto Forced = alignTo(StructSize, ForcedAlignment); 367 368 // Return how many bytes of padding we need to insert. 369 if (Natural != Forced) 370 return std::max(Natural, Forced) - StructSize; 371 372 // Rely on natural alignment. 373 return 0; 374 } 375 376 // If padding required, return the padding field type to insert. 377 ArrayType *getPaddingType(Type *Ty, unsigned ForcedAlignment) { 378 if (auto Padding = computePadding(Ty, ForcedAlignment)) 379 return ArrayType::get(Type::getInt8Ty(Context), Padding); 380 381 return nullptr; 382 } 383 }; 384 } // namespace 385 386 // Build a struct that will keep state for an active coroutine. 387 // struct f.frame { 388 // ResumeFnTy ResumeFnAddr; 389 // ResumeFnTy DestroyFnAddr; 390 // int ResumeIndex; 391 // ... promise (if present) ... 392 // ... spills ... 393 // }; 394 static StructType *buildFrameType(Function &F, coro::Shape &Shape, 395 SpillInfo &Spills) { 396 LLVMContext &C = F.getContext(); 397 const DataLayout &DL = F.getParent()->getDataLayout(); 398 PaddingCalculator Padder(C, DL); 399 SmallString<32> Name(F.getName()); 400 Name.append(".Frame"); 401 StructType *FrameTy = StructType::create(C, Name); 402 SmallVector<Type *, 8> Types; 403 404 AllocaInst *PromiseAlloca = Shape.getPromiseAlloca(); 405 406 if (Shape.ABI == coro::ABI::Switch) { 407 auto *FramePtrTy = FrameTy->getPointerTo(); 408 auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy, 409 /*IsVarArg=*/false); 410 auto *FnPtrTy = FnTy->getPointerTo(); 411 412 // Figure out how wide should be an integer type storing the suspend index. 413 unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size())); 414 Type *PromiseType = PromiseAlloca 415 ? PromiseAlloca->getType()->getElementType() 416 : Type::getInt1Ty(C); 417 Type *IndexType = Type::getIntNTy(C, IndexBits); 418 Types.push_back(FnPtrTy); 419 Types.push_back(FnPtrTy); 420 Types.push_back(PromiseType); 421 Types.push_back(IndexType); 422 } else { 423 assert(PromiseAlloca == nullptr && "lowering doesn't support promises"); 424 } 425 426 Value *CurrentDef = nullptr; 427 428 Padder.addTypes(Types); 429 430 // Create an entry for every spilled value. 431 for (auto &S : Spills) { 432 if (CurrentDef == S.def()) 433 continue; 434 435 CurrentDef = S.def(); 436 // PromiseAlloca was already added to Types array earlier. 437 if (CurrentDef == PromiseAlloca) 438 continue; 439 440 uint64_t Count = 1; 441 Type *Ty = nullptr; 442 if (auto *AI = dyn_cast<AllocaInst>(CurrentDef)) { 443 Ty = AI->getAllocatedType(); 444 if (unsigned AllocaAlignment = AI->getAlignment()) { 445 // If alignment is specified in alloca, see if we need to insert extra 446 // padding. 447 if (auto PaddingTy = Padder.getPaddingType(Ty, AllocaAlignment)) { 448 Types.push_back(PaddingTy); 449 Padder.addType(PaddingTy); 450 } 451 } 452 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) 453 Count = CI->getValue().getZExtValue(); 454 else 455 report_fatal_error("Coroutines cannot handle non static allocas yet"); 456 } else { 457 Ty = CurrentDef->getType(); 458 } 459 S.setFieldIndex(Types.size()); 460 if (Count == 1) 461 Types.push_back(Ty); 462 else 463 Types.push_back(ArrayType::get(Ty, Count)); 464 Padder.addType(Ty); 465 } 466 FrameTy->setBody(Types); 467 468 switch (Shape.ABI) { 469 case coro::ABI::Switch: 470 break; 471 472 // Remember whether the frame is inline in the storage. 473 case coro::ABI::Retcon: 474 case coro::ABI::RetconOnce: { 475 auto &Layout = F.getParent()->getDataLayout(); 476 auto Id = Shape.getRetconCoroId(); 477 Shape.RetconLowering.IsFrameInlineInStorage 478 = (Layout.getTypeAllocSize(FrameTy) <= Id->getStorageSize() && 479 Layout.getABITypeAlignment(FrameTy) <= Id->getStorageAlignment()); 480 break; 481 } 482 } 483 484 return FrameTy; 485 } 486 487 // We need to make room to insert a spill after initial PHIs, but before 488 // catchswitch instruction. Placing it before violates the requirement that 489 // catchswitch, like all other EHPads must be the first nonPHI in a block. 490 // 491 // Split away catchswitch into a separate block and insert in its place: 492 // 493 // cleanuppad <InsertPt> cleanupret. 494 // 495 // cleanupret instruction will act as an insert point for the spill. 496 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) { 497 BasicBlock *CurrentBlock = CatchSwitch->getParent(); 498 BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch); 499 CurrentBlock->getTerminator()->eraseFromParent(); 500 501 auto *CleanupPad = 502 CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock); 503 auto *CleanupRet = 504 CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock); 505 return CleanupRet; 506 } 507 508 // Replace all alloca and SSA values that are accessed across suspend points 509 // with GetElementPointer from coroutine frame + loads and stores. Create an 510 // AllocaSpillBB that will become the new entry block for the resume parts of 511 // the coroutine: 512 // 513 // %hdl = coro.begin(...) 514 // whatever 515 // 516 // becomes: 517 // 518 // %hdl = coro.begin(...) 519 // %FramePtr = bitcast i8* hdl to %f.frame* 520 // br label %AllocaSpillBB 521 // 522 // AllocaSpillBB: 523 // ; geps corresponding to allocas that were moved to coroutine frame 524 // br label PostSpill 525 // 526 // PostSpill: 527 // whatever 528 // 529 // 530 static Instruction *insertSpills(const SpillInfo &Spills, coro::Shape &Shape) { 531 auto *CB = Shape.CoroBegin; 532 LLVMContext &C = CB->getContext(); 533 IRBuilder<> Builder(CB->getNextNode()); 534 StructType *FrameTy = Shape.FrameTy; 535 PointerType *FramePtrTy = FrameTy->getPointerTo(); 536 auto *FramePtr = 537 cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr")); 538 539 Value *CurrentValue = nullptr; 540 BasicBlock *CurrentBlock = nullptr; 541 Value *CurrentReload = nullptr; 542 543 // Proper field number will be read from field definition. 544 unsigned Index = InvalidFieldIndex; 545 546 // We need to keep track of any allocas that need "spilling" 547 // since they will live in the coroutine frame now, all access to them 548 // need to be changed, not just the access across suspend points 549 // we remember allocas and their indices to be handled once we processed 550 // all the spills. 551 SmallVector<std::pair<AllocaInst *, unsigned>, 4> Allocas; 552 // Promise alloca (if present) has a fixed field number. 553 if (auto *PromiseAlloca = Shape.getPromiseAlloca()) { 554 assert(Shape.ABI == coro::ABI::Switch); 555 Allocas.emplace_back(PromiseAlloca, coro::Shape::SwitchFieldIndex::Promise); 556 } 557 558 // Create a GEP with the given index into the coroutine frame for the original 559 // value Orig. Appends an extra 0 index for array-allocas, preserving the 560 // original type. 561 auto GetFramePointer = [&](uint32_t Index, Value *Orig) -> Value * { 562 SmallVector<Value *, 3> Indices = { 563 ConstantInt::get(Type::getInt32Ty(C), 0), 564 ConstantInt::get(Type::getInt32Ty(C), Index), 565 }; 566 567 if (auto *AI = dyn_cast<AllocaInst>(Orig)) { 568 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 569 auto Count = CI->getValue().getZExtValue(); 570 if (Count > 1) { 571 Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0)); 572 } 573 } else { 574 report_fatal_error("Coroutines cannot handle non static allocas yet"); 575 } 576 } 577 578 return Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices); 579 }; 580 581 // Create a load instruction to reload the spilled value from the coroutine 582 // frame. 583 auto CreateReload = [&](Instruction *InsertBefore) { 584 assert(Index != InvalidFieldIndex && "accessing unassigned field number"); 585 Builder.SetInsertPoint(InsertBefore); 586 587 auto *G = GetFramePointer(Index, CurrentValue); 588 G->setName(CurrentValue->getName() + Twine(".reload.addr")); 589 590 return isa<AllocaInst>(CurrentValue) 591 ? G 592 : Builder.CreateLoad(FrameTy->getElementType(Index), G, 593 CurrentValue->getName() + Twine(".reload")); 594 }; 595 596 for (auto const &E : Spills) { 597 // If we have not seen the value, generate a spill. 598 if (CurrentValue != E.def()) { 599 CurrentValue = E.def(); 600 CurrentBlock = nullptr; 601 CurrentReload = nullptr; 602 603 Index = E.fieldIndex(); 604 605 if (auto *AI = dyn_cast<AllocaInst>(CurrentValue)) { 606 // Spilled AllocaInst will be replaced with GEP from the coroutine frame 607 // there is no spill required. 608 Allocas.emplace_back(AI, Index); 609 if (!AI->isStaticAlloca()) 610 report_fatal_error("Coroutines cannot handle non static allocas yet"); 611 } else { 612 // Otherwise, create a store instruction storing the value into the 613 // coroutine frame. 614 615 Instruction *InsertPt = nullptr; 616 if (auto Arg = dyn_cast<Argument>(CurrentValue)) { 617 // For arguments, we will place the store instruction right after 618 // the coroutine frame pointer instruction, i.e. bitcast of 619 // coro.begin from i8* to %f.frame*. 620 InsertPt = FramePtr->getNextNode(); 621 622 // If we're spilling an Argument, make sure we clear 'nocapture' 623 // from the coroutine function. 624 Arg->getParent()->removeParamAttr(Arg->getArgNo(), 625 Attribute::NoCapture); 626 627 } else if (auto *II = dyn_cast<InvokeInst>(CurrentValue)) { 628 // If we are spilling the result of the invoke instruction, split the 629 // normal edge and insert the spill in the new block. 630 auto NewBB = SplitEdge(II->getParent(), II->getNormalDest()); 631 InsertPt = NewBB->getTerminator(); 632 } else if (isa<PHINode>(CurrentValue)) { 633 // Skip the PHINodes and EH pads instructions. 634 BasicBlock *DefBlock = cast<Instruction>(E.def())->getParent(); 635 if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator())) 636 InsertPt = splitBeforeCatchSwitch(CSI); 637 else 638 InsertPt = &*DefBlock->getFirstInsertionPt(); 639 } else if (auto CSI = dyn_cast<AnyCoroSuspendInst>(CurrentValue)) { 640 // Don't spill immediately after a suspend; splitting assumes 641 // that the suspend will be followed by a branch. 642 InsertPt = CSI->getParent()->getSingleSuccessor()->getFirstNonPHI(); 643 } else { 644 // For all other values, the spill is placed immediately after 645 // the definition. 646 assert(!cast<Instruction>(E.def())->isTerminator() && 647 "unexpected terminator"); 648 InsertPt = cast<Instruction>(E.def())->getNextNode(); 649 } 650 651 Builder.SetInsertPoint(InsertPt); 652 auto *G = Builder.CreateConstInBoundsGEP2_32( 653 FrameTy, FramePtr, 0, Index, 654 CurrentValue->getName() + Twine(".spill.addr")); 655 Builder.CreateStore(CurrentValue, G); 656 } 657 } 658 659 // If we have not seen the use block, generate a reload in it. 660 if (CurrentBlock != E.userBlock()) { 661 CurrentBlock = E.userBlock(); 662 CurrentReload = CreateReload(&*CurrentBlock->getFirstInsertionPt()); 663 } 664 665 // If we have a single edge PHINode, remove it and replace it with a reload 666 // from the coroutine frame. (We already took care of multi edge PHINodes 667 // by rewriting them in the rewritePHIs function). 668 if (auto *PN = dyn_cast<PHINode>(E.user())) { 669 assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming " 670 "values in the PHINode"); 671 PN->replaceAllUsesWith(CurrentReload); 672 PN->eraseFromParent(); 673 continue; 674 } 675 676 // Replace all uses of CurrentValue in the current instruction with reload. 677 E.user()->replaceUsesOfWith(CurrentValue, CurrentReload); 678 } 679 680 BasicBlock *FramePtrBB = FramePtr->getParent(); 681 682 auto SpillBlock = 683 FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB"); 684 SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill"); 685 Shape.AllocaSpillBlock = SpillBlock; 686 687 // If we found any allocas, replace all of their remaining uses with Geps. 688 Builder.SetInsertPoint(&SpillBlock->front()); 689 for (auto &P : Allocas) { 690 auto *G = GetFramePointer(P.second, P.first); 691 692 // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G)) here, 693 // as we are changing location of the instruction. 694 G->takeName(P.first); 695 P.first->replaceAllUsesWith(G); 696 P.first->eraseFromParent(); 697 } 698 return FramePtr; 699 } 700 701 // Sets the unwind edge of an instruction to a particular successor. 702 static void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) { 703 if (auto *II = dyn_cast<InvokeInst>(TI)) 704 II->setUnwindDest(Succ); 705 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI)) 706 CS->setUnwindDest(Succ); 707 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI)) 708 CR->setUnwindDest(Succ); 709 else 710 llvm_unreachable("unexpected terminator instruction"); 711 } 712 713 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a 714 // block. 715 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, 716 BasicBlock *NewPred, 717 PHINode *LandingPadReplacement) { 718 unsigned BBIdx = 0; 719 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) { 720 PHINode *PN = cast<PHINode>(I); 721 722 // We manually update the LandingPadReplacement PHINode and it is the last 723 // PHI Node. So, if we find it, we are done. 724 if (LandingPadReplacement == PN) 725 break; 726 727 // Reuse the previous value of BBIdx if it lines up. In cases where we 728 // have multiple phi nodes with *lots* of predecessors, this is a speed 729 // win because we don't have to scan the PHI looking for TIBB. This 730 // happens because the BB list of PHI nodes are usually in the same 731 // order. 732 if (PN->getIncomingBlock(BBIdx) != OldPred) 733 BBIdx = PN->getBasicBlockIndex(OldPred); 734 735 assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!"); 736 PN->setIncomingBlock(BBIdx, NewPred); 737 } 738 } 739 740 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH 741 // specific handling. 742 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, 743 LandingPadInst *OriginalPad, 744 PHINode *LandingPadReplacement) { 745 auto *PadInst = Succ->getFirstNonPHI(); 746 if (!LandingPadReplacement && !PadInst->isEHPad()) 747 return SplitEdge(BB, Succ); 748 749 auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ); 750 setUnwindEdgeTo(BB->getTerminator(), NewBB); 751 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement); 752 753 if (LandingPadReplacement) { 754 auto *NewLP = OriginalPad->clone(); 755 auto *Terminator = BranchInst::Create(Succ, NewBB); 756 NewLP->insertBefore(Terminator); 757 LandingPadReplacement->addIncoming(NewLP, NewBB); 758 return NewBB; 759 } 760 Value *ParentPad = nullptr; 761 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst)) 762 ParentPad = FuncletPad->getParentPad(); 763 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst)) 764 ParentPad = CatchSwitch->getParentPad(); 765 else 766 llvm_unreachable("handling for other EHPads not implemented yet"); 767 768 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB); 769 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB); 770 return NewBB; 771 } 772 773 static void rewritePHIs(BasicBlock &BB) { 774 // For every incoming edge we will create a block holding all 775 // incoming values in a single PHI nodes. 776 // 777 // loop: 778 // %n.val = phi i32[%n, %entry], [%inc, %loop] 779 // 780 // It will create: 781 // 782 // loop.from.entry: 783 // %n.loop.pre = phi i32 [%n, %entry] 784 // br %label loop 785 // loop.from.loop: 786 // %inc.loop.pre = phi i32 [%inc, %loop] 787 // br %label loop 788 // 789 // After this rewrite, further analysis will ignore any phi nodes with more 790 // than one incoming edge. 791 792 // TODO: Simplify PHINodes in the basic block to remove duplicate 793 // predecessors. 794 795 LandingPadInst *LandingPad = nullptr; 796 PHINode *ReplPHI = nullptr; 797 if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) { 798 // ehAwareSplitEdge will clone the LandingPad in all the edge blocks. 799 // We replace the original landing pad with a PHINode that will collect the 800 // results from all of them. 801 ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad); 802 ReplPHI->takeName(LandingPad); 803 LandingPad->replaceAllUsesWith(ReplPHI); 804 // We will erase the original landing pad at the end of this function after 805 // ehAwareSplitEdge cloned it in the transition blocks. 806 } 807 808 SmallVector<BasicBlock *, 8> Preds(pred_begin(&BB), pred_end(&BB)); 809 for (BasicBlock *Pred : Preds) { 810 auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI); 811 IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName()); 812 auto *PN = cast<PHINode>(&BB.front()); 813 do { 814 int Index = PN->getBasicBlockIndex(IncomingBB); 815 Value *V = PN->getIncomingValue(Index); 816 PHINode *InputV = PHINode::Create( 817 V->getType(), 1, V->getName() + Twine(".") + BB.getName(), 818 &IncomingBB->front()); 819 InputV->addIncoming(V, Pred); 820 PN->setIncomingValue(Index, InputV); 821 PN = dyn_cast<PHINode>(PN->getNextNode()); 822 } while (PN != ReplPHI); // ReplPHI is either null or the PHI that replaced 823 // the landing pad. 824 } 825 826 if (LandingPad) { 827 // Calls to ehAwareSplitEdge function cloned the original lading pad. 828 // No longer need it. 829 LandingPad->eraseFromParent(); 830 } 831 } 832 833 static void rewritePHIs(Function &F) { 834 SmallVector<BasicBlock *, 8> WorkList; 835 836 for (BasicBlock &BB : F) 837 if (auto *PN = dyn_cast<PHINode>(&BB.front())) 838 if (PN->getNumIncomingValues() > 1) 839 WorkList.push_back(&BB); 840 841 for (BasicBlock *BB : WorkList) 842 rewritePHIs(*BB); 843 } 844 845 // Check for instructions that we can recreate on resume as opposed to spill 846 // the result into a coroutine frame. 847 static bool materializable(Instruction &V) { 848 return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) || 849 isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V); 850 } 851 852 // Check for structural coroutine intrinsics that should not be spilled into 853 // the coroutine frame. 854 static bool isCoroutineStructureIntrinsic(Instruction &I) { 855 return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) || 856 isa<CoroSuspendInst>(&I); 857 } 858 859 // For every use of the value that is across suspend point, recreate that value 860 // after a suspend point. 861 static void rewriteMaterializableInstructions(IRBuilder<> &IRB, 862 SpillInfo const &Spills) { 863 BasicBlock *CurrentBlock = nullptr; 864 Instruction *CurrentMaterialization = nullptr; 865 Instruction *CurrentDef = nullptr; 866 867 for (auto const &E : Spills) { 868 // If it is a new definition, update CurrentXXX variables. 869 if (CurrentDef != E.def()) { 870 CurrentDef = cast<Instruction>(E.def()); 871 CurrentBlock = nullptr; 872 CurrentMaterialization = nullptr; 873 } 874 875 // If we have not seen this block, materialize the value. 876 if (CurrentBlock != E.userBlock()) { 877 CurrentBlock = E.userBlock(); 878 CurrentMaterialization = cast<Instruction>(CurrentDef)->clone(); 879 CurrentMaterialization->setName(CurrentDef->getName()); 880 CurrentMaterialization->insertBefore( 881 &*CurrentBlock->getFirstInsertionPt()); 882 } 883 884 if (auto *PN = dyn_cast<PHINode>(E.user())) { 885 assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming " 886 "values in the PHINode"); 887 PN->replaceAllUsesWith(CurrentMaterialization); 888 PN->eraseFromParent(); 889 continue; 890 } 891 892 // Replace all uses of CurrentDef in the current instruction with the 893 // CurrentMaterialization for the block. 894 E.user()->replaceUsesOfWith(CurrentDef, CurrentMaterialization); 895 } 896 } 897 898 // Move early uses of spilled variable after CoroBegin. 899 // For example, if a parameter had address taken, we may end up with the code 900 // like: 901 // define @f(i32 %n) { 902 // %n.addr = alloca i32 903 // store %n, %n.addr 904 // ... 905 // call @coro.begin 906 // we need to move the store after coro.begin 907 static void moveSpillUsesAfterCoroBegin(Function &F, SpillInfo const &Spills, 908 CoroBeginInst *CoroBegin) { 909 DominatorTree DT(F); 910 SmallVector<Instruction *, 8> NeedsMoving; 911 912 Value *CurrentValue = nullptr; 913 914 for (auto const &E : Spills) { 915 if (CurrentValue == E.def()) 916 continue; 917 918 CurrentValue = E.def(); 919 920 for (User *U : CurrentValue->users()) { 921 Instruction *I = cast<Instruction>(U); 922 if (!DT.dominates(CoroBegin, I)) { 923 LLVM_DEBUG(dbgs() << "will move: " << *I << "\n"); 924 925 // TODO: Make this more robust. Currently if we run into a situation 926 // where simple instruction move won't work we panic and 927 // report_fatal_error. 928 for (User *UI : I->users()) { 929 if (!DT.dominates(CoroBegin, cast<Instruction>(UI))) 930 report_fatal_error("cannot move instruction since its users are not" 931 " dominated by CoroBegin"); 932 } 933 934 NeedsMoving.push_back(I); 935 } 936 } 937 } 938 939 Instruction *InsertPt = CoroBegin->getNextNode(); 940 for (Instruction *I : NeedsMoving) 941 I->moveBefore(InsertPt); 942 } 943 944 // Splits the block at a particular instruction unless it is the first 945 // instruction in the block with a single predecessor. 946 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) { 947 auto *BB = I->getParent(); 948 if (&BB->front() == I) { 949 if (BB->getSinglePredecessor()) { 950 BB->setName(Name); 951 return BB; 952 } 953 } 954 return BB->splitBasicBlock(I, Name); 955 } 956 957 // Split above and below a particular instruction so that it 958 // will be all alone by itself in a block. 959 static void splitAround(Instruction *I, const Twine &Name) { 960 splitBlockIfNotFirst(I, Name); 961 splitBlockIfNotFirst(I->getNextNode(), "After" + Name); 962 } 963 964 static bool isSuspendBlock(BasicBlock *BB) { 965 return isa<AnyCoroSuspendInst>(BB->front()); 966 } 967 968 typedef SmallPtrSet<BasicBlock*, 8> VisitedBlocksSet; 969 970 /// Does control flow starting at the given block ever reach a suspend 971 /// instruction before reaching a block in VisitedOrFreeBBs? 972 static bool isSuspendReachableFrom(BasicBlock *From, 973 VisitedBlocksSet &VisitedOrFreeBBs) { 974 // Eagerly try to add this block to the visited set. If it's already 975 // there, stop recursing; this path doesn't reach a suspend before 976 // either looping or reaching a freeing block. 977 if (!VisitedOrFreeBBs.insert(From).second) 978 return false; 979 980 // We assume that we'll already have split suspends into their own blocks. 981 if (isSuspendBlock(From)) 982 return true; 983 984 // Recurse on the successors. 985 for (auto Succ : successors(From)) { 986 if (isSuspendReachableFrom(Succ, VisitedOrFreeBBs)) 987 return true; 988 } 989 990 return false; 991 } 992 993 /// Is the given alloca "local", i.e. bounded in lifetime to not cross a 994 /// suspend point? 995 static bool isLocalAlloca(CoroAllocaAllocInst *AI) { 996 // Seed the visited set with all the basic blocks containing a free 997 // so that we won't pass them up. 998 VisitedBlocksSet VisitedOrFreeBBs; 999 for (auto User : AI->users()) { 1000 if (auto FI = dyn_cast<CoroAllocaFreeInst>(User)) 1001 VisitedOrFreeBBs.insert(FI->getParent()); 1002 } 1003 1004 return !isSuspendReachableFrom(AI->getParent(), VisitedOrFreeBBs); 1005 } 1006 1007 /// After we split the coroutine, will the given basic block be along 1008 /// an obvious exit path for the resumption function? 1009 static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB, 1010 unsigned depth = 3) { 1011 // If we've bottomed out our depth count, stop searching and assume 1012 // that the path might loop back. 1013 if (depth == 0) return false; 1014 1015 // If this is a suspend block, we're about to exit the resumption function. 1016 if (isSuspendBlock(BB)) return true; 1017 1018 // Recurse into the successors. 1019 for (auto Succ : successors(BB)) { 1020 if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1)) 1021 return false; 1022 } 1023 1024 // If none of the successors leads back in a loop, we're on an exit/abort. 1025 return true; 1026 } 1027 1028 static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI) { 1029 // Look for a free that isn't sufficiently obviously followed by 1030 // either a suspend or a termination, i.e. something that will leave 1031 // the coro resumption frame. 1032 for (auto U : AI->users()) { 1033 auto FI = dyn_cast<CoroAllocaFreeInst>(U); 1034 if (!FI) continue; 1035 1036 if (!willLeaveFunctionImmediatelyAfter(FI->getParent())) 1037 return true; 1038 } 1039 1040 // If we never found one, we don't need a stack save. 1041 return false; 1042 } 1043 1044 /// Turn each of the given local allocas into a normal (dynamic) alloca 1045 /// instruction. 1046 static void lowerLocalAllocas(ArrayRef<CoroAllocaAllocInst*> LocalAllocas, 1047 SmallVectorImpl<Instruction*> &DeadInsts) { 1048 for (auto AI : LocalAllocas) { 1049 auto M = AI->getModule(); 1050 IRBuilder<> Builder(AI); 1051 1052 // Save the stack depth. Try to avoid doing this if the stackrestore 1053 // is going to immediately precede a return or something. 1054 Value *StackSave = nullptr; 1055 if (localAllocaNeedsStackSave(AI)) 1056 StackSave = Builder.CreateCall( 1057 Intrinsic::getDeclaration(M, Intrinsic::stacksave)); 1058 1059 // Allocate memory. 1060 auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize()); 1061 Alloca->setAlignment(AI->getAlignment()); 1062 1063 for (auto U : AI->users()) { 1064 // Replace gets with the allocation. 1065 if (isa<CoroAllocaGetInst>(U)) { 1066 U->replaceAllUsesWith(Alloca); 1067 1068 // Replace frees with stackrestores. This is safe because 1069 // alloca.alloc is required to obey a stack discipline, although we 1070 // don't enforce that structurally. 1071 } else { 1072 auto FI = cast<CoroAllocaFreeInst>(U); 1073 if (StackSave) { 1074 Builder.SetInsertPoint(FI); 1075 Builder.CreateCall( 1076 Intrinsic::getDeclaration(M, Intrinsic::stackrestore), 1077 StackSave); 1078 } 1079 } 1080 DeadInsts.push_back(cast<Instruction>(U)); 1081 } 1082 1083 DeadInsts.push_back(AI); 1084 } 1085 } 1086 1087 /// Turn the given coro.alloca.alloc call into a dynamic allocation. 1088 /// This happens during the all-instructions iteration, so it must not 1089 /// delete the call. 1090 static Instruction *lowerNonLocalAlloca(CoroAllocaAllocInst *AI, 1091 coro::Shape &Shape, 1092 SmallVectorImpl<Instruction*> &DeadInsts) { 1093 IRBuilder<> Builder(AI); 1094 auto Alloc = Shape.emitAlloc(Builder, AI->getSize(), nullptr); 1095 1096 for (User *U : AI->users()) { 1097 if (isa<CoroAllocaGetInst>(U)) { 1098 U->replaceAllUsesWith(Alloc); 1099 } else { 1100 auto FI = cast<CoroAllocaFreeInst>(U); 1101 Builder.SetInsertPoint(FI); 1102 Shape.emitDealloc(Builder, Alloc, nullptr); 1103 } 1104 DeadInsts.push_back(cast<Instruction>(U)); 1105 } 1106 1107 // Push this on last so that it gets deleted after all the others. 1108 DeadInsts.push_back(AI); 1109 1110 // Return the new allocation value so that we can check for needed spills. 1111 return cast<Instruction>(Alloc); 1112 } 1113 1114 /// Get the current swifterror value. 1115 static Value *emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy, 1116 coro::Shape &Shape) { 1117 // Make a fake function pointer as a sort of intrinsic. 1118 auto FnTy = FunctionType::get(ValueTy, {}, false); 1119 auto Fn = ConstantPointerNull::get(FnTy->getPointerTo()); 1120 1121 auto Call = Builder.CreateCall(Fn, {}); 1122 Shape.SwiftErrorOps.push_back(Call); 1123 1124 return Call; 1125 } 1126 1127 /// Set the given value as the current swifterror value. 1128 /// 1129 /// Returns a slot that can be used as a swifterror slot. 1130 static Value *emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V, 1131 coro::Shape &Shape) { 1132 // Make a fake function pointer as a sort of intrinsic. 1133 auto FnTy = FunctionType::get(V->getType()->getPointerTo(), 1134 {V->getType()}, false); 1135 auto Fn = ConstantPointerNull::get(FnTy->getPointerTo()); 1136 1137 auto Call = Builder.CreateCall(Fn, { V }); 1138 Shape.SwiftErrorOps.push_back(Call); 1139 1140 return Call; 1141 } 1142 1143 /// Set the swifterror value from the given alloca before a call, 1144 /// then put in back in the alloca afterwards. 1145 /// 1146 /// Returns an address that will stand in for the swifterror slot 1147 /// until splitting. 1148 static Value *emitSetAndGetSwiftErrorValueAround(Instruction *Call, 1149 AllocaInst *Alloca, 1150 coro::Shape &Shape) { 1151 auto ValueTy = Alloca->getAllocatedType(); 1152 IRBuilder<> Builder(Call); 1153 1154 // Load the current value from the alloca and set it as the 1155 // swifterror value. 1156 auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca); 1157 auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape); 1158 1159 // Move to after the call. Since swifterror only has a guaranteed 1160 // value on normal exits, we can ignore implicit and explicit unwind 1161 // edges. 1162 if (isa<CallInst>(Call)) { 1163 Builder.SetInsertPoint(Call->getNextNode()); 1164 } else { 1165 auto Invoke = cast<InvokeInst>(Call); 1166 Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg()); 1167 } 1168 1169 // Get the current swifterror value and store it to the alloca. 1170 auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape); 1171 Builder.CreateStore(ValueAfterCall, Alloca); 1172 1173 return Addr; 1174 } 1175 1176 /// Eliminate a formerly-swifterror alloca by inserting the get/set 1177 /// intrinsics and attempting to MemToReg the alloca away. 1178 static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca, 1179 coro::Shape &Shape) { 1180 for (auto UI = Alloca->use_begin(), UE = Alloca->use_end(); UI != UE; ) { 1181 // We're likely changing the use list, so use a mutation-safe 1182 // iteration pattern. 1183 auto &Use = *UI; 1184 ++UI; 1185 1186 // swifterror values can only be used in very specific ways. 1187 // We take advantage of that here. 1188 auto User = Use.getUser(); 1189 if (isa<LoadInst>(User) || isa<StoreInst>(User)) 1190 continue; 1191 1192 assert(isa<CallInst>(User) || isa<InvokeInst>(User)); 1193 auto Call = cast<Instruction>(User); 1194 1195 auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape); 1196 1197 // Use the returned slot address as the call argument. 1198 Use.set(Addr); 1199 } 1200 1201 // All the uses should be loads and stores now. 1202 assert(isAllocaPromotable(Alloca)); 1203 } 1204 1205 /// "Eliminate" a swifterror argument by reducing it to the alloca case 1206 /// and then loading and storing in the prologue and epilog. 1207 /// 1208 /// The argument keeps the swifterror flag. 1209 static void eliminateSwiftErrorArgument(Function &F, Argument &Arg, 1210 coro::Shape &Shape, 1211 SmallVectorImpl<AllocaInst*> &AllocasToPromote) { 1212 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg()); 1213 1214 auto ArgTy = cast<PointerType>(Arg.getType()); 1215 auto ValueTy = ArgTy->getElementType(); 1216 1217 // Reduce to the alloca case: 1218 1219 // Create an alloca and replace all uses of the arg with it. 1220 auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace()); 1221 Arg.replaceAllUsesWith(Alloca); 1222 1223 // Set an initial value in the alloca. swifterror is always null on entry. 1224 auto InitialValue = Constant::getNullValue(ValueTy); 1225 Builder.CreateStore(InitialValue, Alloca); 1226 1227 // Find all the suspends in the function and save and restore around them. 1228 for (auto Suspend : Shape.CoroSuspends) { 1229 (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape); 1230 } 1231 1232 // Find all the coro.ends in the function and restore the error value. 1233 for (auto End : Shape.CoroEnds) { 1234 Builder.SetInsertPoint(End); 1235 auto FinalValue = Builder.CreateLoad(ValueTy, Alloca); 1236 (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape); 1237 } 1238 1239 // Now we can use the alloca logic. 1240 AllocasToPromote.push_back(Alloca); 1241 eliminateSwiftErrorAlloca(F, Alloca, Shape); 1242 } 1243 1244 /// Eliminate all problematic uses of swifterror arguments and allocas 1245 /// from the function. We'll fix them up later when splitting the function. 1246 static void eliminateSwiftError(Function &F, coro::Shape &Shape) { 1247 SmallVector<AllocaInst*, 4> AllocasToPromote; 1248 1249 // Look for a swifterror argument. 1250 for (auto &Arg : F.args()) { 1251 if (!Arg.hasSwiftErrorAttr()) continue; 1252 1253 eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote); 1254 break; 1255 } 1256 1257 // Look for swifterror allocas. 1258 for (auto &Inst : F.getEntryBlock()) { 1259 auto Alloca = dyn_cast<AllocaInst>(&Inst); 1260 if (!Alloca || !Alloca->isSwiftError()) continue; 1261 1262 // Clear the swifterror flag. 1263 Alloca->setSwiftError(false); 1264 1265 AllocasToPromote.push_back(Alloca); 1266 eliminateSwiftErrorAlloca(F, Alloca, Shape); 1267 } 1268 1269 // If we have any allocas to promote, compute a dominator tree and 1270 // promote them en masse. 1271 if (!AllocasToPromote.empty()) { 1272 DominatorTree DT(F); 1273 PromoteMemToReg(AllocasToPromote, DT); 1274 } 1275 } 1276 1277 void coro::buildCoroutineFrame(Function &F, Shape &Shape) { 1278 // Lower coro.dbg.declare to coro.dbg.value, since we are going to rewrite 1279 // access to local variables. 1280 LowerDbgDeclare(F); 1281 1282 eliminateSwiftError(F, Shape); 1283 1284 if (Shape.ABI == coro::ABI::Switch && 1285 Shape.SwitchLowering.PromiseAlloca) { 1286 Shape.getSwitchCoroId()->clearPromise(); 1287 } 1288 1289 // Make sure that all coro.save, coro.suspend and the fallthrough coro.end 1290 // intrinsics are in their own blocks to simplify the logic of building up 1291 // SuspendCrossing data. 1292 for (auto *CSI : Shape.CoroSuspends) { 1293 if (auto *Save = CSI->getCoroSave()) 1294 splitAround(Save, "CoroSave"); 1295 splitAround(CSI, "CoroSuspend"); 1296 } 1297 1298 // Put CoroEnds into their own blocks. 1299 for (CoroEndInst *CE : Shape.CoroEnds) 1300 splitAround(CE, "CoroEnd"); 1301 1302 // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will 1303 // never has its definition separated from the PHI by the suspend point. 1304 rewritePHIs(F); 1305 1306 // Build suspend crossing info. 1307 SuspendCrossingInfo Checker(F, Shape); 1308 1309 IRBuilder<> Builder(F.getContext()); 1310 SpillInfo Spills; 1311 SmallVector<CoroAllocaAllocInst*, 4> LocalAllocas; 1312 SmallVector<Instruction*, 4> DeadInstructions; 1313 1314 for (int Repeat = 0; Repeat < 4; ++Repeat) { 1315 // See if there are materializable instructions across suspend points. 1316 for (Instruction &I : instructions(F)) 1317 if (materializable(I)) 1318 for (User *U : I.users()) 1319 if (Checker.isDefinitionAcrossSuspend(I, U)) 1320 Spills.emplace_back(&I, U); 1321 1322 if (Spills.empty()) 1323 break; 1324 1325 // Rewrite materializable instructions to be materialized at the use point. 1326 LLVM_DEBUG(dump("Materializations", Spills)); 1327 rewriteMaterializableInstructions(Builder, Spills); 1328 Spills.clear(); 1329 } 1330 1331 // Collect the spills for arguments and other not-materializable values. 1332 for (Argument &A : F.args()) 1333 for (User *U : A.users()) 1334 if (Checker.isDefinitionAcrossSuspend(A, U)) 1335 Spills.emplace_back(&A, U); 1336 1337 for (Instruction &I : instructions(F)) { 1338 // Values returned from coroutine structure intrinsics should not be part 1339 // of the Coroutine Frame. 1340 if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin) 1341 continue; 1342 1343 // The Coroutine Promise always included into coroutine frame, no need to 1344 // check for suspend crossing. 1345 if (Shape.ABI == coro::ABI::Switch && 1346 Shape.SwitchLowering.PromiseAlloca == &I) 1347 continue; 1348 1349 // Handle alloca.alloc specially here. 1350 if (auto AI = dyn_cast<CoroAllocaAllocInst>(&I)) { 1351 // Check whether the alloca's lifetime is bounded by suspend points. 1352 if (isLocalAlloca(AI)) { 1353 LocalAllocas.push_back(AI); 1354 continue; 1355 } 1356 1357 // If not, do a quick rewrite of the alloca and then add spills of 1358 // the rewritten value. The rewrite doesn't invalidate anything in 1359 // Spills because the other alloca intrinsics have no other operands 1360 // besides AI, and it doesn't invalidate the iteration because we delay 1361 // erasing AI. 1362 auto Alloc = lowerNonLocalAlloca(AI, Shape, DeadInstructions); 1363 1364 for (User *U : Alloc->users()) { 1365 if (Checker.isDefinitionAcrossSuspend(*Alloc, U)) 1366 Spills.emplace_back(Alloc, U); 1367 } 1368 continue; 1369 } 1370 1371 // Ignore alloca.get; we process this as part of coro.alloca.alloc. 1372 if (isa<CoroAllocaGetInst>(I)) { 1373 continue; 1374 } 1375 1376 for (User *U : I.users()) 1377 if (Checker.isDefinitionAcrossSuspend(I, U)) { 1378 // We cannot spill a token. 1379 if (I.getType()->isTokenTy()) 1380 report_fatal_error( 1381 "token definition is separated from the use by a suspend point"); 1382 Spills.emplace_back(&I, U); 1383 } 1384 } 1385 LLVM_DEBUG(dump("Spills", Spills)); 1386 moveSpillUsesAfterCoroBegin(F, Spills, Shape.CoroBegin); 1387 Shape.FrameTy = buildFrameType(F, Shape, Spills); 1388 Shape.FramePtr = insertSpills(Spills, Shape); 1389 lowerLocalAllocas(LocalAllocas, DeadInstructions); 1390 1391 for (auto I : DeadInstructions) 1392 I->eraseFromParent(); 1393 } 1394