1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass performs loop invariant code motion, attempting to remove as much 11 // code from the body of a loop as possible. It does this by either hoisting 12 // code into the preheader block, or by sinking code to the exit blocks if it is 13 // safe. This pass also promotes must-aliased memory locations in the loop to 14 // live in registers, thus hoisting and sinking "invariant" loads and stores. 15 // 16 // This pass uses alias analysis for two purposes: 17 // 18 // 1. Moving loop invariant loads and calls out of loops. If we can determine 19 // that a load or call inside of a loop never aliases anything stored to, 20 // we can hoist it or sink it like any other instruction. 21 // 2. Scalar Promotion of Memory - If there is a store instruction inside of 22 // the loop, we try to move the store to happen AFTER the loop instead of 23 // inside of the loop. This can only happen if a few conditions are true: 24 // A. The pointer stored through is loop invariant 25 // B. There are no stores or loads in the loop which _may_ alias the 26 // pointer. There are no calls in the loop which mod/ref the pointer. 27 // If these conditions are true, we can promote the loads and stores in the 28 // loop of the pointer to use a temporary alloca'd variable. We then use 29 // the SSAUpdater to construct the appropriate SSA form for the value. 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "llvm/Transforms/Scalar.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AliasSetTracker.h" 37 #include "llvm/Analysis/BasicAliasAnalysis.h" 38 #include "llvm/Analysis/ConstantFolding.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/LoopPass.h" 42 #include "llvm/Analysis/ScalarEvolution.h" 43 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 44 #include "llvm/Analysis/TargetLibraryInfo.h" 45 #include "llvm/Analysis/ValueTracking.h" 46 #include "llvm/IR/CFG.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Dominators.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/PredIteratorCache.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include "llvm/Transforms/Utils/LoopUtils.h" 61 #include "llvm/Transforms/Utils/SSAUpdater.h" 62 #include <algorithm> 63 using namespace llvm; 64 65 #define DEBUG_TYPE "licm" 66 67 STATISTIC(NumSunk , "Number of instructions sunk out of loop"); 68 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop"); 69 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 70 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 71 STATISTIC(NumPromoted , "Number of memory locations promoted to registers"); 72 73 static cl::opt<bool> 74 DisablePromotion("disable-licm-promotion", cl::Hidden, 75 cl::desc("Disable memory promotion in LICM pass")); 76 77 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 78 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 79 const LICMSafetyInfo *SafetyInfo); 80 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 81 const LICMSafetyInfo *SafetyInfo); 82 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 83 const Loop *CurLoop, AliasSetTracker *CurAST, 84 const LICMSafetyInfo *SafetyInfo); 85 static bool isGuaranteedToExecute(const Instruction &Inst, 86 const DominatorTree *DT, 87 const Loop *CurLoop, 88 const LICMSafetyInfo *SafetyInfo); 89 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 90 const DominatorTree *DT, 91 const TargetLibraryInfo *TLI, 92 const Loop *CurLoop, 93 const LICMSafetyInfo *SafetyInfo, 94 const Instruction *CtxI = nullptr); 95 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 96 const AAMDNodes &AAInfo, 97 AliasSetTracker *CurAST); 98 static Instruction * 99 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 100 const LoopInfo *LI, 101 const LICMSafetyInfo *SafetyInfo); 102 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, 103 DominatorTree *DT, TargetLibraryInfo *TLI, 104 Loop *CurLoop, AliasSetTracker *CurAST, 105 LICMSafetyInfo *SafetyInfo); 106 107 namespace { 108 struct LICM : public LoopPass { 109 static char ID; // Pass identification, replacement for typeid 110 LICM() : LoopPass(ID) { 111 initializeLICMPass(*PassRegistry::getPassRegistry()); 112 } 113 114 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 115 116 /// This transformation requires natural loop information & requires that 117 /// loop preheaders be inserted into the CFG... 118 /// 119 void getAnalysisUsage(AnalysisUsage &AU) const override { 120 AU.setPreservesCFG(); 121 AU.addRequired<TargetLibraryInfoWrapperPass>(); 122 getLoopAnalysisUsage(AU); 123 } 124 125 using llvm::Pass::doFinalization; 126 127 bool doFinalization() override { 128 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets"); 129 return false; 130 } 131 132 private: 133 AliasAnalysis *AA; // Current AliasAnalysis information 134 LoopInfo *LI; // Current LoopInfo 135 DominatorTree *DT; // Dominator Tree for the current Loop. 136 137 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding. 138 139 // State that is updated as we process loops. 140 bool Changed; // Set to true when we change anything. 141 BasicBlock *Preheader; // The preheader block of the current loop... 142 Loop *CurLoop; // The current loop we are working on... 143 AliasSetTracker *CurAST; // AliasSet information for the current loop... 144 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap; 145 146 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 147 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 148 Loop *L) override; 149 150 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 151 /// set. 152 void deleteAnalysisValue(Value *V, Loop *L) override; 153 154 /// Simple Analysis hook. Delete loop L from alias set map. 155 void deleteAnalysisLoop(Loop *L) override; 156 157 AliasSetTracker *collectAliasInfoForLoop(Loop *L); 158 }; 159 } 160 161 char LICM::ID = 0; 162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false) 163 INITIALIZE_PASS_DEPENDENCY(LoopPass) 164 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 165 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false) 166 167 Pass *llvm::createLICMPass() { return new LICM(); } 168 169 /// Hoist expressions out of the specified loop. Note, alias info for inner 170 /// loop is not preserved so it is not a good idea to run LICM multiple 171 /// times on one loop. 172 /// 173 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) { 174 if (skipOptnoneFunction(L)) 175 return false; 176 177 Changed = false; 178 179 // Get our Loop and Alias Analysis information... 180 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 181 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 182 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 183 184 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 185 186 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 187 188 CurAST = collectAliasInfoForLoop(L); 189 190 CurLoop = L; 191 192 // Get the preheader block to move instructions into... 193 Preheader = L->getLoopPreheader(); 194 195 // Compute loop safety information. 196 LICMSafetyInfo SafetyInfo; 197 computeLICMSafetyInfo(&SafetyInfo, CurLoop); 198 199 // We want to visit all of the instructions in this loop... that are not parts 200 // of our subloops (they have already had their invariants hoisted out of 201 // their loop, into this loop, so there is no need to process the BODIES of 202 // the subloops). 203 // 204 // Traverse the body of the loop in depth first order on the dominator tree so 205 // that we are guaranteed to see definitions before we see uses. This allows 206 // us to sink instructions in one pass, without iteration. After sinking 207 // instructions, we perform another pass to hoist them out of the loop. 208 // 209 if (L->hasDedicatedExits()) 210 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop, 211 CurAST, &SafetyInfo); 212 if (Preheader) 213 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, 214 CurLoop, CurAST, &SafetyInfo); 215 216 // Now that all loop invariants have been removed from the loop, promote any 217 // memory references to scalars that we can. 218 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) { 219 SmallVector<BasicBlock *, 8> ExitBlocks; 220 SmallVector<Instruction *, 8> InsertPts; 221 PredIteratorCache PIC; 222 223 // Loop over all of the alias sets in the tracker object. 224 for (AliasSet &AS : *CurAST) 225 Changed |= promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, 226 PIC, LI, DT, CurLoop, 227 CurAST, &SafetyInfo); 228 229 // Once we have promoted values across the loop body we have to recursively 230 // reform LCSSA as any nested loop may now have values defined within the 231 // loop used in the outer loop. 232 // FIXME: This is really heavy handed. It would be a bit better to use an 233 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 234 // it as it went. 235 if (Changed) { 236 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 237 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr); 238 } 239 } 240 241 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 242 // specifically moving instructions across the loop boundary and so it is 243 // especially in need of sanity checking here. 244 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 245 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 246 "Parent loop not left in LCSSA form after LICM!"); 247 248 // Clear out loops state information for the next iteration 249 CurLoop = nullptr; 250 Preheader = nullptr; 251 252 // If this loop is nested inside of another one, save the alias information 253 // for when we process the outer loop. 254 if (L->getParentLoop()) 255 LoopToAliasSetMap[L] = CurAST; 256 else 257 delete CurAST; 258 return Changed; 259 } 260 261 /// Walk the specified region of the CFG (defined by all blocks dominated by 262 /// the specified block, and that are in the current loop) in reverse depth 263 /// first order w.r.t the DominatorTree. This allows us to visit uses before 264 /// definitions, allowing us to sink a loop body in one pass without iteration. 265 /// 266 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 267 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 268 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 269 270 // Verify inputs. 271 assert(N != nullptr && AA != nullptr && LI != nullptr && 272 DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 273 SafetyInfo != nullptr && "Unexpected input to sinkRegion"); 274 275 BasicBlock *BB = N->getBlock(); 276 // If this subregion is not in the top level loop at all, exit. 277 if (!CurLoop->contains(BB)) return false; 278 279 // We are processing blocks in reverse dfo, so process children first. 280 bool Changed = false; 281 const std::vector<DomTreeNode*> &Children = N->getChildren(); 282 for (DomTreeNode *Child : Children) 283 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 284 285 // Only need to process the contents of this block if it is not part of a 286 // subloop (which would already have been processed). 287 if (inSubLoop(BB,CurLoop,LI)) return Changed; 288 289 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) { 290 Instruction &I = *--II; 291 292 // If the instruction is dead, we would try to sink it because it isn't used 293 // in the loop, instead, just delete it. 294 if (isInstructionTriviallyDead(&I, TLI)) { 295 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 296 ++II; 297 CurAST->deleteValue(&I); 298 I.eraseFromParent(); 299 Changed = true; 300 continue; 301 } 302 303 // Check to see if we can sink this instruction to the exit blocks 304 // of the loop. We can do this if the all users of the instruction are 305 // outside of the loop. In this case, it doesn't even matter if the 306 // operands of the instruction are loop invariant. 307 // 308 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) && 309 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) { 310 ++II; 311 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo); 312 } 313 } 314 return Changed; 315 } 316 317 /// Walk the specified region of the CFG (defined by all blocks dominated by 318 /// the specified block, and that are in the current loop) in depth first 319 /// order w.r.t the DominatorTree. This allows us to visit definitions before 320 /// uses, allowing us to hoist a loop body in one pass without iteration. 321 /// 322 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 323 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 324 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 325 // Verify inputs. 326 assert(N != nullptr && AA != nullptr && LI != nullptr && 327 DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 328 SafetyInfo != nullptr && "Unexpected input to hoistRegion"); 329 330 BasicBlock *BB = N->getBlock(); 331 332 // If this subregion is not in the top level loop at all, exit. 333 if (!CurLoop->contains(BB)) return false; 334 335 // Only need to process the contents of this block if it is not part of a 336 // subloop (which would already have been processed). 337 bool Changed = false; 338 if (!inSubLoop(BB, CurLoop, LI)) 339 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) { 340 Instruction &I = *II++; 341 // Try constant folding this instruction. If all the operands are 342 // constants, it is technically hoistable, but it would be better to just 343 // fold it. 344 if (Constant *C = ConstantFoldInstruction( 345 &I, I.getModule()->getDataLayout(), TLI)) { 346 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'); 347 CurAST->copyValue(&I, C); 348 CurAST->deleteValue(&I); 349 I.replaceAllUsesWith(C); 350 I.eraseFromParent(); 351 continue; 352 } 353 354 // Try hoisting the instruction out to the preheader. We can only do this 355 // if all of the operands of the instruction are loop invariant and if it 356 // is safe to hoist the instruction. 357 // 358 if (CurLoop->hasLoopInvariantOperands(&I) && 359 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) && 360 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, 361 CurLoop->getLoopPreheader()->getTerminator())) 362 Changed |= hoist(I, DT, CurLoop, SafetyInfo); 363 } 364 365 const std::vector<DomTreeNode*> &Children = N->getChildren(); 366 for (DomTreeNode *Child : Children) 367 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 368 return Changed; 369 } 370 371 /// Computes loop safety information, checks loop body & header 372 /// for the possibility of may throw exception. 373 /// 374 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) { 375 assert(CurLoop != nullptr && "CurLoop cant be null"); 376 BasicBlock *Header = CurLoop->getHeader(); 377 // Setting default safety values. 378 SafetyInfo->MayThrow = false; 379 SafetyInfo->HeaderMayThrow = false; 380 // Iterate over header and compute safety info. 381 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 382 (I != E) && !SafetyInfo->HeaderMayThrow; ++I) 383 SafetyInfo->HeaderMayThrow |= I->mayThrow(); 384 385 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow; 386 // Iterate over loop instructions and compute safety info. 387 for (Loop::block_iterator BB = CurLoop->block_begin(), 388 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB) 389 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); 390 (I != E) && !SafetyInfo->MayThrow; ++I) 391 SafetyInfo->MayThrow |= I->mayThrow(); 392 393 // Compute funclet colors if we might sink/hoist in a function with a funclet 394 // personality routine. 395 Function *Fn = CurLoop->getHeader()->getParent(); 396 if (Fn->hasPersonalityFn()) 397 if (Constant *PersonalityFn = Fn->getPersonalityFn()) 398 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn))) 399 SafetyInfo->BlockColors = colorEHFunclets(*Fn); 400 } 401 402 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this 403 /// instruction. 404 /// 405 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT, 406 TargetLibraryInfo *TLI, Loop *CurLoop, 407 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 408 // Loads have extra constraints we have to verify before we can hoist them. 409 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 410 if (!LI->isUnordered()) 411 return false; // Don't hoist volatile/atomic loads! 412 413 // Loads from constant memory are always safe to move, even if they end up 414 // in the same alias set as something that ends up being modified. 415 if (AA->pointsToConstantMemory(LI->getOperand(0))) 416 return true; 417 if (LI->getMetadata(LLVMContext::MD_invariant_load)) 418 return true; 419 420 // Don't hoist loads which have may-aliased stores in loop. 421 uint64_t Size = 0; 422 if (LI->getType()->isSized()) 423 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType()); 424 425 AAMDNodes AAInfo; 426 LI->getAAMetadata(AAInfo); 427 428 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST); 429 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 430 // Don't sink or hoist dbg info; it's legal, but not useful. 431 if (isa<DbgInfoIntrinsic>(I)) 432 return false; 433 434 // Don't sink calls which can throw. 435 if (CI->mayThrow()) 436 return false; 437 438 // Handle simple cases by querying alias analysis. 439 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 440 if (Behavior == FMRB_DoesNotAccessMemory) 441 return true; 442 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 443 // A readonly argmemonly function only reads from memory pointed to by 444 // it's arguments with arbitrary offsets. If we can prove there are no 445 // writes to this memory in the loop, we can hoist or sink. 446 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 447 for (Value *Op : CI->arg_operands()) 448 if (Op->getType()->isPointerTy() && 449 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize, 450 AAMDNodes(), CurAST)) 451 return false; 452 return true; 453 } 454 // If this call only reads from memory and there are no writes to memory 455 // in the loop, we can hoist or sink the call as appropriate. 456 bool FoundMod = false; 457 for (AliasSet &AS : *CurAST) { 458 if (!AS.isForwardingAliasSet() && AS.isMod()) { 459 FoundMod = true; 460 break; 461 } 462 } 463 if (!FoundMod) return true; 464 } 465 466 // FIXME: This should use mod/ref information to see if we can hoist or 467 // sink the call. 468 469 return false; 470 } 471 472 // Only these instructions are hoistable/sinkable. 473 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 474 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 475 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 476 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 477 !isa<InsertValueInst>(I)) 478 return false; 479 480 // TODO: Plumb the context instruction through to make hoisting and sinking 481 // more powerful. Hoisting of loads already works due to the special casing 482 // above. 483 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, 484 nullptr); 485 } 486 487 /// Returns true if a PHINode is a trivially replaceable with an 488 /// Instruction. 489 /// This is true when all incoming values are that instruction. 490 /// This pattern occurs most often with LCSSA PHI nodes. 491 /// 492 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) { 493 for (const Value *IncValue : PN.incoming_values()) 494 if (IncValue != &I) 495 return false; 496 497 return true; 498 } 499 500 /// Return true if the only users of this instruction are outside of 501 /// the loop. If this is true, we can sink the instruction to the exit 502 /// blocks of the loop. 503 /// 504 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 505 const LICMSafetyInfo *SafetyInfo) { 506 const auto &BlockColors = SafetyInfo->BlockColors; 507 for (const User *U : I.users()) { 508 const Instruction *UI = cast<Instruction>(U); 509 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 510 const BasicBlock *BB = PN->getParent(); 511 // We cannot sink uses in catchswitches. 512 if (isa<CatchSwitchInst>(BB->getTerminator())) 513 return false; 514 515 // We need to sink a callsite to a unique funclet. Avoid sinking if the 516 // phi use is too muddled. 517 if (isa<CallInst>(I)) 518 if (!BlockColors.empty() && 519 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 520 return false; 521 522 // A PHI node where all of the incoming values are this instruction are 523 // special -- they can just be RAUW'ed with the instruction and thus 524 // don't require a use in the predecessor. This is a particular important 525 // special case because it is the pattern found in LCSSA form. 526 if (isTriviallyReplacablePHI(*PN, I)) { 527 if (CurLoop->contains(PN)) 528 return false; 529 else 530 continue; 531 } 532 533 // Otherwise, PHI node uses occur in predecessor blocks if the incoming 534 // values. Check for such a use being inside the loop. 535 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 536 if (PN->getIncomingValue(i) == &I) 537 if (CurLoop->contains(PN->getIncomingBlock(i))) 538 return false; 539 540 continue; 541 } 542 543 if (CurLoop->contains(UI)) 544 return false; 545 } 546 return true; 547 } 548 549 static Instruction * 550 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 551 const LoopInfo *LI, 552 const LICMSafetyInfo *SafetyInfo) { 553 Instruction *New; 554 if (auto *CI = dyn_cast<CallInst>(&I)) { 555 const auto &BlockColors = SafetyInfo->BlockColors; 556 557 // Sinking call-sites need to be handled differently from other 558 // instructions. The cloned call-site needs a funclet bundle operand 559 // appropriate for it's location in the CFG. 560 SmallVector<OperandBundleDef, 1> OpBundles; 561 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 562 BundleIdx != BundleEnd; ++BundleIdx) { 563 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 564 if (Bundle.getTagID() == LLVMContext::OB_funclet) 565 continue; 566 567 OpBundles.emplace_back(Bundle); 568 } 569 570 if (!BlockColors.empty()) { 571 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 572 assert(CV.size() == 1 && "non-unique color for exit block!"); 573 BasicBlock *BBColor = CV.front(); 574 Instruction *EHPad = BBColor->getFirstNonPHI(); 575 if (EHPad->isEHPad()) 576 OpBundles.emplace_back("funclet", EHPad); 577 } 578 579 New = CallInst::Create(CI, OpBundles); 580 } else { 581 New = I.clone(); 582 } 583 584 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 585 if (!I.getName().empty()) New->setName(I.getName() + ".le"); 586 587 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 588 // particularly cheap because we can rip off the PHI node that we're 589 // replacing for the number and blocks of the predecessors. 590 // OPT: If this shows up in a profile, we can instead finish sinking all 591 // invariant instructions, and then walk their operands to re-establish 592 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 593 // sinking bottom-up. 594 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 595 ++OI) 596 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 597 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 598 if (!OLoop->contains(&PN)) { 599 PHINode *OpPN = 600 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 601 OInst->getName() + ".lcssa", &ExitBlock.front()); 602 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 603 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 604 *OI = OpPN; 605 } 606 return New; 607 } 608 609 /// When an instruction is found to only be used outside of the loop, this 610 /// function moves it to the exit blocks and patches up SSA form as needed. 611 /// This method is guaranteed to remove the original instruction from its 612 /// position, and may either delete it or move it to outside of the loop. 613 /// 614 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 615 const Loop *CurLoop, AliasSetTracker *CurAST, 616 const LICMSafetyInfo *SafetyInfo) { 617 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 618 bool Changed = false; 619 if (isa<LoadInst>(I)) ++NumMovedLoads; 620 else if (isa<CallInst>(I)) ++NumMovedCalls; 621 ++NumSunk; 622 Changed = true; 623 624 #ifndef NDEBUG 625 SmallVector<BasicBlock *, 32> ExitBlocks; 626 CurLoop->getUniqueExitBlocks(ExitBlocks); 627 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 628 ExitBlocks.end()); 629 #endif 630 631 // Clones of this instruction. Don't create more than one per exit block! 632 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 633 634 // If this instruction is only used outside of the loop, then all users are 635 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 636 // the instruction. 637 while (!I.use_empty()) { 638 Value::user_iterator UI = I.user_begin(); 639 auto *User = cast<Instruction>(*UI); 640 if (!DT->isReachableFromEntry(User->getParent())) { 641 User->replaceUsesOfWith(&I, UndefValue::get(I.getType())); 642 continue; 643 } 644 // The user must be a PHI node. 645 PHINode *PN = cast<PHINode>(User); 646 647 // Surprisingly, instructions can be used outside of loops without any 648 // exits. This can only happen in PHI nodes if the incoming block is 649 // unreachable. 650 Use &U = UI.getUse(); 651 BasicBlock *BB = PN->getIncomingBlock(U); 652 if (!DT->isReachableFromEntry(BB)) { 653 U = UndefValue::get(I.getType()); 654 continue; 655 } 656 657 BasicBlock *ExitBlock = PN->getParent(); 658 assert(ExitBlockSet.count(ExitBlock) && 659 "The LCSSA PHI is not in an exit block!"); 660 661 Instruction *New; 662 auto It = SunkCopies.find(ExitBlock); 663 if (It != SunkCopies.end()) 664 New = It->second; 665 else 666 New = SunkCopies[ExitBlock] = 667 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo); 668 669 PN->replaceAllUsesWith(New); 670 PN->eraseFromParent(); 671 } 672 673 CurAST->deleteValue(&I); 674 I.eraseFromParent(); 675 return Changed; 676 } 677 678 /// When an instruction is found to only use loop invariant operands that 679 /// is safe to hoist, this instruction is called to do the dirty work. 680 /// 681 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 682 const LICMSafetyInfo *SafetyInfo) { 683 auto *Preheader = CurLoop->getLoopPreheader(); 684 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " 685 << I << "\n"); 686 687 // Metadata can be dependent on conditions we are hoisting above. 688 // Conservatively strip all metadata on the instruction unless we were 689 // guaranteed to execute I if we entered the loop, in which case the metadata 690 // is valid in the loop preheader. 691 if (I.hasMetadataOtherThanDebugLoc() && 692 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 693 // time in isGuaranteedToExecute if we don't actually have anything to 694 // drop. It is a compile time optimization, not required for correctness. 695 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo)) 696 I.dropUnknownNonDebugMetadata(); 697 698 // Move the new node to the Preheader, before its terminator. 699 I.moveBefore(Preheader->getTerminator()); 700 701 if (isa<LoadInst>(I)) ++NumMovedLoads; 702 else if (isa<CallInst>(I)) ++NumMovedCalls; 703 ++NumHoisted; 704 return true; 705 } 706 707 /// Only sink or hoist an instruction if it is not a trapping instruction, 708 /// or if the instruction is known not to trap when moved to the preheader. 709 /// or if it is a trapping instruction and is guaranteed to execute. 710 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 711 const DominatorTree *DT, 712 const TargetLibraryInfo *TLI, 713 const Loop *CurLoop, 714 const LICMSafetyInfo *SafetyInfo, 715 const Instruction *CtxI) { 716 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI)) 717 return true; 718 719 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo); 720 } 721 722 static bool isGuaranteedToExecute(const Instruction &Inst, 723 const DominatorTree *DT, 724 const Loop *CurLoop, 725 const LICMSafetyInfo * SafetyInfo) { 726 727 // We have to check to make sure that the instruction dominates all 728 // of the exit blocks. If it doesn't, then there is a path out of the loop 729 // which does not execute this instruction, so we can't hoist it. 730 731 // If the instruction is in the header block for the loop (which is very 732 // common), it is always guaranteed to dominate the exit blocks. Since this 733 // is a common case, and can save some work, check it now. 734 if (Inst.getParent() == CurLoop->getHeader()) 735 // If there's a throw in the header block, we can't guarantee we'll reach 736 // Inst. 737 return !SafetyInfo->HeaderMayThrow; 738 739 // Somewhere in this loop there is an instruction which may throw and make us 740 // exit the loop. 741 if (SafetyInfo->MayThrow) 742 return false; 743 744 // Get the exit blocks for the current loop. 745 SmallVector<BasicBlock*, 8> ExitBlocks; 746 CurLoop->getExitBlocks(ExitBlocks); 747 748 // Verify that the block dominates each of the exit blocks of the loop. 749 for (BasicBlock *ExitBlock : ExitBlocks) 750 if (!DT->dominates(Inst.getParent(), ExitBlock)) 751 return false; 752 753 // As a degenerate case, if the loop is statically infinite then we haven't 754 // proven anything since there are no exit blocks. 755 if (ExitBlocks.empty()) 756 return false; 757 758 return true; 759 } 760 761 namespace { 762 class LoopPromoter : public LoadAndStorePromoter { 763 Value *SomePtr; // Designated pointer to store to. 764 SmallPtrSetImpl<Value*> &PointerMustAliases; 765 SmallVectorImpl<BasicBlock*> &LoopExitBlocks; 766 SmallVectorImpl<Instruction*> &LoopInsertPts; 767 PredIteratorCache &PredCache; 768 AliasSetTracker &AST; 769 LoopInfo &LI; 770 DebugLoc DL; 771 int Alignment; 772 AAMDNodes AATags; 773 774 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 775 if (Instruction *I = dyn_cast<Instruction>(V)) 776 if (Loop *L = LI.getLoopFor(I->getParent())) 777 if (!L->contains(BB)) { 778 // We need to create an LCSSA PHI node for the incoming value and 779 // store that. 780 PHINode *PN = 781 PHINode::Create(I->getType(), PredCache.size(BB), 782 I->getName() + ".lcssa", &BB->front()); 783 for (BasicBlock *Pred : PredCache.get(BB)) 784 PN->addIncoming(I, Pred); 785 return PN; 786 } 787 return V; 788 } 789 790 public: 791 LoopPromoter(Value *SP, 792 ArrayRef<const Instruction *> Insts, 793 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA, 794 SmallVectorImpl<BasicBlock *> &LEB, 795 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, 796 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, 797 const AAMDNodes &AATags) 798 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 799 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), 800 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {} 801 802 bool isInstInList(Instruction *I, 803 const SmallVectorImpl<Instruction*> &) const override { 804 Value *Ptr; 805 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 806 Ptr = LI->getOperand(0); 807 else 808 Ptr = cast<StoreInst>(I)->getPointerOperand(); 809 return PointerMustAliases.count(Ptr); 810 } 811 812 void doExtraRewritesBeforeFinalDeletion() const override { 813 // Insert stores after in the loop exit blocks. Each exit block gets a 814 // store of the live-out values that feed them. Since we've already told 815 // the SSA updater about the defs in the loop and the preheader 816 // definition, it is all set and we can start using it. 817 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 818 BasicBlock *ExitBlock = LoopExitBlocks[i]; 819 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 820 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 821 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 822 Instruction *InsertPos = LoopInsertPts[i]; 823 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 824 NewSI->setAlignment(Alignment); 825 NewSI->setDebugLoc(DL); 826 if (AATags) NewSI->setAAMetadata(AATags); 827 } 828 } 829 830 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 831 // Update alias analysis. 832 AST.copyValue(LI, V); 833 } 834 void instructionDeleted(Instruction *I) const override { 835 AST.deleteValue(I); 836 } 837 }; 838 } // end anon namespace 839 840 /// Try to promote memory values to scalars by sinking stores out of the 841 /// loop and moving loads to before the loop. We do this by looping over 842 /// the stores in the loop, looking for stores to Must pointers which are 843 /// loop invariant. 844 /// 845 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS, 846 SmallVectorImpl<BasicBlock*>&ExitBlocks, 847 SmallVectorImpl<Instruction*>&InsertPts, 848 PredIteratorCache &PIC, LoopInfo *LI, 849 DominatorTree *DT, Loop *CurLoop, 850 AliasSetTracker *CurAST, 851 LICMSafetyInfo * SafetyInfo) { 852 // Verify inputs. 853 assert(LI != nullptr && DT != nullptr && 854 CurLoop != nullptr && CurAST != nullptr && 855 SafetyInfo != nullptr && 856 "Unexpected Input to promoteLoopAccessesToScalars"); 857 858 // We can promote this alias set if it has a store, if it is a "Must" alias 859 // set, if the pointer is loop invariant, and if we are not eliminating any 860 // volatile loads or stores. 861 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 862 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 863 return false; 864 865 assert(!AS.empty() && 866 "Must alias set should have at least one pointer element in it!"); 867 868 Value *SomePtr = AS.begin()->getValue(); 869 BasicBlock * Preheader = CurLoop->getLoopPreheader(); 870 871 // It isn't safe to promote a load/store from the loop if the load/store is 872 // conditional. For example, turning: 873 // 874 // for () { if (c) *P += 1; } 875 // 876 // into: 877 // 878 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 879 // 880 // is not safe, because *P may only be valid to access if 'c' is true. 881 // 882 // It is safe to promote P if all uses are direct load/stores and if at 883 // least one is guaranteed to be executed. 884 bool GuaranteedToExecute = false; 885 886 SmallVector<Instruction*, 64> LoopUses; 887 SmallPtrSet<Value*, 4> PointerMustAliases; 888 889 // We start with an alignment of one and try to find instructions that allow 890 // us to prove better alignment. 891 unsigned Alignment = 1; 892 AAMDNodes AATags; 893 bool HasDedicatedExits = CurLoop->hasDedicatedExits(); 894 895 // Check that all of the pointers in the alias set have the same type. We 896 // cannot (yet) promote a memory location that is loaded and stored in 897 // different sizes. While we are at it, collect alignment and AA info. 898 bool Changed = false; 899 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) { 900 Value *ASIV = ASI->getValue(); 901 PointerMustAliases.insert(ASIV); 902 903 // Check that all of the pointers in the alias set have the same type. We 904 // cannot (yet) promote a memory location that is loaded and stored in 905 // different sizes. 906 if (SomePtr->getType() != ASIV->getType()) 907 return Changed; 908 909 for (User *U : ASIV->users()) { 910 // Ignore instructions that are outside the loop. 911 Instruction *UI = dyn_cast<Instruction>(U); 912 if (!UI || !CurLoop->contains(UI)) 913 continue; 914 915 // If there is an non-load/store instruction in the loop, we can't promote 916 // it. 917 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) { 918 assert(!Load->isVolatile() && "AST broken"); 919 if (!Load->isSimple()) 920 return Changed; 921 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 922 // Stores *of* the pointer are not interesting, only stores *to* the 923 // pointer. 924 if (UI->getOperand(1) != ASIV) 925 continue; 926 assert(!Store->isVolatile() && "AST broken"); 927 if (!Store->isSimple()) 928 return Changed; 929 // Don't sink stores from loops without dedicated block exits. Exits 930 // containing indirect branches are not transformed by loop simplify, 931 // make sure we catch that. An additional load may be generated in the 932 // preheader for SSA updater, so also avoid sinking when no preheader 933 // is available. 934 if (!HasDedicatedExits || !Preheader) 935 return Changed; 936 937 // Note that we only check GuaranteedToExecute inside the store case 938 // so that we do not introduce stores where they did not exist before 939 // (which would break the LLVM concurrency model). 940 941 // If the alignment of this instruction allows us to specify a more 942 // restrictive (and performant) alignment and if we are sure this 943 // instruction will be executed, update the alignment. 944 // Larger is better, with the exception of 0 being the best alignment. 945 unsigned InstAlignment = Store->getAlignment(); 946 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0) 947 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) { 948 GuaranteedToExecute = true; 949 Alignment = InstAlignment; 950 } 951 952 if (!GuaranteedToExecute) 953 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT, 954 CurLoop, SafetyInfo); 955 956 } else 957 return Changed; // Not a load or store. 958 959 // Merge the AA tags. 960 if (LoopUses.empty()) { 961 // On the first load/store, just take its AA tags. 962 UI->getAAMetadata(AATags); 963 } else if (AATags) { 964 UI->getAAMetadata(AATags, /* Merge = */ true); 965 } 966 967 LoopUses.push_back(UI); 968 } 969 } 970 971 // If there isn't a guaranteed-to-execute instruction, we can't promote. 972 if (!GuaranteedToExecute) 973 return Changed; 974 975 // Figure out the loop exits and their insertion points, if this is the 976 // first promotion. 977 if (ExitBlocks.empty()) { 978 CurLoop->getUniqueExitBlocks(ExitBlocks); 979 InsertPts.clear(); 980 InsertPts.reserve(ExitBlocks.size()); 981 for (BasicBlock *ExitBlock : ExitBlocks) 982 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 983 } 984 985 // Can't insert into a catchswitch. 986 for (BasicBlock *ExitBlock : ExitBlocks) 987 if (isa<CatchSwitchInst>(ExitBlock->getTerminator())) 988 return Changed; 989 990 // Otherwise, this is safe to promote, lets do it! 991 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n'); 992 Changed = true; 993 ++NumPromoted; 994 995 // Grab a debug location for the inserted loads/stores; given that the 996 // inserted loads/stores have little relation to the original loads/stores, 997 // this code just arbitrarily picks a location from one, since any debug 998 // location is better than none. 999 DebugLoc DL = LoopUses[0]->getDebugLoc(); 1000 1001 // We use the SSAUpdater interface to insert phi nodes as required. 1002 SmallVector<PHINode*, 16> NewPHIs; 1003 SSAUpdater SSA(&NewPHIs); 1004 LoopPromoter Promoter(SomePtr, LoopUses, SSA, 1005 PointerMustAliases, ExitBlocks, 1006 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags); 1007 1008 // Set up the preheader to have a definition of the value. It is the live-out 1009 // value from the preheader that uses in the loop will use. 1010 LoadInst *PreheaderLoad = 1011 new LoadInst(SomePtr, SomePtr->getName()+".promoted", 1012 Preheader->getTerminator()); 1013 PreheaderLoad->setAlignment(Alignment); 1014 PreheaderLoad->setDebugLoc(DL); 1015 if (AATags) PreheaderLoad->setAAMetadata(AATags); 1016 SSA.AddAvailableValue(Preheader, PreheaderLoad); 1017 1018 // Rewrite all the loads in the loop and remember all the definitions from 1019 // stores in the loop. 1020 Promoter.run(LoopUses); 1021 1022 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 1023 if (PreheaderLoad->use_empty()) 1024 PreheaderLoad->eraseFromParent(); 1025 1026 return Changed; 1027 } 1028 1029 /// Returns an owning pointer to an alias set which incorporates aliasing info 1030 /// from L and all subloops of L. 1031 AliasSetTracker *LICM::collectAliasInfoForLoop(Loop *L) { 1032 AliasSetTracker *CurAST = nullptr; 1033 SmallVector<Loop *, 4> RecomputeLoops; 1034 for (Loop *InnerL : L->getSubLoops()) { 1035 auto MapI = LoopToAliasSetMap.find(InnerL); 1036 // If the AST for this inner loop is missing it may have been merged into 1037 // some other loop's AST and then that loop unrolled, and so we need to 1038 // recompute it. 1039 if (MapI == LoopToAliasSetMap.end()) { 1040 RecomputeLoops.push_back(InnerL); 1041 continue; 1042 } 1043 AliasSetTracker *InnerAST = MapI->second; 1044 1045 if (CurAST != nullptr) { 1046 // What if InnerLoop was modified by other passes ? 1047 CurAST->add(*InnerAST); 1048 1049 // Once we've incorporated the inner loop's AST into ours, we don't need 1050 // the subloop's anymore. 1051 delete InnerAST; 1052 } else { 1053 CurAST = InnerAST; 1054 } 1055 LoopToAliasSetMap.erase(MapI); 1056 } 1057 if (CurAST == nullptr) 1058 CurAST = new AliasSetTracker(*AA); 1059 1060 auto mergeLoop = [&](Loop *L) { 1061 // Loop over the body of this loop, looking for calls, invokes, and stores. 1062 // Because subloops have already been incorporated into AST, we skip blocks 1063 // in subloops. 1064 for (BasicBlock *BB : L->blocks()) 1065 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops. 1066 CurAST->add(*BB); // Incorporate the specified basic block 1067 }; 1068 1069 // Add everything from the sub loops that are no longer directly available. 1070 for (Loop *InnerL : RecomputeLoops) 1071 mergeLoop(InnerL); 1072 1073 // And merge in this loop. 1074 mergeLoop(L); 1075 1076 return CurAST; 1077 } 1078 1079 /// Simple analysis hook. Clone alias set info. 1080 /// 1081 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) { 1082 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1083 if (!AST) 1084 return; 1085 1086 AST->copyValue(From, To); 1087 } 1088 1089 /// Simple Analysis hook. Delete value V from alias set 1090 /// 1091 void LICM::deleteAnalysisValue(Value *V, Loop *L) { 1092 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1093 if (!AST) 1094 return; 1095 1096 AST->deleteValue(V); 1097 } 1098 1099 /// Simple Analysis hook. Delete value L from alias set map. 1100 /// 1101 void LICM::deleteAnalysisLoop(Loop *L) { 1102 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1103 if (!AST) 1104 return; 1105 1106 delete AST; 1107 LoopToAliasSetMap.erase(L); 1108 } 1109 1110 1111 /// Return true if the body of this loop may store into the memory 1112 /// location pointed to by V. 1113 /// 1114 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 1115 const AAMDNodes &AAInfo, 1116 AliasSetTracker *CurAST) { 1117 // Check to see if any of the basic blocks in CurLoop invalidate *V. 1118 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod(); 1119 } 1120 1121 /// Little predicate that returns true if the specified basic block is in 1122 /// a subloop of the current one, not the current one itself. 1123 /// 1124 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 1125 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 1126 return LI->getLoopFor(BB) != CurLoop; 1127 } 1128 1129