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