1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible. It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe. This pass also promotes must-aliased memory locations in the loop to
16 // This pass uses alias analysis for two purposes:
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
32 //===----------------------------------------------------------------------===//
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"
54 DisablePromotion("disable-licm-promotion", cl::Hidden,
55 cl::desc("Disable memory promotion in LICM pass"));
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");
63 struct LICM : public FunctionPass {
64 virtual bool runOnFunction(Function &F);
66 /// This transformation requires natural loop information & requires that
67 /// loop preheaders be inserted into the CFG...
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequiredID(LoopSimplifyID);
72 AU.addRequired<LoopInfo>();
73 AU.addRequired<DominatorTree>();
74 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
75 AU.addRequired<AliasAnalysis>();
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
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...
91 /// visitLoop - Hoist expressions out of the specified loop...
93 void visitLoop(Loop *L, AliasSetTracker &AST);
95 /// HoistRegion - Walk the specified region of the CFG (defined by all
96 /// blocks dominated by the specified block, and that are in the current
97 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
98 /// visit definitions before uses, allowing us to hoist a loop body in one
99 /// pass without iteration.
101 void HoistRegion(DominatorTree::Node *N);
103 /// inSubLoop - Little predicate that returns true if the specified basic
104 /// block is in a subloop of the current one, not the current one itself.
106 bool inSubLoop(BasicBlock *BB) {
107 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
108 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
109 if (CurLoop->getSubLoops()[i]->contains(BB))
110 return true; // A subloop actually contains this block!
114 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
115 /// specified exit block of the loop is dominated by the specified block
116 /// that is in the body of the loop. We use these constraints to
117 /// dramatically limit the amount of the dominator tree that needs to be
119 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
120 BasicBlock *BlockInLoop) const {
121 // If the block in the loop is the loop header, it must be dominated!
122 BasicBlock *LoopHeader = CurLoop->getHeader();
123 if (BlockInLoop == LoopHeader)
126 DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
127 DominatorTree::Node *IDom = DT->getNode(ExitBlock);
129 // Because the exit block is not in the loop, we know we have to get _at
130 // least_ it's immediate dominator.
132 // Get next Immediate Dominator.
133 IDom = IDom->getIDom();
135 // If we have got to the header of the loop, then the instructions block
136 // did not dominate the exit node, so we can't hoist it.
137 if (IDom->getBlock() == LoopHeader)
140 } while (IDom != BlockInLoopNode);
145 /// sink - When an instruction is found to only be used outside of the loop,
146 /// this function moves it to the exit blocks and patches up SSA form as
149 void sink(Instruction &I);
151 /// hoist - When an instruction is found to only use loop invariant operands
152 /// that is safe to hoist, this instruction is called to do the dirty work.
154 void hoist(Instruction &I);
156 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
157 /// is not a trapping instruction or if it is a trapping instruction and is
158 /// guaranteed to execute.
160 bool isSafeToExecuteUnconditionally(Instruction &I);
162 /// pointerInvalidatedByLoop - Return true if the body of this loop may
163 /// store into the memory location pointed to by V.
165 bool pointerInvalidatedByLoop(Value *V) {
166 // Check to see if any of the basic blocks in CurLoop invalidate *V.
167 return CurAST->getAliasSetForPointer(V, 0).isMod();
170 /// isLoopInvariant - Return true if the specified value is loop invariant
172 inline bool isLoopInvariant(Value *V) {
173 if (Instruction *I = dyn_cast<Instruction>(V))
174 return !CurLoop->contains(I->getParent());
175 return true; // All non-instructions are loop invariant
178 bool canSinkOrHoistInst(Instruction &I);
179 bool isLoopInvariantInst(Instruction &I);
180 bool isNotUsedInLoop(Instruction &I);
182 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
183 /// to scalars as we can.
185 void PromoteValuesInLoop();
187 /// findPromotableValuesInLoop - Check the current loop for stores to
188 /// definite pointers, which are not loaded and stored through may aliases.
189 /// If these are found, create an alloca for the value, add it to the
190 /// PromotedValues list, and keep track of the mapping from value to
193 void findPromotableValuesInLoop(
194 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
195 std::map<Value*, AllocaInst*> &Val2AlMap);
198 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
201 FunctionPass *llvm::createLICMPass() { return new LICM(); }
203 /// runOnFunction - For LICM, this simply traverses the loop structure of the
204 /// function, hoisting expressions out of loops if possible.
206 bool LICM::runOnFunction(Function &) {
209 // Get our Loop and Alias Analysis information...
210 LI = &getAnalysis<LoopInfo>();
211 AA = &getAnalysis<AliasAnalysis>();
212 DF = &getAnalysis<DominanceFrontier>();
213 DT = &getAnalysis<DominatorTree>();
215 // Hoist expressions out of all of the top-level loops.
216 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
217 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
218 E = TopLevelLoops.end(); I != E; ++I) {
219 AliasSetTracker AST(*AA);
226 /// visitLoop - Hoist expressions out of the specified loop...
228 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
229 // Recurse through all subloops before we process this loop...
230 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
231 E = L->getSubLoops().end(); I != E; ++I) {
232 AliasSetTracker SubAST(*AA);
233 visitLoop(*I, SubAST);
235 // Incorporate information about the subloops into this loop...
241 // Get the preheader block to move instructions into...
242 Preheader = L->getLoopPreheader();
243 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
245 // Loop over the body of this loop, looking for calls, invokes, and stores.
246 // Because subloops have already been incorporated into AST, we skip blocks in
249 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
250 E = L->getBlocks().end(); I != E; ++I)
251 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
252 AST.add(**I); // Incorporate the specified basic block
254 // We want to visit all of the instructions in this loop... that are not parts
255 // of our subloops (they have already had their invariants hoisted out of
256 // their loop, into this loop, so there is no need to process the BODIES of
259 // Traverse the body of the loop in depth first order on the dominator tree so
260 // that we are guaranteed to see definitions before we see uses. This allows
261 // us to perform the LICM transformation in one pass, without iteration.
263 HoistRegion(DT->getNode(L->getHeader()));
265 // Now that all loop invariants have been removed from the loop, promote any
266 // memory references to scalars that we can...
267 if (!DisablePromotion)
268 PromoteValuesInLoop();
270 // Clear out loops state information for the next iteration
275 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
276 /// dominated by the specified block, and that are in the current loop) in depth
277 /// first order w.r.t the DominatorTree. This allows us to visit definitions
278 /// before uses, allowing us to hoist a loop body in one pass without iteration.
280 void LICM::HoistRegion(DominatorTree::Node *N) {
281 assert(N != 0 && "Null dominator tree node?");
282 BasicBlock *BB = N->getBlock();
284 // If this subregion is not in the top level loop at all, exit.
285 if (!CurLoop->contains(BB)) return;
287 // Only need to process the contents of this block if it is not part of a
288 // subloop (which would already have been processed).
290 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
291 Instruction &I = *II++;
293 // We can only handle simple expressions and loads with this code.
294 if (canSinkOrHoistInst(I)) {
295 // First check to see if we can sink this instruction to the exit blocks
296 // of the loop. We can do this if the only users of the instruction are
297 // outside of the loop. In this case, it doesn't even matter if the
298 // operands of the instruction are loop invariant.
300 if (isNotUsedInLoop(I))
303 // If we can't sink the instruction, try hoisting it out to the
304 // preheader. We can only do this if all of the operands of the
305 // instruction are loop invariant and if it is safe to hoist the
308 else if (isLoopInvariantInst(I) && isSafeToExecuteUnconditionally(I))
313 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
314 for (unsigned i = 0, e = Children.size(); i != e; ++i)
315 HoistRegion(Children[i]);
318 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
321 bool LICM::canSinkOrHoistInst(Instruction &I) {
322 // Loads have extra constraints we have to verify before we can hoist them.
323 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
324 if (LI->isVolatile())
325 return false; // Don't hoist volatile loads!
327 // Don't hoist loads which have may-aliased stores in loop.
328 return !pointerInvalidatedByLoop(LI->getOperand(0));
331 return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
332 isa<GetElementPtrInst>(I) || isa<VANextInst>(I) || isa<VAArgInst>(I);
335 /// isNotUsedInLoop - Return true if the only users of this instruction are
336 /// outside of the loop. If this is true, we can sink the instruction to the
337 /// exit blocks of the loop.
339 bool LICM::isNotUsedInLoop(Instruction &I) {
340 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
341 Instruction *User = cast<Instruction>(*UI);
342 if (PHINode *PN = dyn_cast<PHINode>(User)) {
343 // PHI node uses occur in predecessor blocks!
344 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
345 if (PN->getIncomingValue(i) == &I)
346 if (CurLoop->contains(PN->getIncomingBlock(i)))
348 } else if (CurLoop->contains(User->getParent())) {
356 /// isLoopInvariantInst - Return true if all operands of this instruction are
357 /// loop invariant. We also filter out non-hoistable instructions here just for
360 bool LICM::isLoopInvariantInst(Instruction &I) {
361 // The instruction is loop invariant if all of its operands are loop-invariant
362 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
363 if (!isLoopInvariant(I.getOperand(i)))
366 // If we got this far, the instruction is loop invariant!
370 /// sink - When an instruction is found to only be used outside of the loop,
371 /// this function moves it to the exit blocks and patches up SSA form as
374 void LICM::sink(Instruction &I) {
375 DEBUG(std::cerr << "LICM sinking instruction: " << I);
377 const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
378 std::vector<Value*> Operands(I.op_begin(), I.op_end());
380 if (isa<LoadInst>(I)) ++NumMovedLoads;
384 // The case where there is only a single exit node of this loop is common
385 // enough that we handle it as a special (more efficient) case. It is more
386 // efficient to handle because there are no PHI nodes that need to be placed.
387 if (ExitBlocks.size() == 1) {
388 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
389 // Instruction is not used, just delete it.
390 I.getParent()->getInstList().erase(&I);
392 // Move the instruction to the start of the exit block, after any PHI
394 I.getParent()->getInstList().remove(&I);
396 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
397 while (isa<PHINode>(InsertPt)) ++InsertPt;
398 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
400 } else if (ExitBlocks.size() == 0) {
401 // The instruction is actually dead if there ARE NO exit blocks.
402 I.getParent()->getInstList().erase(&I);
404 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
405 // do all of the hard work of inserting PHI nodes as necessary. We convert
406 // the value into a stack object to get it to do this.
408 // Firstly, we create a stack object to hold the value...
409 AllocaInst *AI = new AllocaInst(I.getType(), 0, I.getName(),
410 I.getParent()->getParent()->front().begin());
412 // Secondly, insert load instructions for each use of the instruction
413 // outside of the loop.
414 while (!I.use_empty()) {
415 Instruction *U = cast<Instruction>(I.use_back());
417 // If the user is a PHI Node, we actually have to insert load instructions
418 // in all predecessor blocks, not in the PHI block itself!
419 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
420 // Only insert into each predecessor once, so that we don't have
421 // different incoming values from the same block!
422 std::map<BasicBlock*, Value*> InsertedBlocks;
423 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
424 if (UPN->getIncomingValue(i) == &I) {
425 BasicBlock *Pred = UPN->getIncomingBlock(i);
426 Value *&PredVal = InsertedBlocks[Pred];
428 // Insert a new load instruction right before the terminator in
429 // the predecessor block.
430 PredVal = new LoadInst(AI, "", Pred->getTerminator());
433 UPN->setIncomingValue(i, PredVal);
437 LoadInst *L = new LoadInst(AI, "", U);
438 U->replaceUsesOfWith(&I, L);
442 // Thirdly, insert a copy of the instruction in each exit block of the loop
443 // that is dominated by the instruction, storing the result into the memory
444 // location. Be careful not to insert the instruction into any particular
445 // basic block more than once.
446 std::set<BasicBlock*> InsertedBlocks;
447 BasicBlock *InstOrigBB = I.getParent();
449 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
450 BasicBlock *ExitBlock = ExitBlocks[i];
452 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
453 // If we haven't already processed this exit block, do so now.
454 if (InsertedBlocks.insert(ExitBlock).second) {
455 // Insert the code after the last PHI node...
456 BasicBlock::iterator InsertPt = ExitBlock->begin();
457 while (isa<PHINode>(InsertPt)) ++InsertPt;
459 // If this is the first exit block processed, just move the original
460 // instruction, otherwise clone the original instruction and insert
463 if (InsertedBlocks.size() == 1) {
464 I.getParent()->getInstList().remove(&I);
465 ExitBlock->getInstList().insert(InsertPt, &I);
469 New->setName(I.getName()+".le");
470 ExitBlock->getInstList().insert(InsertPt, New);
473 // Now that we have inserted the instruction, store it into the alloca
474 new StoreInst(New, AI, InsertPt);
479 // Finally, promote the fine value to SSA form.
480 std::vector<AllocaInst*> Allocas;
481 Allocas.push_back(AI);
482 PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData());
485 // Since we just sunk an instruction, check to see if any other instructions
486 // used by this instruction are now sinkable. If so, sink them too.
487 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
488 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
489 if (CurLoop->contains(OpI->getParent()) && canSinkOrHoistInst(*OpI) &&
490 isNotUsedInLoop(*OpI) && isSafeToExecuteUnconditionally(*OpI))
494 /// hoist - When an instruction is found to only use loop invariant operands
495 /// that is safe to hoist, this instruction is called to do the dirty work.
497 void LICM::hoist(Instruction &I) {
498 DEBUG(std::cerr << "LICM hoisting to";
499 WriteAsOperand(std::cerr, Preheader, false);
500 std::cerr << ": " << I);
502 // Remove the instruction from its current basic block... but don't delete the
504 I.getParent()->getInstList().remove(&I);
506 // Insert the new node in Preheader, before the terminator.
507 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
509 if (isa<LoadInst>(I)) ++NumMovedLoads;
514 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
515 /// not a trapping instruction or if it is a trapping instruction and is
516 /// guaranteed to execute.
518 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
519 // If it is not a trapping instruction, it is always safe to hoist.
520 if (!Inst.isTrapping()) return true;
522 // Otherwise we have to check to make sure that the instruction dominates all
523 // of the exit blocks. If it doesn't, then there is a path out of the loop
524 // which does not execute this instruction, so we can't hoist it.
526 // If the instruction is in the header block for the loop (which is very
527 // common), it is always guaranteed to dominate the exit blocks. Since this
528 // is a common case, and can save some work, check it now.
529 if (Inst.getParent() == CurLoop->getHeader())
532 // Get the exit blocks for the current loop.
533 const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
535 // For each exit block, get the DT node and walk up the DT until the
536 // instruction's basic block is found or we exit the loop.
537 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
538 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
545 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
546 /// stores out of the loop and moving loads to before the loop. We do this by
547 /// looping over the stores in the loop, looking for stores to Must pointers
548 /// which are loop invariant. We promote these memory locations to use allocas
549 /// instead. These allocas can easily be raised to register values by the
550 /// PromoteMem2Reg functionality.
552 void LICM::PromoteValuesInLoop() {
553 // PromotedValues - List of values that are promoted out of the loop. Each
554 // value has an alloca instruction for it, and a canonical version of the
556 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
557 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
559 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
560 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
563 NumPromoted += PromotedValues.size();
565 // Emit a copy from the value into the alloca'd value in the loop preheader
566 TerminatorInst *LoopPredInst = Preheader->getTerminator();
567 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
568 // Load from the memory we are promoting...
569 LoadInst *LI = new LoadInst(PromotedValues[i].second,
570 PromotedValues[i].second->getName()+".promoted",
572 // Store into the temporary alloca...
573 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
576 // Scan the basic blocks in the loop, replacing uses of our pointers with
577 // uses of the allocas in question.
579 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
580 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
581 E = LoopBBs.end(); I != E; ++I) {
582 // Rewrite all loads and stores in the block of the pointer...
583 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
585 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
586 std::map<Value*, AllocaInst*>::iterator
587 I = ValueToAllocaMap.find(L->getOperand(0));
588 if (I != ValueToAllocaMap.end())
589 L->setOperand(0, I->second); // Rewrite load instruction...
590 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
591 std::map<Value*, AllocaInst*>::iterator
592 I = ValueToAllocaMap.find(S->getOperand(1));
593 if (I != ValueToAllocaMap.end())
594 S->setOperand(1, I->second); // Rewrite store instruction...
599 // Now that the body of the loop uses the allocas instead of the original
600 // memory locations, insert code to copy the alloca value back into the
601 // original memory location on all exits from the loop. Note that we only
602 // want to insert one copy of the code in each exit block, though the loop may
603 // exit to the same block more than once.
605 std::set<BasicBlock*> ProcessedBlocks;
607 const std::vector<BasicBlock*> &ExitBlocks = CurLoop->getExitBlocks();
608 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
609 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
610 // Copy all of the allocas into their memory locations...
611 BasicBlock::iterator BI = ExitBlocks[i]->begin();
612 while (isa<PHINode>(*BI))
613 ++BI; // Skip over all of the phi nodes in the block...
614 Instruction *InsertPos = BI;
615 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
616 // Load from the alloca...
617 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
618 // Store into the memory we promoted...
619 new StoreInst(LI, PromotedValues[i].second, InsertPos);
623 // Now that we have done the deed, use the mem2reg functionality to promote
624 // all of the new allocas we just created into real SSA registers...
626 std::vector<AllocaInst*> PromotedAllocas;
627 PromotedAllocas.reserve(PromotedValues.size());
628 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
629 PromotedAllocas.push_back(PromotedValues[i].first);
630 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData());
633 /// findPromotableValuesInLoop - Check the current loop for stores to definite
634 /// pointers, which are not loaded and stored through may aliases. If these are
635 /// found, create an alloca for the value, add it to the PromotedValues list,
636 /// and keep track of the mapping from value to alloca...
638 void LICM::findPromotableValuesInLoop(
639 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
640 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
641 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
643 // Loop over all of the alias sets in the tracker object...
644 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
647 // We can promote this alias set if it has a store, if it is a "Must" alias
648 // set, and if the pointer is loop invariant.
649 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
650 !AS.isVolatile() && isLoopInvariant(AS.begin()->first)) {
651 assert(AS.begin() != AS.end() &&
652 "Must alias set should have at least one pointer element in it!");
653 Value *V = AS.begin()->first;
655 // Check that all of the pointers in the alias set have the same type. We
656 // cannot (yet) promote a memory location that is loaded and stored in
658 bool PointerOk = true;
659 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
660 if (V->getType() != I->first->getType()) {
666 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
667 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
668 PromotedValues.push_back(std::make_pair(AI, V));
670 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
671 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
673 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");