Rollback some changes that adversely affected performance. I'm currently rethinking
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 mem2reg functionality to construct the appropriate SSA form for the
30 //     variable.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #define DEBUG_TYPE "licm"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/LoopPass.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/AliasSetTracker.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
46 #include "llvm/Support/CFG.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/ADT/Statistic.h"
51 #include <algorithm>
52 using namespace llvm;
53
54 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
55 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
56 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
57 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
58 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
59
60 namespace {
61   cl::opt<bool>
62   DisablePromotion("disable-licm-promotion", cl::Hidden,
63                    cl::desc("Disable memory promotion in LICM pass"));
64
65   struct VISIBILITY_HIDDEN LICM : public LoopPass {
66     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
67
68     /// This transformation requires natural loop information & requires that
69     /// loop preheaders be inserted into the CFG...
70     ///
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.setPreservesCFG();
73       AU.addRequiredID(LoopSimplifyID);
74       AU.addRequired<LoopInfo>();
75       AU.addRequired<DominatorTree>();
76       AU.addRequired<ETForest>();
77       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
78       AU.addRequired<AliasAnalysis>();
79     }
80
81     bool doFinalization() {
82       LoopToAliasMap.clear();
83       return false;
84     }
85
86   private:
87     // Various analyses that we use...
88     AliasAnalysis *AA;       // Current AliasAnalysis information
89     LoopInfo      *LI;       // Current LoopInfo
90     ETForest      *ET;       // ETForest for the current loop..
91     DominatorTree *DT;       // Dominator Tree for the current Loop...
92     DominanceFrontier *DF;   // Current Dominance Frontier
93
94     // State that is updated as we process loops
95     bool Changed;            // Set to true when we change anything.
96     BasicBlock *Preheader;   // The preheader block of the current loop...
97     Loop *CurLoop;           // The current loop we are working on...
98     AliasSetTracker *CurAST; // AliasSet information for the current loop...
99     std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
100
101     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
102     /// dominated by the specified block, and that are in the current loop) in
103     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
104     /// visit uses before definitions, allowing us to sink a loop body in one
105     /// pass without iteration.
106     ///
107     void SinkRegion(DominatorTree::Node *N);
108
109     /// HoistRegion - Walk the specified region of the CFG (defined by all
110     /// blocks dominated by the specified block, and that are in the current
111     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
112     /// visit definitions before uses, allowing us to hoist a loop body in one
113     /// pass without iteration.
114     ///
115     void HoistRegion(DominatorTree::Node *N);
116
117     /// inSubLoop - Little predicate that returns true if the specified basic
118     /// block is in a subloop of the current one, not the current one itself.
119     ///
120     bool inSubLoop(BasicBlock *BB) {
121       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
122       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
123         if ((*I)->contains(BB))
124           return true;  // A subloop actually contains this block!
125       return false;
126     }
127
128     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
129     /// specified exit block of the loop is dominated by the specified block
130     /// that is in the body of the loop.  We use these constraints to
131     /// dramatically limit the amount of the dominator tree that needs to be
132     /// searched.
133     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
134                                            BasicBlock *BlockInLoop) const {
135       // If the block in the loop is the loop header, it must be dominated!
136       BasicBlock *LoopHeader = CurLoop->getHeader();
137       if (BlockInLoop == LoopHeader)
138         return true;
139
140       DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
141       DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
142
143       // Because the exit block is not in the loop, we know we have to get _at
144       // least_ its immediate dominator.
145       do {
146         // Get next Immediate Dominator.
147         IDom = IDom->getIDom();
148
149         // If we have got to the header of the loop, then the instructions block
150         // did not dominate the exit node, so we can't hoist it.
151         if (IDom->getBlock() == LoopHeader)
152           return false;
153
154       } while (IDom != BlockInLoopNode);
155
156       return true;
157     }
158
159     /// sink - When an instruction is found to only be used outside of the loop,
160     /// this function moves it to the exit blocks and patches up SSA form as
161     /// needed.
162     ///
163     void sink(Instruction &I);
164
165     /// hoist - When an instruction is found to only use loop invariant operands
166     /// that is safe to hoist, this instruction is called to do the dirty work.
167     ///
168     void hoist(Instruction &I);
169
170     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
171     /// is not a trapping instruction or if it is a trapping instruction and is
172     /// guaranteed to execute.
173     ///
174     bool isSafeToExecuteUnconditionally(Instruction &I);
175
176     /// pointerInvalidatedByLoop - Return true if the body of this loop may
177     /// store into the memory location pointed to by V.
178     ///
179     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
180       // Check to see if any of the basic blocks in CurLoop invalidate *V.
181       return CurAST->getAliasSetForPointer(V, Size).isMod();
182     }
183
184     bool canSinkOrHoistInst(Instruction &I);
185     bool isLoopInvariantInst(Instruction &I);
186     bool isNotUsedInLoop(Instruction &I);
187
188     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
189     /// to scalars as we can.
190     ///
191     void PromoteValuesInLoop();
192
193     /// FindPromotableValuesInLoop - Check the current loop for stores to
194     /// definite pointers, which are not loaded and stored through may aliases.
195     /// If these are found, create an alloca for the value, add it to the
196     /// PromotedValues list, and keep track of the mapping from value to
197     /// alloca...
198     ///
199     void FindPromotableValuesInLoop(
200                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
201                                     std::map<Value*, AllocaInst*> &Val2AlMap);
202   };
203
204   RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
205 }
206
207 LoopPass *llvm::createLICMPass() { return new LICM(); }
208
209 /// Hoist expressions out of the specified 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   DF = &getAnalysis<DominanceFrontier>();
218   DT = &getAnalysis<DominatorTree>();
219   ET = &getAnalysis<ETForest>();
220
221   CurAST = new AliasSetTracker(*AA);
222   // Collect Alias info frmo subloops
223   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
224        LoopItr != LoopItrE; ++LoopItr) {
225     Loop *InnerL = *LoopItr;
226     AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
227     assert (InnerAST && "Where is my AST?");
228
229     // What if InnerLoop was modified by other passes ?
230     CurAST->add(*InnerAST);
231   }
232   
233   CurLoop = L;
234
235   // Get the preheader block to move instructions into...
236   Preheader = L->getLoopPreheader();
237   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
238
239   // Loop over the body of this loop, looking for calls, invokes, and stores.
240   // Because subloops have already been incorporated into AST, we skip blocks in
241   // subloops.
242   //
243   for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
244          E = L->getBlocks().end(); I != E; ++I)
245     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
246       CurAST->add(**I);                 // Incorporate the specified basic block
247
248   // We want to visit all of the instructions in this loop... that are not parts
249   // of our subloops (they have already had their invariants hoisted out of
250   // their loop, into this loop, so there is no need to process the BODIES of
251   // the subloops).
252   //
253   // Traverse the body of the loop in depth first order on the dominator tree so
254   // that we are guaranteed to see definitions before we see uses.  This allows
255   // us to sink instructions in one pass, without iteration.  AFter sinking
256   // instructions, we perform another pass to hoist them out of the loop.
257   //
258   SinkRegion(DT->getNode(L->getHeader()));
259   HoistRegion(DT->getNode(L->getHeader()));
260
261   // Now that all loop invariants have been removed from the loop, promote any
262   // memory references to scalars that we can...
263   if (!DisablePromotion)
264     PromoteValuesInLoop();
265
266   // Clear out loops state information for the next iteration
267   CurLoop = 0;
268   Preheader = 0;
269
270   LoopToAliasMap[L] = CurAST;
271   return Changed;
272 }
273
274 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
275 /// dominated by the specified block, and that are in the current loop) in
276 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
277 /// uses before definitions, allowing us to sink a loop body in one pass without
278 /// iteration.
279 ///
280 void LICM::SinkRegion(DominatorTree::Node *N) {
281   assert(N != 0 && "Null dominator tree node?");
282   BasicBlock *BB = N->getBlock();
283
284   // If this subregion is not in the top level loop at all, exit.
285   if (!CurLoop->contains(BB)) return;
286
287   // We are processing blocks in reverse dfo, so process children first...
288   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
289   for (unsigned i = 0, e = Children.size(); i != e; ++i)
290     SinkRegion(Children[i]);
291
292   // Only need to process the contents of this block if it is not part of a
293   // subloop (which would already have been processed).
294   if (inSubLoop(BB)) return;
295
296   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
297     Instruction &I = *--II;
298
299     // Check to see if we can sink this instruction to the exit blocks
300     // of the loop.  We can do this if the all users of the instruction are
301     // outside of the loop.  In this case, it doesn't even matter if the
302     // operands of the instruction are loop invariant.
303     //
304     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
305       ++II;
306       sink(I);
307     }
308   }
309 }
310
311
312 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
313 /// dominated by the specified block, and that are in the current loop) in depth
314 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
315 /// before uses, allowing us to hoist a loop body in one pass without iteration.
316 ///
317 void LICM::HoistRegion(DominatorTree::Node *N) {
318   assert(N != 0 && "Null dominator tree node?");
319   BasicBlock *BB = N->getBlock();
320
321   // If this subregion is not in the top level loop at all, exit.
322   if (!CurLoop->contains(BB)) return;
323
324   // Only need to process the contents of this block if it is not part of a
325   // subloop (which would already have been processed).
326   if (!inSubLoop(BB))
327     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
328       Instruction &I = *II++;
329
330       // Try hoisting the instruction out to the preheader.  We can only do this
331       // if all of the operands of the instruction are loop invariant and if it
332       // is safe to hoist the instruction.
333       //
334       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
335           isSafeToExecuteUnconditionally(I))
336         hoist(I);
337       }
338
339   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
340   for (unsigned i = 0, e = Children.size(); i != e; ++i)
341     HoistRegion(Children[i]);
342 }
343
344 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
345 /// instruction.
346 ///
347 bool LICM::canSinkOrHoistInst(Instruction &I) {
348   // Loads have extra constraints we have to verify before we can hoist them.
349   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
350     if (LI->isVolatile())
351       return false;        // Don't hoist volatile loads!
352
353     // Don't hoist loads which have may-aliased stores in loop.
354     unsigned Size = 0;
355     if (LI->getType()->isSized())
356       Size = AA->getTargetData().getTypeSize(LI->getType());
357     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
358   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
359     // Handle obvious cases efficiently.
360     if (Function *Callee = CI->getCalledFunction()) {
361       AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
362       if (Behavior == AliasAnalysis::DoesNotAccessMemory)
363         return true;
364       else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
365         // If this call only reads from memory and there are no writes to memory
366         // in the loop, we can hoist or sink the call as appropriate.
367         bool FoundMod = false;
368         for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
369              I != E; ++I) {
370           AliasSet &AS = *I;
371           if (!AS.isForwardingAliasSet() && AS.isMod()) {
372             FoundMod = true;
373             break;
374           }
375         }
376         if (!FoundMod) return true;
377       }
378     }
379
380     // FIXME: This should use mod/ref information to see if we can hoist or sink
381     // the call.
382
383     return false;
384   }
385
386   // Otherwise these instructions are hoistable/sinkable
387   return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
388          isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I);
389 }
390
391 /// isNotUsedInLoop - Return true if the only users of this instruction are
392 /// outside of the loop.  If this is true, we can sink the instruction to the
393 /// exit blocks of the loop.
394 ///
395 bool LICM::isNotUsedInLoop(Instruction &I) {
396   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
397     Instruction *User = cast<Instruction>(*UI);
398     if (PHINode *PN = dyn_cast<PHINode>(User)) {
399       // PHI node uses occur in predecessor blocks!
400       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
401         if (PN->getIncomingValue(i) == &I)
402           if (CurLoop->contains(PN->getIncomingBlock(i)))
403             return false;
404     } else if (CurLoop->contains(User->getParent())) {
405       return false;
406     }
407   }
408   return true;
409 }
410
411
412 /// isLoopInvariantInst - Return true if all operands of this instruction are
413 /// loop invariant.  We also filter out non-hoistable instructions here just for
414 /// efficiency.
415 ///
416 bool LICM::isLoopInvariantInst(Instruction &I) {
417   // The instruction is loop invariant if all of its operands are loop-invariant
418   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
419     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
420       return false;
421
422   // If we got this far, the instruction is loop invariant!
423   return true;
424 }
425
426 /// sink - When an instruction is found to only be used outside of the loop,
427 /// this function moves it to the exit blocks and patches up SSA form as needed.
428 /// This method is guaranteed to remove the original instruction from its
429 /// position, and may either delete it or move it to outside of the loop.
430 ///
431 void LICM::sink(Instruction &I) {
432   DOUT << "LICM sinking instruction: " << I;
433
434   std::vector<BasicBlock*> ExitBlocks;
435   CurLoop->getExitBlocks(ExitBlocks);
436
437   if (isa<LoadInst>(I)) ++NumMovedLoads;
438   else if (isa<CallInst>(I)) ++NumMovedCalls;
439   ++NumSunk;
440   Changed = true;
441
442   // The case where there is only a single exit node of this loop is common
443   // enough that we handle it as a special (more efficient) case.  It is more
444   // efficient to handle because there are no PHI nodes that need to be placed.
445   if (ExitBlocks.size() == 1) {
446     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
447       // Instruction is not used, just delete it.
448       CurAST->deleteValue(&I);
449       if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
450         I.replaceAllUsesWith(UndefValue::get(I.getType()));
451       I.eraseFromParent();
452     } else {
453       // Move the instruction to the start of the exit block, after any PHI
454       // nodes in it.
455       I.removeFromParent();
456
457       BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
458       while (isa<PHINode>(InsertPt)) ++InsertPt;
459       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
460     }
461   } else if (ExitBlocks.size() == 0) {
462     // The instruction is actually dead if there ARE NO exit blocks.
463     CurAST->deleteValue(&I);
464     if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
465       I.replaceAllUsesWith(UndefValue::get(I.getType()));
466     I.eraseFromParent();
467   } else {
468     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
469     // do all of the hard work of inserting PHI nodes as necessary.  We convert
470     // the value into a stack object to get it to do this.
471
472     // Firstly, we create a stack object to hold the value...
473     AllocaInst *AI = 0;
474
475     if (I.getType() != Type::VoidTy)
476       AI = new AllocaInst(I.getType(), 0, I.getName(),
477                           I.getParent()->getParent()->getEntryBlock().begin());
478
479     // Secondly, insert load instructions for each use of the instruction
480     // outside of the loop.
481     while (!I.use_empty()) {
482       Instruction *U = cast<Instruction>(I.use_back());
483
484       // If the user is a PHI Node, we actually have to insert load instructions
485       // in all predecessor blocks, not in the PHI block itself!
486       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
487         // Only insert into each predecessor once, so that we don't have
488         // different incoming values from the same block!
489         std::map<BasicBlock*, Value*> InsertedBlocks;
490         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
491           if (UPN->getIncomingValue(i) == &I) {
492             BasicBlock *Pred = UPN->getIncomingBlock(i);
493             Value *&PredVal = InsertedBlocks[Pred];
494             if (!PredVal) {
495               // Insert a new load instruction right before the terminator in
496               // the predecessor block.
497               PredVal = new LoadInst(AI, "", Pred->getTerminator());
498             }
499
500             UPN->setIncomingValue(i, PredVal);
501           }
502
503       } else {
504         LoadInst *L = new LoadInst(AI, "", U);
505         U->replaceUsesOfWith(&I, L);
506       }
507     }
508
509     // Thirdly, insert a copy of the instruction in each exit block of the loop
510     // that is dominated by the instruction, storing the result into the memory
511     // location.  Be careful not to insert the instruction into any particular
512     // basic block more than once.
513     std::set<BasicBlock*> InsertedBlocks;
514     BasicBlock *InstOrigBB = I.getParent();
515
516     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
517       BasicBlock *ExitBlock = ExitBlocks[i];
518
519       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
520         // If we haven't already processed this exit block, do so now.
521         if (InsertedBlocks.insert(ExitBlock).second) {
522           // Insert the code after the last PHI node...
523           BasicBlock::iterator InsertPt = ExitBlock->begin();
524           while (isa<PHINode>(InsertPt)) ++InsertPt;
525
526           // If this is the first exit block processed, just move the original
527           // instruction, otherwise clone the original instruction and insert
528           // the copy.
529           Instruction *New;
530           if (InsertedBlocks.size() == 1) {
531             I.removeFromParent();
532             ExitBlock->getInstList().insert(InsertPt, &I);
533             New = &I;
534           } else {
535             New = I.clone();
536             CurAST->copyValue(&I, New);
537             if (!I.getName().empty())
538               New->setName(I.getName()+".le");
539             ExitBlock->getInstList().insert(InsertPt, New);
540           }
541
542           // Now that we have inserted the instruction, store it into the alloca
543           if (AI) new StoreInst(New, AI, InsertPt);
544         }
545       }
546     }
547
548     // If the instruction doesn't dominate any exit blocks, it must be dead.
549     if (InsertedBlocks.empty()) {
550       CurAST->deleteValue(&I);
551       I.eraseFromParent();
552     }
553
554     // Finally, promote the fine value to SSA form.
555     if (AI) {
556       std::vector<AllocaInst*> Allocas;
557       Allocas.push_back(AI);
558       PromoteMemToReg(Allocas, *ET, *DF, AA->getTargetData(), CurAST);
559     }
560   }
561 }
562
563 /// hoist - When an instruction is found to only use loop invariant operands
564 /// that is safe to hoist, this instruction is called to do the dirty work.
565 ///
566 void LICM::hoist(Instruction &I) {
567   DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
568
569   // Remove the instruction from its current basic block... but don't delete the
570   // instruction.
571   I.removeFromParent();
572
573   // Insert the new node in Preheader, before the terminator.
574   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
575
576   if (isa<LoadInst>(I)) ++NumMovedLoads;
577   else if (isa<CallInst>(I)) ++NumMovedCalls;
578   ++NumHoisted;
579   Changed = true;
580 }
581
582 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
583 /// not a trapping instruction or if it is a trapping instruction and is
584 /// guaranteed to execute.
585 ///
586 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
587   // If it is not a trapping instruction, it is always safe to hoist.
588   if (!Inst.isTrapping()) return true;
589
590   // Otherwise we have to check to make sure that the instruction dominates all
591   // of the exit blocks.  If it doesn't, then there is a path out of the loop
592   // which does not execute this instruction, so we can't hoist it.
593
594   // If the instruction is in the header block for the loop (which is very
595   // common), it is always guaranteed to dominate the exit blocks.  Since this
596   // is a common case, and can save some work, check it now.
597   if (Inst.getParent() == CurLoop->getHeader())
598     return true;
599
600   // It's always safe to load from a global or alloca.
601   if (isa<LoadInst>(Inst))
602     if (isa<AllocationInst>(Inst.getOperand(0)) ||
603         isa<GlobalVariable>(Inst.getOperand(0)))
604       return true;
605
606   // Get the exit blocks for the current loop.
607   std::vector<BasicBlock*> ExitBlocks;
608   CurLoop->getExitBlocks(ExitBlocks);
609
610   // For each exit block, get the DT node and walk up the DT until the
611   // instruction's basic block is found or we exit the loop.
612   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
613     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
614       return false;
615
616   return true;
617 }
618
619
620 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
621 /// stores out of the loop and moving loads to before the loop.  We do this by
622 /// looping over the stores in the loop, looking for stores to Must pointers
623 /// which are loop invariant.  We promote these memory locations to use allocas
624 /// instead.  These allocas can easily be raised to register values by the
625 /// PromoteMem2Reg functionality.
626 ///
627 void LICM::PromoteValuesInLoop() {
628   // PromotedValues - List of values that are promoted out of the loop.  Each
629   // value has an alloca instruction for it, and a canonical version of the
630   // pointer.
631   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
632   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
633
634   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
635   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
636
637   Changed = true;
638   NumPromoted += PromotedValues.size();
639
640   std::vector<Value*> PointerValueNumbers;
641
642   // Emit a copy from the value into the alloca'd value in the loop preheader
643   TerminatorInst *LoopPredInst = Preheader->getTerminator();
644   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
645     Value *Ptr = PromotedValues[i].second;
646
647     // If we are promoting a pointer value, update alias information for the
648     // inserted load.
649     Value *LoadValue = 0;
650     if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
651       // Locate a load or store through the pointer, and assign the same value
652       // to LI as we are loading or storing.  Since we know that the value is
653       // stored in this loop, this will always succeed.
654       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
655            UI != E; ++UI)
656         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
657           LoadValue = LI;
658           break;
659         } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
660           if (SI->getOperand(1) == Ptr) {
661             LoadValue = SI->getOperand(0);
662             break;
663           }
664         }
665       assert(LoadValue && "No store through the pointer found!");
666       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
667     }
668
669     // Load from the memory we are promoting.
670     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
671
672     if (LoadValue) CurAST->copyValue(LoadValue, LI);
673
674     // Store into the temporary alloca.
675     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
676   }
677
678   // Scan the basic blocks in the loop, replacing uses of our pointers with
679   // uses of the allocas in question.
680   //
681   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
682   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
683          E = LoopBBs.end(); I != E; ++I) {
684     // Rewrite all loads and stores in the block of the pointer...
685     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
686          II != E; ++II) {
687       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
688         std::map<Value*, AllocaInst*>::iterator
689           I = ValueToAllocaMap.find(L->getOperand(0));
690         if (I != ValueToAllocaMap.end())
691           L->setOperand(0, I->second);    // Rewrite load instruction...
692       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
693         std::map<Value*, AllocaInst*>::iterator
694           I = ValueToAllocaMap.find(S->getOperand(1));
695         if (I != ValueToAllocaMap.end())
696           S->setOperand(1, I->second);    // Rewrite store instruction...
697       }
698     }
699   }
700
701   // Now that the body of the loop uses the allocas instead of the original
702   // memory locations, insert code to copy the alloca value back into the
703   // original memory location on all exits from the loop.  Note that we only
704   // want to insert one copy of the code in each exit block, though the loop may
705   // exit to the same block more than once.
706   //
707   std::set<BasicBlock*> ProcessedBlocks;
708
709   std::vector<BasicBlock*> ExitBlocks;
710   CurLoop->getExitBlocks(ExitBlocks);
711   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
712     if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
713       // Copy all of the allocas into their memory locations.
714       BasicBlock::iterator BI = ExitBlocks[i]->begin();
715       while (isa<PHINode>(*BI))
716         ++BI;             // Skip over all of the phi nodes in the block.
717       Instruction *InsertPos = BI;
718       unsigned PVN = 0;
719       for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
720         // Load from the alloca.
721         LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
722
723         // If this is a pointer type, update alias info appropriately.
724         if (isa<PointerType>(LI->getType()))
725           CurAST->copyValue(PointerValueNumbers[PVN++], LI);
726
727         // Store into the memory we promoted.
728         new StoreInst(LI, PromotedValues[i].second, InsertPos);
729       }
730     }
731
732   // Now that we have done the deed, use the mem2reg functionality to promote
733   // all of the new allocas we just created into real SSA registers.
734   //
735   std::vector<AllocaInst*> PromotedAllocas;
736   PromotedAllocas.reserve(PromotedValues.size());
737   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
738     PromotedAllocas.push_back(PromotedValues[i].first);
739   PromoteMemToReg(PromotedAllocas, *ET, *DF, AA->getTargetData(), CurAST);
740 }
741
742 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
743 /// pointers, which are not loaded and stored through may aliases.  If these are
744 /// found, create an alloca for the value, add it to the PromotedValues list,
745 /// and keep track of the mapping from value to alloca.
746 ///
747 void LICM::FindPromotableValuesInLoop(
748                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
749                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
750   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
751
752   // Loop over all of the alias sets in the tracker object.
753   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
754        I != E; ++I) {
755     AliasSet &AS = *I;
756     // We can promote this alias set if it has a store, if it is a "Must" alias
757     // set, if the pointer is loop invariant, and if we are not eliminating any
758     // volatile loads or stores.
759     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
760         !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
761       assert(AS.begin() != AS.end() &&
762              "Must alias set should have at least one pointer element in it!");
763       Value *V = AS.begin()->first;
764
765       // Check that all of the pointers in the alias set have the same type.  We
766       // cannot (yet) promote a memory location that is loaded and stored in
767       // different sizes.
768       bool PointerOk = true;
769       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
770         if (V->getType() != I->first->getType()) {
771           PointerOk = false;
772           break;
773         }
774
775       if (PointerOk) {
776         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
777         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
778         PromotedValues.push_back(std::make_pair(AI, V));
779
780         // Update the AST and alias analysis.
781         CurAST->copyValue(V, AI);
782
783         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
784           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
785
786         DOUT << "LICM: Promoting value: " << *V << "\n";
787       }
788     }
789   }
790 }