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.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/ConstantFolding.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/ScalarEvolution.h"
41 #include "llvm/Analysis/TargetLibraryInfo.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Dominators.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/PredIteratorCache.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
62 #define DEBUG_TYPE "licm"
64 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
65 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
66 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
71 DisablePromotion("disable-licm-promotion", cl::Hidden,
72 cl::desc("Disable memory promotion in LICM pass"));
74 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop);
76 static bool hoist(Instruction &I, BasicBlock *Preheader);
77 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
78 const Loop *CurLoop, AliasSetTracker *CurAST );
79 static bool isGuaranteedToExecute(const Instruction &Inst,
80 const DominatorTree *DT,
82 const LICMSafetyInfo *SafetyInfo);
83 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
84 const DominatorTree *DT,
85 const TargetLibraryInfo *TLI,
87 const LICMSafetyInfo *SafetyInfo,
88 const Instruction *CtxI = nullptr);
89 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
90 const AAMDNodes &AAInfo,
91 AliasSetTracker *CurAST);
92 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
93 BasicBlock &ExitBlock,
96 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
97 DominatorTree *DT, TargetLibraryInfo *TLI,
98 Loop *CurLoop, AliasSetTracker *CurAST,
99 LICMSafetyInfo *SafetyInfo);
102 struct LICM : public LoopPass {
103 static char ID; // Pass identification, replacement for typeid
104 LICM() : LoopPass(ID) {
105 initializeLICMPass(*PassRegistry::getPassRegistry());
108 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
110 /// This transformation requires natural loop information & requires that
111 /// loop preheaders be inserted into the CFG...
113 void getAnalysisUsage(AnalysisUsage &AU) const override {
114 AU.setPreservesCFG();
115 AU.addRequired<DominatorTreeWrapperPass>();
116 AU.addRequired<LoopInfoWrapperPass>();
117 AU.addRequiredID(LoopSimplifyID);
118 AU.addPreservedID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
120 AU.addPreservedID(LCSSAID);
121 AU.addRequired<AliasAnalysis>();
122 AU.addPreserved<AliasAnalysis>();
123 AU.addPreserved<ScalarEvolution>();
124 AU.addRequired<TargetLibraryInfoWrapperPass>();
127 using llvm::Pass::doFinalization;
129 bool doFinalization() override {
130 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
135 AliasAnalysis *AA; // Current AliasAnalysis information
136 LoopInfo *LI; // Current LoopInfo
137 DominatorTree *DT; // Dominator Tree for the current Loop.
139 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
141 // State that is updated as we process loops.
142 bool Changed; // Set to true when we change anything.
143 BasicBlock *Preheader; // The preheader block of the current loop...
144 Loop *CurLoop; // The current loop we are working on...
145 AliasSetTracker *CurAST; // AliasSet information for the current loop...
146 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
148 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
149 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
152 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
154 void deleteAnalysisValue(Value *V, Loop *L) override;
156 /// Simple Analysis hook. Delete loop L from alias set map.
157 void deleteAnalysisLoop(Loop *L) override;
162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
163 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
164 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
165 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166 INITIALIZE_PASS_DEPENDENCY(LCSSA)
167 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
168 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
169 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
172 Pass *llvm::createLICMPass() { return new LICM(); }
174 /// Hoist expressions out of the specified loop. Note, alias info for inner
175 /// loop is not preserved so it is not a good idea to run LICM multiple
176 /// times on one loop.
178 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
179 if (skipOptnoneFunction(L))
184 // Get our Loop and Alias Analysis information...
185 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
186 AA = &getAnalysis<AliasAnalysis>();
187 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
189 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
191 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
193 CurAST = new AliasSetTracker(*AA);
194 // Collect Alias info from subloops.
195 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
196 LoopItr != LoopItrE; ++LoopItr) {
197 Loop *InnerL = *LoopItr;
198 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
199 assert(InnerAST && "Where is my AST?");
201 // What if InnerLoop was modified by other passes ?
202 CurAST->add(*InnerAST);
204 // Once we've incorporated the inner loop's AST into ours, we don't need the
205 // subloop's anymore.
207 LoopToAliasSetMap.erase(InnerL);
212 // Get the preheader block to move instructions into...
213 Preheader = L->getLoopPreheader();
215 // Loop over the body of this loop, looking for calls, invokes, and stores.
216 // Because subloops have already been incorporated into AST, we skip blocks in
219 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
222 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
223 CurAST->add(*BB); // Incorporate the specified basic block
226 // Compute loop safety information.
227 LICMSafetyInfo SafetyInfo;
228 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
230 // We want to visit all of the instructions in this loop... that are not parts
231 // of our subloops (they have already had their invariants hoisted out of
232 // their loop, into this loop, so there is no need to process the BODIES of
235 // Traverse the body of the loop in depth first order on the dominator tree so
236 // that we are guaranteed to see definitions before we see uses. This allows
237 // us to sink instructions in one pass, without iteration. After sinking
238 // instructions, we perform another pass to hoist them out of the loop.
240 if (L->hasDedicatedExits())
241 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
242 CurAST, &SafetyInfo);
244 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
245 CurLoop, CurAST, &SafetyInfo);
247 // Now that all loop invariants have been removed from the loop, promote any
248 // memory references to scalars that we can.
249 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
250 SmallVector<BasicBlock *, 8> ExitBlocks;
251 SmallVector<Instruction *, 8> InsertPts;
252 PredIteratorCache PIC;
254 // Loop over all of the alias sets in the tracker object.
255 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
257 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
258 PIC, LI, DT, CurLoop,
259 CurAST, &SafetyInfo);
261 // Once we have promoted values across the loop body we have to recursively
262 // reform LCSSA as any nested loop may now have values defined within the
263 // loop used in the outer loop.
264 // FIXME: This is really heavy handed. It would be a bit better to use an
265 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
268 formLCSSARecursively(*L, *DT, LI,
269 getAnalysisIfAvailable<ScalarEvolution>());
272 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
273 // specifically moving instructions across the loop boundary and so it is
274 // especially in need of sanity checking here.
275 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
276 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
277 "Parent loop not left in LCSSA form after LICM!");
279 // Clear out loops state information for the next iteration
283 // If this loop is nested inside of another one, save the alias information
284 // for when we process the outer loop.
285 if (L->getParentLoop())
286 LoopToAliasSetMap[L] = CurAST;
292 /// Walk the specified region of the CFG (defined by all blocks dominated by
293 /// the specified block, and that are in the current loop) in reverse depth
294 /// first order w.r.t the DominatorTree. This allows us to visit uses before
295 /// definitions, allowing us to sink a loop body in one pass without iteration.
297 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
298 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
299 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
302 assert(N != nullptr && AA != nullptr && LI != nullptr &&
303 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
304 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
306 // Set changed as false.
307 bool Changed = false;
309 BasicBlock *BB = N->getBlock();
310 // If this subregion is not in the top level loop at all, exit.
311 if (!CurLoop->contains(BB)) return Changed;
313 // We are processing blocks in reverse dfo, so process children first.
314 const std::vector<DomTreeNode*> &Children = N->getChildren();
315 for (unsigned i = 0, e = Children.size(); i != e; ++i)
317 sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
318 // Only need to process the contents of this block if it is not part of a
319 // subloop (which would already have been processed).
320 if (inSubLoop(BB,CurLoop,LI)) return Changed;
322 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
323 Instruction &I = *--II;
325 // If the instruction is dead, we would try to sink it because it isn't used
326 // in the loop, instead, just delete it.
327 if (isInstructionTriviallyDead(&I, TLI)) {
328 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
330 CurAST->deleteValue(&I);
336 // Check to see if we can sink this instruction to the exit blocks
337 // of the loop. We can do this if the all users of the instruction are
338 // outside of the loop. In this case, it doesn't even matter if the
339 // operands of the instruction are loop invariant.
341 if (isNotUsedInLoop(I, CurLoop) &&
342 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
344 Changed |= sink(I, LI, DT, CurLoop, CurAST);
350 /// Walk the specified region of the CFG (defined by all blocks dominated by
351 /// the specified block, and that are in the current loop) in depth first
352 /// order w.r.t the DominatorTree. This allows us to visit definitions before
353 /// uses, allowing us to hoist a loop body in one pass without iteration.
355 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
356 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
357 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
359 assert(N != nullptr && AA != nullptr && LI != nullptr &&
360 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
361 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
362 // Set changed as false.
363 bool Changed = false;
365 BasicBlock *BB = N->getBlock();
366 // If this subregion is not in the top level loop at all, exit.
367 if (!CurLoop->contains(BB)) return Changed;
368 // Only need to process the contents of this block if it is not part of a
369 // subloop (which would already have been processed).
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 CurAST->deleteValue(&I);
381 I.replaceAllUsesWith(C);
386 // Try hoisting the instruction out to the preheader. We can only do this
387 // if all of the operands of the instruction are loop invariant and if it
388 // is safe to hoist the instruction.
390 if (CurLoop->hasLoopInvariantOperands(&I) &&
391 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
392 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
393 CurLoop->getLoopPreheader()->getTerminator()))
394 Changed |= hoist(I, CurLoop->getLoopPreheader());
397 const std::vector<DomTreeNode*> &Children = N->getChildren();
398 for (unsigned i = 0, e = Children.size(); i != e; ++i)
400 hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
404 /// Computes loop safety information, checks loop body & header
405 /// for the possiblity of may throw exception.
407 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
408 assert(CurLoop != nullptr && "CurLoop cant be null");
409 BasicBlock *Header = CurLoop->getHeader();
410 // Setting default safety values.
411 SafetyInfo->MayThrow = false;
412 SafetyInfo->HeaderMayThrow = false;
413 // Iterate over header and compute dafety info.
414 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
415 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
416 SafetyInfo->HeaderMayThrow |= I->mayThrow();
418 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
419 // Iterate over loop instructions and compute safety info.
420 for (Loop::block_iterator BB = CurLoop->block_begin(),
421 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
422 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
423 (I != E) && !SafetyInfo->MayThrow; ++I)
424 SafetyInfo->MayThrow |= I->mayThrow();
427 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
430 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
431 TargetLibraryInfo *TLI, Loop *CurLoop,
432 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
433 // Loads have extra constraints we have to verify before we can hoist them.
434 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
435 if (!LI->isUnordered())
436 return false; // Don't hoist volatile/atomic loads!
438 // Loads from constant memory are always safe to move, even if they end up
439 // in the same alias set as something that ends up being modified.
440 if (AA->pointsToConstantMemory(LI->getOperand(0)))
442 if (LI->getMetadata(LLVMContext::MD_invariant_load))
445 // Don't hoist loads which have may-aliased stores in loop.
447 if (LI->getType()->isSized())
448 Size = AA->getTypeStoreSize(LI->getType());
451 LI->getAAMetadata(AAInfo);
453 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
454 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
455 // Don't sink or hoist dbg info; it's legal, but not useful.
456 if (isa<DbgInfoIntrinsic>(I))
459 // Handle simple cases by querying alias analysis.
460 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
461 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
463 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
464 // If this call only reads from memory and there are no writes to memory
465 // in the loop, we can hoist or sink the call as appropriate.
466 bool FoundMod = false;
467 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
470 if (!AS.isForwardingAliasSet() && AS.isMod()) {
475 if (!FoundMod) return true;
478 // FIXME: This should use mod/ref information to see if we can hoist or
484 // Only these instructions are hoistable/sinkable.
485 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
486 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
487 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
488 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
489 !isa<InsertValueInst>(I))
492 // TODO: Plumb the context instruction through to make hoisting and sinking
493 // more powerful. Hoisting of loads already works due to the special casing
495 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
499 /// Returns true if a PHINode is a trivially replaceable with an
501 /// This is true when all incoming values are that instruction.
502 /// This pattern occurs most often with LCSSA PHI nodes.
504 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
505 for (const Value *IncValue : PN.incoming_values())
512 /// Return true if the only users of this instruction are outside of
513 /// the loop. If this is true, we can sink the instruction to the exit
514 /// blocks of the loop.
516 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) {
517 for (const User *U : I.users()) {
518 const Instruction *UI = cast<Instruction>(U);
519 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
520 // A PHI node where all of the incoming values are this instruction are
521 // special -- they can just be RAUW'ed with the instruction and thus
522 // don't require a use in the predecessor. This is a particular important
523 // special case because it is the pattern found in LCSSA form.
524 if (isTriviallyReplacablePHI(*PN, I)) {
525 if (CurLoop->contains(PN))
531 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
532 // values. Check for such a use being inside the loop.
533 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
534 if (PN->getIncomingValue(i) == &I)
535 if (CurLoop->contains(PN->getIncomingBlock(i)))
541 if (CurLoop->contains(UI))
547 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
548 BasicBlock &ExitBlock,
550 const LoopInfo *LI) {
551 Instruction *New = I.clone();
552 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
553 if (!I.getName().empty()) New->setName(I.getName() + ".le");
555 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
556 // particularly cheap because we can rip off the PHI node that we're
557 // replacing for the number and blocks of the predecessors.
558 // OPT: If this shows up in a profile, we can instead finish sinking all
559 // invariant instructions, and then walk their operands to re-establish
560 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
561 // sinking bottom-up.
562 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
564 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
565 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
566 if (!OLoop->contains(&PN)) {
568 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
569 OInst->getName() + ".lcssa", ExitBlock.begin());
570 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
571 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
577 /// When an instruction is found to only be used outside of the loop, this
578 /// function moves it to the exit blocks and patches up SSA form as needed.
579 /// This method is guaranteed to remove the original instruction from its
580 /// position, and may either delete it or move it to outside of the loop.
582 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
583 const Loop *CurLoop, AliasSetTracker *CurAST ) {
584 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
585 bool Changed = false;
586 if (isa<LoadInst>(I)) ++NumMovedLoads;
587 else if (isa<CallInst>(I)) ++NumMovedCalls;
592 SmallVector<BasicBlock *, 32> ExitBlocks;
593 CurLoop->getUniqueExitBlocks(ExitBlocks);
594 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
598 // Clones of this instruction. Don't create more than one per exit block!
599 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
601 // If this instruction is only used outside of the loop, then all users are
602 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
604 while (!I.use_empty()) {
605 Instruction *User = I.user_back();
606 if (!DT->isReachableFromEntry(User->getParent())) {
607 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
610 // The user must be a PHI node.
611 PHINode *PN = cast<PHINode>(User);
613 BasicBlock *ExitBlock = PN->getParent();
614 assert(ExitBlockSet.count(ExitBlock) &&
615 "The LCSSA PHI is not in an exit block!");
618 auto It = SunkCopies.find(ExitBlock);
619 if (It != SunkCopies.end())
622 New = SunkCopies[ExitBlock] =
623 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
625 PN->replaceAllUsesWith(New);
626 PN->eraseFromParent();
629 CurAST->deleteValue(&I);
634 /// When an instruction is found to only use loop invariant operands that
635 /// is safe to hoist, this instruction is called to do the dirty work.
637 static bool hoist(Instruction &I, BasicBlock *Preheader) {
638 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
640 // Move the new node to the Preheader, before its terminator.
641 I.moveBefore(Preheader->getTerminator());
643 if (isa<LoadInst>(I)) ++NumMovedLoads;
644 else if (isa<CallInst>(I)) ++NumMovedCalls;
649 /// Only sink or hoist an instruction if it is not a trapping instruction,
650 /// or if the instruction is known not to trap when moved to the preheader.
651 /// or if it is a trapping instruction and is guaranteed to execute.
652 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
653 const DominatorTree *DT,
654 const TargetLibraryInfo *TLI,
656 const LICMSafetyInfo *SafetyInfo,
657 const Instruction *CtxI) {
658 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
661 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
664 static bool isGuaranteedToExecute(const Instruction &Inst,
665 const DominatorTree *DT,
667 const LICMSafetyInfo * SafetyInfo) {
669 // We have to check to make sure that the instruction dominates all
670 // of the exit blocks. If it doesn't, then there is a path out of the loop
671 // which does not execute this instruction, so we can't hoist it.
673 // If the instruction is in the header block for the loop (which is very
674 // common), it is always guaranteed to dominate the exit blocks. Since this
675 // is a common case, and can save some work, check it now.
676 if (Inst.getParent() == CurLoop->getHeader())
677 // If there's a throw in the header block, we can't guarantee we'll reach
679 return !SafetyInfo->HeaderMayThrow;
681 // Somewhere in this loop there is an instruction which may throw and make us
683 if (SafetyInfo->MayThrow)
686 // Get the exit blocks for the current loop.
687 SmallVector<BasicBlock*, 8> ExitBlocks;
688 CurLoop->getExitBlocks(ExitBlocks);
690 // Verify that the block dominates each of the exit blocks of the loop.
691 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
692 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
695 // As a degenerate case, if the loop is statically infinite then we haven't
696 // proven anything since there are no exit blocks.
697 if (ExitBlocks.empty())
704 class LoopPromoter : public LoadAndStorePromoter {
705 Value *SomePtr; // Designated pointer to store to.
706 SmallPtrSetImpl<Value*> &PointerMustAliases;
707 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
708 SmallVectorImpl<Instruction*> &LoopInsertPts;
709 PredIteratorCache &PredCache;
710 AliasSetTracker &AST;
716 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
717 if (Instruction *I = dyn_cast<Instruction>(V))
718 if (Loop *L = LI.getLoopFor(I->getParent()))
719 if (!L->contains(BB)) {
720 // We need to create an LCSSA PHI node for the incoming value and
722 PHINode *PN = PHINode::Create(
723 I->getType(), PredCache.size(BB),
724 I->getName() + ".lcssa", BB->begin());
725 for (BasicBlock *Pred : PredCache.get(BB))
726 PN->addIncoming(I, Pred);
733 LoopPromoter(Value *SP,
734 ArrayRef<const Instruction *> Insts,
735 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
736 SmallVectorImpl<BasicBlock *> &LEB,
737 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
738 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
739 const AAMDNodes &AATags)
740 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
741 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
742 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
744 bool isInstInList(Instruction *I,
745 const SmallVectorImpl<Instruction*> &) const override {
747 if (LoadInst *LI = dyn_cast<LoadInst>(I))
748 Ptr = LI->getOperand(0);
750 Ptr = cast<StoreInst>(I)->getPointerOperand();
751 return PointerMustAliases.count(Ptr);
754 void doExtraRewritesBeforeFinalDeletion() const override {
755 // Insert stores after in the loop exit blocks. Each exit block gets a
756 // store of the live-out values that feed them. Since we've already told
757 // the SSA updater about the defs in the loop and the preheader
758 // definition, it is all set and we can start using it.
759 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
760 BasicBlock *ExitBlock = LoopExitBlocks[i];
761 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
762 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
763 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
764 Instruction *InsertPos = LoopInsertPts[i];
765 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
766 NewSI->setAlignment(Alignment);
767 NewSI->setDebugLoc(DL);
768 if (AATags) NewSI->setAAMetadata(AATags);
772 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
773 // Update alias analysis.
774 AST.copyValue(LI, V);
776 void instructionDeleted(Instruction *I) const override {
780 } // end anon namespace
782 /// Try to promote memory values to scalars by sinking stores out of the
783 /// loop and moving loads to before the loop. We do this by looping over
784 /// the stores in the loop, looking for stores to Must pointers which are
787 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
788 SmallVectorImpl<BasicBlock*>&ExitBlocks,
789 SmallVectorImpl<Instruction*>&InsertPts,
790 PredIteratorCache &PIC, LoopInfo *LI,
791 DominatorTree *DT, Loop *CurLoop,
792 AliasSetTracker *CurAST,
793 LICMSafetyInfo * SafetyInfo) {
795 assert(LI != nullptr && DT != nullptr &&
796 CurLoop != nullptr && CurAST != nullptr &&
797 SafetyInfo != nullptr &&
798 "Unexpected Input to promoteLoopAccessesToScalars");
799 // Initially set Changed status to false.
800 bool Changed = false;
801 // We can promote this alias set if it has a store, if it is a "Must" alias
802 // set, if the pointer is loop invariant, and if we are not eliminating any
803 // volatile loads or stores.
804 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
805 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
808 assert(!AS.empty() &&
809 "Must alias set should have at least one pointer element in it!");
811 Value *SomePtr = AS.begin()->getValue();
812 BasicBlock * Preheader = CurLoop->getLoopPreheader();
814 // It isn't safe to promote a load/store from the loop if the load/store is
815 // conditional. For example, turning:
817 // for () { if (c) *P += 1; }
821 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
823 // is not safe, because *P may only be valid to access if 'c' is true.
825 // It is safe to promote P if all uses are direct load/stores and if at
826 // least one is guaranteed to be executed.
827 bool GuaranteedToExecute = false;
829 SmallVector<Instruction*, 64> LoopUses;
830 SmallPtrSet<Value*, 4> PointerMustAliases;
832 // We start with an alignment of one and try to find instructions that allow
833 // us to prove better alignment.
834 unsigned Alignment = 1;
836 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
838 // Check that all of the pointers in the alias set have the same type. We
839 // cannot (yet) promote a memory location that is loaded and stored in
840 // different sizes. While we are at it, collect alignment and AA info.
841 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
842 Value *ASIV = ASI->getValue();
843 PointerMustAliases.insert(ASIV);
845 // Check that all of the pointers in the alias set have the same type. We
846 // cannot (yet) promote a memory location that is loaded and stored in
848 if (SomePtr->getType() != ASIV->getType())
851 for (User *U : ASIV->users()) {
852 // Ignore instructions that are outside the loop.
853 Instruction *UI = dyn_cast<Instruction>(U);
854 if (!UI || !CurLoop->contains(UI))
857 // If there is an non-load/store instruction in the loop, we can't promote
859 if (const LoadInst *load = dyn_cast<LoadInst>(UI)) {
860 assert(!load->isVolatile() && "AST broken");
861 if (!load->isSimple())
863 } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) {
864 // Stores *of* the pointer are not interesting, only stores *to* the
866 if (UI->getOperand(1) != ASIV)
868 assert(!store->isVolatile() && "AST broken");
869 if (!store->isSimple())
871 // Don't sink stores from loops without dedicated block exits. Exits
872 // containing indirect branches are not transformed by loop simplify,
873 // make sure we catch that. An additional load may be generated in the
874 // preheader for SSA updater, so also avoid sinking when no preheader
876 if (!HasDedicatedExits || !Preheader)
879 // Note that we only check GuaranteedToExecute inside the store case
880 // so that we do not introduce stores where they did not exist before
881 // (which would break the LLVM concurrency model).
883 // If the alignment of this instruction allows us to specify a more
884 // restrictive (and performant) alignment and if we are sure this
885 // instruction will be executed, update the alignment.
886 // Larger is better, with the exception of 0 being the best alignment.
887 unsigned InstAlignment = store->getAlignment();
888 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
889 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
890 GuaranteedToExecute = true;
891 Alignment = InstAlignment;
894 if (!GuaranteedToExecute)
895 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
896 CurLoop, SafetyInfo);
899 return Changed; // Not a load or store.
901 // Merge the AA tags.
902 if (LoopUses.empty()) {
903 // On the first load/store, just take its AA tags.
904 UI->getAAMetadata(AATags);
906 UI->getAAMetadata(AATags, /* Merge = */ true);
909 LoopUses.push_back(UI);
913 // If there isn't a guaranteed-to-execute instruction, we can't promote.
914 if (!GuaranteedToExecute)
917 // Otherwise, this is safe to promote, lets do it!
918 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
922 // Grab a debug location for the inserted loads/stores; given that the
923 // inserted loads/stores have little relation to the original loads/stores,
924 // this code just arbitrarily picks a location from one, since any debug
925 // location is better than none.
926 DebugLoc DL = LoopUses[0]->getDebugLoc();
928 // Figure out the loop exits and their insertion points, if this is the
930 if (ExitBlocks.empty()) {
931 CurLoop->getUniqueExitBlocks(ExitBlocks);
932 InsertPts.resize(ExitBlocks.size());
933 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
934 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
937 // We use the SSAUpdater interface to insert phi nodes as required.
938 SmallVector<PHINode*, 16> NewPHIs;
939 SSAUpdater SSA(&NewPHIs);
940 LoopPromoter Promoter(SomePtr, LoopUses, SSA,
941 PointerMustAliases, ExitBlocks,
942 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
944 // Set up the preheader to have a definition of the value. It is the live-out
945 // value from the preheader that uses in the loop will use.
946 LoadInst *PreheaderLoad =
947 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
948 Preheader->getTerminator());
949 PreheaderLoad->setAlignment(Alignment);
950 PreheaderLoad->setDebugLoc(DL);
951 if (AATags) PreheaderLoad->setAAMetadata(AATags);
952 SSA.AddAvailableValue(Preheader, PreheaderLoad);
954 // Rewrite all the loads in the loop and remember all the definitions from
955 // stores in the loop.
956 Promoter.run(LoopUses);
958 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
959 if (PreheaderLoad->use_empty())
960 PreheaderLoad->eraseFromParent();
965 /// Simple Analysis hook. Clone alias set info.
967 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
968 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
972 AST->copyValue(From, To);
975 /// Simple Analysis hook. Delete value V from alias set
977 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
978 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
985 /// Simple Analysis hook. Delete value L from alias set map.
987 void LICM::deleteAnalysisLoop(Loop *L) {
988 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
993 LoopToAliasSetMap.erase(L);
997 /// Return true if the body of this loop may store into the memory
998 /// location pointed to by V.
1000 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1001 const AAMDNodes &AAInfo,
1002 AliasSetTracker *CurAST) {
1003 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1004 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1007 /// Little predicate that returns true if the specified basic block is in
1008 /// a subloop of the current one, not the current one itself.
1010 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1011 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1012 return LI->getLoopFor(BB) != CurLoop;