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/ValueTracking.h"
42 #include "llvm/IR/CFG.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Dominators.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.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/Analysis/TargetLibraryInfo.h"
57 #include "llvm/Transforms/Utils/Local.h"
58 #include "llvm/Transforms/Utils/LoopUtils.h"
59 #include "llvm/Transforms/Utils/SSAUpdater.h"
63 #define DEBUG_TYPE "licm"
65 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
66 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
67 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
68 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
69 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
72 DisablePromotion("disable-licm-promotion", cl::Hidden,
73 cl::desc("Disable memory promotion in LICM pass"));
75 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
76 static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop);
77 static bool hoist(Instruction &I, BasicBlock *Preheader);
78 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
79 Loop *CurLoop, AliasSetTracker *CurAST );
80 static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
81 Loop *CurLoop, LICMSafetyInfo * SafetyInfo);
82 static bool isSafeToExecuteUnconditionally(Instruction &Inst,DominatorTree *DT,
83 const DataLayout *DL, Loop *CurLoop,
84 LICMSafetyInfo * SafetyInfo);
85 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
86 const AAMDNodes &AAInfo,
87 AliasSetTracker *CurAST);
88 static Instruction *CloneInstructionInExitBlock(Instruction &I,
89 BasicBlock &ExitBlock,
90 PHINode &PN, LoopInfo *LI);
91 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
92 DominatorTree *DT, const DataLayout *DL,
93 Loop *CurLoop, AliasSetTracker *CurAST,
94 LICMSafetyInfo * SafetyInfo);
97 struct LICM : public LoopPass {
98 static char ID; // Pass identification, replacement for typeid
99 LICM() : LoopPass(ID) {
100 initializeLICMPass(*PassRegistry::getPassRegistry());
103 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
108 void getAnalysisUsage(AnalysisUsage &AU) const override {
109 AU.setPreservesCFG();
110 AU.addRequired<DominatorTreeWrapperPass>();
111 AU.addRequired<LoopInfoWrapperPass>();
112 AU.addRequiredID(LoopSimplifyID);
113 AU.addPreservedID(LoopSimplifyID);
114 AU.addRequiredID(LCSSAID);
115 AU.addPreservedID(LCSSAID);
116 AU.addRequired<AliasAnalysis>();
117 AU.addPreserved<AliasAnalysis>();
118 AU.addPreserved<ScalarEvolution>();
119 AU.addRequired<TargetLibraryInfoWrapperPass>();
122 using llvm::Pass::doFinalization;
124 bool doFinalization() override {
125 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
130 AliasAnalysis *AA; // Current AliasAnalysis information
131 LoopInfo *LI; // Current LoopInfo
132 DominatorTree *DT; // Dominator Tree for the current Loop.
134 const DataLayout *DL; // DataLayout for constant folding.
135 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
137 // State that is updated as we process loops.
138 bool Changed; // Set to true when we change anything.
139 BasicBlock *Preheader; // The preheader block of the current loop...
140 Loop *CurLoop; // The current loop we are working on...
141 AliasSetTracker *CurAST; // AliasSet information for the current loop...
142 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
144 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
145 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
148 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
150 void deleteAnalysisValue(Value *V, Loop *L) override;
152 /// Simple Analysis hook. Delete loop L from alias set map.
153 void deleteAnalysisLoop(Loop *L) override;
158 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
159 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
160 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
161 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
162 INITIALIZE_PASS_DEPENDENCY(LCSSA)
163 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
164 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
165 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
166 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
168 Pass *llvm::createLICMPass() { return new LICM(); }
170 /// Hoist expressions out of the specified loop. Note, alias info for inner
171 /// loop is not preserved so it is not a good idea to run LICM multiple
172 /// times on one loop.
174 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
175 if (skipOptnoneFunction(L))
180 // Get our Loop and Alias Analysis information...
181 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
182 AA = &getAnalysis<AliasAnalysis>();
183 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
185 DL = &L->getHeader()->getModule()->getDataLayout();
186 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
188 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
190 CurAST = new AliasSetTracker(*AA);
191 // Collect Alias info from subloops.
192 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
193 LoopItr != LoopItrE; ++LoopItr) {
194 Loop *InnerL = *LoopItr;
195 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
196 assert(InnerAST && "Where is my AST?");
198 // What if InnerLoop was modified by other passes ?
199 CurAST->add(*InnerAST);
201 // Once we've incorporated the inner loop's AST into ours, we don't need the
202 // subloop's anymore.
204 LoopToAliasSetMap.erase(InnerL);
209 // Get the preheader block to move instructions into...
210 Preheader = L->getLoopPreheader();
212 // Loop over the body of this loop, looking for calls, invokes, and stores.
213 // Because subloops have already been incorporated into AST, we skip blocks in
216 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
219 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
220 CurAST->add(*BB); // Incorporate the specified basic block
223 // Compute loop safety information.
224 LICMSafetyInfo SafetyInfo;
225 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
227 // We want to visit all of the instructions in this loop... that are not parts
228 // of our subloops (they have already had their invariants hoisted out of
229 // their loop, into this loop, so there is no need to process the BODIES of
232 // Traverse the body of the loop in depth first order on the dominator tree so
233 // that we are guaranteed to see definitions before we see uses. This allows
234 // us to sink instructions in one pass, without iteration. After sinking
235 // instructions, we perform another pass to hoist them out of the loop.
237 if (L->hasDedicatedExits())
238 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, DL, TLI,
239 CurLoop, CurAST, &SafetyInfo);
241 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, DL, TLI,
242 CurLoop, CurAST, &SafetyInfo);
244 // Now that all loop invariants have been removed from the loop, promote any
245 // memory references to scalars that we can.
246 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
247 SmallVector<BasicBlock *, 8> ExitBlocks;
248 SmallVector<Instruction *, 8> InsertPts;
249 PredIteratorCache PIC;
251 // Loop over all of the alias sets in the tracker object.
252 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
254 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
255 PIC, LI, DT, CurLoop,
256 CurAST, &SafetyInfo);
258 // Once we have promoted values across the loop body we have to recursively
259 // reform LCSSA as any nested loop may now have values defined within the
260 // loop used in the outer loop.
261 // FIXME: This is really heavy handed. It would be a bit better to use an
262 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
265 formLCSSARecursively(*L, *DT, LI,
266 getAnalysisIfAvailable<ScalarEvolution>());
269 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
270 // specifically moving instructions across the loop boundary and so it is
271 // especially in need of sanity checking here.
272 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
273 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
274 "Parent loop not left in LCSSA form after LICM!");
276 // Clear out loops state information for the next iteration
280 // If this loop is nested inside of another one, save the alias information
281 // for when we process the outer loop.
282 if (L->getParentLoop())
283 LoopToAliasSetMap[L] = CurAST;
289 /// Walk the specified region of the CFG (defined by all blocks dominated by
290 /// the specified block, and that are in the current loop) in reverse depth
291 /// first order w.r.t the DominatorTree. This allows us to visit uses before
292 /// definitions, allowing us to sink a loop body in one pass without iteration.
294 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
295 DominatorTree *DT, const DataLayout *DL,
296 TargetLibraryInfo *TLI, Loop *CurLoop,
297 AliasSetTracker *CurAST, LICMSafetyInfo * SafetyInfo) {
300 assert(N != nullptr && AA != nullptr && LI != nullptr &&
301 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
302 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
304 // Set changed as false.
305 bool Changed = false;
307 BasicBlock *BB = N->getBlock();
308 // If this subregion is not in the top level loop at all, exit.
309 if (!CurLoop->contains(BB)) return Changed;
311 // We are processing blocks in reverse dfo, so process children first.
312 const std::vector<DomTreeNode*> &Children = N->getChildren();
313 for (unsigned i = 0, e = Children.size(); i != e; ++i)
314 Changed |= sinkRegion(Children[i], AA, LI, DT, DL, TLI, CurLoop,
316 // Only need to process the contents of this block if it is not part of a
317 // subloop (which would already have been processed).
318 if (inSubLoop(BB,CurLoop,LI)) return Changed;
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) &&
340 canSinkOrHoistInst(I, AA, DT, DL, CurLoop, CurAST, SafetyInfo)) {
342 Changed |= sink(I, LI, DT, CurLoop, CurAST);
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, const DataLayout *DL,
355 TargetLibraryInfo *TLI, Loop *CurLoop,
356 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
358 assert(N != nullptr && AA != nullptr && LI != nullptr &&
359 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
360 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
361 // Set changed as false.
362 bool Changed = false;
364 BasicBlock *BB = N->getBlock();
365 // If this subregion is not in the top level loop at all, exit.
366 if (!CurLoop->contains(BB)) return Changed;
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 if (!inSubLoop(BB, CurLoop, LI))
370 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
371 Instruction &I = *II++;
372 // Try constant folding this instruction. If all the operands are
373 // constants, it is technically hoistable, but it would be better to just
375 if (Constant *C = ConstantFoldInstruction(&I, DL, TLI)) {
376 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
377 CurAST->copyValue(&I, C);
378 CurAST->deleteValue(&I);
379 I.replaceAllUsesWith(C);
384 // Try hoisting the instruction out to the preheader. We can only do this
385 // if all of the operands of the instruction are loop invariant and if it
386 // is safe to hoist the instruction.
388 if (CurLoop->hasLoopInvariantOperands(&I) &&
389 canSinkOrHoistInst(I, AA, DT, DL, CurLoop, CurAST, SafetyInfo) &&
390 isSafeToExecuteUnconditionally(I, DT, DL, CurLoop, SafetyInfo))
391 Changed |= hoist(I, CurLoop->getLoopPreheader());
394 const std::vector<DomTreeNode*> &Children = N->getChildren();
395 for (unsigned i = 0, e = Children.size(); i != e; ++i)
396 Changed |= hoistRegion(Children[i], AA, LI, DT, DL, TLI, CurLoop,
401 /// Computes loop safety information, checks loop body & header
402 /// for the possiblity of may throw exception.
404 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
405 assert(CurLoop != nullptr && "CurLoop cant be null");
406 BasicBlock *Header = CurLoop->getHeader();
407 // Setting default safety values.
408 SafetyInfo->MayThrow = false;
409 SafetyInfo->HeaderMayThrow = false;
410 // Iterate over header and compute dafety info.
411 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
412 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
413 SafetyInfo->HeaderMayThrow |= I->mayThrow();
415 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
416 // Iterate over loop instructions and compute safety info.
417 for (Loop::block_iterator BB = CurLoop->block_begin(),
418 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
419 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
420 (I != E) && !SafetyInfo->MayThrow; ++I)
421 SafetyInfo->MayThrow |= I->mayThrow();
424 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
427 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
428 DominatorTree *DT, const DataLayout *DL,
429 Loop *CurLoop, AliasSetTracker *CurAST,
430 LICMSafetyInfo * SafetyInfo) {
431 // Loads have extra constraints we have to verify before we can hoist them.
432 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
433 if (!LI->isUnordered())
434 return false; // Don't hoist volatile/atomic loads!
436 // Loads from constant memory are always safe to move, even if they end up
437 // in the same alias set as something that ends up being modified.
438 if (AA->pointsToConstantMemory(LI->getOperand(0)))
440 if (LI->getMetadata(LLVMContext::MD_invariant_load))
443 // Don't hoist loads which have may-aliased stores in loop.
445 if (LI->getType()->isSized())
446 Size = AA->getTypeStoreSize(LI->getType());
449 LI->getAAMetadata(AAInfo);
451 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
452 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
453 // Don't sink or hoist dbg info; it's legal, but not useful.
454 if (isa<DbgInfoIntrinsic>(I))
457 // Handle simple cases by querying alias analysis.
458 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
459 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
461 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
462 // If this call only reads from memory and there are no writes to memory
463 // in the loop, we can hoist or sink the call as appropriate.
464 bool FoundMod = false;
465 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
468 if (!AS.isForwardingAliasSet() && AS.isMod()) {
473 if (!FoundMod) return true;
476 // FIXME: This should use mod/ref information to see if we can hoist or
482 // Only these instructions are hoistable/sinkable.
483 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
484 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
485 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
486 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
487 !isa<InsertValueInst>(I))
490 return isSafeToExecuteUnconditionally(I, DT, DL, CurLoop, SafetyInfo);
493 /// Returns true if a PHINode is a trivially replaceable with an
495 /// This is true when all incoming values are that instruction.
496 /// This pattern occurs most often with LCSSA PHI nodes.
498 static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
499 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
500 if (PN.getIncomingValue(i) != &I)
506 /// Return true if the only users of this instruction are outside of
507 /// the loop. If this is true, we can sink the instruction to the exit
508 /// blocks of the loop.
510 static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop) {
511 for (User *U : I.users()) {
512 Instruction *UI = cast<Instruction>(U);
513 if (PHINode *PN = dyn_cast<PHINode>(UI)) {
514 // A PHI node where all of the incoming values are this instruction are
515 // special -- they can just be RAUW'ed with the instruction and thus
516 // don't require a use in the predecessor. This is a particular important
517 // special case because it is the pattern found in LCSSA form.
518 if (isTriviallyReplacablePHI(*PN, I)) {
519 if (CurLoop->contains(PN))
525 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
526 // values. Check for such a use being inside the loop.
527 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
528 if (PN->getIncomingValue(i) == &I)
529 if (CurLoop->contains(PN->getIncomingBlock(i)))
535 if (CurLoop->contains(UI))
541 static Instruction *CloneInstructionInExitBlock(Instruction &I,
542 BasicBlock &ExitBlock,
543 PHINode &PN, LoopInfo *LI) {
544 Instruction *New = I.clone();
545 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
546 if (!I.getName().empty()) New->setName(I.getName() + ".le");
548 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
549 // particularly cheap because we can rip off the PHI node that we're
550 // replacing for the number and blocks of the predecessors.
551 // OPT: If this shows up in a profile, we can instead finish sinking all
552 // invariant instructions, and then walk their operands to re-establish
553 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
554 // sinking bottom-up.
555 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
557 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
558 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
559 if (!OLoop->contains(&PN)) {
561 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
562 OInst->getName() + ".lcssa", ExitBlock.begin());
563 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
564 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
570 /// When an instruction is found to only be used outside of the loop, this
571 /// function moves it to the exit blocks and patches up SSA form as needed.
572 /// This method is guaranteed to remove the original instruction from its
573 /// position, and may either delete it or move it to outside of the loop.
575 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
576 Loop *CurLoop, AliasSetTracker *CurAST ) {
577 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
578 bool Changed = false;
579 if (isa<LoadInst>(I)) ++NumMovedLoads;
580 else if (isa<CallInst>(I)) ++NumMovedCalls;
585 SmallVector<BasicBlock *, 32> ExitBlocks;
586 CurLoop->getUniqueExitBlocks(ExitBlocks);
587 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
591 // Clones of this instruction. Don't create more than one per exit block!
592 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
594 // If this instruction is only used outside of the loop, then all users are
595 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
597 while (!I.use_empty()) {
598 Instruction *User = I.user_back();
599 if (!DT->isReachableFromEntry(User->getParent())) {
600 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
603 // The user must be a PHI node.
604 PHINode *PN = cast<PHINode>(User);
606 BasicBlock *ExitBlock = PN->getParent();
607 assert(ExitBlockSet.count(ExitBlock) &&
608 "The LCSSA PHI is not in an exit block!");
611 auto It = SunkCopies.find(ExitBlock);
612 if (It != SunkCopies.end())
615 New = SunkCopies[ExitBlock] =
616 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
618 PN->replaceAllUsesWith(New);
619 PN->eraseFromParent();
622 CurAST->deleteValue(&I);
627 /// When an instruction is found to only use loop invariant operands that
628 /// is safe to hoist, this instruction is called to do the dirty work.
630 static bool hoist(Instruction &I, BasicBlock *Preheader) {
631 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
633 // Move the new node to the Preheader, before its terminator.
634 I.moveBefore(Preheader->getTerminator());
636 if (isa<LoadInst>(I)) ++NumMovedLoads;
637 else if (isa<CallInst>(I)) ++NumMovedCalls;
642 /// Only sink or hoist an instruction if it is not a trapping instruction
643 /// or if it is a trapping instruction and is guaranteed to execute.
645 static bool isSafeToExecuteUnconditionally(Instruction &Inst, DominatorTree *DT,
646 const DataLayout *DL, Loop *CurLoop,
647 LICMSafetyInfo * SafetyInfo) {
648 // If it is not a trapping instruction, it is always safe to hoist.
649 if (isSafeToSpeculativelyExecute(&Inst, DL))
652 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
655 static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
656 Loop *CurLoop, LICMSafetyInfo * SafetyInfo) {
658 // We have to check to make sure that the instruction dominates all
659 // of the exit blocks. If it doesn't, then there is a path out of the loop
660 // which does not execute this instruction, so we can't hoist it.
662 // If the instruction is in the header block for the loop (which is very
663 // common), it is always guaranteed to dominate the exit blocks. Since this
664 // is a common case, and can save some work, check it now.
665 if (Inst.getParent() == CurLoop->getHeader())
666 // If there's a throw in the header block, we can't guarantee we'll reach
668 return !SafetyInfo->HeaderMayThrow;
670 // Somewhere in this loop there is an instruction which may throw and make us
672 if (SafetyInfo->MayThrow)
675 // Get the exit blocks for the current loop.
676 SmallVector<BasicBlock*, 8> ExitBlocks;
677 CurLoop->getExitBlocks(ExitBlocks);
679 // Verify that the block dominates each of the exit blocks of the loop.
680 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
681 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
684 // As a degenerate case, if the loop is statically infinite then we haven't
685 // proven anything since there are no exit blocks.
686 if (ExitBlocks.empty())
693 class LoopPromoter : public LoadAndStorePromoter {
694 Value *SomePtr; // Designated pointer to store to.
695 SmallPtrSetImpl<Value*> &PointerMustAliases;
696 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
697 SmallVectorImpl<Instruction*> &LoopInsertPts;
698 PredIteratorCache &PredCache;
699 AliasSetTracker &AST;
705 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
706 if (Instruction *I = dyn_cast<Instruction>(V))
707 if (Loop *L = LI.getLoopFor(I->getParent()))
708 if (!L->contains(BB)) {
709 // We need to create an LCSSA PHI node for the incoming value and
711 PHINode *PN = PHINode::Create(
712 I->getType(), PredCache.GetNumPreds(BB),
713 I->getName() + ".lcssa", BB->begin());
714 for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
715 PN->addIncoming(I, *PI);
722 LoopPromoter(Value *SP, const SmallVectorImpl<Instruction *> &Insts,
723 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
724 SmallVectorImpl<BasicBlock *> &LEB,
725 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
726 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
727 const AAMDNodes &AATags)
728 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
729 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
730 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
732 bool isInstInList(Instruction *I,
733 const SmallVectorImpl<Instruction*> &) const override {
735 if (LoadInst *LI = dyn_cast<LoadInst>(I))
736 Ptr = LI->getOperand(0);
738 Ptr = cast<StoreInst>(I)->getPointerOperand();
739 return PointerMustAliases.count(Ptr);
742 void doExtraRewritesBeforeFinalDeletion() const override {
743 // Insert stores after in the loop exit blocks. Each exit block gets a
744 // store of the live-out values that feed them. Since we've already told
745 // the SSA updater about the defs in the loop and the preheader
746 // definition, it is all set and we can start using it.
747 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
748 BasicBlock *ExitBlock = LoopExitBlocks[i];
749 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
750 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
751 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
752 Instruction *InsertPos = LoopInsertPts[i];
753 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
754 NewSI->setAlignment(Alignment);
755 NewSI->setDebugLoc(DL);
756 if (AATags) NewSI->setAAMetadata(AATags);
760 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
761 // Update alias analysis.
762 AST.copyValue(LI, V);
764 void instructionDeleted(Instruction *I) const override {
768 } // end anon namespace
770 /// Try to promote memory values to scalars by sinking stores out of the
771 /// loop and moving loads to before the loop. We do this by looping over
772 /// the stores in the loop, looking for stores to Must pointers which are
775 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
776 SmallVectorImpl<BasicBlock*>&ExitBlocks,
777 SmallVectorImpl<Instruction*>&InsertPts,
778 PredIteratorCache &PIC, LoopInfo *LI,
779 DominatorTree *DT, Loop *CurLoop,
780 AliasSetTracker *CurAST,
781 LICMSafetyInfo * SafetyInfo) {
783 assert(LI != nullptr && DT != nullptr &&
784 CurLoop != nullptr && CurAST != nullptr &&
785 SafetyInfo != nullptr &&
786 "Unexpected Input to promoteLoopAccessesToScalars");
787 // Initially set Changed status to false.
788 bool Changed = false;
789 // We can promote this alias set if it has a store, if it is a "Must" alias
790 // set, if the pointer is loop invariant, and if we are not eliminating any
791 // volatile loads or stores.
792 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
793 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
796 assert(!AS.empty() &&
797 "Must alias set should have at least one pointer element in it!");
799 Value *SomePtr = AS.begin()->getValue();
800 BasicBlock * Preheader = CurLoop->getLoopPreheader();
802 // It isn't safe to promote a load/store from the loop if the load/store is
803 // conditional. For example, turning:
805 // for () { if (c) *P += 1; }
809 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
811 // is not safe, because *P may only be valid to access if 'c' is true.
813 // It is safe to promote P if all uses are direct load/stores and if at
814 // least one is guaranteed to be executed.
815 bool GuaranteedToExecute = false;
817 SmallVector<Instruction*, 64> LoopUses;
818 SmallPtrSet<Value*, 4> PointerMustAliases;
820 // We start with an alignment of one and try to find instructions that allow
821 // us to prove better alignment.
822 unsigned Alignment = 1;
824 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
826 // Check that all of the pointers in the alias set have the same type. We
827 // cannot (yet) promote a memory location that is loaded and stored in
828 // different sizes. While we are at it, collect alignment and AA info.
829 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
830 Value *ASIV = ASI->getValue();
831 PointerMustAliases.insert(ASIV);
833 // Check that all of the pointers in the alias set have the same type. We
834 // cannot (yet) promote a memory location that is loaded and stored in
836 if (SomePtr->getType() != ASIV->getType())
839 for (User *U : ASIV->users()) {
840 // Ignore instructions that are outside the loop.
841 Instruction *UI = dyn_cast<Instruction>(U);
842 if (!UI || !CurLoop->contains(UI))
845 // If there is an non-load/store instruction in the loop, we can't promote
847 if (LoadInst *load = dyn_cast<LoadInst>(UI)) {
848 assert(!load->isVolatile() && "AST broken");
849 if (!load->isSimple())
851 } else if (StoreInst *store = dyn_cast<StoreInst>(UI)) {
852 // Stores *of* the pointer are not interesting, only stores *to* the
854 if (UI->getOperand(1) != ASIV)
856 assert(!store->isVolatile() && "AST broken");
857 if (!store->isSimple())
859 // Don't sink stores from loops without dedicated block exits. Exits
860 // containing indirect branches are not transformed by loop simplify,
861 // make sure we catch that. An additional load may be generated in the
862 // preheader for SSA updater, so also avoid sinking when no preheader
864 if (!HasDedicatedExits || !Preheader)
867 // Note that we only check GuaranteedToExecute inside the store case
868 // so that we do not introduce stores where they did not exist before
869 // (which would break the LLVM concurrency model).
871 // If the alignment of this instruction allows us to specify a more
872 // restrictive (and performant) alignment and if we are sure this
873 // instruction will be executed, update the alignment.
874 // Larger is better, with the exception of 0 being the best alignment.
875 unsigned InstAlignment = store->getAlignment();
876 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
877 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
878 GuaranteedToExecute = true;
879 Alignment = InstAlignment;
882 if (!GuaranteedToExecute)
883 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
884 CurLoop, SafetyInfo);
887 return Changed; // Not a load or store.
889 // Merge the AA tags.
890 if (LoopUses.empty()) {
891 // On the first load/store, just take its AA tags.
892 UI->getAAMetadata(AATags);
894 UI->getAAMetadata(AATags, /* Merge = */ true);
897 LoopUses.push_back(UI);
901 // If there isn't a guaranteed-to-execute instruction, we can't promote.
902 if (!GuaranteedToExecute)
905 // Otherwise, this is safe to promote, lets do it!
906 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
910 // Grab a debug location for the inserted loads/stores; given that the
911 // inserted loads/stores have little relation to the original loads/stores,
912 // this code just arbitrarily picks a location from one, since any debug
913 // location is better than none.
914 DebugLoc DL = LoopUses[0]->getDebugLoc();
916 // Figure out the loop exits and their insertion points, if this is the
918 if (ExitBlocks.empty()) {
919 CurLoop->getUniqueExitBlocks(ExitBlocks);
920 InsertPts.resize(ExitBlocks.size());
921 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
922 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
925 // We use the SSAUpdater interface to insert phi nodes as required.
926 SmallVector<PHINode*, 16> NewPHIs;
927 SSAUpdater SSA(&NewPHIs);
928 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
929 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
931 // Set up the preheader to have a definition of the value. It is the live-out
932 // value from the preheader that uses in the loop will use.
933 LoadInst *PreheaderLoad =
934 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
935 Preheader->getTerminator());
936 PreheaderLoad->setAlignment(Alignment);
937 PreheaderLoad->setDebugLoc(DL);
938 if (AATags) PreheaderLoad->setAAMetadata(AATags);
939 SSA.AddAvailableValue(Preheader, PreheaderLoad);
941 // Rewrite all the loads in the loop and remember all the definitions from
942 // stores in the loop.
943 Promoter.run(LoopUses);
945 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
946 if (PreheaderLoad->use_empty())
947 PreheaderLoad->eraseFromParent();
952 /// Simple Analysis hook. Clone alias set info.
954 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
955 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
959 AST->copyValue(From, To);
962 /// Simple Analysis hook. Delete value V from alias set
964 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
965 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
972 /// Simple Analysis hook. Delete value L from alias set map.
974 void LICM::deleteAnalysisLoop(Loop *L) {
975 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
980 LoopToAliasSetMap.erase(L);
984 /// Return true if the body of this loop may store into the memory
985 /// location pointed to by V.
987 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
988 const AAMDNodes &AAInfo,
989 AliasSetTracker *CurAST) {
990 // Check to see if any of the basic blocks in CurLoop invalidate *V.
991 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
994 /// Little predicate that returns true if the specified basic block is in
995 /// a subloop of the current one, not the current one itself.
997 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
998 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
999 return LI->getLoopFor(BB) != CurLoop;