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]->getChildren()) 517 AddRegionToWorklist(Child); 518 519 return Worklist; 520 } 521 522 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, 523 LoopInfo *LI, MemorySSA *MSSA) { 524 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 525 auto *Preheader = L->getLoopPreheader(); 526 assert(Preheader && "Preheader should exist!"); 527 528 std::unique_ptr<MemorySSAUpdater> MSSAU; 529 if (MSSA) 530 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 531 532 // Now that we know the removal is safe, remove the loop by changing the 533 // branch from the preheader to go to the single exit block. 534 // 535 // Because we're deleting a large chunk of code at once, the sequence in which 536 // we remove things is very important to avoid invalidation issues. 537 538 // Tell ScalarEvolution that the loop is deleted. Do this before 539 // deleting the loop so that ScalarEvolution can look at the loop 540 // to determine what it needs to clean up. 541 if (SE) 542 SE->forgetLoop(L); 543 544 auto *ExitBlock = L->getUniqueExitBlock(); 545 assert(ExitBlock && "Should have a unique exit block!"); 546 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 547 548 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 549 assert(OldBr && "Preheader must end with a branch"); 550 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 551 // Connect the preheader to the exit block. Keep the old edge to the header 552 // around to perform the dominator tree update in two separate steps 553 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 554 // preheader -> header. 555 // 556 // 557 // 0. Preheader 1. Preheader 2. Preheader 558 // | | | | 559 // V | V | 560 // Header <--\ | Header <--\ | Header <--\ 561 // | | | | | | | | | | | 562 // | V | | | V | | | V | 563 // | Body --/ | | Body --/ | | Body --/ 564 // V V V V V 565 // Exit Exit Exit 566 // 567 // By doing this is two separate steps we can perform the dominator tree 568 // update without using the batch update API. 569 // 570 // Even when the loop is never executed, we cannot remove the edge from the 571 // source block to the exit block. Consider the case where the unexecuted loop 572 // branches back to an outer loop. If we deleted the loop and removed the edge 573 // coming to this inner loop, this will break the outer loop structure (by 574 // deleting the backedge of the outer loop). If the outer loop is indeed a 575 // non-loop, it will be deleted in a future iteration of loop deletion pass. 576 IRBuilder<> Builder(OldBr); 577 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 578 // Remove the old branch. The conditional branch becomes a new terminator. 579 OldBr->eraseFromParent(); 580 581 // Rewrite phis in the exit block to get their inputs from the Preheader 582 // instead of the exiting block. 583 for (PHINode &P : ExitBlock->phis()) { 584 // Set the zero'th element of Phi to be from the preheader and remove all 585 // other incoming values. Given the loop has dedicated exits, all other 586 // incoming values must be from the exiting blocks. 587 int PredIndex = 0; 588 P.setIncomingBlock(PredIndex, Preheader); 589 // Removes all incoming values from all other exiting blocks (including 590 // duplicate values from an exiting block). 591 // Nuke all entries except the zero'th entry which is the preheader entry. 592 // NOTE! We need to remove Incoming Values in the reverse order as done 593 // below, to keep the indices valid for deletion (removeIncomingValues 594 // updates getNumIncomingValues and shifts all values down into the operand 595 // being deleted). 596 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 597 P.removeIncomingValue(e - i, false); 598 599 assert((P.getNumIncomingValues() == 1 && 600 P.getIncomingBlock(PredIndex) == Preheader) && 601 "Should have exactly one value and that's from the preheader!"); 602 } 603 604 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 605 if (DT) { 606 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}); 607 if (MSSA) { 608 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT); 609 if (VerifyMemorySSA) 610 MSSA->verifyMemorySSA(); 611 } 612 } 613 614 // Disconnect the loop body by branching directly to its exit. 615 Builder.SetInsertPoint(Preheader->getTerminator()); 616 Builder.CreateBr(ExitBlock); 617 // Remove the old branch. 618 Preheader->getTerminator()->eraseFromParent(); 619 620 if (DT) { 621 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}); 622 if (MSSA) { 623 MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}, 624 *DT); 625 if (VerifyMemorySSA) 626 MSSA->verifyMemorySSA(); 627 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(), 628 L->block_end()); 629 MSSAU->removeBlocks(DeadBlockSet); 630 } 631 } 632 633 // Use a map to unique and a vector to guarantee deterministic ordering. 634 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 635 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 636 637 // Given LCSSA form is satisfied, we should not have users of instructions 638 // within the dead loop outside of the loop. However, LCSSA doesn't take 639 // unreachable uses into account. We handle them here. 640 // We could do it after drop all references (in this case all users in the 641 // loop will be already eliminated and we have less work to do but according 642 // to API doc of User::dropAllReferences only valid operation after dropping 643 // references, is deletion. So let's substitute all usages of 644 // instruction from the loop with undef value of corresponding type first. 645 for (auto *Block : L->blocks()) 646 for (Instruction &I : *Block) { 647 auto *Undef = UndefValue::get(I.getType()); 648 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 649 Use &U = *UI; 650 ++UI; 651 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 652 if (L->contains(Usr->getParent())) 653 continue; 654 // If we have a DT then we can check that uses outside a loop only in 655 // unreachable block. 656 if (DT) 657 assert(!DT->isReachableFromEntry(U) && 658 "Unexpected user in reachable block"); 659 U.set(Undef); 660 } 661 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 662 if (!DVI) 663 continue; 664 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 665 if (Key != DeadDebugSet.end()) 666 continue; 667 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 668 DeadDebugInst.push_back(DVI); 669 } 670 671 // After the loop has been deleted all the values defined and modified 672 // inside the loop are going to be unavailable. 673 // Since debug values in the loop have been deleted, inserting an undef 674 // dbg.value truncates the range of any dbg.value before the loop where the 675 // loop used to be. This is particularly important for constant values. 676 DIBuilder DIB(*ExitBlock->getModule()); 677 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 678 assert(InsertDbgValueBefore && 679 "There should be a non-PHI instruction in exit block, else these " 680 "instructions will have no parent."); 681 for (auto *DVI : DeadDebugInst) 682 DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), 683 DVI->getVariable(), DVI->getExpression(), 684 DVI->getDebugLoc(), InsertDbgValueBefore); 685 686 // Remove the block from the reference counting scheme, so that we can 687 // delete it freely later. 688 for (auto *Block : L->blocks()) 689 Block->dropAllReferences(); 690 691 if (MSSA && VerifyMemorySSA) 692 MSSA->verifyMemorySSA(); 693 694 if (LI) { 695 // Erase the instructions and the blocks without having to worry 696 // about ordering because we already dropped the references. 697 // NOTE: This iteration is safe because erasing the block does not remove 698 // its entry from the loop's block list. We do that in the next section. 699 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 700 LpI != LpE; ++LpI) 701 (*LpI)->eraseFromParent(); 702 703 // Finally, the blocks from loopinfo. This has to happen late because 704 // otherwise our loop iterators won't work. 705 706 SmallPtrSet<BasicBlock *, 8> blocks; 707 blocks.insert(L->block_begin(), L->block_end()); 708 for (BasicBlock *BB : blocks) 709 LI->removeBlock(BB); 710 711 // The last step is to update LoopInfo now that we've eliminated this loop. 712 // Note: LoopInfo::erase remove the given loop and relink its subloops with 713 // its parent. While removeLoop/removeChildLoop remove the given loop but 714 // not relink its subloops, which is what we want. 715 if (Loop *ParentLoop = L->getParentLoop()) { 716 Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L); 717 assert(I != ParentLoop->end() && "Couldn't find loop"); 718 ParentLoop->removeChildLoop(I); 719 } else { 720 Loop::iterator I = find(LI->begin(), LI->end(), L); 721 assert(I != LI->end() && "Couldn't find loop"); 722 LI->removeLoop(I); 723 } 724 LI->destroy(L); 725 } 726 } 727 728 /// Checks if \p L has single exit through latch block except possibly 729 /// "deoptimizing" exits. Returns branch instruction terminating the loop 730 /// latch if above check is successful, nullptr otherwise. 731 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { 732 BasicBlock *Latch = L->getLoopLatch(); 733 if (!Latch) 734 return nullptr; 735 736 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 737 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 738 return nullptr; 739 740 assert((LatchBR->getSuccessor(0) == L->getHeader() || 741 LatchBR->getSuccessor(1) == L->getHeader()) && 742 "At least one edge out of the latch must go to the header"); 743 744 SmallVector<BasicBlock *, 4> ExitBlocks; 745 L->getUniqueNonLatchExitBlocks(ExitBlocks); 746 if (any_of(ExitBlocks, [](const BasicBlock *EB) { 747 return !EB->getTerminatingDeoptimizeCall(); 748 })) 749 return nullptr; 750 751 return LatchBR; 752 } 753 754 Optional<unsigned> 755 llvm::getLoopEstimatedTripCount(Loop *L, 756 unsigned *EstimatedLoopInvocationWeight) { 757 // Support loops with an exiting latch and other existing exists only 758 // deoptimize. 759 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 760 if (!LatchBranch) 761 return None; 762 763 // To estimate the number of times the loop body was executed, we want to 764 // know the number of times the backedge was taken, vs. the number of times 765 // we exited the loop. 766 uint64_t BackedgeTakenWeight, LatchExitWeight; 767 if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight)) 768 return None; 769 770 if (LatchBranch->getSuccessor(0) != L->getHeader()) 771 std::swap(BackedgeTakenWeight, LatchExitWeight); 772 773 if (!LatchExitWeight) 774 return None; 775 776 if (EstimatedLoopInvocationWeight) 777 *EstimatedLoopInvocationWeight = LatchExitWeight; 778 779 // Estimated backedge taken count is a ratio of the backedge taken weight by 780 // the weight of the edge exiting the loop, rounded to nearest. 781 uint64_t BackedgeTakenCount = 782 llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight); 783 // Estimated trip count is one plus estimated backedge taken count. 784 return BackedgeTakenCount + 1; 785 } 786 787 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, 788 unsigned EstimatedloopInvocationWeight) { 789 // Support loops with an exiting latch and other existing exists only 790 // deoptimize. 791 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 792 if (!LatchBranch) 793 return false; 794 795 // Calculate taken and exit weights. 796 unsigned LatchExitWeight = 0; 797 unsigned BackedgeTakenWeight = 0; 798 799 if (EstimatedTripCount > 0) { 800 LatchExitWeight = EstimatedloopInvocationWeight; 801 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight; 802 } 803 804 // Make a swap if back edge is taken when condition is "false". 805 if (LatchBranch->getSuccessor(0) != L->getHeader()) 806 std::swap(BackedgeTakenWeight, LatchExitWeight); 807 808 MDBuilder MDB(LatchBranch->getContext()); 809 810 // Set/Update profile metadata. 811 LatchBranch->setMetadata( 812 LLVMContext::MD_prof, 813 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight)); 814 815 return true; 816 } 817 818 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 819 ScalarEvolution &SE) { 820 Loop *OuterL = InnerLoop->getParentLoop(); 821 if (!OuterL) 822 return true; 823 824 // Get the backedge taken count for the inner loop 825 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 826 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 827 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 828 !InnerLoopBECountSC->getType()->isIntegerTy()) 829 return false; 830 831 // Get whether count is invariant to the outer loop 832 ScalarEvolution::LoopDisposition LD = 833 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 834 if (LD != ScalarEvolution::LoopInvariant) 835 return false; 836 837 return true; 838 } 839 840 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, 841 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 842 Value *Left, Value *Right) { 843 CmpInst::Predicate P = CmpInst::ICMP_NE; 844 switch (RK) { 845 default: 846 llvm_unreachable("Unknown min/max recurrence kind"); 847 case RecurrenceDescriptor::MRK_UIntMin: 848 P = CmpInst::ICMP_ULT; 849 break; 850 case RecurrenceDescriptor::MRK_UIntMax: 851 P = CmpInst::ICMP_UGT; 852 break; 853 case RecurrenceDescriptor::MRK_SIntMin: 854 P = CmpInst::ICMP_SLT; 855 break; 856 case RecurrenceDescriptor::MRK_SIntMax: 857 P = CmpInst::ICMP_SGT; 858 break; 859 case RecurrenceDescriptor::MRK_FloatMin: 860 P = CmpInst::FCMP_OLT; 861 break; 862 case RecurrenceDescriptor::MRK_FloatMax: 863 P = CmpInst::FCMP_OGT; 864 break; 865 } 866 867 // We only match FP sequences that are 'fast', so we can unconditionally 868 // set it on any generated instructions. 869 IRBuilderBase::FastMathFlagGuard FMFG(Builder); 870 FastMathFlags FMF; 871 FMF.setFast(); 872 Builder.setFastMathFlags(FMF); 873 874 Value *Cmp; 875 if (RK == RecurrenceDescriptor::MRK_FloatMin || 876 RK == RecurrenceDescriptor::MRK_FloatMax) 877 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 878 else 879 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 880 881 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 882 return Select; 883 } 884 885 // Helper to generate an ordered reduction. 886 Value * 887 llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, 888 unsigned Op, 889 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 890 ArrayRef<Value *> RedOps) { 891 unsigned VF = cast<VectorType>(Src->getType())->getNumElements(); 892 893 // Extract and apply reduction ops in ascending order: 894 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 895 Value *Result = Acc; 896 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 897 Value *Ext = 898 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 899 900 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 901 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 902 "bin.rdx"); 903 } else { 904 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 905 "Invalid min/max"); 906 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 907 } 908 909 if (!RedOps.empty()) 910 propagateIRFlags(Result, RedOps); 911 } 912 913 return Result; 914 } 915 916 // Helper to generate a log2 shuffle reduction. 917 Value * 918 llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, 919 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 920 ArrayRef<Value *> RedOps) { 921 unsigned VF = cast<VectorType>(Src->getType())->getNumElements(); 922 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 923 // and vector ops, reducing the set of values being computed by half each 924 // round. 925 assert(isPowerOf2_32(VF) && 926 "Reduction emission only supported for pow2 vectors!"); 927 Value *TmpVec = Src; 928 SmallVector<int, 32> ShuffleMask(VF); 929 for (unsigned i = VF; i != 1; i >>= 1) { 930 // Move the upper half of the vector to the lower half. 931 for (unsigned j = 0; j != i / 2; ++j) 932 ShuffleMask[j] = i / 2 + j; 933 934 // Fill the rest of the mask with undef. 935 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1); 936 937 Value *Shuf = Builder.CreateShuffleVector( 938 TmpVec, UndefValue::get(TmpVec->getType()), ShuffleMask, "rdx.shuf"); 939 940 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 941 // The builder propagates its fast-math-flags setting. 942 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 943 "bin.rdx"); 944 } else { 945 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 946 "Invalid min/max"); 947 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 948 } 949 if (!RedOps.empty()) 950 propagateIRFlags(TmpVec, RedOps); 951 952 // We may compute the reassociated scalar ops in a way that does not 953 // preserve nsw/nuw etc. Conservatively, drop those flags. 954 if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec)) 955 ReductionInst->dropPoisonGeneratingFlags(); 956 } 957 // The result is in the first element of the vector. 958 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 959 } 960 961 /// Create a simple vector reduction specified by an opcode and some 962 /// flags (if generating min/max reductions). 963 Value *llvm::createSimpleTargetReduction( 964 IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 965 Value *Src, TargetTransformInfo::ReductionFlags Flags, 966 ArrayRef<Value *> RedOps) { 967 auto *SrcVTy = cast<VectorType>(Src->getType()); 968 969 std::function<Value *()> BuildFunc; 970 using RD = RecurrenceDescriptor; 971 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 972 973 switch (Opcode) { 974 case Instruction::Add: 975 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 976 break; 977 case Instruction::Mul: 978 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 979 break; 980 case Instruction::And: 981 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 982 break; 983 case Instruction::Or: 984 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 985 break; 986 case Instruction::Xor: 987 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 988 break; 989 case Instruction::FAdd: 990 BuildFunc = [&]() { 991 auto Rdx = Builder.CreateFAddReduce( 992 Constant::getNullValue(SrcVTy->getElementType()), Src); 993 return Rdx; 994 }; 995 break; 996 case Instruction::FMul: 997 BuildFunc = [&]() { 998 Type *Ty = SrcVTy->getElementType(); 999 auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); 1000 return Rdx; 1001 }; 1002 break; 1003 case Instruction::ICmp: 1004 if (Flags.IsMaxOp) { 1005 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 1006 BuildFunc = [&]() { 1007 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 1008 }; 1009 } else { 1010 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 1011 BuildFunc = [&]() { 1012 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 1013 }; 1014 } 1015 break; 1016 case Instruction::FCmp: 1017 if (Flags.IsMaxOp) { 1018 MinMaxKind = RD::MRK_FloatMax; 1019 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 1020 } else { 1021 MinMaxKind = RD::MRK_FloatMin; 1022 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 1023 } 1024 break; 1025 default: 1026 llvm_unreachable("Unhandled opcode"); 1027 break; 1028 } 1029 if (ForceReductionIntrinsic || 1030 TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 1031 return BuildFunc(); 1032 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 1033 } 1034 1035 /// Create a vector reduction using a given recurrence descriptor. 1036 Value *llvm::createTargetReduction(IRBuilderBase &B, 1037 const TargetTransformInfo *TTI, 1038 RecurrenceDescriptor &Desc, Value *Src, 1039 bool NoNaN) { 1040 // TODO: Support in-order reductions based on the recurrence descriptor. 1041 using RD = RecurrenceDescriptor; 1042 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 1043 TargetTransformInfo::ReductionFlags Flags; 1044 Flags.NoNaN = NoNaN; 1045 1046 // All ops in the reduction inherit fast-math-flags from the recurrence 1047 // descriptor. 1048 IRBuilderBase::FastMathFlagGuard FMFGuard(B); 1049 B.setFastMathFlags(Desc.getFastMathFlags()); 1050 1051 switch (RecKind) { 1052 case RD::RK_FloatAdd: 1053 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 1054 case RD::RK_FloatMult: 1055 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 1056 case RD::RK_IntegerAdd: 1057 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 1058 case RD::RK_IntegerMult: 1059 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 1060 case RD::RK_IntegerAnd: 1061 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 1062 case RD::RK_IntegerOr: 1063 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 1064 case RD::RK_IntegerXor: 1065 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 1066 case RD::RK_IntegerMinMax: { 1067 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 1068 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 1069 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 1070 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 1071 } 1072 case RD::RK_FloatMinMax: { 1073 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 1074 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 1075 } 1076 default: 1077 llvm_unreachable("Unhandled RecKind"); 1078 } 1079 } 1080 1081 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 1082 auto *VecOp = dyn_cast<Instruction>(I); 1083 if (!VecOp) 1084 return; 1085 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 1086 : dyn_cast<Instruction>(OpValue); 1087 if (!Intersection) 1088 return; 1089 const unsigned Opcode = Intersection->getOpcode(); 1090 VecOp->copyIRFlags(Intersection); 1091 for (auto *V : VL) { 1092 auto *Instr = dyn_cast<Instruction>(V); 1093 if (!Instr) 1094 continue; 1095 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1096 VecOp->andIRFlags(V); 1097 } 1098 } 1099 1100 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1101 ScalarEvolution &SE) { 1102 const SCEV *Zero = SE.getZero(S->getType()); 1103 return SE.isAvailableAtLoopEntry(S, L) && 1104 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1105 } 1106 1107 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1108 ScalarEvolution &SE) { 1109 const SCEV *Zero = SE.getZero(S->getType()); 1110 return SE.isAvailableAtLoopEntry(S, L) && 1111 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1112 } 1113 1114 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1115 bool Signed) { 1116 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1117 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1118 APInt::getMinValue(BitWidth); 1119 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1120 return SE.isAvailableAtLoopEntry(S, L) && 1121 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1122 SE.getConstant(Min)); 1123 } 1124 1125 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1126 bool Signed) { 1127 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1128 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1129 APInt::getMaxValue(BitWidth); 1130 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1131 return SE.isAvailableAtLoopEntry(S, L) && 1132 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1133 SE.getConstant(Max)); 1134 } 1135 1136 //===----------------------------------------------------------------------===// 1137 // rewriteLoopExitValues - Optimize IV users outside the loop. 1138 // As a side effect, reduces the amount of IV processing within the loop. 1139 //===----------------------------------------------------------------------===// 1140 1141 // Return true if the SCEV expansion generated by the rewriter can replace the 1142 // original value. SCEV guarantees that it produces the same value, but the way 1143 // it is produced may be illegal IR. Ideally, this function will only be 1144 // called for verification. 1145 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) { 1146 // If an SCEV expression subsumed multiple pointers, its expansion could 1147 // reassociate the GEP changing the base pointer. This is illegal because the 1148 // final address produced by a GEP chain must be inbounds relative to its 1149 // underlying object. Otherwise basic alias analysis, among other things, 1150 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 1151 // producing an expression involving multiple pointers. Until then, we must 1152 // bail out here. 1153 // 1154 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 1155 // because it understands lcssa phis while SCEV does not. 1156 Value *FromPtr = FromVal; 1157 Value *ToPtr = ToVal; 1158 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) 1159 FromPtr = GEP->getPointerOperand(); 1160 1161 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) 1162 ToPtr = GEP->getPointerOperand(); 1163 1164 if (FromPtr != FromVal || ToPtr != ToVal) { 1165 // Quickly check the common case 1166 if (FromPtr == ToPtr) 1167 return true; 1168 1169 // SCEV may have rewritten an expression that produces the GEP's pointer 1170 // operand. That's ok as long as the pointer operand has the same base 1171 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 1172 // base of a recurrence. This handles the case in which SCEV expansion 1173 // converts a pointer type recurrence into a nonrecurrent pointer base 1174 // indexed by an integer recurrence. 1175 1176 // If the GEP base pointer is a vector of pointers, abort. 1177 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 1178 return false; 1179 1180 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 1181 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 1182 if (FromBase == ToBase) 1183 return true; 1184 1185 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out " 1186 << *FromBase << " != " << *ToBase << "\n"); 1187 1188 return false; 1189 } 1190 return true; 1191 } 1192 1193 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) { 1194 SmallPtrSet<const Instruction *, 8> Visited; 1195 SmallVector<const Instruction *, 8> WorkList; 1196 Visited.insert(I); 1197 WorkList.push_back(I); 1198 while (!WorkList.empty()) { 1199 const Instruction *Curr = WorkList.pop_back_val(); 1200 // This use is outside the loop, nothing to do. 1201 if (!L->contains(Curr)) 1202 continue; 1203 // Do we assume it is a "hard" use which will not be eliminated easily? 1204 if (Curr->mayHaveSideEffects()) 1205 return true; 1206 // Otherwise, add all its users to worklist. 1207 for (auto U : Curr->users()) { 1208 auto *UI = cast<Instruction>(U); 1209 if (Visited.insert(UI).second) 1210 WorkList.push_back(UI); 1211 } 1212 } 1213 return false; 1214 } 1215 1216 // Collect information about PHI nodes which can be transformed in 1217 // rewriteLoopExitValues. 1218 struct RewritePhi { 1219 PHINode *PN; 1220 unsigned Ith; // Ith incoming value. 1221 Value *Val; // Exit value after expansion. 1222 bool HighCost; // High Cost when expansion. 1223 1224 RewritePhi(PHINode *P, unsigned I, Value *V, bool H) 1225 : PN(P), Ith(I), Val(V), HighCost(H) {} 1226 }; 1227 1228 // Check whether it is possible to delete the loop after rewriting exit 1229 // value. If it is possible, ignore ReplaceExitValue and do rewriting 1230 // aggressively. 1231 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 1232 BasicBlock *Preheader = L->getLoopPreheader(); 1233 // If there is no preheader, the loop will not be deleted. 1234 if (!Preheader) 1235 return false; 1236 1237 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 1238 // We obviate multiple ExitingBlocks case for simplicity. 1239 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 1240 // after exit value rewriting, we can enhance the logic here. 1241 SmallVector<BasicBlock *, 4> ExitingBlocks; 1242 L->getExitingBlocks(ExitingBlocks); 1243 SmallVector<BasicBlock *, 8> ExitBlocks; 1244 L->getUniqueExitBlocks(ExitBlocks); 1245 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1) 1246 return false; 1247 1248 BasicBlock *ExitBlock = ExitBlocks[0]; 1249 BasicBlock::iterator BI = ExitBlock->begin(); 1250 while (PHINode *P = dyn_cast<PHINode>(BI)) { 1251 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 1252 1253 // If the Incoming value of P is found in RewritePhiSet, we know it 1254 // could be rewritten to use a loop invariant value in transformation 1255 // phase later. Skip it in the loop invariant check below. 1256 bool found = false; 1257 for (const RewritePhi &Phi : RewritePhiSet) { 1258 unsigned i = Phi.Ith; 1259 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 1260 found = true; 1261 break; 1262 } 1263 } 1264 1265 Instruction *I; 1266 if (!found && (I = dyn_cast<Instruction>(Incoming))) 1267 if (!L->hasLoopInvariantOperands(I)) 1268 return false; 1269 1270 ++BI; 1271 } 1272 1273 for (auto *BB : L->blocks()) 1274 if (llvm::any_of(*BB, [](Instruction &I) { 1275 return I.mayHaveSideEffects(); 1276 })) 1277 return false; 1278 1279 return true; 1280 } 1281 1282 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, 1283 ScalarEvolution *SE, 1284 const TargetTransformInfo *TTI, 1285 SCEVExpander &Rewriter, DominatorTree *DT, 1286 ReplaceExitVal ReplaceExitValue, 1287 SmallVector<WeakTrackingVH, 16> &DeadInsts) { 1288 // Check a pre-condition. 1289 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 1290 "Indvars did not preserve LCSSA!"); 1291 1292 SmallVector<BasicBlock*, 8> ExitBlocks; 1293 L->getUniqueExitBlocks(ExitBlocks); 1294 1295 SmallVector<RewritePhi, 8> RewritePhiSet; 1296 // Find all values that are computed inside the loop, but used outside of it. 1297 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 1298 // the exit blocks of the loop to find them. 1299 for (BasicBlock *ExitBB : ExitBlocks) { 1300 // If there are no PHI nodes in this exit block, then no values defined 1301 // inside the loop are used on this path, skip it. 1302 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 1303 if (!PN) continue; 1304 1305 unsigned NumPreds = PN->getNumIncomingValues(); 1306 1307 // Iterate over all of the PHI nodes. 1308 BasicBlock::iterator BBI = ExitBB->begin(); 1309 while ((PN = dyn_cast<PHINode>(BBI++))) { 1310 if (PN->use_empty()) 1311 continue; // dead use, don't replace it 1312 1313 if (!SE->isSCEVable(PN->getType())) 1314 continue; 1315 1316 // It's necessary to tell ScalarEvolution about this explicitly so that 1317 // it can walk the def-use list and forget all SCEVs, as it may not be 1318 // watching the PHI itself. Once the new exit value is in place, there 1319 // may not be a def-use connection between the loop and every instruction 1320 // which got a SCEVAddRecExpr for that loop. 1321 SE->forgetValue(PN); 1322 1323 // Iterate over all of the values in all the PHI nodes. 1324 for (unsigned i = 0; i != NumPreds; ++i) { 1325 // If the value being merged in is not integer or is not defined 1326 // in the loop, skip it. 1327 Value *InVal = PN->getIncomingValue(i); 1328 if (!isa<Instruction>(InVal)) 1329 continue; 1330 1331 // If this pred is for a subloop, not L itself, skip it. 1332 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 1333 continue; // The Block is in a subloop, skip it. 1334 1335 // Check that InVal is defined in the loop. 1336 Instruction *Inst = cast<Instruction>(InVal); 1337 if (!L->contains(Inst)) 1338 continue; 1339 1340 // Okay, this instruction has a user outside of the current loop 1341 // and varies predictably *inside* the loop. Evaluate the value it 1342 // contains when the loop exits, if possible. We prefer to start with 1343 // expressions which are true for all exits (so as to maximize 1344 // expression reuse by the SCEVExpander), but resort to per-exit 1345 // evaluation if that fails. 1346 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 1347 if (isa<SCEVCouldNotCompute>(ExitValue) || 1348 !SE->isLoopInvariant(ExitValue, L) || 1349 !isSafeToExpand(ExitValue, *SE)) { 1350 // TODO: This should probably be sunk into SCEV in some way; maybe a 1351 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for 1352 // most SCEV expressions and other recurrence types (e.g. shift 1353 // recurrences). Is there existing code we can reuse? 1354 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i)); 1355 if (isa<SCEVCouldNotCompute>(ExitCount)) 1356 continue; 1357 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst))) 1358 if (AddRec->getLoop() == L) 1359 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE); 1360 if (isa<SCEVCouldNotCompute>(ExitValue) || 1361 !SE->isLoopInvariant(ExitValue, L) || 1362 !isSafeToExpand(ExitValue, *SE)) 1363 continue; 1364 } 1365 1366 // Computing the value outside of the loop brings no benefit if it is 1367 // definitely used inside the loop in a way which can not be optimized 1368 // away. Avoid doing so unless we know we have a value which computes 1369 // the ExitValue already. TODO: This should be merged into SCEV 1370 // expander to leverage its knowledge of existing expressions. 1371 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) && 1372 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst)) 1373 continue; 1374 1375 bool HighCost = Rewriter.isHighCostExpansion( 1376 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst); 1377 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); 1378 1379 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " 1380 << *ExitVal << '\n' << " LoopVal = " << *Inst 1381 << "\n"); 1382 1383 if (!isValidRewrite(SE, Inst, ExitVal)) { 1384 DeadInsts.push_back(ExitVal); 1385 continue; 1386 } 1387 1388 #ifndef NDEBUG 1389 // If we reuse an instruction from a loop which is neither L nor one of 1390 // its containing loops, we end up breaking LCSSA form for this loop by 1391 // creating a new use of its instruction. 1392 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal)) 1393 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent())) 1394 if (EVL != L) 1395 assert(EVL->contains(L) && "LCSSA breach detected!"); 1396 #endif 1397 1398 // Collect all the candidate PHINodes to be rewritten. 1399 RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost); 1400 } 1401 } 1402 } 1403 1404 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 1405 int NumReplaced = 0; 1406 1407 // Transformation. 1408 for (const RewritePhi &Phi : RewritePhiSet) { 1409 PHINode *PN = Phi.PN; 1410 Value *ExitVal = Phi.Val; 1411 1412 // Only do the rewrite when the ExitValue can be expanded cheaply. 1413 // If LoopCanBeDel is true, rewrite exit value aggressively. 1414 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 1415 DeadInsts.push_back(ExitVal); 1416 continue; 1417 } 1418 1419 NumReplaced++; 1420 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 1421 PN->setIncomingValue(Phi.Ith, ExitVal); 1422 1423 // If this instruction is dead now, delete it. Don't do it now to avoid 1424 // invalidating iterators. 1425 if (isInstructionTriviallyDead(Inst, TLI)) 1426 DeadInsts.push_back(Inst); 1427 1428 // Replace PN with ExitVal if that is legal and does not break LCSSA. 1429 if (PN->getNumIncomingValues() == 1 && 1430 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 1431 PN->replaceAllUsesWith(ExitVal); 1432 PN->eraseFromParent(); 1433 } 1434 } 1435 1436 // The insertion point instruction may have been deleted; clear it out 1437 // so that the rewriter doesn't trip over it later. 1438 Rewriter.clearInsertPoint(); 1439 return NumReplaced; 1440 } 1441 1442 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for 1443 /// \p OrigLoop. 1444 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, 1445 Loop *RemainderLoop, uint64_t UF) { 1446 assert(UF > 0 && "Zero unrolled factor is not supported"); 1447 assert(UnrolledLoop != RemainderLoop && 1448 "Unrolled and Remainder loops are expected to distinct"); 1449 1450 // Get number of iterations in the original scalar loop. 1451 unsigned OrigLoopInvocationWeight = 0; 1452 Optional<unsigned> OrigAverageTripCount = 1453 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight); 1454 if (!OrigAverageTripCount) 1455 return; 1456 1457 // Calculate number of iterations in unrolled loop. 1458 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF; 1459 // Calculate number of iterations for remainder loop. 1460 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF; 1461 1462 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount, 1463 OrigLoopInvocationWeight); 1464 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount, 1465 OrigLoopInvocationWeight); 1466 } 1467 1468 /// Utility that implements appending of loops onto a worklist. 1469 /// Loops are added in preorder (analogous for reverse postorder for trees), 1470 /// and the worklist is processed LIFO. 1471 template <typename RangeT> 1472 void llvm::appendReversedLoopsToWorklist( 1473 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) { 1474 // We use an internal worklist to build up the preorder traversal without 1475 // recursion. 1476 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1477 1478 // We walk the initial sequence of loops in reverse because we generally want 1479 // to visit defs before uses and the worklist is LIFO. 1480 for (Loop *RootL : Loops) { 1481 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1482 assert(PreOrderWorklist.empty() && 1483 "Must start with an empty preorder walk worklist."); 1484 PreOrderWorklist.push_back(RootL); 1485 do { 1486 Loop *L = PreOrderWorklist.pop_back_val(); 1487 PreOrderWorklist.append(L->begin(), L->end()); 1488 PreOrderLoops.push_back(L); 1489 } while (!PreOrderWorklist.empty()); 1490 1491 Worklist.insert(std::move(PreOrderLoops)); 1492 PreOrderLoops.clear(); 1493 } 1494 } 1495 1496 template <typename RangeT> 1497 void llvm::appendLoopsToWorklist(RangeT &&Loops, 1498 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1499 appendReversedLoopsToWorklist(reverse(Loops), Worklist); 1500 } 1501 1502 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>( 1503 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist); 1504 1505 template void 1506 llvm::appendLoopsToWorklist<Loop &>(Loop &L, 1507 SmallPriorityWorklist<Loop *, 4> &Worklist); 1508 1509 void llvm::appendLoopsToWorklist(LoopInfo &LI, 1510 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1511 appendReversedLoopsToWorklist(LI, Worklist); 1512 } 1513 1514 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, 1515 LoopInfo *LI, LPPassManager *LPM) { 1516 Loop &New = *LI->AllocateLoop(); 1517 if (PL) 1518 PL->addChildLoop(&New); 1519 else 1520 LI->addTopLevelLoop(&New); 1521 1522 if (LPM) 1523 LPM->addLoop(New); 1524 1525 // Add all of the blocks in L to the new loop. 1526 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 1527 I != E; ++I) 1528 if (LI->getLoopFor(*I) == L) 1529 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); 1530 1531 // Add all of the subloops to the new loop. 1532 for (Loop *I : *L) 1533 cloneLoop(I, &New, VM, LI, LPM); 1534 1535 return &New; 1536 } 1537 1538 /// IR Values for the lower and upper bounds of a pointer evolution. We 1539 /// need to use value-handles because SCEV expansion can invalidate previously 1540 /// expanded values. Thus expansion of a pointer can invalidate the bounds for 1541 /// a previous one. 1542 struct PointerBounds { 1543 TrackingVH<Value> Start; 1544 TrackingVH<Value> End; 1545 }; 1546 1547 /// Expand code for the lower and upper bound of the pointer group \p CG 1548 /// in \p TheLoop. \return the values for the bounds. 1549 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG, 1550 Loop *TheLoop, Instruction *Loc, 1551 SCEVExpander &Exp, ScalarEvolution *SE) { 1552 // TODO: Add helper to retrieve pointers to CG. 1553 Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue; 1554 const SCEV *Sc = SE->getSCEV(Ptr); 1555 1556 unsigned AS = Ptr->getType()->getPointerAddressSpace(); 1557 LLVMContext &Ctx = Loc->getContext(); 1558 1559 // Use this type for pointer arithmetic. 1560 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); 1561 1562 if (SE->isLoopInvariant(Sc, TheLoop)) { 1563 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" 1564 << *Ptr << "\n"); 1565 // Ptr could be in the loop body. If so, expand a new one at the correct 1566 // location. 1567 Instruction *Inst = dyn_cast<Instruction>(Ptr); 1568 Value *NewPtr = (Inst && TheLoop->contains(Inst)) 1569 ? Exp.expandCodeFor(Sc, PtrArithTy, Loc) 1570 : Ptr; 1571 // We must return a half-open range, which means incrementing Sc. 1572 const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy)); 1573 Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc); 1574 return {NewPtr, NewPtrPlusOne}; 1575 } else { 1576 Value *Start = nullptr, *End = nullptr; 1577 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n"); 1578 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc); 1579 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc); 1580 LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High 1581 << "\n"); 1582 return {Start, End}; 1583 } 1584 } 1585 1586 /// Turns a collection of checks into a collection of expanded upper and 1587 /// lower bounds for both pointers in the check. 1588 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> 1589 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L, 1590 Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) { 1591 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds; 1592 1593 // Here we're relying on the SCEV Expander's cache to only emit code for the 1594 // same bounds once. 1595 transform(PointerChecks, std::back_inserter(ChecksWithBounds), 1596 [&](const RuntimePointerCheck &Check) { 1597 PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE), 1598 Second = 1599 expandBounds(Check.second, L, Loc, Exp, SE); 1600 return std::make_pair(First, Second); 1601 }); 1602 1603 return ChecksWithBounds; 1604 } 1605 1606 std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks( 1607 Instruction *Loc, Loop *TheLoop, 1608 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, 1609 ScalarEvolution *SE) { 1610 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible. 1611 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible 1612 const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 1613 SCEVExpander Exp(*SE, DL, "induction"); 1614 auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp); 1615 1616 LLVMContext &Ctx = Loc->getContext(); 1617 Instruction *FirstInst = nullptr; 1618 IRBuilder<> ChkBuilder(Loc); 1619 // Our instructions might fold to a constant. 1620 Value *MemoryRuntimeCheck = nullptr; 1621 1622 // FIXME: this helper is currently a duplicate of the one in 1623 // LoopVectorize.cpp. 1624 auto GetFirstInst = [](Instruction *FirstInst, Value *V, 1625 Instruction *Loc) -> Instruction * { 1626 if (FirstInst) 1627 return FirstInst; 1628 if (Instruction *I = dyn_cast<Instruction>(V)) 1629 return I->getParent() == Loc->getParent() ? I : nullptr; 1630 return nullptr; 1631 }; 1632 1633 for (const auto &Check : ExpandedChecks) { 1634 const PointerBounds &A = Check.first, &B = Check.second; 1635 // Check if two pointers (A and B) conflict where conflict is computed as: 1636 // start(A) <= end(B) && start(B) <= end(A) 1637 unsigned AS0 = A.Start->getType()->getPointerAddressSpace(); 1638 unsigned AS1 = B.Start->getType()->getPointerAddressSpace(); 1639 1640 assert((AS0 == B.End->getType()->getPointerAddressSpace()) && 1641 (AS1 == A.End->getType()->getPointerAddressSpace()) && 1642 "Trying to bounds check pointers with different address spaces"); 1643 1644 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); 1645 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); 1646 1647 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc"); 1648 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc"); 1649 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc"); 1650 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc"); 1651 1652 // [A|B].Start points to the first accessed byte under base [A|B]. 1653 // [A|B].End points to the last accessed byte, plus one. 1654 // There is no conflict when the intervals are disjoint: 1655 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End) 1656 // 1657 // bound0 = (B.Start < A.End) 1658 // bound1 = (A.Start < B.End) 1659 // IsConflict = bound0 & bound1 1660 Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0"); 1661 FirstInst = GetFirstInst(FirstInst, Cmp0, Loc); 1662 Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1"); 1663 FirstInst = GetFirstInst(FirstInst, Cmp1, Loc); 1664 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1665 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1666 if (MemoryRuntimeCheck) { 1667 IsConflict = 1668 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx"); 1669 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1670 } 1671 MemoryRuntimeCheck = IsConflict; 1672 } 1673 1674 if (!MemoryRuntimeCheck) 1675 return std::make_pair(nullptr, nullptr); 1676 1677 // We have to do this trickery because the IRBuilder might fold the check to a 1678 // constant expression in which case there is no Instruction anchored in a 1679 // the block. 1680 Instruction *Check = 1681 BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx)); 1682 ChkBuilder.Insert(Check, "memcheck.conflict"); 1683 FirstInst = GetFirstInst(FirstInst, Check, Loc); 1684 return std::make_pair(FirstInst, Check); 1685 } 1686