Fix typo in code to cap the loop code size reduction calculation.
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible.  It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe.  This pass also promotes must-aliased memory locations in the loop to
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
15 //
16 // This pass uses alias analysis for two purposes:
17 //
18 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
19 //     that a load or call inside of a loop never aliases anything stored to,
20 //     we can hoist it or sink it like any other instruction.
21 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
22 //     the loop, we try to move the store to happen AFTER the loop instead of
23 //     inside of the loop.  This can only happen if a few conditions are true:
24 //       A. The pointer stored through is loop invariant
25 //       B. There are no stores or loads in the loop which _may_ alias the
26 //          pointer.  There are no calls in the loop which mod/ref the pointer.
27 //     If these conditions are true, we can promote the loads and stores in the
28 //     loop of the pointer to use a temporary alloca'd variable.  We then use
29 //     the SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32
33 #define DEBUG_TYPE "licm"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Constants.h"
36 #include "llvm/DerivedTypes.h"
37 #include "llvm/IntrinsicInst.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Analysis/AliasAnalysis.h"
40 #include "llvm/Analysis/AliasSetTracker.h"
41 #include "llvm/Analysis/ConstantFolding.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/LoopPass.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/SSAUpdater.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/ADT/Statistic.h"
53 #include <algorithm>
54 using namespace llvm;
55
56 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
57 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
58 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
59 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
60 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
61
62 static cl::opt<bool>
63 DisablePromotion("disable-licm-promotion", cl::Hidden,
64                  cl::desc("Disable memory promotion in LICM pass"));
65
66 namespace {
67   struct LICM : public LoopPass {
68     static char ID; // Pass identification, replacement for typeid
69     LICM() : LoopPass(ID) {}
70
71     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
72
73     /// This transformation requires natural loop information & requires that
74     /// loop preheaders be inserted into the CFG...
75     ///
76     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77       AU.setPreservesCFG();
78       AU.addRequired<DominatorTree>();
79       AU.addRequired<LoopInfo>();
80       AU.addRequiredID(LoopSimplifyID);
81       AU.addRequired<AliasAnalysis>();
82       AU.addPreserved<AliasAnalysis>();
83       AU.addPreserved<ScalarEvolution>();
84       AU.addPreservedID(LoopSimplifyID);
85     }
86
87     bool doFinalization() {
88       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
89       return false;
90     }
91
92   private:
93     AliasAnalysis *AA;       // Current AliasAnalysis information
94     LoopInfo      *LI;       // Current LoopInfo
95     DominatorTree *DT;       // Dominator Tree for the current Loop.
96
97     // State that is updated as we process loops.
98     bool Changed;            // Set to true when we change anything.
99     BasicBlock *Preheader;   // The preheader block of the current loop...
100     Loop *CurLoop;           // The current loop we are working on...
101     AliasSetTracker *CurAST; // AliasSet information for the current loop...
102     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
103
104     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
105     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
106
107     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
108     /// set.
109     void deleteAnalysisValue(Value *V, Loop *L);
110
111     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
112     /// dominated by the specified block, and that are in the current loop) in
113     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
114     /// visit uses before definitions, allowing us to sink a loop body in one
115     /// pass without iteration.
116     ///
117     void SinkRegion(DomTreeNode *N);
118
119     /// HoistRegion - Walk the specified region of the CFG (defined by all
120     /// blocks dominated by the specified block, and that are in the current
121     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
122     /// visit definitions before uses, allowing us to hoist a loop body in one
123     /// pass without iteration.
124     ///
125     void HoistRegion(DomTreeNode *N);
126
127     /// inSubLoop - Little predicate that returns true if the specified basic
128     /// block is in a subloop of the current one, not the current one itself.
129     ///
130     bool inSubLoop(BasicBlock *BB) {
131       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
132       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
133         if ((*I)->contains(BB))
134           return true;  // A subloop actually contains this block!
135       return false;
136     }
137
138     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
139     /// specified exit block of the loop is dominated by the specified block
140     /// that is in the body of the loop.  We use these constraints to
141     /// dramatically limit the amount of the dominator tree that needs to be
142     /// searched.
143     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
144                                            BasicBlock *BlockInLoop) const {
145       // If the block in the loop is the loop header, it must be dominated!
146       BasicBlock *LoopHeader = CurLoop->getHeader();
147       if (BlockInLoop == LoopHeader)
148         return true;
149
150       DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
151       DomTreeNode *IDom            = DT->getNode(ExitBlock);
152
153       // Because the exit block is not in the loop, we know we have to get _at
154       // least_ its immediate dominator.
155       IDom = IDom->getIDom();
156       
157       while (IDom && IDom != BlockInLoopNode) {
158         // If we have got to the header of the loop, then the instructions block
159         // did not dominate the exit node, so we can't hoist it.
160         if (IDom->getBlock() == LoopHeader)
161           return false;
162
163         // Get next Immediate Dominator.
164         IDom = IDom->getIDom();
165       };
166
167       return true;
168     }
169
170     /// sink - When an instruction is found to only be used outside of the loop,
171     /// this function moves it to the exit blocks and patches up SSA form as
172     /// needed.
173     ///
174     void sink(Instruction &I);
175
176     /// hoist - When an instruction is found to only use loop invariant operands
177     /// that is safe to hoist, this instruction is called to do the dirty work.
178     ///
179     void hoist(Instruction &I);
180
181     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
182     /// is not a trapping instruction or if it is a trapping instruction and is
183     /// guaranteed to execute.
184     ///
185     bool isSafeToExecuteUnconditionally(Instruction &I);
186
187     /// pointerInvalidatedByLoop - Return true if the body of this loop may
188     /// store into the memory location pointed to by V.
189     ///
190     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
191       // Check to see if any of the basic blocks in CurLoop invalidate *V.
192       return CurAST->getAliasSetForPointer(V, Size).isMod();
193     }
194
195     bool canSinkOrHoistInst(Instruction &I);
196     bool isNotUsedInLoop(Instruction &I);
197
198     void PromoteAliasSet(AliasSet &AS);
199   };
200 }
201
202 char LICM::ID = 0;
203 INITIALIZE_PASS(LICM, "licm", "Loop Invariant Code Motion", false, false);
204
205 Pass *llvm::createLICMPass() { return new LICM(); }
206
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.
210 ///
211 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
212   Changed = false;
213
214   // Get our Loop and Alias Analysis information...
215   LI = &getAnalysis<LoopInfo>();
216   AA = &getAnalysis<AliasAnalysis>();
217   DT = &getAnalysis<DominatorTree>();
218
219   CurAST = new AliasSetTracker(*AA);
220   // Collect Alias info from subloops.
221   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
222        LoopItr != LoopItrE; ++LoopItr) {
223     Loop *InnerL = *LoopItr;
224     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
225     assert(InnerAST && "Where is my AST?");
226
227     // What if InnerLoop was modified by other passes ?
228     CurAST->add(*InnerAST);
229     
230     // Once we've incorporated the inner loop's AST into ours, we don't need the
231     // subloop's anymore.
232     delete InnerAST;
233     LoopToAliasSetMap.erase(InnerL);
234   }
235   
236   CurLoop = L;
237
238   // Get the preheader block to move instructions into...
239   Preheader = L->getLoopPreheader();
240
241   // Loop over the body of this loop, looking for calls, invokes, and stores.
242   // Because subloops have already been incorporated into AST, we skip blocks in
243   // subloops.
244   //
245   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
246        I != E; ++I) {
247     BasicBlock *BB = *I;
248     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
249       CurAST->add(*BB);                 // Incorporate the specified basic block
250   }
251
252   // We want to visit all of the instructions in this loop... that are not parts
253   // of our subloops (they have already had their invariants hoisted out of
254   // their loop, into this loop, so there is no need to process the BODIES of
255   // the subloops).
256   //
257   // Traverse the body of the loop in depth first order on the dominator tree so
258   // that we are guaranteed to see definitions before we see uses.  This allows
259   // us to sink instructions in one pass, without iteration.  After sinking
260   // instructions, we perform another pass to hoist them out of the loop.
261   //
262   if (L->hasDedicatedExits())
263     SinkRegion(DT->getNode(L->getHeader()));
264   if (Preheader)
265     HoistRegion(DT->getNode(L->getHeader()));
266
267   // Now that all loop invariants have been removed from the loop, promote any
268   // memory references to scalars that we can.
269   if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
270     // Loop over all of the alias sets in the tracker object.
271     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
272          I != E; ++I)
273       PromoteAliasSet(*I);
274   }
275   
276   // Clear out loops state information for the next iteration
277   CurLoop = 0;
278   Preheader = 0;
279
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;
284   else
285     delete CurAST;
286   return Changed;
287 }
288
289 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
290 /// dominated by the specified block, and that are in the current loop) in
291 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
292 /// uses before definitions, allowing us to sink a loop body in one pass without
293 /// iteration.
294 ///
295 void LICM::SinkRegion(DomTreeNode *N) {
296   assert(N != 0 && "Null dominator tree node?");
297   BasicBlock *BB = N->getBlock();
298
299   // If this subregion is not in the top level loop at all, exit.
300   if (!CurLoop->contains(BB)) return;
301
302   // We are processing blocks in reverse dfo, so process children first.
303   const std::vector<DomTreeNode*> &Children = N->getChildren();
304   for (unsigned i = 0, e = Children.size(); i != e; ++i)
305     SinkRegion(Children[i]);
306
307   // Only need to process the contents of this block if it is not part of a
308   // subloop (which would already have been processed).
309   if (inSubLoop(BB)) return;
310
311   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
312     Instruction &I = *--II;
313     
314     // If the instruction is dead, we would try to sink it because it isn't used
315     // in the loop, instead, just delete it.
316     if (isInstructionTriviallyDead(&I)) {
317       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
318       ++II;
319       CurAST->deleteValue(&I);
320       I.eraseFromParent();
321       Changed = true;
322       continue;
323     }
324
325     // Check to see if we can sink this instruction to the exit blocks
326     // of the loop.  We can do this if the all users of the instruction are
327     // outside of the loop.  In this case, it doesn't even matter if the
328     // operands of the instruction are loop invariant.
329     //
330     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
331       ++II;
332       sink(I);
333     }
334   }
335 }
336
337 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
338 /// dominated by the specified block, and that are in the current loop) in depth
339 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
340 /// before uses, allowing us to hoist a loop body in one pass without iteration.
341 ///
342 void LICM::HoistRegion(DomTreeNode *N) {
343   assert(N != 0 && "Null dominator tree node?");
344   BasicBlock *BB = N->getBlock();
345
346   // If this subregion is not in the top level loop at all, exit.
347   if (!CurLoop->contains(BB)) return;
348
349   // Only need to process the contents of this block if it is not part of a
350   // subloop (which would already have been processed).
351   if (!inSubLoop(BB))
352     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
353       Instruction &I = *II++;
354
355       // Try constant folding this instruction.  If all the operands are
356       // constants, it is technically hoistable, but it would be better to just
357       // fold it.
358       if (Constant *C = ConstantFoldInstruction(&I)) {
359         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
360         CurAST->copyValue(&I, C);
361         CurAST->deleteValue(&I);
362         I.replaceAllUsesWith(C);
363         I.eraseFromParent();
364         continue;
365       }
366       
367       // Try hoisting the instruction out to the preheader.  We can only do this
368       // if all of the operands of the instruction are loop invariant and if it
369       // is safe to hoist the instruction.
370       //
371       if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
372           isSafeToExecuteUnconditionally(I))
373         hoist(I);
374     }
375
376   const std::vector<DomTreeNode*> &Children = N->getChildren();
377   for (unsigned i = 0, e = Children.size(); i != e; ++i)
378     HoistRegion(Children[i]);
379 }
380
381 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
382 /// instruction.
383 ///
384 bool LICM::canSinkOrHoistInst(Instruction &I) {
385   // Loads have extra constraints we have to verify before we can hoist them.
386   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
387     if (LI->isVolatile())
388       return false;        // Don't hoist volatile loads!
389
390     // Loads from constant memory are always safe to move, even if they end up
391     // in the same alias set as something that ends up being modified.
392     if (AA->pointsToConstantMemory(LI->getOperand(0)))
393       return true;
394     
395     // Don't hoist loads which have may-aliased stores in loop.
396     unsigned Size = 0;
397     if (LI->getType()->isSized())
398       Size = AA->getTypeStoreSize(LI->getType());
399     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
400   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
401     // Handle obvious cases efficiently.
402     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
403     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
404       return true;
405     else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
406       // If this call only reads from memory and there are no writes to memory
407       // in the loop, we can hoist or sink the call as appropriate.
408       bool FoundMod = false;
409       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
410            I != E; ++I) {
411         AliasSet &AS = *I;
412         if (!AS.isForwardingAliasSet() && AS.isMod()) {
413           FoundMod = true;
414           break;
415         }
416       }
417       if (!FoundMod) return true;
418     }
419
420     // FIXME: This should use mod/ref information to see if we can hoist or sink
421     // the call.
422
423     return false;
424   }
425
426   // Otherwise these instructions are hoistable/sinkable
427   return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
428          isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
429          isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
430          isa<ShuffleVectorInst>(I);
431 }
432
433 /// isNotUsedInLoop - Return true if the only users of this instruction are
434 /// outside of the loop.  If this is true, we can sink the instruction to the
435 /// exit blocks of the loop.
436 ///
437 bool LICM::isNotUsedInLoop(Instruction &I) {
438   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
439     Instruction *User = cast<Instruction>(*UI);
440     if (PHINode *PN = dyn_cast<PHINode>(User)) {
441       // PHI node uses occur in predecessor blocks!
442       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
443         if (PN->getIncomingValue(i) == &I)
444           if (CurLoop->contains(PN->getIncomingBlock(i)))
445             return false;
446     } else if (CurLoop->contains(User)) {
447       return false;
448     }
449   }
450   return true;
451 }
452
453
454 /// sink - When an instruction is found to only be used outside of the loop,
455 /// this function moves it to the exit blocks and patches up SSA form as needed.
456 /// This method is guaranteed to remove the original instruction from its
457 /// position, and may either delete it or move it to outside of the loop.
458 ///
459 void LICM::sink(Instruction &I) {
460   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
461
462   SmallVector<BasicBlock*, 8> ExitBlocks;
463   CurLoop->getUniqueExitBlocks(ExitBlocks);
464
465   if (isa<LoadInst>(I)) ++NumMovedLoads;
466   else if (isa<CallInst>(I)) ++NumMovedCalls;
467   ++NumSunk;
468   Changed = true;
469
470   // The case where there is only a single exit node of this loop is common
471   // enough that we handle it as a special (more efficient) case.  It is more
472   // efficient to handle because there are no PHI nodes that need to be placed.
473   if (ExitBlocks.size() == 1) {
474     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
475       // Instruction is not used, just delete it.
476       CurAST->deleteValue(&I);
477       // If I has users in unreachable blocks, eliminate.
478       // If I is not void type then replaceAllUsesWith undef.
479       // This allows ValueHandlers and custom metadata to adjust itself.
480       if (!I.use_empty())
481         I.replaceAllUsesWith(UndefValue::get(I.getType()));
482       I.eraseFromParent();
483     } else {
484       // Move the instruction to the start of the exit block, after any PHI
485       // nodes in it.
486       I.moveBefore(ExitBlocks[0]->getFirstNonPHI());
487
488       // This instruction is no longer in the AST for the current loop, because
489       // we just sunk it out of the loop.  If we just sunk it into an outer
490       // loop, we will rediscover the operation when we process it.
491       CurAST->deleteValue(&I);
492     }
493     return;
494   }
495   
496   if (ExitBlocks.empty()) {
497     // The instruction is actually dead if there ARE NO exit blocks.
498     CurAST->deleteValue(&I);
499     // If I has users in unreachable blocks, eliminate.
500     // If I is not void type then replaceAllUsesWith undef.
501     // This allows ValueHandlers and custom metadata to adjust itself.
502     if (!I.use_empty())
503       I.replaceAllUsesWith(UndefValue::get(I.getType()));
504     I.eraseFromParent();
505     return;
506   }
507   
508   // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
509   // hard work of inserting PHI nodes as necessary.
510   SmallVector<PHINode*, 8> NewPHIs;
511   SSAUpdater SSA(&NewPHIs);
512   
513   if (!I.use_empty())
514     SSA.Initialize(I.getType(), I.getName());
515   
516   // Insert a copy of the instruction in each exit block of the loop that is
517   // dominated by the instruction.  Each exit block is known to only be in the
518   // ExitBlocks list once.
519   BasicBlock *InstOrigBB = I.getParent();
520   unsigned NumInserted = 0;
521   
522   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
523     BasicBlock *ExitBlock = ExitBlocks[i];
524     
525     if (!isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB))
526       continue;
527     
528     // Insert the code after the last PHI node.
529     BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
530     
531     // If this is the first exit block processed, just move the original
532     // instruction, otherwise clone the original instruction and insert
533     // the copy.
534     Instruction *New;
535     if (NumInserted++ == 0) {
536       I.moveBefore(InsertPt);
537       New = &I;
538     } else {
539       New = I.clone();
540       if (!I.getName().empty())
541         New->setName(I.getName()+".le");
542       ExitBlock->getInstList().insert(InsertPt, New);
543     }
544     
545     // Now that we have inserted the instruction, inform SSAUpdater.
546     if (!I.use_empty())
547       SSA.AddAvailableValue(ExitBlock, New);
548   }
549   
550   // If the instruction doesn't dominate any exit blocks, it must be dead.
551   if (NumInserted == 0) {
552     CurAST->deleteValue(&I);
553     if (!I.use_empty())
554       I.replaceAllUsesWith(UndefValue::get(I.getType()));
555     I.eraseFromParent();
556     return;
557   }
558   
559   // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
560   for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
561     // Grab the use before incrementing the iterator.
562     Use &U = UI.getUse();
563     // Increment the iterator before removing the use from the list.
564     ++UI;
565     SSA.RewriteUseAfterInsertions(U);
566   }
567   
568   // Update CurAST for NewPHIs if I had pointer type.
569   if (I.getType()->isPointerTy())
570     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
571       CurAST->copyValue(&I, NewPHIs[i]);
572   
573   // Finally, remove the instruction from CurAST.  It is no longer in the loop.
574   CurAST->deleteValue(&I);
575 }
576
577 /// hoist - When an instruction is found to only use loop invariant operands
578 /// that is safe to hoist, this instruction is called to do the dirty work.
579 ///
580 void LICM::hoist(Instruction &I) {
581   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
582         << I << "\n");
583
584   // Move the new node to the Preheader, before its terminator.
585   I.moveBefore(Preheader->getTerminator());
586
587   if (isa<LoadInst>(I)) ++NumMovedLoads;
588   else if (isa<CallInst>(I)) ++NumMovedCalls;
589   ++NumHoisted;
590   Changed = true;
591 }
592
593 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
594 /// not a trapping instruction or if it is a trapping instruction and is
595 /// guaranteed to execute.
596 ///
597 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
598   // If it is not a trapping instruction, it is always safe to hoist.
599   if (Inst.isSafeToSpeculativelyExecute())
600     return true;
601
602   // Otherwise we have to check to make sure that the instruction dominates all
603   // of the exit blocks.  If it doesn't, then there is a path out of the loop
604   // which does not execute this instruction, so we can't hoist it.
605
606   // If the instruction is in the header block for the loop (which is very
607   // common), it is always guaranteed to dominate the exit blocks.  Since this
608   // is a common case, and can save some work, check it now.
609   if (Inst.getParent() == CurLoop->getHeader())
610     return true;
611
612   // Get the exit blocks for the current loop.
613   SmallVector<BasicBlock*, 8> ExitBlocks;
614   CurLoop->getExitBlocks(ExitBlocks);
615
616   // For each exit block, get the DT node and walk up the DT until the
617   // instruction's basic block is found or we exit the loop.
618   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
619     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
620       return false;
621
622   return true;
623 }
624
625 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
626 /// stores out of the loop and moving loads to before the loop.  We do this by
627 /// looping over the stores in the loop, looking for stores to Must pointers
628 /// which are loop invariant.
629 ///
630 void LICM::PromoteAliasSet(AliasSet &AS) {
631   // We can promote this alias set if it has a store, if it is a "Must" alias
632   // set, if the pointer is loop invariant, and if we are not eliminating any
633   // volatile loads or stores.
634   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
635       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
636     return;
637   
638   assert(!AS.empty() &&
639          "Must alias set should have at least one pointer element in it!");
640   Value *SomePtr = AS.begin()->getValue();
641
642   // It isn't safe to promote a load/store from the loop if the load/store is
643   // conditional.  For example, turning:
644   //
645   //    for () { if (c) *P += 1; }
646   //
647   // into:
648   //
649   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
650   //
651   // is not safe, because *P may only be valid to access if 'c' is true.
652   // 
653   // It is safe to promote P if all uses are direct load/stores and if at
654   // least one is guaranteed to be executed.
655   bool GuaranteedToExecute = false;
656   
657   SmallVector<Instruction*, 64> LoopUses;
658   SmallPtrSet<Value*, 4> PointerMustAliases;
659
660   // Check that all of the pointers in the alias set have the same type.  We
661   // cannot (yet) promote a memory location that is loaded and stored in
662   // different sizes.
663   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
664     Value *ASIV = ASI->getValue();
665     PointerMustAliases.insert(ASIV);
666     
667     // Check that all of the pointers in the alias set have the same type.  We
668     // cannot (yet) promote a memory location that is loaded and stored in
669     // different sizes.
670     if (SomePtr->getType() != ASIV->getType())
671       return;
672     
673     for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
674          UI != UE; ++UI) {
675       // Ignore instructions that are outside the loop.
676       Instruction *Use = dyn_cast<Instruction>(*UI);
677       if (!Use || !CurLoop->contains(Use))
678         continue;
679       
680       // If there is an non-load/store instruction in the loop, we can't promote
681       // it.
682       if (isa<LoadInst>(Use))
683         assert(!cast<LoadInst>(Use)->isVolatile() && "AST broken");
684       else if (isa<StoreInst>(Use)) {
685         assert(!cast<StoreInst>(Use)->isVolatile() && "AST broken");
686         if (Use->getOperand(0) == ASIV) return;
687       } else
688         return; // Not a load or store.
689       
690       if (!GuaranteedToExecute)
691         GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
692       
693       LoopUses.push_back(Use);
694     }
695   }
696   
697   // If there isn't a guaranteed-to-execute instruction, we can't promote.
698   if (!GuaranteedToExecute)
699     return;
700   
701   // Otherwise, this is safe to promote, lets do it!
702   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');  
703   Changed = true;
704   ++NumPromoted;
705
706   // We use the SSAUpdater interface to insert phi nodes as required.
707   SmallVector<PHINode*, 16> NewPHIs;
708   SSAUpdater SSA(&NewPHIs);
709   
710   // It wants to know some value of the same type as what we'll be inserting.
711   Value *SomeValue;
712   if (isa<LoadInst>(LoopUses[0]))
713     SomeValue = LoopUses[0];
714   else
715     SomeValue = cast<StoreInst>(LoopUses[0])->getOperand(0);
716   SSA.Initialize(SomeValue->getType(), SomeValue->getName());
717
718   // First step: bucket up uses of the pointers by the block they occur in.
719   // This is important because we have to handle multiple defs/uses in a block
720   // ourselves: SSAUpdater is purely for cross-block references.
721   // FIXME: Want a TinyVector<Instruction*> since there is usually 0/1 element.
722   DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
723   for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
724     Instruction *User = LoopUses[i];
725     UsesByBlock[User->getParent()].push_back(User);
726   }
727   
728   // Okay, now we can iterate over all the blocks in the loop with uses,
729   // processing them.  Keep track of which loads are loading a live-in value.
730   SmallVector<LoadInst*, 32> LiveInLoads;
731   DenseMap<Value*, Value*> ReplacedLoads;
732   
733   for (unsigned LoopUse = 0, e = LoopUses.size(); LoopUse != e; ++LoopUse) {
734     Instruction *User = LoopUses[LoopUse];
735     std::vector<Instruction*> &BlockUses = UsesByBlock[User->getParent()];
736     
737     // If this block has already been processed, ignore this repeat use.
738     if (BlockUses.empty()) continue;
739     
740     // Okay, this is the first use in the block.  If this block just has a
741     // single user in it, we can rewrite it trivially.
742     if (BlockUses.size() == 1) {
743       // If it is a store, it is a trivial def of the value in the block.
744       if (isa<StoreInst>(User)) {
745         SSA.AddAvailableValue(User->getParent(),
746                               cast<StoreInst>(User)->getOperand(0));
747       } else {
748         // Otherwise it is a load, queue it to rewrite as a live-in load.
749         LiveInLoads.push_back(cast<LoadInst>(User));
750       }
751       BlockUses.clear();
752       continue;
753     }
754     
755     // Otherwise, check to see if this block is all loads.  If so, we can queue
756     // them all as live in loads.
757     bool HasStore = false;
758     for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
759       if (isa<StoreInst>(BlockUses[i])) {
760         HasStore = true;
761         break;
762       }
763     }
764     
765     if (!HasStore) {
766       for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
767         LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
768       BlockUses.clear();
769       continue;
770     }
771
772     // Otherwise, we have mixed loads and stores (or just a bunch of stores).
773     // Since SSAUpdater is purely for cross-block values, we need to determine
774     // the order of these instructions in the block.  If the first use in the
775     // block is a load, then it uses the live in value.  The last store defines
776     // the live out value.  We handle this by doing a linear scan of the block.
777     BasicBlock *BB = User->getParent();
778     Value *StoredValue = 0;
779     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
780       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
781         // If this is a load from an unrelated pointer, ignore it.
782         if (!PointerMustAliases.count(L->getOperand(0))) continue;
783
784         // If we haven't seen a store yet, this is a live in use, otherwise
785         // use the stored value.
786         if (StoredValue) {
787           L->replaceAllUsesWith(StoredValue);
788           ReplacedLoads[L] = StoredValue;
789         } else {
790           LiveInLoads.push_back(L);
791         }
792         continue;
793       }
794       
795       if (StoreInst *S = dyn_cast<StoreInst>(II)) {
796         // If this is a store to an unrelated pointer, ignore it.
797         if (!PointerMustAliases.count(S->getOperand(1))) continue;
798
799         // Remember that this is the active value in the block.
800         StoredValue = S->getOperand(0);
801       }
802     }
803     
804     // The last stored value that happened is the live-out for the block.
805     assert(StoredValue && "Already checked that there is a store in block");
806     SSA.AddAvailableValue(BB, StoredValue);
807     BlockUses.clear();
808   }
809   
810   // Now that all the intra-loop values are classified, set up the preheader.
811   // It gets a load of the pointer we're promoting, and it is the live-out value
812   // from the preheader.
813   LoadInst *PreheaderLoad = new LoadInst(SomePtr,SomePtr->getName()+".promoted",
814                                          Preheader->getTerminator());
815   SSA.AddAvailableValue(Preheader, PreheaderLoad);
816
817   // Now that the preheader is good to go, set up the exit blocks.  Each exit
818   // block gets a store of the live-out values that feed them.  Since we've
819   // already told the SSA updater about the defs in the loop and the preheader
820   // definition, it is all set and we can start using it.
821   SmallVector<BasicBlock*, 8> ExitBlocks;
822   CurLoop->getUniqueExitBlocks(ExitBlocks);
823   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
824     BasicBlock *ExitBlock = ExitBlocks[i];
825     Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
826     Instruction *InsertPos = ExitBlock->getFirstNonPHI();
827     new StoreInst(LiveInValue, SomePtr, InsertPos);
828   }
829
830   // Okay, now we rewrite all loads that use live-in values in the loop,
831   // inserting PHI nodes as necessary.
832   for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
833     LoadInst *ALoad = LiveInLoads[i];
834     Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
835     ALoad->replaceAllUsesWith(NewVal);
836     CurAST->copyValue(ALoad, NewVal);
837     ReplacedLoads[ALoad] = NewVal;
838   }
839   
840   // Now that everything is rewritten, delete the old instructions from the body
841   // of the loop.  They should all be dead now.
842   for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
843     Instruction *User = LoopUses[i];
844     
845     // If this is a load that still has uses, then the load must have been added
846     // as a live value in the SSAUpdate data structure for a block (e.g. because
847     // the loaded value was stored later).  In this case, we need to recursively
848     // propagate the updates until we get to the real value.
849     if (!User->use_empty()) {
850       Value *NewVal = ReplacedLoads[User];
851       assert(NewVal && "not a replaced load?");
852       
853       // Propagate down to the ultimate replacee.  The intermediately loads
854       // could theoretically already have been deleted, so we don't want to
855       // dereference the Value*'s.
856       DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
857       while (RLI != ReplacedLoads.end()) {
858         NewVal = RLI->second;
859         RLI = ReplacedLoads.find(NewVal);
860       }
861       
862       User->replaceAllUsesWith(NewVal);
863       CurAST->copyValue(User, NewVal);
864     }
865     
866     CurAST->deleteValue(User);
867     User->eraseFromParent();
868   }
869   
870   // If the preheader load is itself a pointer, we need to tell alias analysis
871   // about the new pointer we created in the preheader block and about any PHI
872   // nodes that just got inserted.
873   if (PreheaderLoad->getType()->isPointerTy()) {
874     // Copy any value stored to or loaded from a must-alias of the pointer.
875     CurAST->copyValue(SomeValue, PreheaderLoad);
876
877     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
878       CurAST->copyValue(SomeValue, NewPHIs[i]);
879   }
880   
881   // fwew, we're done!
882 }
883
884
885 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
886 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
887   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
888   if (!AST)
889     return;
890
891   AST->copyValue(From, To);
892 }
893
894 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
895 /// set.
896 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
897   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
898   if (!AST)
899     return;
900
901   AST->deleteValue(V);
902 }