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/Module.h" 36 #include "llvm/IR/PatternMatch.h" 37 #include "llvm/IR/ValueHandle.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/KnownBits.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 44 using namespace llvm; 45 using namespace llvm::PatternMatch; 46 47 #define DEBUG_TYPE "loop-utils" 48 49 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 50 static const char *LLVMLoopDisableLICM = "llvm.licm.disable"; 51 52 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 53 MemorySSAUpdater *MSSAU, 54 bool PreserveLCSSA) { 55 bool Changed = false; 56 57 // We re-use a vector for the in-loop predecesosrs. 58 SmallVector<BasicBlock *, 4> InLoopPredecessors; 59 60 auto RewriteExit = [&](BasicBlock *BB) { 61 assert(InLoopPredecessors.empty() && 62 "Must start with an empty predecessors list!"); 63 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 64 65 // See if there are any non-loop predecessors of this exit block and 66 // keep track of the in-loop predecessors. 67 bool IsDedicatedExit = true; 68 for (auto *PredBB : predecessors(BB)) 69 if (L->contains(PredBB)) { 70 if (isa<IndirectBrInst>(PredBB->getTerminator())) 71 // We cannot rewrite exiting edges from an indirectbr. 72 return false; 73 if (isa<CallBrInst>(PredBB->getTerminator())) 74 // We cannot rewrite exiting edges from a callbr. 75 return false; 76 77 InLoopPredecessors.push_back(PredBB); 78 } else { 79 IsDedicatedExit = false; 80 } 81 82 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!"); 83 84 // Nothing to do if this is already a dedicated exit. 85 if (IsDedicatedExit) 86 return false; 87 88 auto *NewExitBB = SplitBlockPredecessors( 89 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA); 90 91 if (!NewExitBB) 92 LLVM_DEBUG( 93 dbgs() << "WARNING: Can't create a dedicated exit block for loop: " 94 << *L << "\n"); 95 else 96 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 97 << NewExitBB->getName() << "\n"); 98 return true; 99 }; 100 101 // Walk the exit blocks directly rather than building up a data structure for 102 // them, but only visit each one once. 103 SmallPtrSet<BasicBlock *, 4> Visited; 104 for (auto *BB : L->blocks()) 105 for (auto *SuccBB : successors(BB)) { 106 // We're looking for exit blocks so skip in-loop successors. 107 if (L->contains(SuccBB)) 108 continue; 109 110 // Visit each exit block exactly once. 111 if (!Visited.insert(SuccBB).second) 112 continue; 113 114 Changed |= RewriteExit(SuccBB); 115 } 116 117 return Changed; 118 } 119 120 /// Returns the instructions that use values defined in the loop. 121 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 122 SmallVector<Instruction *, 8> UsedOutside; 123 124 for (auto *Block : L->getBlocks()) 125 // FIXME: I believe that this could use copy_if if the Inst reference could 126 // be adapted into a pointer. 127 for (auto &Inst : *Block) { 128 auto Users = Inst.users(); 129 if (any_of(Users, [&](User *U) { 130 auto *Use = cast<Instruction>(U); 131 return !L->contains(Use->getParent()); 132 })) 133 UsedOutside.push_back(&Inst); 134 } 135 136 return UsedOutside; 137 } 138 139 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 140 // By definition, all loop passes need the LoopInfo analysis and the 141 // Dominator tree it depends on. Because they all participate in the loop 142 // pass manager, they must also preserve these. 143 AU.addRequired<DominatorTreeWrapperPass>(); 144 AU.addPreserved<DominatorTreeWrapperPass>(); 145 AU.addRequired<LoopInfoWrapperPass>(); 146 AU.addPreserved<LoopInfoWrapperPass>(); 147 148 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 149 // here because users shouldn't directly get them from this header. 150 extern char &LoopSimplifyID; 151 extern char &LCSSAID; 152 AU.addRequiredID(LoopSimplifyID); 153 AU.addPreservedID(LoopSimplifyID); 154 AU.addRequiredID(LCSSAID); 155 AU.addPreservedID(LCSSAID); 156 // This is used in the LPPassManager to perform LCSSA verification on passes 157 // which preserve lcssa form 158 AU.addRequired<LCSSAVerificationPass>(); 159 AU.addPreserved<LCSSAVerificationPass>(); 160 161 // Loop passes are designed to run inside of a loop pass manager which means 162 // that any function analyses they require must be required by the first loop 163 // pass in the manager (so that it is computed before the loop pass manager 164 // runs) and preserved by all loop pasess in the manager. To make this 165 // reasonably robust, the set needed for most loop passes is maintained here. 166 // If your loop pass requires an analysis not listed here, you will need to 167 // carefully audit the loop pass manager nesting structure that results. 168 AU.addRequired<AAResultsWrapperPass>(); 169 AU.addPreserved<AAResultsWrapperPass>(); 170 AU.addPreserved<BasicAAWrapperPass>(); 171 AU.addPreserved<GlobalsAAWrapperPass>(); 172 AU.addPreserved<SCEVAAWrapperPass>(); 173 AU.addRequired<ScalarEvolutionWrapperPass>(); 174 AU.addPreserved<ScalarEvolutionWrapperPass>(); 175 // FIXME: When all loop passes preserve MemorySSA, it can be required and 176 // preserved here instead of the individual handling in each pass. 177 } 178 179 /// Manually defined generic "LoopPass" dependency initialization. This is used 180 /// to initialize the exact set of passes from above in \c 181 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 182 /// with: 183 /// 184 /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 185 /// 186 /// As-if "LoopPass" were a pass. 187 void llvm::initializeLoopPassPass(PassRegistry &Registry) { 188 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 189 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 190 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 191 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 192 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 193 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 194 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 195 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 196 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 197 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 198 } 199 200 /// Create MDNode for input string. 201 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) { 202 LLVMContext &Context = TheLoop->getHeader()->getContext(); 203 Metadata *MDs[] = { 204 MDString::get(Context, Name), 205 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))}; 206 return MDNode::get(Context, MDs); 207 } 208 209 /// Set input string into loop metadata by keeping other values intact. 210 /// If the string is already in loop metadata update value if it is 211 /// different. 212 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD, 213 unsigned V) { 214 SmallVector<Metadata *, 4> MDs(1); 215 // If the loop already has metadata, retain it. 216 MDNode *LoopID = TheLoop->getLoopID(); 217 if (LoopID) { 218 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 219 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 220 // If it is of form key = value, try to parse it. 221 if (Node->getNumOperands() == 2) { 222 MDString *S = dyn_cast<MDString>(Node->getOperand(0)); 223 if (S && S->getString().equals(StringMD)) { 224 ConstantInt *IntMD = 225 mdconst::extract_or_null<ConstantInt>(Node->getOperand(1)); 226 if (IntMD && IntMD->getSExtValue() == V) 227 // It is already in place. Do nothing. 228 return; 229 // We need to update the value, so just skip it here and it will 230 // be added after copying other existed nodes. 231 continue; 232 } 233 } 234 MDs.push_back(Node); 235 } 236 } 237 // Add new metadata. 238 MDs.push_back(createStringMetadata(TheLoop, StringMD, V)); 239 // Replace current metadata node with new one. 240 LLVMContext &Context = TheLoop->getHeader()->getContext(); 241 MDNode *NewLoopID = MDNode::get(Context, MDs); 242 // Set operand 0 to refer to the loop id itself. 243 NewLoopID->replaceOperandWith(0, NewLoopID); 244 TheLoop->setLoopID(NewLoopID); 245 } 246 247 /// Find string metadata for loop 248 /// 249 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 250 /// operand or null otherwise. If the string metadata is not found return 251 /// Optional's not-a-value. 252 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, 253 StringRef Name) { 254 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 255 if (!MD) 256 return None; 257 switch (MD->getNumOperands()) { 258 case 1: 259 return nullptr; 260 case 2: 261 return &MD->getOperand(1); 262 default: 263 llvm_unreachable("loop metadata has 0 or 1 operand"); 264 } 265 } 266 267 static Optional<bool> getOptionalBoolLoopAttribute(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 // When the value is absent it is interpreted as 'attribute set'. 275 return true; 276 case 2: 277 if (ConstantInt *IntMD = 278 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) 279 return IntMD->getZExtValue(); 280 return true; 281 } 282 llvm_unreachable("unexpected number of options"); 283 } 284 285 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 286 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 287 } 288 289 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 290 StringRef Name) { 291 const MDOperand *AttrMD = 292 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 293 if (!AttrMD) 294 return None; 295 296 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 297 if (!IntMD) 298 return None; 299 300 return IntMD->getSExtValue(); 301 } 302 303 Optional<MDNode *> llvm::makeFollowupLoopID( 304 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 305 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 306 if (!OrigLoopID) { 307 if (AlwaysNew) 308 return nullptr; 309 return None; 310 } 311 312 assert(OrigLoopID->getOperand(0) == OrigLoopID); 313 314 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 315 bool InheritSomeAttrs = 316 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 317 SmallVector<Metadata *, 8> MDs; 318 MDs.push_back(nullptr); 319 320 bool Changed = false; 321 if (InheritAllAttrs || InheritSomeAttrs) { 322 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 323 MDNode *Op = cast<MDNode>(Existing.get()); 324 325 auto InheritThisAttribute = [InheritSomeAttrs, 326 InheritOptionsExceptPrefix](MDNode *Op) { 327 if (!InheritSomeAttrs) 328 return false; 329 330 // Skip malformatted attribute metadata nodes. 331 if (Op->getNumOperands() == 0) 332 return true; 333 Metadata *NameMD = Op->getOperand(0).get(); 334 if (!isa<MDString>(NameMD)) 335 return true; 336 StringRef AttrName = cast<MDString>(NameMD)->getString(); 337 338 // Do not inherit excluded attributes. 339 return !AttrName.startswith(InheritOptionsExceptPrefix); 340 }; 341 342 if (InheritThisAttribute(Op)) 343 MDs.push_back(Op); 344 else 345 Changed = true; 346 } 347 } else { 348 // Modified if we dropped at least one attribute. 349 Changed = OrigLoopID->getNumOperands() > 1; 350 } 351 352 bool HasAnyFollowup = false; 353 for (StringRef OptionName : FollowupOptions) { 354 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 355 if (!FollowupNode) 356 continue; 357 358 HasAnyFollowup = true; 359 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 360 MDs.push_back(Option.get()); 361 Changed = true; 362 } 363 } 364 365 // Attributes of the followup loop not specified explicity, so signal to the 366 // transformation pass to add suitable attributes. 367 if (!AlwaysNew && !HasAnyFollowup) 368 return None; 369 370 // If no attributes were added or remove, the previous loop Id can be reused. 371 if (!AlwaysNew && !Changed) 372 return OrigLoopID; 373 374 // No attributes is equivalent to having no !llvm.loop metadata at all. 375 if (MDs.size() == 1) 376 return nullptr; 377 378 // Build the new loop ID. 379 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 380 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 381 return FollowupLoopID; 382 } 383 384 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 385 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 386 } 387 388 bool llvm::hasDisableLICMTransformsHint(const Loop *L) { 389 return getBooleanLoopAttribute(L, LLVMLoopDisableLICM); 390 } 391 392 TransformationMode llvm::hasUnrollTransformation(Loop *L) { 393 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 394 return TM_SuppressedByUser; 395 396 Optional<int> Count = 397 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 398 if (Count.hasValue()) 399 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 400 401 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 402 return TM_ForcedByUser; 403 404 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 405 return TM_ForcedByUser; 406 407 if (hasDisableAllTransformsHint(L)) 408 return TM_Disable; 409 410 return TM_Unspecified; 411 } 412 413 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 414 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 415 return TM_SuppressedByUser; 416 417 Optional<int> Count = 418 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 419 if (Count.hasValue()) 420 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 421 422 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 423 return TM_ForcedByUser; 424 425 if (hasDisableAllTransformsHint(L)) 426 return TM_Disable; 427 428 return TM_Unspecified; 429 } 430 431 TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 432 Optional<bool> Enable = 433 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 434 435 if (Enable == false) 436 return TM_SuppressedByUser; 437 438 Optional<int> VectorizeWidth = 439 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 440 Optional<int> InterleaveCount = 441 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 442 443 // 'Forcing' vector width and interleave count to one effectively disables 444 // this tranformation. 445 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1) 446 return TM_SuppressedByUser; 447 448 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 449 return TM_Disable; 450 451 if (Enable == true) 452 return TM_ForcedByUser; 453 454 if (VectorizeWidth == 1 && InterleaveCount == 1) 455 return TM_Disable; 456 457 if (VectorizeWidth > 1 || InterleaveCount > 1) 458 return TM_Enable; 459 460 if (hasDisableAllTransformsHint(L)) 461 return TM_Disable; 462 463 return TM_Unspecified; 464 } 465 466 TransformationMode llvm::hasDistributeTransformation(Loop *L) { 467 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 468 return TM_ForcedByUser; 469 470 if (hasDisableAllTransformsHint(L)) 471 return TM_Disable; 472 473 return TM_Unspecified; 474 } 475 476 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 477 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 478 return TM_SuppressedByUser; 479 480 if (hasDisableAllTransformsHint(L)) 481 return TM_Disable; 482 483 return TM_Unspecified; 484 } 485 486 /// Does a BFS from a given node to all of its children inside a given loop. 487 /// The returned vector of nodes includes the starting point. 488 SmallVector<DomTreeNode *, 16> 489 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 490 SmallVector<DomTreeNode *, 16> Worklist; 491 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 492 // Only include subregions in the top level loop. 493 BasicBlock *BB = DTN->getBlock(); 494 if (CurLoop->contains(BB)) 495 Worklist.push_back(DTN); 496 }; 497 498 AddRegionToWorklist(N); 499 500 for (size_t I = 0; I < Worklist.size(); I++) 501 for (DomTreeNode *Child : Worklist[I]->getChildren()) 502 AddRegionToWorklist(Child); 503 504 return Worklist; 505 } 506 507 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr, 508 ScalarEvolution *SE = nullptr, 509 LoopInfo *LI = nullptr) { 510 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 511 auto *Preheader = L->getLoopPreheader(); 512 assert(Preheader && "Preheader should exist!"); 513 514 // Now that we know the removal is safe, remove the loop by changing the 515 // branch from the preheader to go to the single exit block. 516 // 517 // Because we're deleting a large chunk of code at once, the sequence in which 518 // we remove things is very important to avoid invalidation issues. 519 520 // Tell ScalarEvolution that the loop is deleted. Do this before 521 // deleting the loop so that ScalarEvolution can look at the loop 522 // to determine what it needs to clean up. 523 if (SE) 524 SE->forgetLoop(L); 525 526 auto *ExitBlock = L->getUniqueExitBlock(); 527 assert(ExitBlock && "Should have a unique exit block!"); 528 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 529 530 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 531 assert(OldBr && "Preheader must end with a branch"); 532 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 533 // Connect the preheader to the exit block. Keep the old edge to the header 534 // around to perform the dominator tree update in two separate steps 535 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 536 // preheader -> header. 537 // 538 // 539 // 0. Preheader 1. Preheader 2. Preheader 540 // | | | | 541 // V | V | 542 // Header <--\ | Header <--\ | Header <--\ 543 // | | | | | | | | | | | 544 // | V | | | V | | | V | 545 // | Body --/ | | Body --/ | | Body --/ 546 // V V V V V 547 // Exit Exit Exit 548 // 549 // By doing this is two separate steps we can perform the dominator tree 550 // update without using the batch update API. 551 // 552 // Even when the loop is never executed, we cannot remove the edge from the 553 // source block to the exit block. Consider the case where the unexecuted loop 554 // branches back to an outer loop. If we deleted the loop and removed the edge 555 // coming to this inner loop, this will break the outer loop structure (by 556 // deleting the backedge of the outer loop). If the outer loop is indeed a 557 // non-loop, it will be deleted in a future iteration of loop deletion pass. 558 IRBuilder<> Builder(OldBr); 559 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 560 // Remove the old branch. The conditional branch becomes a new terminator. 561 OldBr->eraseFromParent(); 562 563 // Rewrite phis in the exit block to get their inputs from the Preheader 564 // instead of the exiting block. 565 for (PHINode &P : ExitBlock->phis()) { 566 // Set the zero'th element of Phi to be from the preheader and remove all 567 // other incoming values. Given the loop has dedicated exits, all other 568 // incoming values must be from the exiting blocks. 569 int PredIndex = 0; 570 P.setIncomingBlock(PredIndex, Preheader); 571 // Removes all incoming values from all other exiting blocks (including 572 // duplicate values from an exiting block). 573 // Nuke all entries except the zero'th entry which is the preheader entry. 574 // NOTE! We need to remove Incoming Values in the reverse order as done 575 // below, to keep the indices valid for deletion (removeIncomingValues 576 // updates getNumIncomingValues and shifts all values down into the operand 577 // being deleted). 578 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 579 P.removeIncomingValue(e - i, false); 580 581 assert((P.getNumIncomingValues() == 1 && 582 P.getIncomingBlock(PredIndex) == Preheader) && 583 "Should have exactly one value and that's from the preheader!"); 584 } 585 586 // Disconnect the loop body by branching directly to its exit. 587 Builder.SetInsertPoint(Preheader->getTerminator()); 588 Builder.CreateBr(ExitBlock); 589 // Remove the old branch. 590 Preheader->getTerminator()->eraseFromParent(); 591 592 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 593 if (DT) { 594 // Update the dominator tree by informing it about the new edge from the 595 // preheader to the exit and the removed edge. 596 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}, 597 {DominatorTree::Delete, Preheader, L->getHeader()}}); 598 } 599 600 // Use a map to unique and a vector to guarantee deterministic ordering. 601 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 602 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 603 604 // Given LCSSA form is satisfied, we should not have users of instructions 605 // within the dead loop outside of the loop. However, LCSSA doesn't take 606 // unreachable uses into account. We handle them here. 607 // We could do it after drop all references (in this case all users in the 608 // loop will be already eliminated and we have less work to do but according 609 // to API doc of User::dropAllReferences only valid operation after dropping 610 // references, is deletion. So let's substitute all usages of 611 // instruction from the loop with undef value of corresponding type first. 612 for (auto *Block : L->blocks()) 613 for (Instruction &I : *Block) { 614 auto *Undef = UndefValue::get(I.getType()); 615 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 616 Use &U = *UI; 617 ++UI; 618 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 619 if (L->contains(Usr->getParent())) 620 continue; 621 // If we have a DT then we can check that uses outside a loop only in 622 // unreachable block. 623 if (DT) 624 assert(!DT->isReachableFromEntry(U) && 625 "Unexpected user in reachable block"); 626 U.set(Undef); 627 } 628 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 629 if (!DVI) 630 continue; 631 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 632 if (Key != DeadDebugSet.end()) 633 continue; 634 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 635 DeadDebugInst.push_back(DVI); 636 } 637 638 // After the loop has been deleted all the values defined and modified 639 // inside the loop are going to be unavailable. 640 // Since debug values in the loop have been deleted, inserting an undef 641 // dbg.value truncates the range of any dbg.value before the loop where the 642 // loop used to be. This is particularly important for constant values. 643 DIBuilder DIB(*ExitBlock->getModule()); 644 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 645 assert(InsertDbgValueBefore && 646 "There should be a non-PHI instruction in exit block, else these " 647 "instructions will have no parent."); 648 for (auto *DVI : DeadDebugInst) 649 DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), 650 DVI->getVariable(), DVI->getExpression(), 651 DVI->getDebugLoc(), InsertDbgValueBefore); 652 653 // Remove the block from the reference counting scheme, so that we can 654 // delete it freely later. 655 for (auto *Block : L->blocks()) 656 Block->dropAllReferences(); 657 658 if (LI) { 659 // Erase the instructions and the blocks without having to worry 660 // about ordering because we already dropped the references. 661 // NOTE: This iteration is safe because erasing the block does not remove 662 // its entry from the loop's block list. We do that in the next section. 663 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 664 LpI != LpE; ++LpI) 665 (*LpI)->eraseFromParent(); 666 667 // Finally, the blocks from loopinfo. This has to happen late because 668 // otherwise our loop iterators won't work. 669 670 SmallPtrSet<BasicBlock *, 8> blocks; 671 blocks.insert(L->block_begin(), L->block_end()); 672 for (BasicBlock *BB : blocks) 673 LI->removeBlock(BB); 674 675 // The last step is to update LoopInfo now that we've eliminated this loop. 676 // Note: LoopInfo::erase remove the given loop and relink its subloops with 677 // its parent. While removeLoop/removeChildLoop remove the given loop but 678 // not relink its subloops, which is what we want. 679 if (Loop *ParentLoop = L->getParentLoop()) { 680 Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L); 681 assert(I != ParentLoop->end() && "Couldn't find loop"); 682 ParentLoop->removeChildLoop(I); 683 } else { 684 Loop::iterator I = find(LI->begin(), LI->end(), L); 685 assert(I != LI->end() && "Couldn't find loop"); 686 LI->removeLoop(I); 687 } 688 LI->destroy(L); 689 } 690 } 691 692 Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { 693 // Support loops with an exiting latch and other existing exists only 694 // deoptimize. 695 696 // Get the branch weights for the loop's backedge. 697 BasicBlock *Latch = L->getLoopLatch(); 698 if (!Latch) 699 return None; 700 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 701 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 702 return None; 703 704 assert((LatchBR->getSuccessor(0) == L->getHeader() || 705 LatchBR->getSuccessor(1) == L->getHeader()) && 706 "At least one edge out of the latch must go to the header"); 707 708 SmallVector<BasicBlock *, 4> ExitBlocks; 709 L->getUniqueNonLatchExitBlocks(ExitBlocks); 710 if (any_of(ExitBlocks, [](const BasicBlock *EB) { 711 return !EB->getTerminatingDeoptimizeCall(); 712 })) 713 return None; 714 715 // To estimate the number of times the loop body was executed, we want to 716 // know the number of times the backedge was taken, vs. the number of times 717 // we exited the loop. 718 uint64_t TrueVal, FalseVal; 719 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal)) 720 return None; 721 722 if (!TrueVal || !FalseVal) 723 return 0; 724 725 // Divide the count of the backedge by the count of the edge exiting the loop, 726 // rounding to nearest. 727 if (LatchBR->getSuccessor(0) == L->getHeader()) 728 return (TrueVal + (FalseVal / 2)) / FalseVal; 729 else 730 return (FalseVal + (TrueVal / 2)) / TrueVal; 731 } 732 733 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 734 ScalarEvolution &SE) { 735 Loop *OuterL = InnerLoop->getParentLoop(); 736 if (!OuterL) 737 return true; 738 739 // Get the backedge taken count for the inner loop 740 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 741 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 742 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 743 !InnerLoopBECountSC->getType()->isIntegerTy()) 744 return false; 745 746 // Get whether count is invariant to the outer loop 747 ScalarEvolution::LoopDisposition LD = 748 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 749 if (LD != ScalarEvolution::LoopInvariant) 750 return false; 751 752 return true; 753 } 754 755 Value *llvm::createMinMaxOp(IRBuilder<> &Builder, 756 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 757 Value *Left, Value *Right) { 758 CmpInst::Predicate P = CmpInst::ICMP_NE; 759 switch (RK) { 760 default: 761 llvm_unreachable("Unknown min/max recurrence kind"); 762 case RecurrenceDescriptor::MRK_UIntMin: 763 P = CmpInst::ICMP_ULT; 764 break; 765 case RecurrenceDescriptor::MRK_UIntMax: 766 P = CmpInst::ICMP_UGT; 767 break; 768 case RecurrenceDescriptor::MRK_SIntMin: 769 P = CmpInst::ICMP_SLT; 770 break; 771 case RecurrenceDescriptor::MRK_SIntMax: 772 P = CmpInst::ICMP_SGT; 773 break; 774 case RecurrenceDescriptor::MRK_FloatMin: 775 P = CmpInst::FCMP_OLT; 776 break; 777 case RecurrenceDescriptor::MRK_FloatMax: 778 P = CmpInst::FCMP_OGT; 779 break; 780 } 781 782 // We only match FP sequences that are 'fast', so we can unconditionally 783 // set it on any generated instructions. 784 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 785 FastMathFlags FMF; 786 FMF.setFast(); 787 Builder.setFastMathFlags(FMF); 788 789 Value *Cmp; 790 if (RK == RecurrenceDescriptor::MRK_FloatMin || 791 RK == RecurrenceDescriptor::MRK_FloatMax) 792 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 793 else 794 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 795 796 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 797 return Select; 798 } 799 800 // Helper to generate an ordered reduction. 801 Value * 802 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src, 803 unsigned Op, 804 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 805 ArrayRef<Value *> RedOps) { 806 unsigned VF = Src->getType()->getVectorNumElements(); 807 808 // Extract and apply reduction ops in ascending order: 809 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 810 Value *Result = Acc; 811 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 812 Value *Ext = 813 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 814 815 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 816 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 817 "bin.rdx"); 818 } else { 819 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 820 "Invalid min/max"); 821 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 822 } 823 824 if (!RedOps.empty()) 825 propagateIRFlags(Result, RedOps); 826 } 827 828 return Result; 829 } 830 831 // Helper to generate a log2 shuffle reduction. 832 Value * 833 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, 834 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 835 ArrayRef<Value *> RedOps) { 836 unsigned VF = Src->getType()->getVectorNumElements(); 837 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 838 // and vector ops, reducing the set of values being computed by half each 839 // round. 840 assert(isPowerOf2_32(VF) && 841 "Reduction emission only supported for pow2 vectors!"); 842 Value *TmpVec = Src; 843 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 844 for (unsigned i = VF; i != 1; i >>= 1) { 845 // Move the upper half of the vector to the lower half. 846 for (unsigned j = 0; j != i / 2; ++j) 847 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 848 849 // Fill the rest of the mask with undef. 850 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 851 UndefValue::get(Builder.getInt32Ty())); 852 853 Value *Shuf = Builder.CreateShuffleVector( 854 TmpVec, UndefValue::get(TmpVec->getType()), 855 ConstantVector::get(ShuffleMask), "rdx.shuf"); 856 857 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 858 // The builder propagates its fast-math-flags setting. 859 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 860 "bin.rdx"); 861 } else { 862 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 863 "Invalid min/max"); 864 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 865 } 866 if (!RedOps.empty()) 867 propagateIRFlags(TmpVec, RedOps); 868 } 869 // The result is in the first element of the vector. 870 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 871 } 872 873 /// Create a simple vector reduction specified by an opcode and some 874 /// flags (if generating min/max reductions). 875 Value *llvm::createSimpleTargetReduction( 876 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 877 Value *Src, TargetTransformInfo::ReductionFlags Flags, 878 ArrayRef<Value *> RedOps) { 879 assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); 880 881 std::function<Value *()> BuildFunc; 882 using RD = RecurrenceDescriptor; 883 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 884 885 switch (Opcode) { 886 case Instruction::Add: 887 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 888 break; 889 case Instruction::Mul: 890 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 891 break; 892 case Instruction::And: 893 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 894 break; 895 case Instruction::Or: 896 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 897 break; 898 case Instruction::Xor: 899 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 900 break; 901 case Instruction::FAdd: 902 BuildFunc = [&]() { 903 auto Rdx = Builder.CreateFAddReduce( 904 Constant::getNullValue(Src->getType()->getVectorElementType()), Src); 905 return Rdx; 906 }; 907 break; 908 case Instruction::FMul: 909 BuildFunc = [&]() { 910 Type *Ty = Src->getType()->getVectorElementType(); 911 auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); 912 return Rdx; 913 }; 914 break; 915 case Instruction::ICmp: 916 if (Flags.IsMaxOp) { 917 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 918 BuildFunc = [&]() { 919 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 920 }; 921 } else { 922 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 923 BuildFunc = [&]() { 924 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 925 }; 926 } 927 break; 928 case Instruction::FCmp: 929 if (Flags.IsMaxOp) { 930 MinMaxKind = RD::MRK_FloatMax; 931 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 932 } else { 933 MinMaxKind = RD::MRK_FloatMin; 934 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 935 } 936 break; 937 default: 938 llvm_unreachable("Unhandled opcode"); 939 break; 940 } 941 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 942 return BuildFunc(); 943 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 944 } 945 946 /// Create a vector reduction using a given recurrence descriptor. 947 Value *llvm::createTargetReduction(IRBuilder<> &B, 948 const TargetTransformInfo *TTI, 949 RecurrenceDescriptor &Desc, Value *Src, 950 bool NoNaN) { 951 // TODO: Support in-order reductions based on the recurrence descriptor. 952 using RD = RecurrenceDescriptor; 953 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 954 TargetTransformInfo::ReductionFlags Flags; 955 Flags.NoNaN = NoNaN; 956 957 // All ops in the reduction inherit fast-math-flags from the recurrence 958 // descriptor. 959 IRBuilder<>::FastMathFlagGuard FMFGuard(B); 960 B.setFastMathFlags(Desc.getFastMathFlags()); 961 962 switch (RecKind) { 963 case RD::RK_FloatAdd: 964 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 965 case RD::RK_FloatMult: 966 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 967 case RD::RK_IntegerAdd: 968 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 969 case RD::RK_IntegerMult: 970 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 971 case RD::RK_IntegerAnd: 972 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 973 case RD::RK_IntegerOr: 974 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 975 case RD::RK_IntegerXor: 976 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 977 case RD::RK_IntegerMinMax: { 978 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 979 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 980 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 981 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 982 } 983 case RD::RK_FloatMinMax: { 984 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 985 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 986 } 987 default: 988 llvm_unreachable("Unhandled RecKind"); 989 } 990 } 991 992 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 993 auto *VecOp = dyn_cast<Instruction>(I); 994 if (!VecOp) 995 return; 996 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 997 : dyn_cast<Instruction>(OpValue); 998 if (!Intersection) 999 return; 1000 const unsigned Opcode = Intersection->getOpcode(); 1001 VecOp->copyIRFlags(Intersection); 1002 for (auto *V : VL) { 1003 auto *Instr = dyn_cast<Instruction>(V); 1004 if (!Instr) 1005 continue; 1006 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1007 VecOp->andIRFlags(V); 1008 } 1009 } 1010 1011 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1012 ScalarEvolution &SE) { 1013 const SCEV *Zero = SE.getZero(S->getType()); 1014 return SE.isAvailableAtLoopEntry(S, L) && 1015 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1016 } 1017 1018 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1019 ScalarEvolution &SE) { 1020 const SCEV *Zero = SE.getZero(S->getType()); 1021 return SE.isAvailableAtLoopEntry(S, L) && 1022 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1023 } 1024 1025 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1026 bool Signed) { 1027 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1028 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1029 APInt::getMinValue(BitWidth); 1030 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1031 return SE.isAvailableAtLoopEntry(S, L) && 1032 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1033 SE.getConstant(Min)); 1034 } 1035 1036 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1037 bool Signed) { 1038 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1039 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1040 APInt::getMaxValue(BitWidth); 1041 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1042 return SE.isAvailableAtLoopEntry(S, L) && 1043 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1044 SE.getConstant(Max)); 1045 } 1046