1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 // This pass uses alias analysis for two purposes:
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.
31 //===----------------------------------------------------------------------===//
33 #include "llvm/Transforms/Scalar/LICM.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/CaptureTracking.h"
39 #include "llvm/Analysis/ConstantFolding.h"
40 #include "llvm/Analysis/GlobalsModRef.h"
41 #include "llvm/Analysis/Loads.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/LoopPass.h"
44 #include "llvm/Analysis/LoopPassManager.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/Analysis/ScalarEvolution.h"
47 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/IR/CFG.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/PredIteratorCache.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Utils/Local.h"
65 #include "llvm/Transforms/Utils/LoopUtils.h"
66 #include "llvm/Transforms/Utils/SSAUpdater.h"
71 #define DEBUG_TYPE "licm"
73 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
74 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
75 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
76 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
77 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
80 DisablePromotion("disable-licm-promotion", cl::Hidden,
81 cl::desc("Disable memory promotion in LICM pass"));
83 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
84 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
85 const LoopSafetyInfo *SafetyInfo);
86 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
87 const LoopSafetyInfo *SafetyInfo);
88 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
89 const Loop *CurLoop, AliasSetTracker *CurAST,
90 const LoopSafetyInfo *SafetyInfo);
91 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
92 const DominatorTree *DT,
94 const LoopSafetyInfo *SafetyInfo,
95 const Instruction *CtxI = nullptr);
96 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
97 const AAMDNodes &AAInfo,
98 AliasSetTracker *CurAST);
100 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
102 const LoopSafetyInfo *SafetyInfo);
103 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
104 DominatorTree *DT, TargetLibraryInfo *TLI,
105 Loop *CurLoop, AliasSetTracker *CurAST,
106 LoopSafetyInfo *SafetyInfo);
109 struct LoopInvariantCodeMotion {
110 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
111 TargetLibraryInfo *TLI, ScalarEvolution *SE, bool DeleteAST);
113 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
114 return LoopToAliasSetMap;
118 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
120 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
124 struct LegacyLICMPass : public LoopPass {
125 static char ID; // Pass identification, replacement for typeid
126 LegacyLICMPass() : LoopPass(ID) {
127 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
130 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
134 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
135 return LICM.runOnLoop(L,
136 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
137 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
138 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
139 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
140 SE ? &SE->getSE() : nullptr, false);
143 /// This transformation requires natural loop information & requires that
144 /// loop preheaders be inserted into the CFG...
146 void getAnalysisUsage(AnalysisUsage &AU) const override {
147 AU.setPreservesCFG();
148 AU.addRequired<TargetLibraryInfoWrapperPass>();
149 getLoopAnalysisUsage(AU);
152 using llvm::Pass::doFinalization;
154 bool doFinalization() override {
155 assert(LICM.getLoopToAliasSetMap().empty() &&
156 "Didn't free loop alias sets");
161 LoopInvariantCodeMotion LICM;
163 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
164 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
167 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
169 void deleteAnalysisValue(Value *V, Loop *L) override;
171 /// Simple Analysis hook. Delete loop L from alias set map.
172 void deleteAnalysisLoop(Loop *L) override;
176 PreservedAnalyses LICMPass::run(Loop &L, AnalysisManager<Loop> &AM) {
178 AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
179 Function *F = L.getHeader()->getParent();
181 auto *AA = FAM.getCachedResult<AAManager>(*F);
182 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
183 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
184 auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
185 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
186 assert((AA && LI && DT && TLI && SE) && "Analyses for LICM not available");
188 LoopInvariantCodeMotion LICM;
190 if (!LICM.runOnLoop(&L, AA, LI, DT, TLI, SE, true))
191 return PreservedAnalyses::all();
193 // FIXME: There is no setPreservesCFG in the new PM. When that becomes
194 // available, it should be used here.
195 return getLoopPassPreservedAnalyses();
198 char LegacyLICMPass::ID = 0;
199 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
201 INITIALIZE_PASS_DEPENDENCY(LoopPass)
202 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
203 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
206 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
208 /// Hoist expressions out of the specified loop. Note, alias info for inner
209 /// loop is not preserved so it is not a good idea to run LICM multiple
210 /// times on one loop.
211 /// We should delete AST for inner loops in the new pass manager to avoid
214 bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
215 LoopInfo *LI, DominatorTree *DT,
216 TargetLibraryInfo *TLI,
217 ScalarEvolution *SE, bool DeleteAST) {
218 bool Changed = false;
220 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
222 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
224 // Get the preheader block to move instructions into...
225 BasicBlock *Preheader = L->getLoopPreheader();
227 // Compute loop safety information.
228 LoopSafetyInfo SafetyInfo;
229 computeLoopSafetyInfo(&SafetyInfo, L);
231 // We want to visit all of the instructions in this loop... that are not parts
232 // of our subloops (they have already had their invariants hoisted out of
233 // their loop, into this loop, so there is no need to process the BODIES of
236 // Traverse the body of the loop in depth first order on the dominator tree so
237 // that we are guaranteed to see definitions before we see uses. This allows
238 // us to sink instructions in one pass, without iteration. After sinking
239 // instructions, we perform another pass to hoist them out of the loop.
241 if (L->hasDedicatedExits())
242 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
243 CurAST, &SafetyInfo);
245 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
246 CurAST, &SafetyInfo);
248 // Now that all loop invariants have been removed from the loop, promote any
249 // memory references to scalars that we can.
250 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
251 SmallVector<BasicBlock *, 8> ExitBlocks;
252 SmallVector<Instruction *, 8> InsertPts;
253 PredIteratorCache PIC;
255 // Loop over all of the alias sets in the tracker object.
256 for (AliasSet &AS : *CurAST)
257 Changed |= promoteLoopAccessesToScalars(
258 AS, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L, CurAST, &SafetyInfo);
260 // Once we have promoted values across the loop body we have to recursively
261 // reform LCSSA as any nested loop may now have values defined within the
262 // loop used in the outer loop.
263 // FIXME: This is really heavy handed. It would be a bit better to use an
264 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
267 formLCSSARecursively(*L, *DT, LI, SE);
271 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
272 // specifically moving instructions across the loop boundary and so it is
273 // especially in need of sanity checking here.
274 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
275 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
276 "Parent loop not left in LCSSA form after LICM!");
278 // If this loop is nested inside of another one, save the alias information
279 // for when we process the outer loop.
280 if (L->getParentLoop() && !DeleteAST)
281 LoopToAliasSetMap[L] = CurAST;
286 SE->forgetLoopDispositions(L);
290 /// Walk the specified region of the CFG (defined by all blocks dominated by
291 /// the specified block, and that are in the current loop) in reverse depth
292 /// first order w.r.t the DominatorTree. This allows us to visit uses before
293 /// definitions, allowing us to sink a loop body in one pass without iteration.
295 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
296 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
297 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
300 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
301 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
302 "Unexpected input to sinkRegion");
304 BasicBlock *BB = N->getBlock();
305 // If this subregion is not in the top level loop at all, exit.
306 if (!CurLoop->contains(BB))
309 // We are processing blocks in reverse dfo, so process children first.
310 bool Changed = false;
311 const std::vector<DomTreeNode *> &Children = N->getChildren();
312 for (DomTreeNode *Child : Children)
313 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
315 // Only need to process the contents of this block if it is not part of a
316 // subloop (which would already have been processed).
317 if (inSubLoop(BB, CurLoop, LI))
320 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
321 Instruction &I = *--II;
323 // If the instruction is dead, we would try to sink it because it isn't used
324 // in the loop, instead, just delete it.
325 if (isInstructionTriviallyDead(&I, TLI)) {
326 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
328 CurAST->deleteValue(&I);
334 // Check to see if we can sink this instruction to the exit blocks
335 // of the loop. We can do this if the all users of the instruction are
336 // outside of the loop. In this case, it doesn't even matter if the
337 // operands of the instruction are loop invariant.
339 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
340 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
342 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
348 /// Walk the specified region of the CFG (defined by all blocks dominated by
349 /// the specified block, and that are in the current loop) in depth first
350 /// order w.r.t the DominatorTree. This allows us to visit definitions before
351 /// uses, allowing us to hoist a loop body in one pass without iteration.
353 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
355 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
357 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
358 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
359 "Unexpected input to hoistRegion");
361 BasicBlock *BB = N->getBlock();
363 // If this subregion is not in the top level loop at all, exit.
364 if (!CurLoop->contains(BB))
367 // Only need to process the contents of this block if it is not part of a
368 // subloop (which would already have been processed).
369 bool Changed = false;
370 if (!inSubLoop(BB, CurLoop, LI))
371 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
372 Instruction &I = *II++;
373 // Try constant folding this instruction. If all the operands are
374 // constants, it is technically hoistable, but it would be better to just
376 if (Constant *C = ConstantFoldInstruction(
377 &I, I.getModule()->getDataLayout(), TLI)) {
378 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
379 CurAST->copyValue(&I, C);
380 I.replaceAllUsesWith(C);
381 if (isInstructionTriviallyDead(&I, TLI)) {
382 CurAST->deleteValue(&I);
388 // Try hoisting the instruction out to the preheader. We can only do this
389 // if all of the operands of the instruction are loop invariant and if it
390 // is safe to hoist the instruction.
392 if (CurLoop->hasLoopInvariantOperands(&I) &&
393 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
394 isSafeToExecuteUnconditionally(
395 I, DT, CurLoop, SafetyInfo,
396 CurLoop->getLoopPreheader()->getTerminator()))
397 Changed |= hoist(I, DT, CurLoop, SafetyInfo);
400 const std::vector<DomTreeNode *> &Children = N->getChildren();
401 for (DomTreeNode *Child : Children)
402 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
406 /// Computes loop safety information, checks loop body & header
407 /// for the possibility of may throw exception.
409 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
410 assert(CurLoop != nullptr && "CurLoop cant be null");
411 BasicBlock *Header = CurLoop->getHeader();
412 // Setting default safety values.
413 SafetyInfo->MayThrow = false;
414 SafetyInfo->HeaderMayThrow = false;
415 // Iterate over header and compute safety info.
416 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
417 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
418 SafetyInfo->HeaderMayThrow |=
419 !isGuaranteedToTransferExecutionToSuccessor(&*I);
421 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
422 // Iterate over loop instructions and compute safety info.
423 for (Loop::block_iterator BB = CurLoop->block_begin(),
424 BBE = CurLoop->block_end();
425 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
426 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
427 (I != E) && !SafetyInfo->MayThrow; ++I)
428 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
430 // Compute funclet colors if we might sink/hoist in a function with a funclet
431 // personality routine.
432 Function *Fn = CurLoop->getHeader()->getParent();
433 if (Fn->hasPersonalityFn())
434 if (Constant *PersonalityFn = Fn->getPersonalityFn())
435 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
436 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
439 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
442 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
443 TargetLibraryInfo *TLI, Loop *CurLoop,
444 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
445 // Loads have extra constraints we have to verify before we can hoist them.
446 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
447 if (!LI->isUnordered())
448 return false; // Don't hoist volatile/atomic loads!
450 // Loads from constant memory are always safe to move, even if they end up
451 // in the same alias set as something that ends up being modified.
452 if (AA->pointsToConstantMemory(LI->getOperand(0)))
454 if (LI->getMetadata(LLVMContext::MD_invariant_load))
457 // Don't hoist loads which have may-aliased stores in loop.
459 if (LI->getType()->isSized())
460 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
463 LI->getAAMetadata(AAInfo);
465 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
466 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
467 // Don't sink or hoist dbg info; it's legal, but not useful.
468 if (isa<DbgInfoIntrinsic>(I))
471 // Don't sink calls which can throw.
475 // Handle simple cases by querying alias analysis.
476 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
477 if (Behavior == FMRB_DoesNotAccessMemory)
479 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
480 // A readonly argmemonly function only reads from memory pointed to by
481 // it's arguments with arbitrary offsets. If we can prove there are no
482 // writes to this memory in the loop, we can hoist or sink.
483 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
484 for (Value *Op : CI->arg_operands())
485 if (Op->getType()->isPointerTy() &&
486 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
487 AAMDNodes(), CurAST))
491 // If this call only reads from memory and there are no writes to memory
492 // in the loop, we can hoist or sink the call as appropriate.
493 bool FoundMod = false;
494 for (AliasSet &AS : *CurAST) {
495 if (!AS.isForwardingAliasSet() && AS.isMod()) {
504 // FIXME: This should use mod/ref information to see if we can hoist or
510 // Only these instructions are hoistable/sinkable.
511 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
512 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
513 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
514 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
515 !isa<InsertValueInst>(I))
518 // TODO: Plumb the context instruction through to make hoisting and sinking
519 // more powerful. Hoisting of loads already works due to the special casing
521 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
524 /// Returns true if a PHINode is a trivially replaceable with an
526 /// This is true when all incoming values are that instruction.
527 /// This pattern occurs most often with LCSSA PHI nodes.
529 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
530 for (const Value *IncValue : PN.incoming_values())
537 /// Return true if the only users of this instruction are outside of
538 /// the loop. If this is true, we can sink the instruction to the exit
539 /// blocks of the loop.
541 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
542 const LoopSafetyInfo *SafetyInfo) {
543 const auto &BlockColors = SafetyInfo->BlockColors;
544 for (const User *U : I.users()) {
545 const Instruction *UI = cast<Instruction>(U);
546 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
547 const BasicBlock *BB = PN->getParent();
548 // We cannot sink uses in catchswitches.
549 if (isa<CatchSwitchInst>(BB->getTerminator()))
552 // We need to sink a callsite to a unique funclet. Avoid sinking if the
553 // phi use is too muddled.
554 if (isa<CallInst>(I))
555 if (!BlockColors.empty() &&
556 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
559 // A PHI node where all of the incoming values are this instruction are
560 // special -- they can just be RAUW'ed with the instruction and thus
561 // don't require a use in the predecessor. This is a particular important
562 // special case because it is the pattern found in LCSSA form.
563 if (isTriviallyReplacablePHI(*PN, I)) {
564 if (CurLoop->contains(PN))
570 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
571 // values. Check for such a use being inside the loop.
572 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
573 if (PN->getIncomingValue(i) == &I)
574 if (CurLoop->contains(PN->getIncomingBlock(i)))
580 if (CurLoop->contains(UI))
587 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
589 const LoopSafetyInfo *SafetyInfo) {
591 if (auto *CI = dyn_cast<CallInst>(&I)) {
592 const auto &BlockColors = SafetyInfo->BlockColors;
594 // Sinking call-sites need to be handled differently from other
595 // instructions. The cloned call-site needs a funclet bundle operand
596 // appropriate for it's location in the CFG.
597 SmallVector<OperandBundleDef, 1> OpBundles;
598 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
599 BundleIdx != BundleEnd; ++BundleIdx) {
600 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
601 if (Bundle.getTagID() == LLVMContext::OB_funclet)
604 OpBundles.emplace_back(Bundle);
607 if (!BlockColors.empty()) {
608 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
609 assert(CV.size() == 1 && "non-unique color for exit block!");
610 BasicBlock *BBColor = CV.front();
611 Instruction *EHPad = BBColor->getFirstNonPHI();
612 if (EHPad->isEHPad())
613 OpBundles.emplace_back("funclet", EHPad);
616 New = CallInst::Create(CI, OpBundles);
621 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
622 if (!I.getName().empty())
623 New->setName(I.getName() + ".le");
625 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
626 // particularly cheap because we can rip off the PHI node that we're
627 // replacing for the number and blocks of the predecessors.
628 // OPT: If this shows up in a profile, we can instead finish sinking all
629 // invariant instructions, and then walk their operands to re-establish
630 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
631 // sinking bottom-up.
632 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
634 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
635 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
636 if (!OLoop->contains(&PN)) {
638 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
639 OInst->getName() + ".lcssa", &ExitBlock.front());
640 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
641 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
647 /// When an instruction is found to only be used outside of the loop, this
648 /// function moves it to the exit blocks and patches up SSA form as needed.
649 /// This method is guaranteed to remove the original instruction from its
650 /// position, and may either delete it or move it to outside of the loop.
652 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
653 const Loop *CurLoop, AliasSetTracker *CurAST,
654 const LoopSafetyInfo *SafetyInfo) {
655 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
656 bool Changed = false;
657 if (isa<LoadInst>(I))
659 else if (isa<CallInst>(I))
665 SmallVector<BasicBlock *, 32> ExitBlocks;
666 CurLoop->getUniqueExitBlocks(ExitBlocks);
667 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
671 // Clones of this instruction. Don't create more than one per exit block!
672 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
674 // If this instruction is only used outside of the loop, then all users are
675 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
677 while (!I.use_empty()) {
678 Value::user_iterator UI = I.user_begin();
679 auto *User = cast<Instruction>(*UI);
680 if (!DT->isReachableFromEntry(User->getParent())) {
681 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
684 // The user must be a PHI node.
685 PHINode *PN = cast<PHINode>(User);
687 // Surprisingly, instructions can be used outside of loops without any
688 // exits. This can only happen in PHI nodes if the incoming block is
690 Use &U = UI.getUse();
691 BasicBlock *BB = PN->getIncomingBlock(U);
692 if (!DT->isReachableFromEntry(BB)) {
693 U = UndefValue::get(I.getType());
697 BasicBlock *ExitBlock = PN->getParent();
698 assert(ExitBlockSet.count(ExitBlock) &&
699 "The LCSSA PHI is not in an exit block!");
702 auto It = SunkCopies.find(ExitBlock);
703 if (It != SunkCopies.end())
706 New = SunkCopies[ExitBlock] =
707 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
709 PN->replaceAllUsesWith(New);
710 PN->eraseFromParent();
713 CurAST->deleteValue(&I);
718 /// When an instruction is found to only use loop invariant operands that
719 /// is safe to hoist, this instruction is called to do the dirty work.
721 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
722 const LoopSafetyInfo *SafetyInfo) {
723 auto *Preheader = CurLoop->getLoopPreheader();
724 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
727 // Metadata can be dependent on conditions we are hoisting above.
728 // Conservatively strip all metadata on the instruction unless we were
729 // guaranteed to execute I if we entered the loop, in which case the metadata
730 // is valid in the loop preheader.
731 if (I.hasMetadataOtherThanDebugLoc() &&
732 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
733 // time in isGuaranteedToExecute if we don't actually have anything to
734 // drop. It is a compile time optimization, not required for correctness.
735 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
736 I.dropUnknownNonDebugMetadata();
738 // Move the new node to the Preheader, before its terminator.
739 I.moveBefore(Preheader->getTerminator());
741 if (isa<LoadInst>(I))
743 else if (isa<CallInst>(I))
749 /// Only sink or hoist an instruction if it is not a trapping instruction,
750 /// or if the instruction is known not to trap when moved to the preheader.
751 /// or if it is a trapping instruction and is guaranteed to execute.
752 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
753 const DominatorTree *DT,
755 const LoopSafetyInfo *SafetyInfo,
756 const Instruction *CtxI) {
757 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
760 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
764 class LoopPromoter : public LoadAndStorePromoter {
765 Value *SomePtr; // Designated pointer to store to.
766 SmallPtrSetImpl<Value *> &PointerMustAliases;
767 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
768 SmallVectorImpl<Instruction *> &LoopInsertPts;
769 PredIteratorCache &PredCache;
770 AliasSetTracker &AST;
776 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
777 if (Instruction *I = dyn_cast<Instruction>(V))
778 if (Loop *L = LI.getLoopFor(I->getParent()))
779 if (!L->contains(BB)) {
780 // We need to create an LCSSA PHI node for the incoming value and
782 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
783 I->getName() + ".lcssa", &BB->front());
784 for (BasicBlock *Pred : PredCache.get(BB))
785 PN->addIncoming(I, Pred);
792 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
793 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(std::move(dl)), Alignment(alignment), AATags(AATags) {}
802 bool isInstInList(Instruction *I,
803 const SmallVectorImpl<Instruction *> &) const override {
805 if (LoadInst *LI = dyn_cast<LoadInst>(I))
806 Ptr = LI->getOperand(0);
808 Ptr = cast<StoreInst>(I)->getPointerOperand();
809 return PointerMustAliases.count(Ptr);
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);
827 NewSI->setAAMetadata(AATags);
831 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
832 // Update alias analysis.
833 AST.copyValue(LI, V);
835 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
837 } // end anon namespace
839 /// Try to promote memory values to scalars by sinking stores out of the
840 /// loop and moving loads to before the loop. We do this by looping over
841 /// the stores in the loop, looking for stores to Must pointers which are
844 bool llvm::promoteLoopAccessesToScalars(
845 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
846 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
847 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
848 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
850 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
851 CurAST != nullptr && SafetyInfo != nullptr &&
852 "Unexpected Input to promoteLoopAccessesToScalars");
854 // We can promote this alias set if it has a store, if it is a "Must" alias
855 // set, if the pointer is loop invariant, and if we are not eliminating any
856 // volatile loads or stores.
857 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
858 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
861 assert(!AS.empty() &&
862 "Must alias set should have at least one pointer element in it!");
864 Value *SomePtr = AS.begin()->getValue();
865 BasicBlock *Preheader = CurLoop->getLoopPreheader();
867 // It isn't safe to promote a load/store from the loop if the load/store is
868 // conditional. For example, turning:
870 // for () { if (c) *P += 1; }
874 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
876 // is not safe, because *P may only be valid to access if 'c' is true.
878 // The safety property divides into two parts:
879 // 1) The memory may not be dereferenceable on entry to the loop. In this
880 // case, we can't insert the required load in the preheader.
881 // 2) The memory model does not allow us to insert a store along any dynamic
882 // path which did not originally have one.
884 // It is safe to promote P if all uses are direct load/stores and if at
885 // least one is guaranteed to be executed.
886 bool GuaranteedToExecute = false;
888 // It is also safe to promote P if we can prove that speculating a load into
889 // the preheader is safe (i.e. proving dereferenceability on all
890 // paths through the loop), and that the memory can be proven thread local
891 // (so that the memory model requirement doesn't apply.) We first establish
892 // the former, and then run a capture analysis below to establish the later.
893 // We can use any access within the alias set to prove dereferenceability
894 // since they're all must alias.
895 bool CanSpeculateLoad = false;
897 SmallVector<Instruction *, 64> LoopUses;
898 SmallPtrSet<Value *, 4> PointerMustAliases;
900 // We start with an alignment of one and try to find instructions that allow
901 // us to prove better alignment.
902 unsigned Alignment = 1;
904 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
906 // Don't sink stores from loops without dedicated block exits. Exits
907 // containing indirect branches are not transformed by loop simplify,
908 // make sure we catch that. An additional load may be generated in the
909 // preheader for SSA updater, so also avoid sinking when no preheader
911 if (!HasDedicatedExits || !Preheader)
914 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
916 if (SafetyInfo->MayThrow) {
917 // If a loop can throw, we have to insert a store along each unwind edge.
918 // That said, we can't actually make the unwind edge explicit. Therefore,
919 // we have to prove that the store is dead along the unwind edge.
921 // Currently, this code just special-cases alloca instructions.
922 if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
926 // Check that all of the pointers in the alias set have the same type. We
927 // cannot (yet) promote a memory location that is loaded and stored in
928 // different sizes. While we are at it, collect alignment and AA info.
929 bool Changed = false;
930 for (const auto &ASI : AS) {
931 Value *ASIV = ASI.getValue();
932 PointerMustAliases.insert(ASIV);
934 // Check that all of the pointers in the alias set have the same type. We
935 // cannot (yet) promote a memory location that is loaded and stored in
937 if (SomePtr->getType() != ASIV->getType())
940 for (User *U : ASIV->users()) {
941 // Ignore instructions that are outside the loop.
942 Instruction *UI = dyn_cast<Instruction>(U);
943 if (!UI || !CurLoop->contains(UI))
946 // If there is an non-load/store instruction in the loop, we can't promote
948 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
949 assert(!Load->isVolatile() && "AST broken");
950 if (!Load->isSimple())
953 if (!GuaranteedToExecute && !CanSpeculateLoad)
954 CanSpeculateLoad = isSafeToExecuteUnconditionally(
955 *Load, DT, CurLoop, SafetyInfo, Preheader->getTerminator());
956 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
957 // Stores *of* the pointer are not interesting, only stores *to* the
959 if (UI->getOperand(1) != ASIV)
961 assert(!Store->isVolatile() && "AST broken");
962 if (!Store->isSimple())
965 // Note that we only check GuaranteedToExecute inside the store case
966 // so that we do not introduce stores where they did not exist before
967 // (which would break the LLVM concurrency model).
969 // If the alignment of this instruction allows us to specify a more
970 // restrictive (and performant) alignment and if we are sure this
971 // instruction will be executed, update the alignment.
972 // Larger is better, with the exception of 0 being the best alignment.
973 unsigned InstAlignment = Store->getAlignment();
974 if ((InstAlignment > Alignment || InstAlignment == 0) &&
976 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
977 GuaranteedToExecute = true;
978 Alignment = InstAlignment;
980 } else if (!GuaranteedToExecute) {
981 GuaranteedToExecute =
982 isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
985 if (!GuaranteedToExecute && !CanSpeculateLoad) {
986 CanSpeculateLoad = isDereferenceableAndAlignedPointer(
987 Store->getPointerOperand(), Store->getAlignment(), MDL,
988 Preheader->getTerminator(), DT);
991 return Changed; // Not a load or store.
993 // Merge the AA tags.
994 if (LoopUses.empty()) {
995 // On the first load/store, just take its AA tags.
996 UI->getAAMetadata(AATags);
998 UI->getAAMetadata(AATags, /* Merge = */ true);
1001 LoopUses.push_back(UI);
1005 // Check legality per comment above. Otherwise, we can't promote.
1006 bool PromotionIsLegal = GuaranteedToExecute;
1007 if (!PromotionIsLegal && CanSpeculateLoad) {
1008 // If this is a thread local location, then we can insert stores along
1009 // paths which originally didn't have them without violating the memory
1011 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1013 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
1015 if (!PromotionIsLegal)
1018 // Figure out the loop exits and their insertion points, if this is the
1020 if (ExitBlocks.empty()) {
1021 CurLoop->getUniqueExitBlocks(ExitBlocks);
1023 InsertPts.reserve(ExitBlocks.size());
1024 for (BasicBlock *ExitBlock : ExitBlocks)
1025 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
1028 // Can't insert into a catchswitch.
1029 for (BasicBlock *ExitBlock : ExitBlocks)
1030 if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1033 // Otherwise, this is safe to promote, lets do it!
1034 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1039 // Grab a debug location for the inserted loads/stores; given that the
1040 // inserted loads/stores have little relation to the original loads/stores,
1041 // this code just arbitrarily picks a location from one, since any debug
1042 // location is better than none.
1043 DebugLoc DL = LoopUses[0]->getDebugLoc();
1045 // We use the SSAUpdater interface to insert phi nodes as required.
1046 SmallVector<PHINode *, 16> NewPHIs;
1047 SSAUpdater SSA(&NewPHIs);
1048 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1049 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
1051 // Set up the preheader to have a definition of the value. It is the live-out
1052 // value from the preheader that uses in the loop will use.
1053 LoadInst *PreheaderLoad = new LoadInst(
1054 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1055 PreheaderLoad->setAlignment(Alignment);
1056 PreheaderLoad->setDebugLoc(DL);
1058 PreheaderLoad->setAAMetadata(AATags);
1059 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1061 // Rewrite all the loads in the loop and remember all the definitions from
1062 // stores in the loop.
1063 Promoter.run(LoopUses);
1065 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1066 if (PreheaderLoad->use_empty())
1067 PreheaderLoad->eraseFromParent();
1072 /// Returns an owning pointer to an alias set which incorporates aliasing info
1073 /// from L and all subloops of L.
1074 /// FIXME: In new pass manager, there is no helper functions to handle loop
1075 /// analysis such as cloneBasicBlockAnalysis. So the AST needs to be recompute
1076 /// from scratch for every loop. Hook up with the helper functions when
1077 /// available in the new pass manager to avoid redundant computation.
1079 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1080 AliasAnalysis *AA) {
1081 AliasSetTracker *CurAST = nullptr;
1082 SmallVector<Loop *, 4> RecomputeLoops;
1083 for (Loop *InnerL : L->getSubLoops()) {
1084 auto MapI = LoopToAliasSetMap.find(InnerL);
1085 // If the AST for this inner loop is missing it may have been merged into
1086 // some other loop's AST and then that loop unrolled, and so we need to
1088 if (MapI == LoopToAliasSetMap.end()) {
1089 RecomputeLoops.push_back(InnerL);
1092 AliasSetTracker *InnerAST = MapI->second;
1094 if (CurAST != nullptr) {
1095 // What if InnerLoop was modified by other passes ?
1096 CurAST->add(*InnerAST);
1098 // Once we've incorporated the inner loop's AST into ours, we don't need
1099 // the subloop's anymore.
1104 LoopToAliasSetMap.erase(MapI);
1106 if (CurAST == nullptr)
1107 CurAST = new AliasSetTracker(*AA);
1109 auto mergeLoop = [&](Loop *L) {
1110 // Loop over the body of this loop, looking for calls, invokes, and stores.
1111 // Because subloops have already been incorporated into AST, we skip blocks
1113 for (BasicBlock *BB : L->blocks())
1114 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1115 CurAST->add(*BB); // Incorporate the specified basic block
1118 // Add everything from the sub loops that are no longer directly available.
1119 for (Loop *InnerL : RecomputeLoops)
1122 // And merge in this loop.
1128 /// Simple analysis hook. Clone alias set info.
1130 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1132 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1136 AST->copyValue(From, To);
1139 /// Simple Analysis hook. Delete value V from alias set
1141 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1142 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1146 AST->deleteValue(V);
1149 /// Simple Analysis hook. Delete value L from alias set map.
1151 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1152 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1157 LICM.getLoopToAliasSetMap().erase(L);
1160 /// Return true if the body of this loop may store into the memory
1161 /// location pointed to by V.
1163 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1164 const AAMDNodes &AAInfo,
1165 AliasSetTracker *CurAST) {
1166 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1167 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1170 /// Little predicate that returns true if the specified basic block is in
1171 /// a subloop of the current one, not the current one itself.
1173 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1174 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1175 return LI->getLoopFor(BB) != CurLoop;