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