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 #define DEBUG_TYPE "licm"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Analysis/ConstantFolding.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ValueTracking.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/Support/CFG.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetLibraryInfo.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
62 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
63 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
64 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
65 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
66 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
69 DisablePromotion("disable-licm-promotion", cl::Hidden,
70 cl::desc("Disable memory promotion in LICM pass"));
73 struct LICM : public LoopPass {
74 static char ID; // Pass identification, replacement for typeid
75 LICM() : LoopPass(ID) {
76 initializeLICMPass(*PassRegistry::getPassRegistry());
79 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
81 /// This transformation requires natural loop information & requires that
82 /// loop preheaders be inserted into the CFG...
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<DominatorTreeWrapperPass>();
87 AU.addRequired<LoopInfo>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addPreservedID(LoopSimplifyID);
90 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
92 AU.addRequired<AliasAnalysis>();
93 AU.addPreserved<AliasAnalysis>();
94 AU.addPreserved<ScalarEvolution>();
95 AU.addRequired<TargetLibraryInfo>();
98 using llvm::Pass::doFinalization;
100 bool doFinalization() {
101 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
106 AliasAnalysis *AA; // Current AliasAnalysis information
107 LoopInfo *LI; // Current LoopInfo
108 DominatorTree *DT; // Dominator Tree for the current Loop.
110 DataLayout *TD; // DataLayout for constant folding.
111 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
113 // State that is updated as we process loops.
114 bool Changed; // Set to true when we change anything.
115 BasicBlock *Preheader; // The preheader block of the current loop...
116 Loop *CurLoop; // The current loop we are working on...
117 AliasSetTracker *CurAST; // AliasSet information for the current loop...
118 bool MayThrow; // The current loop contains an instruction which
119 // may throw, thus preventing code motion of
120 // instructions with side effects.
121 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
123 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
124 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
126 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
128 void deleteAnalysisValue(Value *V, Loop *L);
130 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
131 /// dominated by the specified block, and that are in the current loop) in
132 /// reverse depth first order w.r.t the DominatorTree. This allows us to
133 /// visit uses before definitions, allowing us to sink a loop body in one
134 /// pass without iteration.
136 void SinkRegion(DomTreeNode *N);
138 /// HoistRegion - Walk the specified region of the CFG (defined by all
139 /// blocks dominated by the specified block, and that are in the current
140 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
141 /// visit definitions before uses, allowing us to hoist a loop body in one
142 /// pass without iteration.
144 void HoistRegion(DomTreeNode *N);
146 /// inSubLoop - Little predicate that returns true if the specified basic
147 /// block is in a subloop of the current one, not the current one itself.
149 bool inSubLoop(BasicBlock *BB) {
150 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
151 return LI->getLoopFor(BB) != CurLoop;
154 /// sink - When an instruction is found to only be used outside of the loop,
155 /// this function moves it to the exit blocks and patches up SSA form as
158 void sink(Instruction &I);
160 /// hoist - When an instruction is found to only use loop invariant operands
161 /// that is safe to hoist, this instruction is called to do the dirty work.
163 void hoist(Instruction &I);
165 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
166 /// is not a trapping instruction or if it is a trapping instruction and is
167 /// guaranteed to execute.
169 bool isSafeToExecuteUnconditionally(Instruction &I);
171 /// isGuaranteedToExecute - Check that the instruction is guaranteed to
174 bool isGuaranteedToExecute(Instruction &I);
176 /// pointerInvalidatedByLoop - Return true if the body of this loop may
177 /// store into the memory location pointed to by V.
179 bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
180 const MDNode *TBAAInfo) {
181 // Check to see if any of the basic blocks in CurLoop invalidate *V.
182 return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
185 bool canSinkOrHoistInst(Instruction &I);
186 bool isNotUsedInLoop(Instruction &I);
188 void PromoteAliasSet(AliasSet &AS,
189 SmallVectorImpl<BasicBlock*> &ExitBlocks,
190 SmallVectorImpl<Instruction*> &InsertPts);
195 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
196 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
197 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
198 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
199 INITIALIZE_PASS_DEPENDENCY(LCSSA)
200 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
201 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
202 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
203 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
205 Pass *llvm::createLICMPass() { return new LICM(); }
207 /// Hoist expressions out of the specified loop. Note, alias info for inner
208 /// loop is not preserved so it is not a good idea to run LICM multiple
209 /// times on one loop.
211 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
214 // Get our Loop and Alias Analysis information...
215 LI = &getAnalysis<LoopInfo>();
216 AA = &getAnalysis<AliasAnalysis>();
217 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
219 TD = getAnalysisIfAvailable<DataLayout>();
220 TLI = &getAnalysis<TargetLibraryInfo>();
222 CurAST = new AliasSetTracker(*AA);
223 // Collect Alias info from subloops.
224 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
225 LoopItr != LoopItrE; ++LoopItr) {
226 Loop *InnerL = *LoopItr;
227 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
228 assert(InnerAST && "Where is my AST?");
230 // What if InnerLoop was modified by other passes ?
231 CurAST->add(*InnerAST);
233 // Once we've incorporated the inner loop's AST into ours, we don't need the
234 // subloop's anymore.
236 LoopToAliasSetMap.erase(InnerL);
241 // Get the preheader block to move instructions into...
242 Preheader = L->getLoopPreheader();
244 // Loop over the body of this loop, looking for calls, invokes, and stores.
245 // Because subloops have already been incorporated into AST, we skip blocks in
248 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
251 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
252 CurAST->add(*BB); // Incorporate the specified basic block
256 // TODO: We've already searched for instructions which may throw in subloops.
257 // We may want to reuse this information.
258 for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end();
259 (BB != BBE) && !MayThrow ; ++BB)
260 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
261 (I != E) && !MayThrow; ++I)
262 MayThrow |= I->mayThrow();
264 // We want to visit all of the instructions in this loop... that are not parts
265 // of our subloops (they have already had their invariants hoisted out of
266 // their loop, into this loop, so there is no need to process the BODIES of
269 // Traverse the body of the loop in depth first order on the dominator tree so
270 // that we are guaranteed to see definitions before we see uses. This allows
271 // us to sink instructions in one pass, without iteration. After sinking
272 // instructions, we perform another pass to hoist them out of the loop.
274 if (L->hasDedicatedExits())
275 SinkRegion(DT->getNode(L->getHeader()));
277 HoistRegion(DT->getNode(L->getHeader()));
279 // Now that all loop invariants have been removed from the loop, promote any
280 // memory references to scalars that we can.
281 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
282 SmallVector<BasicBlock *, 8> ExitBlocks;
283 SmallVector<Instruction *, 8> InsertPts;
285 // Loop over all of the alias sets in the tracker object.
286 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
288 PromoteAliasSet(*I, ExitBlocks, InsertPts);
290 // Once we have promoted values across the loop body we have to recursively
291 // reform LCSSA as any nested loop may now have values defined within the
292 // loop used in the outer loop.
293 // FIXME: This is really heavy handed. It would be a bit better to use an
294 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
297 formLCSSARecursively(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
299 } else if (Changed) {
300 // If we have successfully changed the loop but not used SSAUpdater to
301 // re-write instructions throughout the loop body, re-form LCSSA just for
303 formLCSSA(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
306 // Regardless of how we changed the loop, reform LCSSA on its parent as
307 // hoisting or sinking could have disrupted it.
309 if (Loop *ParentL = L->getParentLoop())
310 formLCSSA(*ParentL, *DT, getAnalysisIfAvailable<ScalarEvolution>());
312 // Clear out loops state information for the next iteration
316 // If this loop is nested inside of another one, save the alias information
317 // for when we process the outer loop.
318 if (L->getParentLoop())
319 LoopToAliasSetMap[L] = CurAST;
325 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
326 /// dominated by the specified block, and that are in the current loop) in
327 /// reverse depth first order w.r.t the DominatorTree. This allows us to visit
328 /// uses before definitions, allowing us to sink a loop body in one pass without
331 void LICM::SinkRegion(DomTreeNode *N) {
332 assert(N != 0 && "Null dominator tree node?");
333 BasicBlock *BB = N->getBlock();
335 // If this subregion is not in the top level loop at all, exit.
336 if (!CurLoop->contains(BB)) return;
338 // We are processing blocks in reverse dfo, so process children first.
339 const std::vector<DomTreeNode*> &Children = N->getChildren();
340 for (unsigned i = 0, e = Children.size(); i != e; ++i)
341 SinkRegion(Children[i]);
343 // Only need to process the contents of this block if it is not part of a
344 // subloop (which would already have been processed).
345 if (inSubLoop(BB)) return;
347 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
348 Instruction &I = *--II;
350 // If the instruction is dead, we would try to sink it because it isn't used
351 // in the loop, instead, just delete it.
352 if (isInstructionTriviallyDead(&I, TLI)) {
353 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
355 CurAST->deleteValue(&I);
361 // Check to see if we can sink this instruction to the exit blocks
362 // of the loop. We can do this if the all users of the instruction are
363 // outside of the loop. In this case, it doesn't even matter if the
364 // operands of the instruction are loop invariant.
366 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
373 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
374 /// dominated by the specified block, and that are in the current loop) in depth
375 /// first order w.r.t the DominatorTree. This allows us to visit definitions
376 /// before uses, allowing us to hoist a loop body in one pass without iteration.
378 void LICM::HoistRegion(DomTreeNode *N) {
379 assert(N != 0 && "Null dominator tree node?");
380 BasicBlock *BB = N->getBlock();
382 // If this subregion is not in the top level loop at all, exit.
383 if (!CurLoop->contains(BB)) return;
385 // Only need to process the contents of this block if it is not part of a
386 // subloop (which would already have been processed).
388 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
389 Instruction &I = *II++;
391 // Try constant folding this instruction. If all the operands are
392 // constants, it is technically hoistable, but it would be better to just
394 if (Constant *C = ConstantFoldInstruction(&I, TD, TLI)) {
395 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
396 CurAST->copyValue(&I, C);
397 CurAST->deleteValue(&I);
398 I.replaceAllUsesWith(C);
403 // Try hoisting the instruction out to the preheader. We can only do this
404 // if all of the operands of the instruction are loop invariant and if it
405 // is safe to hoist the instruction.
407 if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
408 isSafeToExecuteUnconditionally(I))
412 const std::vector<DomTreeNode*> &Children = N->getChildren();
413 for (unsigned i = 0, e = Children.size(); i != e; ++i)
414 HoistRegion(Children[i]);
417 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
420 bool LICM::canSinkOrHoistInst(Instruction &I) {
421 // Loads have extra constraints we have to verify before we can hoist them.
422 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
423 if (!LI->isUnordered())
424 return false; // Don't hoist volatile/atomic loads!
426 // Loads from constant memory are always safe to move, even if they end up
427 // in the same alias set as something that ends up being modified.
428 if (AA->pointsToConstantMemory(LI->getOperand(0)))
430 if (LI->getMetadata("invariant.load"))
433 // Don't hoist loads which have may-aliased stores in loop.
435 if (LI->getType()->isSized())
436 Size = AA->getTypeStoreSize(LI->getType());
437 return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
438 LI->getMetadata(LLVMContext::MD_tbaa));
439 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
440 // Don't sink or hoist dbg info; it's legal, but not useful.
441 if (isa<DbgInfoIntrinsic>(I))
444 // Handle simple cases by querying alias analysis.
445 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
446 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
448 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
449 // If this call only reads from memory and there are no writes to memory
450 // in the loop, we can hoist or sink the call as appropriate.
451 bool FoundMod = false;
452 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
455 if (!AS.isForwardingAliasSet() && AS.isMod()) {
460 if (!FoundMod) return true;
463 // FIXME: This should use mod/ref information to see if we can hoist or
469 // Only these instructions are hoistable/sinkable.
470 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
471 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
472 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
473 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
474 !isa<InsertValueInst>(I))
477 return isSafeToExecuteUnconditionally(I);
480 /// \brief Returns true if a PHINode is a trivially replaceable with an
483 /// This is true when all incoming values are that instruction. This pattern
484 /// occurs most often with LCSSA PHI nodes.
485 static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
486 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
487 if (PN.getIncomingValue(i) != &I)
493 /// isNotUsedInLoop - Return true if the only users of this instruction are
494 /// outside of the loop. If this is true, we can sink the instruction to the
495 /// exit blocks of the loop.
497 bool LICM::isNotUsedInLoop(Instruction &I) {
498 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
499 Instruction *User = cast<Instruction>(*UI);
500 if (PHINode *PN = dyn_cast<PHINode>(User)) {
501 // A PHI node where all of the incoming values are this instruction are
502 // special -- they can just be RAUW'ed with the instruction and thus
503 // don't require a use in the predecessor. This is a particular important
504 // special case because it is the pattern found in LCSSA form.
505 if (isTriviallyReplacablePHI(*PN, I)) {
506 if (CurLoop->contains(PN))
512 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
513 // values. Check for such a use being inside the loop.
514 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
515 if (PN->getIncomingValue(i) == &I)
516 if (CurLoop->contains(PN->getIncomingBlock(i)))
522 if (CurLoop->contains(User))
528 static BasicBlock::iterator
529 replaceTrivialPHIsAndGetInsertionPt(BasicBlock &BB, Instruction &I) {
530 BasicBlock::iterator II = BB.begin();
531 while (PHINode *PN = dyn_cast<PHINode>(II)) {
533 if (isTriviallyReplacablePHI(*PN, I)) {
534 PN->replaceAllUsesWith(&I);
535 PN->eraseFromParent();
538 if (isa<LandingPadInst>(II))
544 /// sink - When an instruction is found to only be used outside of the loop,
545 /// this function moves it to the exit blocks and patches up SSA form as needed.
546 /// This method is guaranteed to remove the original instruction from its
547 /// position, and may either delete it or move it to outside of the loop.
549 void LICM::sink(Instruction &I) {
550 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
552 SmallVector<BasicBlock*, 8> ExitBlocks;
553 CurLoop->getUniqueExitBlocks(ExitBlocks);
555 if (isa<LoadInst>(I)) ++NumMovedLoads;
556 else if (isa<CallInst>(I)) ++NumMovedCalls;
560 // The case where there is only a single exit node of this loop is common
561 // enough that we handle it as a special (more efficient) case. It is more
562 // efficient to handle because there are no PHI nodes that need to be placed.
563 if (ExitBlocks.size() == 1) {
564 if (!DT->dominates(I.getParent(), ExitBlocks[0])) {
565 // Instruction is not used, just delete it.
566 CurAST->deleteValue(&I);
567 // If I has users in unreachable blocks, eliminate.
568 // If I is not void type then replaceAllUsesWith undef.
569 // This allows ValueHandlers and custom metadata to adjust itself.
571 I.replaceAllUsesWith(UndefValue::get(I.getType()));
574 // Look for any LCSSA PHI nodes for this instruction in the exit blocks
576 BasicBlock::iterator II =
577 replaceTrivialPHIsAndGetInsertionPt(*ExitBlocks[0], I);
579 // Move the instruction to the start of the exit block, after any PHI
583 // This instruction is no longer in the AST for the current loop, because
584 // we just sunk it out of the loop. If we just sunk it into an outer
585 // loop, we will rediscover the operation when we process it.
586 CurAST->deleteValue(&I);
591 if (ExitBlocks.empty()) {
592 // The instruction is actually dead if there ARE NO exit blocks.
593 CurAST->deleteValue(&I);
594 // If I has users in unreachable blocks, eliminate.
595 // If I is not void type then replaceAllUsesWith undef.
596 // This allows ValueHandlers and custom metadata to adjust itself.
598 I.replaceAllUsesWith(UndefValue::get(I.getType()));
603 // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
604 // hard work of inserting PHI nodes as necessary.
605 SmallVector<PHINode*, 8> NewPHIs;
606 SSAUpdater SSA(&NewPHIs);
609 SSA.Initialize(I.getType(), I.getName());
611 // Insert a copy of the instruction in each exit block of the loop that is
612 // dominated by the instruction. Each exit block is known to only be in the
613 // ExitBlocks list once.
614 BasicBlock *InstOrigBB = I.getParent();
615 unsigned NumInserted = 0;
617 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
618 BasicBlock *ExitBlock = ExitBlocks[i];
620 if (!DT->dominates(InstOrigBB, ExitBlock))
623 // Look for any LCSSA PHI nodes for this instruction in the exit blocks
624 // and replace them. Then get the insertion point after the last PHI.
625 BasicBlock::iterator InsertPt =
626 replaceTrivialPHIsAndGetInsertionPt(*ExitBlock, I);
628 // If this is the first exit block processed, just move the original
629 // instruction, otherwise clone the original instruction and insert
632 if (NumInserted++ == 0) {
633 I.moveBefore(InsertPt);
637 if (!I.getName().empty())
638 New->setName(I.getName()+".le");
639 ExitBlock->getInstList().insert(InsertPt, New);
642 // Now that we have inserted the instruction, inform SSAUpdater.
644 SSA.AddAvailableValue(ExitBlock, New);
647 // If the instruction doesn't dominate any exit blocks, it must be dead.
648 if (NumInserted == 0) {
649 CurAST->deleteValue(&I);
651 I.replaceAllUsesWith(UndefValue::get(I.getType()));
656 // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
657 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
658 // Grab the use before incrementing the iterator.
659 Use &U = UI.getUse();
660 // Increment the iterator before removing the use from the list.
662 SSA.RewriteUseAfterInsertions(U);
665 // Update CurAST for NewPHIs if I had pointer type.
666 if (I.getType()->isPointerTy())
667 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
668 CurAST->copyValue(&I, NewPHIs[i]);
670 // Finally, remove the instruction from CurAST. It is no longer in the loop.
671 CurAST->deleteValue(&I);
674 /// hoist - When an instruction is found to only use loop invariant operands
675 /// that is safe to hoist, this instruction is called to do the dirty work.
677 void LICM::hoist(Instruction &I) {
678 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
681 // Move the new node to the Preheader, before its terminator.
682 I.moveBefore(Preheader->getTerminator());
684 if (isa<LoadInst>(I)) ++NumMovedLoads;
685 else if (isa<CallInst>(I)) ++NumMovedCalls;
690 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
691 /// not a trapping instruction or if it is a trapping instruction and is
692 /// guaranteed to execute.
694 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
695 // If it is not a trapping instruction, it is always safe to hoist.
696 if (isSafeToSpeculativelyExecute(&Inst))
699 return isGuaranteedToExecute(Inst);
702 bool LICM::isGuaranteedToExecute(Instruction &Inst) {
704 // Somewhere in this loop there is an instruction which may throw and make us
709 // Otherwise we have to check to make sure that the instruction dominates all
710 // of the exit blocks. If it doesn't, then there is a path out of the loop
711 // which does not execute this instruction, so we can't hoist it.
713 // If the instruction is in the header block for the loop (which is very
714 // common), it is always guaranteed to dominate the exit blocks. Since this
715 // is a common case, and can save some work, check it now.
716 if (Inst.getParent() == CurLoop->getHeader())
719 // Get the exit blocks for the current loop.
720 SmallVector<BasicBlock*, 8> ExitBlocks;
721 CurLoop->getExitBlocks(ExitBlocks);
723 // Verify that the block dominates each of the exit blocks of the loop.
724 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
725 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
728 // As a degenerate case, if the loop is statically infinite then we haven't
729 // proven anything since there are no exit blocks.
730 if (ExitBlocks.empty())
737 class LoopPromoter : public LoadAndStorePromoter {
738 Value *SomePtr; // Designated pointer to store to.
739 SmallPtrSet<Value*, 4> &PointerMustAliases;
740 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
741 SmallVectorImpl<Instruction*> &LoopInsertPts;
742 AliasSetTracker &AST;
747 LoopPromoter(Value *SP,
748 const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
749 SmallPtrSet<Value*, 4> &PMA,
750 SmallVectorImpl<BasicBlock*> &LEB,
751 SmallVectorImpl<Instruction*> &LIP,
752 AliasSetTracker &ast, DebugLoc dl, int alignment,
754 : LoadAndStorePromoter(Insts, S), SomePtr(SP),
755 PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP),
756 AST(ast), DL(dl), Alignment(alignment), TBAATag(TBAATag) {}
758 virtual bool isInstInList(Instruction *I,
759 const SmallVectorImpl<Instruction*> &) const {
761 if (LoadInst *LI = dyn_cast<LoadInst>(I))
762 Ptr = LI->getOperand(0);
764 Ptr = cast<StoreInst>(I)->getPointerOperand();
765 return PointerMustAliases.count(Ptr);
768 virtual void doExtraRewritesBeforeFinalDeletion() const {
769 // Insert stores after in the loop exit blocks. Each exit block gets a
770 // store of the live-out values that feed them. Since we've already told
771 // the SSA updater about the defs in the loop and the preheader
772 // definition, it is all set and we can start using it.
773 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
774 BasicBlock *ExitBlock = LoopExitBlocks[i];
775 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
776 Instruction *InsertPos = LoopInsertPts[i];
777 StoreInst *NewSI = new StoreInst(LiveInValue, SomePtr, InsertPos);
778 NewSI->setAlignment(Alignment);
779 NewSI->setDebugLoc(DL);
780 if (TBAATag) NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
784 virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {
785 // Update alias analysis.
786 AST.copyValue(LI, V);
788 virtual void instructionDeleted(Instruction *I) const {
792 } // end anon namespace
794 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
795 /// stores out of the loop and moving loads to before the loop. We do this by
796 /// looping over the stores in the loop, looking for stores to Must pointers
797 /// which are loop invariant.
799 void LICM::PromoteAliasSet(AliasSet &AS,
800 SmallVectorImpl<BasicBlock*> &ExitBlocks,
801 SmallVectorImpl<Instruction*> &InsertPts) {
802 // We can promote this alias set if it has a store, if it is a "Must" alias
803 // set, if the pointer is loop invariant, and if we are not eliminating any
804 // volatile loads or stores.
805 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
806 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
809 assert(!AS.empty() &&
810 "Must alias set should have at least one pointer element in it!");
811 Value *SomePtr = AS.begin()->getValue();
813 // It isn't safe to promote a load/store from the loop if the load/store is
814 // conditional. For example, turning:
816 // for () { if (c) *P += 1; }
820 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
822 // is not safe, because *P may only be valid to access if 'c' is true.
824 // It is safe to promote P if all uses are direct load/stores and if at
825 // least one is guaranteed to be executed.
826 bool GuaranteedToExecute = false;
828 SmallVector<Instruction*, 64> LoopUses;
829 SmallPtrSet<Value*, 4> PointerMustAliases;
831 // We start with an alignment of one and try to find instructions that allow
832 // us to prove better alignment.
833 unsigned Alignment = 1;
836 // Check that all of the pointers in the alias set have the same type. We
837 // cannot (yet) promote a memory location that is loaded and stored in
838 // different sizes. While we are at it, collect alignment and TBAA info.
839 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
840 Value *ASIV = ASI->getValue();
841 PointerMustAliases.insert(ASIV);
843 // Check that all of the pointers in the alias set have the same type. We
844 // cannot (yet) promote a memory location that is loaded and stored in
846 if (SomePtr->getType() != ASIV->getType())
849 for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
851 // Ignore instructions that are outside the loop.
852 Instruction *Use = dyn_cast<Instruction>(*UI);
853 if (!Use || !CurLoop->contains(Use))
856 // If there is an non-load/store instruction in the loop, we can't promote
858 if (LoadInst *load = dyn_cast<LoadInst>(Use)) {
859 assert(!load->isVolatile() && "AST broken");
860 if (!load->isSimple())
862 } else if (StoreInst *store = dyn_cast<StoreInst>(Use)) {
863 // Stores *of* the pointer are not interesting, only stores *to* the
865 if (Use->getOperand(1) != ASIV)
867 assert(!store->isVolatile() && "AST broken");
868 if (!store->isSimple())
871 // Note that we only check GuaranteedToExecute inside the store case
872 // so that we do not introduce stores where they did not exist before
873 // (which would break the LLVM concurrency model).
875 // If the alignment of this instruction allows us to specify a more
876 // restrictive (and performant) alignment and if we are sure this
877 // instruction will be executed, update the alignment.
878 // Larger is better, with the exception of 0 being the best alignment.
879 unsigned InstAlignment = store->getAlignment();
880 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
881 if (isGuaranteedToExecute(*Use)) {
882 GuaranteedToExecute = true;
883 Alignment = InstAlignment;
886 if (!GuaranteedToExecute)
887 GuaranteedToExecute = isGuaranteedToExecute(*Use);
890 return; // Not a load or store.
892 // Merge the TBAA tags.
893 if (LoopUses.empty()) {
894 // On the first load/store, just take its TBAA tag.
895 TBAATag = Use->getMetadata(LLVMContext::MD_tbaa);
896 } else if (TBAATag) {
897 TBAATag = MDNode::getMostGenericTBAA(TBAATag,
898 Use->getMetadata(LLVMContext::MD_tbaa));
901 LoopUses.push_back(Use);
905 // If there isn't a guaranteed-to-execute instruction, we can't promote.
906 if (!GuaranteedToExecute)
909 // Otherwise, this is safe to promote, lets do it!
910 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
914 // Grab a debug location for the inserted loads/stores; given that the
915 // inserted loads/stores have little relation to the original loads/stores,
916 // this code just arbitrarily picks a location from one, since any debug
917 // location is better than none.
918 DebugLoc DL = LoopUses[0]->getDebugLoc();
920 // Figure out the loop exits and their insertion points, if this is the
922 if (ExitBlocks.empty()) {
923 CurLoop->getUniqueExitBlocks(ExitBlocks);
924 InsertPts.resize(ExitBlocks.size());
925 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
926 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
929 // We use the SSAUpdater interface to insert phi nodes as required.
930 SmallVector<PHINode*, 16> NewPHIs;
931 SSAUpdater SSA(&NewPHIs);
932 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
933 InsertPts, *CurAST, DL, Alignment, TBAATag);
935 // Set up the preheader to have a definition of the value. It is the live-out
936 // value from the preheader that uses in the loop will use.
937 LoadInst *PreheaderLoad =
938 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
939 Preheader->getTerminator());
940 PreheaderLoad->setAlignment(Alignment);
941 PreheaderLoad->setDebugLoc(DL);
942 if (TBAATag) PreheaderLoad->setMetadata(LLVMContext::MD_tbaa, TBAATag);
943 SSA.AddAvailableValue(Preheader, PreheaderLoad);
945 // Rewrite all the loads in the loop and remember all the definitions from
946 // stores in the loop.
947 Promoter.run(LoopUses);
949 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
950 if (PreheaderLoad->use_empty())
951 PreheaderLoad->eraseFromParent();
955 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
956 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
957 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
961 AST->copyValue(From, To);
964 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
966 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
967 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);