1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// 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 defines common loop utility functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Utils/LoopUtils.h" 14 #include "llvm/ADT/DenseSet.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/PriorityWorklist.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/BasicAliasAnalysis.h" 23 #include "llvm/Analysis/DomTreeUpdater.h" 24 #include "llvm/Analysis/GlobalsModRef.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/LoopAccessAnalysis.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/Analysis/LoopPass.h" 29 #include "llvm/Analysis/MemorySSA.h" 30 #include "llvm/Analysis/MemorySSAUpdater.h" 31 #include "llvm/Analysis/MustExecute.h" 32 #include "llvm/Analysis/ScalarEvolution.h" 33 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 34 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 35 #include "llvm/Analysis/TargetTransformInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/IR/DIBuilder.h" 38 #include "llvm/IR/Dominators.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/MDBuilder.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/IR/Operator.h" 44 #include "llvm/IR/PatternMatch.h" 45 #include "llvm/IR/ValueHandle.h" 46 #include "llvm/InitializePasses.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/KnownBits.h" 50 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 51 #include "llvm/Transforms/Utils/Local.h" 52 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 53 54 using namespace llvm; 55 using namespace llvm::PatternMatch; 56 57 static cl::opt<bool> ForceReductionIntrinsic( 58 "force-reduction-intrinsics", cl::Hidden, 59 cl::desc("Force creating reduction intrinsics for testing."), 60 cl::init(false)); 61 62 #define DEBUG_TYPE "loop-utils" 63 64 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 65 static const char *LLVMLoopDisableLICM = "llvm.licm.disable"; 66 67 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 68 MemorySSAUpdater *MSSAU, 69 bool PreserveLCSSA) { 70 bool Changed = false; 71 72 // We re-use a vector for the in-loop predecesosrs. 73 SmallVector<BasicBlock *, 4> InLoopPredecessors; 74 75 auto RewriteExit = [&](BasicBlock *BB) { 76 assert(InLoopPredecessors.empty() && 77 "Must start with an empty predecessors list!"); 78 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 79 80 // See if there are any non-loop predecessors of this exit block and 81 // keep track of the in-loop predecessors. 82 bool IsDedicatedExit = true; 83 for (auto *PredBB : predecessors(BB)) 84 if (L->contains(PredBB)) { 85 if (isa<IndirectBrInst>(PredBB->getTerminator())) 86 // We cannot rewrite exiting edges from an indirectbr. 87 return false; 88 if (isa<CallBrInst>(PredBB->getTerminator())) 89 // We cannot rewrite exiting edges from a callbr. 90 return false; 91 92 InLoopPredecessors.push_back(PredBB); 93 } else { 94 IsDedicatedExit = false; 95 } 96 97 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!"); 98 99 // Nothing to do if this is already a dedicated exit. 100 if (IsDedicatedExit) 101 return false; 102 103 auto *NewExitBB = SplitBlockPredecessors( 104 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA); 105 106 if (!NewExitBB) 107 LLVM_DEBUG( 108 dbgs() << "WARNING: Can't create a dedicated exit block for loop: " 109 << *L << "\n"); 110 else 111 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 112 << NewExitBB->getName() << "\n"); 113 return true; 114 }; 115 116 // Walk the exit blocks directly rather than building up a data structure for 117 // them, but only visit each one once. 118 SmallPtrSet<BasicBlock *, 4> Visited; 119 for (auto *BB : L->blocks()) 120 for (auto *SuccBB : successors(BB)) { 121 // We're looking for exit blocks so skip in-loop successors. 122 if (L->contains(SuccBB)) 123 continue; 124 125 // Visit each exit block exactly once. 126 if (!Visited.insert(SuccBB).second) 127 continue; 128 129 Changed |= RewriteExit(SuccBB); 130 } 131 132 return Changed; 133 } 134 135 /// Returns the instructions that use values defined in the loop. 136 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 137 SmallVector<Instruction *, 8> UsedOutside; 138 139 for (auto *Block : L->getBlocks()) 140 // FIXME: I believe that this could use copy_if if the Inst reference could 141 // be adapted into a pointer. 142 for (auto &Inst : *Block) { 143 auto Users = Inst.users(); 144 if (any_of(Users, [&](User *U) { 145 auto *Use = cast<Instruction>(U); 146 return !L->contains(Use->getParent()); 147 })) 148 UsedOutside.push_back(&Inst); 149 } 150 151 return UsedOutside; 152 } 153 154 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 155 // By definition, all loop passes need the LoopInfo analysis and the 156 // Dominator tree it depends on. Because they all participate in the loop 157 // pass manager, they must also preserve these. 158 AU.addRequired<DominatorTreeWrapperPass>(); 159 AU.addPreserved<DominatorTreeWrapperPass>(); 160 AU.addRequired<LoopInfoWrapperPass>(); 161 AU.addPreserved<LoopInfoWrapperPass>(); 162 163 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 164 // here because users shouldn't directly get them from this header. 165 extern char &LoopSimplifyID; 166 extern char &LCSSAID; 167 AU.addRequiredID(LoopSimplifyID); 168 AU.addPreservedID(LoopSimplifyID); 169 AU.addRequiredID(LCSSAID); 170 AU.addPreservedID(LCSSAID); 171 // This is used in the LPPassManager to perform LCSSA verification on passes 172 // which preserve lcssa form 173 AU.addRequired<LCSSAVerificationPass>(); 174 AU.addPreserved<LCSSAVerificationPass>(); 175 176 // Loop passes are designed to run inside of a loop pass manager which means 177 // that any function analyses they require must be required by the first loop 178 // pass in the manager (so that it is computed before the loop pass manager 179 // runs) and preserved by all loop pasess in the manager. To make this 180 // reasonably robust, the set needed for most loop passes is maintained here. 181 // If your loop pass requires an analysis not listed here, you will need to 182 // carefully audit the loop pass manager nesting structure that results. 183 AU.addRequired<AAResultsWrapperPass>(); 184 AU.addPreserved<AAResultsWrapperPass>(); 185 AU.addPreserved<BasicAAWrapperPass>(); 186 AU.addPreserved<GlobalsAAWrapperPass>(); 187 AU.addPreserved<SCEVAAWrapperPass>(); 188 AU.addRequired<ScalarEvolutionWrapperPass>(); 189 AU.addPreserved<ScalarEvolutionWrapperPass>(); 190 // FIXME: When all loop passes preserve MemorySSA, it can be required and 191 // preserved here instead of the individual handling in each pass. 192 } 193 194 /// Manually defined generic "LoopPass" dependency initialization. This is used 195 /// to initialize the exact set of passes from above in \c 196 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 197 /// with: 198 /// 199 /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 200 /// 201 /// As-if "LoopPass" were a pass. 202 void llvm::initializeLoopPassPass(PassRegistry &Registry) { 203 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 204 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 205 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 206 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 207 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 208 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 209 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 210 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 211 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 212 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 213 } 214 215 /// Create MDNode for input string. 216 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) { 217 LLVMContext &Context = TheLoop->getHeader()->getContext(); 218 Metadata *MDs[] = { 219 MDString::get(Context, Name), 220 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))}; 221 return MDNode::get(Context, MDs); 222 } 223 224 /// Set input string into loop metadata by keeping other values intact. 225 /// If the string is already in loop metadata update value if it is 226 /// different. 227 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD, 228 unsigned V) { 229 SmallVector<Metadata *, 4> MDs(1); 230 // If the loop already has metadata, retain it. 231 MDNode *LoopID = TheLoop->getLoopID(); 232 if (LoopID) { 233 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 234 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 235 // If it is of form key = value, try to parse it. 236 if (Node->getNumOperands() == 2) { 237 MDString *S = dyn_cast<MDString>(Node->getOperand(0)); 238 if (S && S->getString().equals(StringMD)) { 239 ConstantInt *IntMD = 240 mdconst::extract_or_null<ConstantInt>(Node->getOperand(1)); 241 if (IntMD && IntMD->getSExtValue() == V) 242 // It is already in place. Do nothing. 243 return; 244 // We need to update the value, so just skip it here and it will 245 // be added after copying other existed nodes. 246 continue; 247 } 248 } 249 MDs.push_back(Node); 250 } 251 } 252 // Add new metadata. 253 MDs.push_back(createStringMetadata(TheLoop, StringMD, V)); 254 // Replace current metadata node with new one. 255 LLVMContext &Context = TheLoop->getHeader()->getContext(); 256 MDNode *NewLoopID = MDNode::get(Context, MDs); 257 // Set operand 0 to refer to the loop id itself. 258 NewLoopID->replaceOperandWith(0, NewLoopID); 259 TheLoop->setLoopID(NewLoopID); 260 } 261 262 /// Find string metadata for loop 263 /// 264 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 265 /// operand or null otherwise. If the string metadata is not found return 266 /// Optional's not-a-value. 267 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, 268 StringRef Name) { 269 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 270 if (!MD) 271 return None; 272 switch (MD->getNumOperands()) { 273 case 1: 274 return nullptr; 275 case 2: 276 return &MD->getOperand(1); 277 default: 278 llvm_unreachable("loop metadata has 0 or 1 operand"); 279 } 280 } 281 282 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, 283 StringRef Name) { 284 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 285 if (!MD) 286 return None; 287 switch (MD->getNumOperands()) { 288 case 1: 289 // When the value is absent it is interpreted as 'attribute set'. 290 return true; 291 case 2: 292 if (ConstantInt *IntMD = 293 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) 294 return IntMD->getZExtValue(); 295 return true; 296 } 297 llvm_unreachable("unexpected number of options"); 298 } 299 300 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 301 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 302 } 303 304 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 305 StringRef Name) { 306 const MDOperand *AttrMD = 307 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 308 if (!AttrMD) 309 return None; 310 311 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 312 if (!IntMD) 313 return None; 314 315 return IntMD->getSExtValue(); 316 } 317 318 Optional<MDNode *> llvm::makeFollowupLoopID( 319 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 320 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 321 if (!OrigLoopID) { 322 if (AlwaysNew) 323 return nullptr; 324 return None; 325 } 326 327 assert(OrigLoopID->getOperand(0) == OrigLoopID); 328 329 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 330 bool InheritSomeAttrs = 331 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 332 SmallVector<Metadata *, 8> MDs; 333 MDs.push_back(nullptr); 334 335 bool Changed = false; 336 if (InheritAllAttrs || InheritSomeAttrs) { 337 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 338 MDNode *Op = cast<MDNode>(Existing.get()); 339 340 auto InheritThisAttribute = [InheritSomeAttrs, 341 InheritOptionsExceptPrefix](MDNode *Op) { 342 if (!InheritSomeAttrs) 343 return false; 344 345 // Skip malformatted attribute metadata nodes. 346 if (Op->getNumOperands() == 0) 347 return true; 348 Metadata *NameMD = Op->getOperand(0).get(); 349 if (!isa<MDString>(NameMD)) 350 return true; 351 StringRef AttrName = cast<MDString>(NameMD)->getString(); 352 353 // Do not inherit excluded attributes. 354 return !AttrName.startswith(InheritOptionsExceptPrefix); 355 }; 356 357 if (InheritThisAttribute(Op)) 358 MDs.push_back(Op); 359 else 360 Changed = true; 361 } 362 } else { 363 // Modified if we dropped at least one attribute. 364 Changed = OrigLoopID->getNumOperands() > 1; 365 } 366 367 bool HasAnyFollowup = false; 368 for (StringRef OptionName : FollowupOptions) { 369 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 370 if (!FollowupNode) 371 continue; 372 373 HasAnyFollowup = true; 374 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 375 MDs.push_back(Option.get()); 376 Changed = true; 377 } 378 } 379 380 // Attributes of the followup loop not specified explicity, so signal to the 381 // transformation pass to add suitable attributes. 382 if (!AlwaysNew && !HasAnyFollowup) 383 return None; 384 385 // If no attributes were added or remove, the previous loop Id can be reused. 386 if (!AlwaysNew && !Changed) 387 return OrigLoopID; 388 389 // No attributes is equivalent to having no !llvm.loop metadata at all. 390 if (MDs.size() == 1) 391 return nullptr; 392 393 // Build the new loop ID. 394 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 395 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 396 return FollowupLoopID; 397 } 398 399 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 400 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 401 } 402 403 bool llvm::hasDisableLICMTransformsHint(const Loop *L) { 404 return getBooleanLoopAttribute(L, LLVMLoopDisableLICM); 405 } 406 407 TransformationMode llvm::hasUnrollTransformation(Loop *L) { 408 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 409 return TM_SuppressedByUser; 410 411 Optional<int> Count = 412 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 413 if (Count.hasValue()) 414 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 415 416 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 417 return TM_ForcedByUser; 418 419 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 420 return TM_ForcedByUser; 421 422 if (hasDisableAllTransformsHint(L)) 423 return TM_Disable; 424 425 return TM_Unspecified; 426 } 427 428 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 429 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 430 return TM_SuppressedByUser; 431 432 Optional<int> Count = 433 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 434 if (Count.hasValue()) 435 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 436 437 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 438 return TM_ForcedByUser; 439 440 if (hasDisableAllTransformsHint(L)) 441 return TM_Disable; 442 443 return TM_Unspecified; 444 } 445 446 TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 447 Optional<bool> Enable = 448 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 449 450 if (Enable == false) 451 return TM_SuppressedByUser; 452 453 Optional<int> VectorizeWidth = 454 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 455 Optional<int> InterleaveCount = 456 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 457 458 // 'Forcing' vector width and interleave count to one effectively disables 459 // this tranformation. 460 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1) 461 return TM_SuppressedByUser; 462 463 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 464 return TM_Disable; 465 466 if (Enable == true) 467 return TM_ForcedByUser; 468 469 if (VectorizeWidth == 1 && InterleaveCount == 1) 470 return TM_Disable; 471 472 if (VectorizeWidth > 1 || InterleaveCount > 1) 473 return TM_Enable; 474 475 if (hasDisableAllTransformsHint(L)) 476 return TM_Disable; 477 478 return TM_Unspecified; 479 } 480 481 TransformationMode llvm::hasDistributeTransformation(Loop *L) { 482 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 483 return TM_ForcedByUser; 484 485 if (hasDisableAllTransformsHint(L)) 486 return TM_Disable; 487 488 return TM_Unspecified; 489 } 490 491 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 492 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 493 return TM_SuppressedByUser; 494 495 if (hasDisableAllTransformsHint(L)) 496 return TM_Disable; 497 498 return TM_Unspecified; 499 } 500 501 /// Does a BFS from a given node to all of its children inside a given loop. 502 /// The returned vector of nodes includes the starting point. 503 SmallVector<DomTreeNode *, 16> 504 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 505 SmallVector<DomTreeNode *, 16> Worklist; 506 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 507 // Only include subregions in the top level loop. 508 BasicBlock *BB = DTN->getBlock(); 509 if (CurLoop->contains(BB)) 510 Worklist.push_back(DTN); 511 }; 512 513 AddRegionToWorklist(N); 514 515 for (size_t I = 0; I < Worklist.size(); I++) { 516 for (DomTreeNode *Child : Worklist[I]->children()) 517 AddRegionToWorklist(Child); 518 } 519 520 return Worklist; 521 } 522 523 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, 524 LoopInfo *LI, MemorySSA *MSSA) { 525 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 526 auto *Preheader = L->getLoopPreheader(); 527 assert(Preheader && "Preheader should exist!"); 528 529 std::unique_ptr<MemorySSAUpdater> MSSAU; 530 if (MSSA) 531 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 532 533 // Now that we know the removal is safe, remove the loop by changing the 534 // branch from the preheader to go to the single exit block. 535 // 536 // Because we're deleting a large chunk of code at once, the sequence in which 537 // we remove things is very important to avoid invalidation issues. 538 539 // Tell ScalarEvolution that the loop is deleted. Do this before 540 // deleting the loop so that ScalarEvolution can look at the loop 541 // to determine what it needs to clean up. 542 if (SE) 543 SE->forgetLoop(L); 544 545 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 546 assert(OldBr && "Preheader must end with a branch"); 547 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 548 // Connect the preheader to the exit block. Keep the old edge to the header 549 // around to perform the dominator tree update in two separate steps 550 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 551 // preheader -> header. 552 // 553 // 554 // 0. Preheader 1. Preheader 2. Preheader 555 // | | | | 556 // V | V | 557 // Header <--\ | Header <--\ | Header <--\ 558 // | | | | | | | | | | | 559 // | V | | | V | | | V | 560 // | Body --/ | | Body --/ | | Body --/ 561 // V V V V V 562 // Exit Exit Exit 563 // 564 // By doing this is two separate steps we can perform the dominator tree 565 // update without using the batch update API. 566 // 567 // Even when the loop is never executed, we cannot remove the edge from the 568 // source block to the exit block. Consider the case where the unexecuted loop 569 // branches back to an outer loop. If we deleted the loop and removed the edge 570 // coming to this inner loop, this will break the outer loop structure (by 571 // deleting the backedge of the outer loop). If the outer loop is indeed a 572 // non-loop, it will be deleted in a future iteration of loop deletion pass. 573 IRBuilder<> Builder(OldBr); 574 575 auto *ExitBlock = L->getUniqueExitBlock(); 576 if (ExitBlock) { 577 assert(ExitBlock && "Should have a unique exit block!"); 578 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 579 580 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 581 // Remove the old branch. The conditional branch becomes a new terminator. 582 OldBr->eraseFromParent(); 583 584 // Rewrite phis in the exit block to get their inputs from the Preheader 585 // instead of the exiting block. 586 for (PHINode &P : ExitBlock->phis()) { 587 // Set the zero'th element of Phi to be from the preheader and remove all 588 // other incoming values. Given the loop has dedicated exits, all other 589 // incoming values must be from the exiting blocks. 590 int PredIndex = 0; 591 P.setIncomingBlock(PredIndex, Preheader); 592 // Removes all incoming values from all other exiting blocks (including 593 // duplicate values from an exiting block). 594 // Nuke all entries except the zero'th entry which is the preheader entry. 595 // NOTE! We need to remove Incoming Values in the reverse order as done 596 // below, to keep the indices valid for deletion (removeIncomingValues 597 // updates getNumIncomingValues and shifts all values down into the 598 // operand being deleted). 599 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 600 P.removeIncomingValue(e - i, false); 601 602 assert((P.getNumIncomingValues() == 1 && 603 P.getIncomingBlock(PredIndex) == Preheader) && 604 "Should have exactly one value and that's from the preheader!"); 605 } 606 607 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 608 if (DT) { 609 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}); 610 if (MSSA) { 611 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, 612 *DT); 613 if (VerifyMemorySSA) 614 MSSA->verifyMemorySSA(); 615 } 616 } 617 618 // Disconnect the loop body by branching directly to its exit. 619 Builder.SetInsertPoint(Preheader->getTerminator()); 620 Builder.CreateBr(ExitBlock); 621 // Remove the old branch. 622 Preheader->getTerminator()->eraseFromParent(); 623 624 if (DT) { 625 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}); 626 if (MSSA) { 627 MSSAU->applyUpdates( 628 {{DominatorTree::Delete, Preheader, L->getHeader()}}, *DT); 629 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(), 630 L->block_end()); 631 MSSAU->removeBlocks(DeadBlockSet); 632 if (VerifyMemorySSA) 633 MSSA->verifyMemorySSA(); 634 } 635 } 636 } else { 637 assert(L->hasNoExitBlocks() && 638 "Loop should have either zero or one exit blocks."); 639 Builder.SetInsertPoint(OldBr); 640 Builder.CreateUnreachable(); 641 Preheader->getTerminator()->eraseFromParent(); 642 } 643 644 // Use a map to unique and a vector to guarantee deterministic ordering. 645 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 646 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 647 648 if (ExitBlock) { 649 // Given LCSSA form is satisfied, we should not have users of instructions 650 // within the dead loop outside of the loop. However, LCSSA doesn't take 651 // unreachable uses into account. We handle them here. 652 // We could do it after drop all references (in this case all users in the 653 // loop will be already eliminated and we have less work to do but according 654 // to API doc of User::dropAllReferences only valid operation after dropping 655 // references, is deletion. So let's substitute all usages of 656 // instruction from the loop with undef value of corresponding type first. 657 for (auto *Block : L->blocks()) 658 for (Instruction &I : *Block) { 659 auto *Undef = UndefValue::get(I.getType()); 660 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); 661 UI != E;) { 662 Use &U = *UI; 663 ++UI; 664 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 665 if (L->contains(Usr->getParent())) 666 continue; 667 // If we have a DT then we can check that uses outside a loop only in 668 // unreachable block. 669 if (DT) 670 assert(!DT->isReachableFromEntry(U) && 671 "Unexpected user in reachable block"); 672 U.set(Undef); 673 } 674 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 675 if (!DVI) 676 continue; 677 auto Key = 678 DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 679 if (Key != DeadDebugSet.end()) 680 continue; 681 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 682 DeadDebugInst.push_back(DVI); 683 } 684 685 // After the loop has been deleted all the values defined and modified 686 // inside the loop are going to be unavailable. 687 // Since debug values in the loop have been deleted, inserting an undef 688 // dbg.value truncates the range of any dbg.value before the loop where the 689 // loop used to be. This is particularly important for constant values. 690 DIBuilder DIB(*ExitBlock->getModule()); 691 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 692 assert(InsertDbgValueBefore && 693 "There should be a non-PHI instruction in exit block, else these " 694 "instructions will have no parent."); 695 for (auto *DVI : DeadDebugInst) 696 DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), 697 DVI->getVariable(), DVI->getExpression(), 698 DVI->getDebugLoc(), InsertDbgValueBefore); 699 } 700 701 // Remove the block from the reference counting scheme, so that we can 702 // delete it freely later. 703 for (auto *Block : L->blocks()) 704 Block->dropAllReferences(); 705 706 if (MSSA && VerifyMemorySSA) 707 MSSA->verifyMemorySSA(); 708 709 if (LI) { 710 // Erase the instructions and the blocks without having to worry 711 // about ordering because we already dropped the references. 712 // NOTE: This iteration is safe because erasing the block does not remove 713 // its entry from the loop's block list. We do that in the next section. 714 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 715 LpI != LpE; ++LpI) 716 (*LpI)->eraseFromParent(); 717 718 // Finally, the blocks from loopinfo. This has to happen late because 719 // otherwise our loop iterators won't work. 720 721 SmallPtrSet<BasicBlock *, 8> blocks; 722 blocks.insert(L->block_begin(), L->block_end()); 723 for (BasicBlock *BB : blocks) 724 LI->removeBlock(BB); 725 726 // The last step is to update LoopInfo now that we've eliminated this loop. 727 // Note: LoopInfo::erase remove the given loop and relink its subloops with 728 // its parent. While removeLoop/removeChildLoop remove the given loop but 729 // not relink its subloops, which is what we want. 730 if (Loop *ParentLoop = L->getParentLoop()) { 731 Loop::iterator I = find(*ParentLoop, L); 732 assert(I != ParentLoop->end() && "Couldn't find loop"); 733 ParentLoop->removeChildLoop(I); 734 } else { 735 Loop::iterator I = find(*LI, L); 736 assert(I != LI->end() && "Couldn't find loop"); 737 LI->removeLoop(I); 738 } 739 LI->destroy(L); 740 } 741 } 742 743 /// Checks if \p L has single exit through latch block except possibly 744 /// "deoptimizing" exits. Returns branch instruction terminating the loop 745 /// latch if above check is successful, nullptr otherwise. 746 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { 747 BasicBlock *Latch = L->getLoopLatch(); 748 if (!Latch) 749 return nullptr; 750 751 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 752 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 753 return nullptr; 754 755 assert((LatchBR->getSuccessor(0) == L->getHeader() || 756 LatchBR->getSuccessor(1) == L->getHeader()) && 757 "At least one edge out of the latch must go to the header"); 758 759 SmallVector<BasicBlock *, 4> ExitBlocks; 760 L->getUniqueNonLatchExitBlocks(ExitBlocks); 761 if (any_of(ExitBlocks, [](const BasicBlock *EB) { 762 return !EB->getTerminatingDeoptimizeCall(); 763 })) 764 return nullptr; 765 766 return LatchBR; 767 } 768 769 Optional<unsigned> 770 llvm::getLoopEstimatedTripCount(Loop *L, 771 unsigned *EstimatedLoopInvocationWeight) { 772 // Support loops with an exiting latch and other existing exists only 773 // deoptimize. 774 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 775 if (!LatchBranch) 776 return None; 777 778 // To estimate the number of times the loop body was executed, we want to 779 // know the number of times the backedge was taken, vs. the number of times 780 // we exited the loop. 781 uint64_t BackedgeTakenWeight, LatchExitWeight; 782 if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight)) 783 return None; 784 785 if (LatchBranch->getSuccessor(0) != L->getHeader()) 786 std::swap(BackedgeTakenWeight, LatchExitWeight); 787 788 if (!LatchExitWeight) 789 return None; 790 791 if (EstimatedLoopInvocationWeight) 792 *EstimatedLoopInvocationWeight = LatchExitWeight; 793 794 // Estimated backedge taken count is a ratio of the backedge taken weight by 795 // the weight of the edge exiting the loop, rounded to nearest. 796 uint64_t BackedgeTakenCount = 797 llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight); 798 // Estimated trip count is one plus estimated backedge taken count. 799 return BackedgeTakenCount + 1; 800 } 801 802 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, 803 unsigned EstimatedloopInvocationWeight) { 804 // Support loops with an exiting latch and other existing exists only 805 // deoptimize. 806 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 807 if (!LatchBranch) 808 return false; 809 810 // Calculate taken and exit weights. 811 unsigned LatchExitWeight = 0; 812 unsigned BackedgeTakenWeight = 0; 813 814 if (EstimatedTripCount > 0) { 815 LatchExitWeight = EstimatedloopInvocationWeight; 816 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight; 817 } 818 819 // Make a swap if back edge is taken when condition is "false". 820 if (LatchBranch->getSuccessor(0) != L->getHeader()) 821 std::swap(BackedgeTakenWeight, LatchExitWeight); 822 823 MDBuilder MDB(LatchBranch->getContext()); 824 825 // Set/Update profile metadata. 826 LatchBranch->setMetadata( 827 LLVMContext::MD_prof, 828 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight)); 829 830 return true; 831 } 832 833 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 834 ScalarEvolution &SE) { 835 Loop *OuterL = InnerLoop->getParentLoop(); 836 if (!OuterL) 837 return true; 838 839 // Get the backedge taken count for the inner loop 840 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 841 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 842 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 843 !InnerLoopBECountSC->getType()->isIntegerTy()) 844 return false; 845 846 // Get whether count is invariant to the outer loop 847 ScalarEvolution::LoopDisposition LD = 848 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 849 if (LD != ScalarEvolution::LoopInvariant) 850 return false; 851 852 return true; 853 } 854 855 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, 856 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 857 Value *Left, Value *Right) { 858 CmpInst::Predicate P = CmpInst::ICMP_NE; 859 switch (RK) { 860 default: 861 llvm_unreachable("Unknown min/max recurrence kind"); 862 case RecurrenceDescriptor::MRK_UIntMin: 863 P = CmpInst::ICMP_ULT; 864 break; 865 case RecurrenceDescriptor::MRK_UIntMax: 866 P = CmpInst::ICMP_UGT; 867 break; 868 case RecurrenceDescriptor::MRK_SIntMin: 869 P = CmpInst::ICMP_SLT; 870 break; 871 case RecurrenceDescriptor::MRK_SIntMax: 872 P = CmpInst::ICMP_SGT; 873 break; 874 case RecurrenceDescriptor::MRK_FloatMin: 875 P = CmpInst::FCMP_OLT; 876 break; 877 case RecurrenceDescriptor::MRK_FloatMax: 878 P = CmpInst::FCMP_OGT; 879 break; 880 } 881 882 // We only match FP sequences that are 'fast', so we can unconditionally 883 // set it on any generated instructions. 884 IRBuilderBase::FastMathFlagGuard FMFG(Builder); 885 FastMathFlags FMF; 886 FMF.setFast(); 887 Builder.setFastMathFlags(FMF); 888 Value *Cmp = Builder.CreateCmp(P, Left, Right, "rdx.minmax.cmp"); 889 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 890 return Select; 891 } 892 893 // Helper to generate an ordered reduction. 894 Value * 895 llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, 896 unsigned Op, 897 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 898 ArrayRef<Value *> RedOps) { 899 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 900 901 // Extract and apply reduction ops in ascending order: 902 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 903 Value *Result = Acc; 904 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 905 Value *Ext = 906 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 907 908 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 909 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 910 "bin.rdx"); 911 } else { 912 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 913 "Invalid min/max"); 914 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 915 } 916 917 if (!RedOps.empty()) 918 propagateIRFlags(Result, RedOps); 919 } 920 921 return Result; 922 } 923 924 // Helper to generate a log2 shuffle reduction. 925 Value * 926 llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, 927 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 928 ArrayRef<Value *> RedOps) { 929 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 930 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 931 // and vector ops, reducing the set of values being computed by half each 932 // round. 933 assert(isPowerOf2_32(VF) && 934 "Reduction emission only supported for pow2 vectors!"); 935 Value *TmpVec = Src; 936 SmallVector<int, 32> ShuffleMask(VF); 937 for (unsigned i = VF; i != 1; i >>= 1) { 938 // Move the upper half of the vector to the lower half. 939 for (unsigned j = 0; j != i / 2; ++j) 940 ShuffleMask[j] = i / 2 + j; 941 942 // Fill the rest of the mask with undef. 943 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1); 944 945 Value *Shuf = Builder.CreateShuffleVector( 946 TmpVec, UndefValue::get(TmpVec->getType()), ShuffleMask, "rdx.shuf"); 947 948 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 949 // The builder propagates its fast-math-flags setting. 950 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 951 "bin.rdx"); 952 } else { 953 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 954 "Invalid min/max"); 955 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 956 } 957 if (!RedOps.empty()) 958 propagateIRFlags(TmpVec, RedOps); 959 960 // We may compute the reassociated scalar ops in a way that does not 961 // preserve nsw/nuw etc. Conservatively, drop those flags. 962 if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec)) 963 ReductionInst->dropPoisonGeneratingFlags(); 964 } 965 // The result is in the first element of the vector. 966 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 967 } 968 969 /// Create a simple vector reduction specified by an opcode and some 970 /// flags (if generating min/max reductions). 971 Value *llvm::createSimpleTargetReduction( 972 IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 973 Value *Src, TargetTransformInfo::ReductionFlags Flags, 974 ArrayRef<Value *> RedOps) { 975 auto *SrcVTy = cast<VectorType>(Src->getType()); 976 977 std::function<Value *()> BuildFunc; 978 using RD = RecurrenceDescriptor; 979 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 980 981 switch (Opcode) { 982 case Instruction::Add: 983 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 984 break; 985 case Instruction::Mul: 986 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 987 break; 988 case Instruction::And: 989 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 990 break; 991 case Instruction::Or: 992 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 993 break; 994 case Instruction::Xor: 995 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 996 break; 997 case Instruction::FAdd: 998 BuildFunc = [&]() { 999 auto Rdx = Builder.CreateFAddReduce( 1000 ConstantFP::getNegativeZero(SrcVTy->getElementType()), Src); 1001 return Rdx; 1002 }; 1003 break; 1004 case Instruction::FMul: 1005 BuildFunc = [&]() { 1006 Type *Ty = SrcVTy->getElementType(); 1007 auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); 1008 return Rdx; 1009 }; 1010 break; 1011 case Instruction::ICmp: 1012 if (Flags.IsMaxOp) { 1013 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 1014 BuildFunc = [&]() { 1015 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 1016 }; 1017 } else { 1018 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 1019 BuildFunc = [&]() { 1020 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 1021 }; 1022 } 1023 break; 1024 case Instruction::FCmp: 1025 if (Flags.IsMaxOp) { 1026 MinMaxKind = RD::MRK_FloatMax; 1027 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 1028 } else { 1029 MinMaxKind = RD::MRK_FloatMin; 1030 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 1031 } 1032 break; 1033 default: 1034 llvm_unreachable("Unhandled opcode"); 1035 break; 1036 } 1037 if (ForceReductionIntrinsic || 1038 TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 1039 return BuildFunc(); 1040 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 1041 } 1042 1043 /// Create a vector reduction using a given recurrence descriptor. 1044 Value *llvm::createTargetReduction(IRBuilderBase &B, 1045 const TargetTransformInfo *TTI, 1046 RecurrenceDescriptor &Desc, Value *Src, 1047 bool NoNaN) { 1048 // TODO: Support in-order reductions based on the recurrence descriptor. 1049 using RD = RecurrenceDescriptor; 1050 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 1051 TargetTransformInfo::ReductionFlags Flags; 1052 Flags.NoNaN = NoNaN; 1053 1054 // All ops in the reduction inherit fast-math-flags from the recurrence 1055 // descriptor. 1056 IRBuilderBase::FastMathFlagGuard FMFGuard(B); 1057 B.setFastMathFlags(Desc.getFastMathFlags()); 1058 1059 switch (RecKind) { 1060 case RD::RK_FloatAdd: 1061 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 1062 case RD::RK_FloatMult: 1063 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 1064 case RD::RK_IntegerAdd: 1065 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 1066 case RD::RK_IntegerMult: 1067 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 1068 case RD::RK_IntegerAnd: 1069 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 1070 case RD::RK_IntegerOr: 1071 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 1072 case RD::RK_IntegerXor: 1073 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 1074 case RD::RK_IntegerMinMax: { 1075 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 1076 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 1077 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 1078 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 1079 } 1080 case RD::RK_FloatMinMax: { 1081 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 1082 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 1083 } 1084 default: 1085 llvm_unreachable("Unhandled RecKind"); 1086 } 1087 } 1088 1089 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 1090 auto *VecOp = dyn_cast<Instruction>(I); 1091 if (!VecOp) 1092 return; 1093 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 1094 : dyn_cast<Instruction>(OpValue); 1095 if (!Intersection) 1096 return; 1097 const unsigned Opcode = Intersection->getOpcode(); 1098 VecOp->copyIRFlags(Intersection); 1099 for (auto *V : VL) { 1100 auto *Instr = dyn_cast<Instruction>(V); 1101 if (!Instr) 1102 continue; 1103 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1104 VecOp->andIRFlags(V); 1105 } 1106 } 1107 1108 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1109 ScalarEvolution &SE) { 1110 const SCEV *Zero = SE.getZero(S->getType()); 1111 return SE.isAvailableAtLoopEntry(S, L) && 1112 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1113 } 1114 1115 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1116 ScalarEvolution &SE) { 1117 const SCEV *Zero = SE.getZero(S->getType()); 1118 return SE.isAvailableAtLoopEntry(S, L) && 1119 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1120 } 1121 1122 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1123 bool Signed) { 1124 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1125 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1126 APInt::getMinValue(BitWidth); 1127 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1128 return SE.isAvailableAtLoopEntry(S, L) && 1129 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1130 SE.getConstant(Min)); 1131 } 1132 1133 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1134 bool Signed) { 1135 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1136 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1137 APInt::getMaxValue(BitWidth); 1138 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1139 return SE.isAvailableAtLoopEntry(S, L) && 1140 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1141 SE.getConstant(Max)); 1142 } 1143 1144 //===----------------------------------------------------------------------===// 1145 // rewriteLoopExitValues - Optimize IV users outside the loop. 1146 // As a side effect, reduces the amount of IV processing within the loop. 1147 //===----------------------------------------------------------------------===// 1148 1149 // Return true if the SCEV expansion generated by the rewriter can replace the 1150 // original value. SCEV guarantees that it produces the same value, but the way 1151 // it is produced may be illegal IR. Ideally, this function will only be 1152 // called for verification. 1153 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) { 1154 // If an SCEV expression subsumed multiple pointers, its expansion could 1155 // reassociate the GEP changing the base pointer. This is illegal because the 1156 // final address produced by a GEP chain must be inbounds relative to its 1157 // underlying object. Otherwise basic alias analysis, among other things, 1158 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 1159 // producing an expression involving multiple pointers. Until then, we must 1160 // bail out here. 1161 // 1162 // Retrieve the pointer operand of the GEP. Don't use getUnderlyingObject 1163 // because it understands lcssa phis while SCEV does not. 1164 Value *FromPtr = FromVal; 1165 Value *ToPtr = ToVal; 1166 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) 1167 FromPtr = GEP->getPointerOperand(); 1168 1169 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) 1170 ToPtr = GEP->getPointerOperand(); 1171 1172 if (FromPtr != FromVal || ToPtr != ToVal) { 1173 // Quickly check the common case 1174 if (FromPtr == ToPtr) 1175 return true; 1176 1177 // SCEV may have rewritten an expression that produces the GEP's pointer 1178 // operand. That's ok as long as the pointer operand has the same base 1179 // pointer. Unlike getUnderlyingObject(), getPointerBase() will find the 1180 // base of a recurrence. This handles the case in which SCEV expansion 1181 // converts a pointer type recurrence into a nonrecurrent pointer base 1182 // indexed by an integer recurrence. 1183 1184 // If the GEP base pointer is a vector of pointers, abort. 1185 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 1186 return false; 1187 1188 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 1189 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 1190 if (FromBase == ToBase) 1191 return true; 1192 1193 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out " 1194 << *FromBase << " != " << *ToBase << "\n"); 1195 1196 return false; 1197 } 1198 return true; 1199 } 1200 1201 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) { 1202 SmallPtrSet<const Instruction *, 8> Visited; 1203 SmallVector<const Instruction *, 8> WorkList; 1204 Visited.insert(I); 1205 WorkList.push_back(I); 1206 while (!WorkList.empty()) { 1207 const Instruction *Curr = WorkList.pop_back_val(); 1208 // This use is outside the loop, nothing to do. 1209 if (!L->contains(Curr)) 1210 continue; 1211 // Do we assume it is a "hard" use which will not be eliminated easily? 1212 if (Curr->mayHaveSideEffects()) 1213 return true; 1214 // Otherwise, add all its users to worklist. 1215 for (auto U : Curr->users()) { 1216 auto *UI = cast<Instruction>(U); 1217 if (Visited.insert(UI).second) 1218 WorkList.push_back(UI); 1219 } 1220 } 1221 return false; 1222 } 1223 1224 // Collect information about PHI nodes which can be transformed in 1225 // rewriteLoopExitValues. 1226 struct RewritePhi { 1227 PHINode *PN; // For which PHI node is this replacement? 1228 unsigned Ith; // For which incoming value? 1229 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting. 1230 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV? 1231 bool HighCost; // Is this expansion a high-cost? 1232 1233 Value *Expansion = nullptr; 1234 bool ValidRewrite = false; 1235 1236 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt, 1237 bool H) 1238 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt), 1239 HighCost(H) {} 1240 }; 1241 1242 // Check whether it is possible to delete the loop after rewriting exit 1243 // value. If it is possible, ignore ReplaceExitValue and do rewriting 1244 // aggressively. 1245 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 1246 BasicBlock *Preheader = L->getLoopPreheader(); 1247 // If there is no preheader, the loop will not be deleted. 1248 if (!Preheader) 1249 return false; 1250 1251 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 1252 // We obviate multiple ExitingBlocks case for simplicity. 1253 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 1254 // after exit value rewriting, we can enhance the logic here. 1255 SmallVector<BasicBlock *, 4> ExitingBlocks; 1256 L->getExitingBlocks(ExitingBlocks); 1257 SmallVector<BasicBlock *, 8> ExitBlocks; 1258 L->getUniqueExitBlocks(ExitBlocks); 1259 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1) 1260 return false; 1261 1262 BasicBlock *ExitBlock = ExitBlocks[0]; 1263 BasicBlock::iterator BI = ExitBlock->begin(); 1264 while (PHINode *P = dyn_cast<PHINode>(BI)) { 1265 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 1266 1267 // If the Incoming value of P is found in RewritePhiSet, we know it 1268 // could be rewritten to use a loop invariant value in transformation 1269 // phase later. Skip it in the loop invariant check below. 1270 bool found = false; 1271 for (const RewritePhi &Phi : RewritePhiSet) { 1272 if (!Phi.ValidRewrite) 1273 continue; 1274 unsigned i = Phi.Ith; 1275 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 1276 found = true; 1277 break; 1278 } 1279 } 1280 1281 Instruction *I; 1282 if (!found && (I = dyn_cast<Instruction>(Incoming))) 1283 if (!L->hasLoopInvariantOperands(I)) 1284 return false; 1285 1286 ++BI; 1287 } 1288 1289 for (auto *BB : L->blocks()) 1290 if (llvm::any_of(*BB, [](Instruction &I) { 1291 return I.mayHaveSideEffects(); 1292 })) 1293 return false; 1294 1295 return true; 1296 } 1297 1298 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, 1299 ScalarEvolution *SE, 1300 const TargetTransformInfo *TTI, 1301 SCEVExpander &Rewriter, DominatorTree *DT, 1302 ReplaceExitVal ReplaceExitValue, 1303 SmallVector<WeakTrackingVH, 16> &DeadInsts) { 1304 // Check a pre-condition. 1305 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 1306 "Indvars did not preserve LCSSA!"); 1307 1308 SmallVector<BasicBlock*, 8> ExitBlocks; 1309 L->getUniqueExitBlocks(ExitBlocks); 1310 1311 SmallVector<RewritePhi, 8> RewritePhiSet; 1312 // Find all values that are computed inside the loop, but used outside of it. 1313 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 1314 // the exit blocks of the loop to find them. 1315 for (BasicBlock *ExitBB : ExitBlocks) { 1316 // If there are no PHI nodes in this exit block, then no values defined 1317 // inside the loop are used on this path, skip it. 1318 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 1319 if (!PN) continue; 1320 1321 unsigned NumPreds = PN->getNumIncomingValues(); 1322 1323 // Iterate over all of the PHI nodes. 1324 BasicBlock::iterator BBI = ExitBB->begin(); 1325 while ((PN = dyn_cast<PHINode>(BBI++))) { 1326 if (PN->use_empty()) 1327 continue; // dead use, don't replace it 1328 1329 if (!SE->isSCEVable(PN->getType())) 1330 continue; 1331 1332 // It's necessary to tell ScalarEvolution about this explicitly so that 1333 // it can walk the def-use list and forget all SCEVs, as it may not be 1334 // watching the PHI itself. Once the new exit value is in place, there 1335 // may not be a def-use connection between the loop and every instruction 1336 // which got a SCEVAddRecExpr for that loop. 1337 SE->forgetValue(PN); 1338 1339 // Iterate over all of the values in all the PHI nodes. 1340 for (unsigned i = 0; i != NumPreds; ++i) { 1341 // If the value being merged in is not integer or is not defined 1342 // in the loop, skip it. 1343 Value *InVal = PN->getIncomingValue(i); 1344 if (!isa<Instruction>(InVal)) 1345 continue; 1346 1347 // If this pred is for a subloop, not L itself, skip it. 1348 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 1349 continue; // The Block is in a subloop, skip it. 1350 1351 // Check that InVal is defined in the loop. 1352 Instruction *Inst = cast<Instruction>(InVal); 1353 if (!L->contains(Inst)) 1354 continue; 1355 1356 // Okay, this instruction has a user outside of the current loop 1357 // and varies predictably *inside* the loop. Evaluate the value it 1358 // contains when the loop exits, if possible. We prefer to start with 1359 // expressions which are true for all exits (so as to maximize 1360 // expression reuse by the SCEVExpander), but resort to per-exit 1361 // evaluation if that fails. 1362 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 1363 if (isa<SCEVCouldNotCompute>(ExitValue) || 1364 !SE->isLoopInvariant(ExitValue, L) || 1365 !isSafeToExpand(ExitValue, *SE)) { 1366 // TODO: This should probably be sunk into SCEV in some way; maybe a 1367 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for 1368 // most SCEV expressions and other recurrence types (e.g. shift 1369 // recurrences). Is there existing code we can reuse? 1370 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i)); 1371 if (isa<SCEVCouldNotCompute>(ExitCount)) 1372 continue; 1373 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst))) 1374 if (AddRec->getLoop() == L) 1375 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE); 1376 if (isa<SCEVCouldNotCompute>(ExitValue) || 1377 !SE->isLoopInvariant(ExitValue, L) || 1378 !isSafeToExpand(ExitValue, *SE)) 1379 continue; 1380 } 1381 1382 // Computing the value outside of the loop brings no benefit if it is 1383 // definitely used inside the loop in a way which can not be optimized 1384 // away. Avoid doing so unless we know we have a value which computes 1385 // the ExitValue already. TODO: This should be merged into SCEV 1386 // expander to leverage its knowledge of existing expressions. 1387 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) && 1388 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst)) 1389 continue; 1390 1391 // Check if expansions of this SCEV would count as being high cost. 1392 bool HighCost = Rewriter.isHighCostExpansion( 1393 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst); 1394 1395 // Note that we must not perform expansions until after 1396 // we query *all* the costs, because if we perform temporary expansion 1397 // inbetween, one that we might not intend to keep, said expansion 1398 // *may* affect cost calculation of the the next SCEV's we'll query, 1399 // and next SCEV may errneously get smaller cost. 1400 1401 // Collect all the candidate PHINodes to be rewritten. 1402 RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost); 1403 } 1404 } 1405 } 1406 1407 // Now that we've done preliminary filtering and billed all the SCEV's, 1408 // we can perform the last sanity check - the expansion must be valid. 1409 for (RewritePhi &Phi : RewritePhiSet) { 1410 Phi.Expansion = Rewriter.expandCodeFor(Phi.ExpansionSCEV, Phi.PN->getType(), 1411 Phi.ExpansionPoint); 1412 1413 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " 1414 << *(Phi.Expansion) << '\n' 1415 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n"); 1416 1417 // FIXME: isValidRewrite() is a hack. it should be an assert, eventually. 1418 Phi.ValidRewrite = isValidRewrite(SE, Phi.ExpansionPoint, Phi.Expansion); 1419 if (!Phi.ValidRewrite) { 1420 DeadInsts.push_back(Phi.Expansion); 1421 continue; 1422 } 1423 1424 #ifndef NDEBUG 1425 // If we reuse an instruction from a loop which is neither L nor one of 1426 // its containing loops, we end up breaking LCSSA form for this loop by 1427 // creating a new use of its instruction. 1428 if (auto *ExitInsn = dyn_cast<Instruction>(Phi.Expansion)) 1429 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent())) 1430 if (EVL != L) 1431 assert(EVL->contains(L) && "LCSSA breach detected!"); 1432 #endif 1433 } 1434 1435 // TODO: after isValidRewrite() is an assertion, evaluate whether 1436 // it is beneficial to change how we calculate high-cost: 1437 // if we have SCEV 'A' which we know we will expand, should we calculate 1438 // the cost of other SCEV's after expanding SCEV 'A', 1439 // thus potentially giving cost bonus to those other SCEV's? 1440 1441 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 1442 int NumReplaced = 0; 1443 1444 // Transformation. 1445 for (const RewritePhi &Phi : RewritePhiSet) { 1446 if (!Phi.ValidRewrite) 1447 continue; 1448 1449 PHINode *PN = Phi.PN; 1450 Value *ExitVal = Phi.Expansion; 1451 1452 // Only do the rewrite when the ExitValue can be expanded cheaply. 1453 // If LoopCanBeDel is true, rewrite exit value aggressively. 1454 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 1455 DeadInsts.push_back(ExitVal); 1456 continue; 1457 } 1458 1459 NumReplaced++; 1460 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 1461 PN->setIncomingValue(Phi.Ith, ExitVal); 1462 1463 // If this instruction is dead now, delete it. Don't do it now to avoid 1464 // invalidating iterators. 1465 if (isInstructionTriviallyDead(Inst, TLI)) 1466 DeadInsts.push_back(Inst); 1467 1468 // Replace PN with ExitVal if that is legal and does not break LCSSA. 1469 if (PN->getNumIncomingValues() == 1 && 1470 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 1471 PN->replaceAllUsesWith(ExitVal); 1472 PN->eraseFromParent(); 1473 } 1474 } 1475 1476 // The insertion point instruction may have been deleted; clear it out 1477 // so that the rewriter doesn't trip over it later. 1478 Rewriter.clearInsertPoint(); 1479 return NumReplaced; 1480 } 1481 1482 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for 1483 /// \p OrigLoop. 1484 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, 1485 Loop *RemainderLoop, uint64_t UF) { 1486 assert(UF > 0 && "Zero unrolled factor is not supported"); 1487 assert(UnrolledLoop != RemainderLoop && 1488 "Unrolled and Remainder loops are expected to distinct"); 1489 1490 // Get number of iterations in the original scalar loop. 1491 unsigned OrigLoopInvocationWeight = 0; 1492 Optional<unsigned> OrigAverageTripCount = 1493 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight); 1494 if (!OrigAverageTripCount) 1495 return; 1496 1497 // Calculate number of iterations in unrolled loop. 1498 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF; 1499 // Calculate number of iterations for remainder loop. 1500 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF; 1501 1502 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount, 1503 OrigLoopInvocationWeight); 1504 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount, 1505 OrigLoopInvocationWeight); 1506 } 1507 1508 /// Utility that implements appending of loops onto a worklist. 1509 /// Loops are added in preorder (analogous for reverse postorder for trees), 1510 /// and the worklist is processed LIFO. 1511 template <typename RangeT> 1512 void llvm::appendReversedLoopsToWorklist( 1513 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) { 1514 // We use an internal worklist to build up the preorder traversal without 1515 // recursion. 1516 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1517 1518 // We walk the initial sequence of loops in reverse because we generally want 1519 // to visit defs before uses and the worklist is LIFO. 1520 for (Loop *RootL : Loops) { 1521 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1522 assert(PreOrderWorklist.empty() && 1523 "Must start with an empty preorder walk worklist."); 1524 PreOrderWorklist.push_back(RootL); 1525 do { 1526 Loop *L = PreOrderWorklist.pop_back_val(); 1527 PreOrderWorklist.append(L->begin(), L->end()); 1528 PreOrderLoops.push_back(L); 1529 } while (!PreOrderWorklist.empty()); 1530 1531 Worklist.insert(std::move(PreOrderLoops)); 1532 PreOrderLoops.clear(); 1533 } 1534 } 1535 1536 template <typename RangeT> 1537 void llvm::appendLoopsToWorklist(RangeT &&Loops, 1538 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1539 appendReversedLoopsToWorklist(reverse(Loops), Worklist); 1540 } 1541 1542 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>( 1543 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist); 1544 1545 template void 1546 llvm::appendLoopsToWorklist<Loop &>(Loop &L, 1547 SmallPriorityWorklist<Loop *, 4> &Worklist); 1548 1549 void llvm::appendLoopsToWorklist(LoopInfo &LI, 1550 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1551 appendReversedLoopsToWorklist(LI, Worklist); 1552 } 1553 1554 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, 1555 LoopInfo *LI, LPPassManager *LPM) { 1556 Loop &New = *LI->AllocateLoop(); 1557 if (PL) 1558 PL->addChildLoop(&New); 1559 else 1560 LI->addTopLevelLoop(&New); 1561 1562 if (LPM) 1563 LPM->addLoop(New); 1564 1565 // Add all of the blocks in L to the new loop. 1566 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 1567 I != E; ++I) 1568 if (LI->getLoopFor(*I) == L) 1569 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); 1570 1571 // Add all of the subloops to the new loop. 1572 for (Loop *I : *L) 1573 cloneLoop(I, &New, VM, LI, LPM); 1574 1575 return &New; 1576 } 1577 1578 /// IR Values for the lower and upper bounds of a pointer evolution. We 1579 /// need to use value-handles because SCEV expansion can invalidate previously 1580 /// expanded values. Thus expansion of a pointer can invalidate the bounds for 1581 /// a previous one. 1582 struct PointerBounds { 1583 TrackingVH<Value> Start; 1584 TrackingVH<Value> End; 1585 }; 1586 1587 /// Expand code for the lower and upper bound of the pointer group \p CG 1588 /// in \p TheLoop. \return the values for the bounds. 1589 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG, 1590 Loop *TheLoop, Instruction *Loc, 1591 SCEVExpander &Exp, ScalarEvolution *SE) { 1592 // TODO: Add helper to retrieve pointers to CG. 1593 Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue; 1594 const SCEV *Sc = SE->getSCEV(Ptr); 1595 1596 unsigned AS = Ptr->getType()->getPointerAddressSpace(); 1597 LLVMContext &Ctx = Loc->getContext(); 1598 1599 // Use this type for pointer arithmetic. 1600 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); 1601 1602 if (SE->isLoopInvariant(Sc, TheLoop)) { 1603 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" 1604 << *Ptr << "\n"); 1605 // Ptr could be in the loop body. If so, expand a new one at the correct 1606 // location. 1607 Instruction *Inst = dyn_cast<Instruction>(Ptr); 1608 Value *NewPtr = (Inst && TheLoop->contains(Inst)) 1609 ? Exp.expandCodeFor(Sc, PtrArithTy, Loc) 1610 : Ptr; 1611 // We must return a half-open range, which means incrementing Sc. 1612 const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy)); 1613 Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc); 1614 return {NewPtr, NewPtrPlusOne}; 1615 } else { 1616 Value *Start = nullptr, *End = nullptr; 1617 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n"); 1618 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc); 1619 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc); 1620 LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High 1621 << "\n"); 1622 return {Start, End}; 1623 } 1624 } 1625 1626 /// Turns a collection of checks into a collection of expanded upper and 1627 /// lower bounds for both pointers in the check. 1628 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> 1629 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L, 1630 Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) { 1631 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds; 1632 1633 // Here we're relying on the SCEV Expander's cache to only emit code for the 1634 // same bounds once. 1635 transform(PointerChecks, std::back_inserter(ChecksWithBounds), 1636 [&](const RuntimePointerCheck &Check) { 1637 PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE), 1638 Second = 1639 expandBounds(Check.second, L, Loc, Exp, SE); 1640 return std::make_pair(First, Second); 1641 }); 1642 1643 return ChecksWithBounds; 1644 } 1645 1646 std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks( 1647 Instruction *Loc, Loop *TheLoop, 1648 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, 1649 ScalarEvolution *SE) { 1650 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible. 1651 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible 1652 const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 1653 SCEVExpander Exp(*SE, DL, "induction"); 1654 auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp); 1655 1656 LLVMContext &Ctx = Loc->getContext(); 1657 Instruction *FirstInst = nullptr; 1658 IRBuilder<> ChkBuilder(Loc); 1659 // Our instructions might fold to a constant. 1660 Value *MemoryRuntimeCheck = nullptr; 1661 1662 // FIXME: this helper is currently a duplicate of the one in 1663 // LoopVectorize.cpp. 1664 auto GetFirstInst = [](Instruction *FirstInst, Value *V, 1665 Instruction *Loc) -> Instruction * { 1666 if (FirstInst) 1667 return FirstInst; 1668 if (Instruction *I = dyn_cast<Instruction>(V)) 1669 return I->getParent() == Loc->getParent() ? I : nullptr; 1670 return nullptr; 1671 }; 1672 1673 for (const auto &Check : ExpandedChecks) { 1674 const PointerBounds &A = Check.first, &B = Check.second; 1675 // Check if two pointers (A and B) conflict where conflict is computed as: 1676 // start(A) <= end(B) && start(B) <= end(A) 1677 unsigned AS0 = A.Start->getType()->getPointerAddressSpace(); 1678 unsigned AS1 = B.Start->getType()->getPointerAddressSpace(); 1679 1680 assert((AS0 == B.End->getType()->getPointerAddressSpace()) && 1681 (AS1 == A.End->getType()->getPointerAddressSpace()) && 1682 "Trying to bounds check pointers with different address spaces"); 1683 1684 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); 1685 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); 1686 1687 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc"); 1688 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc"); 1689 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc"); 1690 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc"); 1691 1692 // [A|B].Start points to the first accessed byte under base [A|B]. 1693 // [A|B].End points to the last accessed byte, plus one. 1694 // There is no conflict when the intervals are disjoint: 1695 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End) 1696 // 1697 // bound0 = (B.Start < A.End) 1698 // bound1 = (A.Start < B.End) 1699 // IsConflict = bound0 & bound1 1700 Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0"); 1701 FirstInst = GetFirstInst(FirstInst, Cmp0, Loc); 1702 Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1"); 1703 FirstInst = GetFirstInst(FirstInst, Cmp1, Loc); 1704 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1705 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1706 if (MemoryRuntimeCheck) { 1707 IsConflict = 1708 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx"); 1709 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1710 } 1711 MemoryRuntimeCheck = IsConflict; 1712 } 1713 1714 if (!MemoryRuntimeCheck) 1715 return std::make_pair(nullptr, nullptr); 1716 1717 // We have to do this trickery because the IRBuilder might fold the check to a 1718 // constant expression in which case there is no Instruction anchored in a 1719 // the block. 1720 Instruction *Check = 1721 BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx)); 1722 ChkBuilder.Insert(Check, "memcheck.conflict"); 1723 FirstInst = GetFirstInst(FirstInst, Check, Loc); 1724 return std::make_pair(FirstInst, Check); 1725 } 1726