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
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
16 // This pass uses alias analysis for two purposes:
18 // 1. Moving loop invariant loads and calls out of loops. If we can determine
19 // that a load or call inside of a loop never aliases anything stored to,
20 // we can hoist it or sink it like any other instruction.
21 // 2. Scalar Promotion of Memory - If there is a store instruction inside of
22 // the loop, we try to move the store to happen AFTER the loop instead of
23 // inside of the loop. This can only happen if a few conditions are true:
24 // A. The pointer stored through is loop invariant
25 // B. There are no stores or loads in the loop which _may_ alias the
26 // pointer. There are no calls in the loop which mod/ref the pointer.
27 // If these conditions are true, we can promote the loads and stores in the
28 // loop of the pointer to use a temporary alloca'd variable. We then use
29 // the mem2reg functionality to construct the appropriate SSA form for the
32 //===----------------------------------------------------------------------===//
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/Analysis/ScalarEvolution.h"
46 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/ADT/Statistic.h"
55 STATISTIC(NumSunk
, "Number of instructions sunk out of loop");
56 STATISTIC(NumHoisted
, "Number of instructions hoisted out of loop");
57 STATISTIC(NumMovedLoads
, "Number of load insts hoisted or sunk");
58 STATISTIC(NumMovedCalls
, "Number of call insts hoisted or sunk");
59 STATISTIC(NumPromoted
, "Number of memory locations promoted to registers");
63 DisablePromotion("disable-licm-promotion", cl::Hidden
,
64 cl::desc("Disable memory promotion in LICM pass"));
66 struct VISIBILITY_HIDDEN LICM
: public LoopPass
{
67 static char ID
; // Pass identification, replacement for typeid
68 LICM() : LoopPass((intptr_t)&ID
) {}
70 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
);
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
75 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
77 AU
.addRequiredID(LoopSimplifyID
);
78 AU
.addRequired
<LoopInfo
>();
79 AU
.addRequired
<DominatorTree
>();
80 AU
.addRequired
<DominanceFrontier
>(); // For scalar promotion (mem2reg)
81 AU
.addRequired
<AliasAnalysis
>();
82 AU
.addPreserved
<ScalarEvolution
>();
83 AU
.addPreserved
<DominanceFrontier
>();
86 bool doFinalization() {
87 LoopToAliasMap
.clear();
92 // Various analyses that we use...
93 AliasAnalysis
*AA
; // Current AliasAnalysis information
94 LoopInfo
*LI
; // Current LoopInfo
95 DominatorTree
*DT
; // Dominator Tree for the current Loop...
96 DominanceFrontier
*DF
; // Current Dominance Frontier
98 // State that is updated as we process loops
99 bool Changed
; // Set to true when we change anything.
100 BasicBlock
*Preheader
; // The preheader block of the current loop...
101 Loop
*CurLoop
; // The current loop we are working on...
102 AliasSetTracker
*CurAST
; // AliasSet information for the current loop...
103 std::map
<Loop
*, AliasSetTracker
*> LoopToAliasMap
;
105 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
106 void cloneBasicBlockAnalysis(BasicBlock
*From
, BasicBlock
*To
, Loop
*L
);
108 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
110 void deleteAnalysisValue(Value
*V
, Loop
*L
);
112 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
113 /// dominated by the specified block, and that are in the current loop) in
114 /// reverse depth first order w.r.t the DominatorTree. This allows us to
115 /// visit uses before definitions, allowing us to sink a loop body in one
116 /// pass without iteration.
118 void SinkRegion(DomTreeNode
*N
);
120 /// HoistRegion - Walk the specified region of the CFG (defined by all
121 /// blocks dominated by the specified block, and that are in the current
122 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
123 /// visit definitions before uses, allowing us to hoist a loop body in one
124 /// pass without iteration.
126 void HoistRegion(DomTreeNode
*N
);
128 /// inSubLoop - Little predicate that returns true if the specified basic
129 /// block is in a subloop of the current one, not the current one itself.
131 bool inSubLoop(BasicBlock
*BB
) {
132 assert(CurLoop
->contains(BB
) && "Only valid if BB is IN the loop");
133 for (Loop::iterator I
= CurLoop
->begin(), E
= CurLoop
->end(); I
!= E
; ++I
)
134 if ((*I
)->contains(BB
))
135 return true; // A subloop actually contains this block!
139 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
140 /// specified exit block of the loop is dominated by the specified block
141 /// that is in the body of the loop. We use these constraints to
142 /// dramatically limit the amount of the dominator tree that needs to be
144 bool isExitBlockDominatedByBlockInLoop(BasicBlock
*ExitBlock
,
145 BasicBlock
*BlockInLoop
) const {
146 // If the block in the loop is the loop header, it must be dominated!
147 BasicBlock
*LoopHeader
= CurLoop
->getHeader();
148 if (BlockInLoop
== LoopHeader
)
151 DomTreeNode
*BlockInLoopNode
= DT
->getNode(BlockInLoop
);
152 DomTreeNode
*IDom
= DT
->getNode(ExitBlock
);
154 // Because the exit block is not in the loop, we know we have to get _at
155 // least_ its immediate dominator.
157 // Get next Immediate Dominator.
158 IDom
= IDom
->getIDom();
160 // If we have got to the header of the loop, then the instructions block
161 // did not dominate the exit node, so we can't hoist it.
162 if (IDom
->getBlock() == LoopHeader
)
165 } while (IDom
!= BlockInLoopNode
);
170 /// sink - When an instruction is found to only be used outside of the loop,
171 /// this function moves it to the exit blocks and patches up SSA form as
174 void sink(Instruction
&I
);
176 /// hoist - When an instruction is found to only use loop invariant operands
177 /// that is safe to hoist, this instruction is called to do the dirty work.
179 void hoist(Instruction
&I
);
181 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
182 /// is not a trapping instruction or if it is a trapping instruction and is
183 /// guaranteed to execute.
185 bool isSafeToExecuteUnconditionally(Instruction
&I
);
187 /// pointerInvalidatedByLoop - Return true if the body of this loop may
188 /// store into the memory location pointed to by V.
190 bool pointerInvalidatedByLoop(Value
*V
, unsigned Size
) {
191 // Check to see if any of the basic blocks in CurLoop invalidate *V.
192 return CurAST
->getAliasSetForPointer(V
, Size
).isMod();
195 bool canSinkOrHoistInst(Instruction
&I
);
196 bool isLoopInvariantInst(Instruction
&I
);
197 bool isNotUsedInLoop(Instruction
&I
);
199 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
200 /// to scalars as we can.
202 void PromoteValuesInLoop();
204 /// FindPromotableValuesInLoop - Check the current loop for stores to
205 /// definite pointers, which are not loaded and stored through may aliases.
206 /// If these are found, create an alloca for the value, add it to the
207 /// PromotedValues list, and keep track of the mapping from value to
210 void FindPromotableValuesInLoop(
211 std::vector
<std::pair
<AllocaInst
*, Value
*> > &PromotedValues
,
212 std::map
<Value
*, AllocaInst
*> &Val2AlMap
);
216 RegisterPass
<LICM
> X("licm", "Loop Invariant Code Motion");
219 LoopPass
*llvm::createLICMPass() { return new LICM(); }
221 /// Hoist expressions out of the specified loop. Note, alias info for inner
222 /// loop is not preserved so it is not a good idea to run LICM multiple
223 /// times on one loop.
225 bool LICM::runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
228 // Get our Loop and Alias Analysis information...
229 LI
= &getAnalysis
<LoopInfo
>();
230 AA
= &getAnalysis
<AliasAnalysis
>();
231 DF
= &getAnalysis
<DominanceFrontier
>();
232 DT
= &getAnalysis
<DominatorTree
>();
234 CurAST
= new AliasSetTracker(*AA
);
235 // Collect Alias info from subloops
236 for (Loop::iterator LoopItr
= L
->begin(), LoopItrE
= L
->end();
237 LoopItr
!= LoopItrE
; ++LoopItr
) {
238 Loop
*InnerL
= *LoopItr
;
239 AliasSetTracker
*InnerAST
= LoopToAliasMap
[InnerL
];
240 assert (InnerAST
&& "Where is my AST?");
242 // What if InnerLoop was modified by other passes ?
243 CurAST
->add(*InnerAST
);
248 // Get the preheader block to move instructions into...
249 Preheader
= L
->getLoopPreheader();
250 assert(Preheader
&&"Preheader insertion pass guarantees we have a preheader!");
252 // Loop over the body of this loop, looking for calls, invokes, and stores.
253 // Because subloops have already been incorporated into AST, we skip blocks in
256 for (std::vector
<BasicBlock
*>::const_iterator I
= L
->getBlocks().begin(),
257 E
= L
->getBlocks().end(); I
!= E
; ++I
)
258 if (LI
->getLoopFor(*I
) == L
) // Ignore blocks in subloops...
259 CurAST
->add(**I
); // Incorporate the specified basic block
261 // We want to visit all of the instructions in this loop... that are not parts
262 // of our subloops (they have already had their invariants hoisted out of
263 // their loop, into this loop, so there is no need to process the BODIES of
266 // Traverse the body of the loop in depth first order on the dominator tree so
267 // that we are guaranteed to see definitions before we see uses. This allows
268 // us to sink instructions in one pass, without iteration. After sinking
269 // instructions, we perform another pass to hoist them out of the loop.
271 SinkRegion(DT
->getNode(L
->getHeader()));
272 HoistRegion(DT
->getNode(L
->getHeader()));
274 // Now that all loop invariants have been removed from the loop, promote any
275 // memory references to scalars that we can...
276 if (!DisablePromotion
)
277 PromoteValuesInLoop();
279 // Clear out loops state information for the next iteration
283 LoopToAliasMap
[L
] = CurAST
;
287 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
288 /// dominated by the specified block, and that are in the current loop) in
289 /// reverse depth first order w.r.t the DominatorTree. This allows us to visit
290 /// uses before definitions, allowing us to sink a loop body in one pass without
293 void LICM::SinkRegion(DomTreeNode
*N
) {
294 assert(N
!= 0 && "Null dominator tree node?");
295 BasicBlock
*BB
= N
->getBlock();
297 // If this subregion is not in the top level loop at all, exit.
298 if (!CurLoop
->contains(BB
)) return;
300 // We are processing blocks in reverse dfo, so process children first...
301 const std::vector
<DomTreeNode
*> &Children
= N
->getChildren();
302 for (unsigned i
= 0, e
= Children
.size(); i
!= e
; ++i
)
303 SinkRegion(Children
[i
]);
305 // Only need to process the contents of this block if it is not part of a
306 // subloop (which would already have been processed).
307 if (inSubLoop(BB
)) return;
309 for (BasicBlock::iterator II
= BB
->end(); II
!= BB
->begin(); ) {
310 Instruction
&I
= *--II
;
312 // Check to see if we can sink this instruction to the exit blocks
313 // of the loop. We can do this if the all users of the instruction are
314 // outside of the loop. In this case, it doesn't even matter if the
315 // operands of the instruction are loop invariant.
317 if (isNotUsedInLoop(I
) && canSinkOrHoistInst(I
)) {
325 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
326 /// dominated by the specified block, and that are in the current loop) in depth
327 /// first order w.r.t the DominatorTree. This allows us to visit definitions
328 /// before uses, allowing us to hoist a loop body in one pass without iteration.
330 void LICM::HoistRegion(DomTreeNode
*N
) {
331 assert(N
!= 0 && "Null dominator tree node?");
332 BasicBlock
*BB
= N
->getBlock();
334 // If this subregion is not in the top level loop at all, exit.
335 if (!CurLoop
->contains(BB
)) return;
337 // Only need to process the contents of this block if it is not part of a
338 // subloop (which would already have been processed).
340 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
; ) {
341 Instruction
&I
= *II
++;
343 // Try hoisting the instruction out to the preheader. We can only do this
344 // if all of the operands of the instruction are loop invariant and if it
345 // is safe to hoist the instruction.
347 if (isLoopInvariantInst(I
) && canSinkOrHoistInst(I
) &&
348 isSafeToExecuteUnconditionally(I
))
352 const std::vector
<DomTreeNode
*> &Children
= N
->getChildren();
353 for (unsigned i
= 0, e
= Children
.size(); i
!= e
; ++i
)
354 HoistRegion(Children
[i
]);
357 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
360 bool LICM::canSinkOrHoistInst(Instruction
&I
) {
361 // Loads have extra constraints we have to verify before we can hoist them.
362 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(&I
)) {
363 if (LI
->isVolatile())
364 return false; // Don't hoist volatile loads!
366 // Don't hoist loads which have may-aliased stores in loop.
368 if (LI
->getType()->isSized())
369 Size
= AA
->getTargetData().getTypeSize(LI
->getType());
370 return !pointerInvalidatedByLoop(LI
->getOperand(0), Size
);
371 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
372 // Handle obvious cases efficiently.
373 if (Function
*Callee
= CI
->getCalledFunction()) {
374 AliasAnalysis::ModRefBehavior Behavior
=AA
->getModRefBehavior(Callee
, CI
);
375 if (Behavior
== AliasAnalysis::DoesNotAccessMemory
)
377 else if (Behavior
== AliasAnalysis::OnlyReadsMemory
) {
378 // If this call only reads from memory and there are no writes to memory
379 // in the loop, we can hoist or sink the call as appropriate.
380 bool FoundMod
= false;
381 for (AliasSetTracker::iterator I
= CurAST
->begin(), E
= CurAST
->end();
384 if (!AS
.isForwardingAliasSet() && AS
.isMod()) {
389 if (!FoundMod
) return true;
393 // FIXME: This should use mod/ref information to see if we can hoist or sink
399 // Otherwise these instructions are hoistable/sinkable
400 return isa
<BinaryOperator
>(I
) || isa
<CastInst
>(I
) ||
401 isa
<SelectInst
>(I
) || isa
<GetElementPtrInst
>(I
) || isa
<CmpInst
>(I
) ||
402 isa
<InsertElementInst
>(I
) || isa
<ExtractElementInst
>(I
) ||
403 isa
<ShuffleVectorInst
>(I
);
406 /// isNotUsedInLoop - Return true if the only users of this instruction are
407 /// outside of the loop. If this is true, we can sink the instruction to the
408 /// exit blocks of the loop.
410 bool LICM::isNotUsedInLoop(Instruction
&I
) {
411 for (Value::use_iterator UI
= I
.use_begin(), E
= I
.use_end(); UI
!= E
; ++UI
) {
412 Instruction
*User
= cast
<Instruction
>(*UI
);
413 if (PHINode
*PN
= dyn_cast
<PHINode
>(User
)) {
414 // PHI node uses occur in predecessor blocks!
415 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
416 if (PN
->getIncomingValue(i
) == &I
)
417 if (CurLoop
->contains(PN
->getIncomingBlock(i
)))
419 } else if (CurLoop
->contains(User
->getParent())) {
427 /// isLoopInvariantInst - Return true if all operands of this instruction are
428 /// loop invariant. We also filter out non-hoistable instructions here just for
431 bool LICM::isLoopInvariantInst(Instruction
&I
) {
432 // The instruction is loop invariant if all of its operands are loop-invariant
433 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
434 if (!CurLoop
->isLoopInvariant(I
.getOperand(i
)))
437 // If we got this far, the instruction is loop invariant!
441 /// sink - When an instruction is found to only be used outside of the loop,
442 /// this function moves it to the exit blocks and patches up SSA form as needed.
443 /// This method is guaranteed to remove the original instruction from its
444 /// position, and may either delete it or move it to outside of the loop.
446 void LICM::sink(Instruction
&I
) {
447 DOUT
<< "LICM sinking instruction: " << I
;
449 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
450 CurLoop
->getExitBlocks(ExitBlocks
);
452 if (isa
<LoadInst
>(I
)) ++NumMovedLoads
;
453 else if (isa
<CallInst
>(I
)) ++NumMovedCalls
;
457 // The case where there is only a single exit node of this loop is common
458 // enough that we handle it as a special (more efficient) case. It is more
459 // efficient to handle because there are no PHI nodes that need to be placed.
460 if (ExitBlocks
.size() == 1) {
461 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks
[0], I
.getParent())) {
462 // Instruction is not used, just delete it.
463 CurAST
->deleteValue(&I
);
464 if (!I
.use_empty()) // If I has users in unreachable blocks, eliminate.
465 I
.replaceAllUsesWith(UndefValue::get(I
.getType()));
468 // Move the instruction to the start of the exit block, after any PHI
470 I
.removeFromParent();
472 BasicBlock::iterator InsertPt
= ExitBlocks
[0]->begin();
473 while (isa
<PHINode
>(InsertPt
)) ++InsertPt
;
474 ExitBlocks
[0]->getInstList().insert(InsertPt
, &I
);
476 } else if (ExitBlocks
.size() == 0) {
477 // The instruction is actually dead if there ARE NO exit blocks.
478 CurAST
->deleteValue(&I
);
479 if (!I
.use_empty()) // If I has users in unreachable blocks, eliminate.
480 I
.replaceAllUsesWith(UndefValue::get(I
.getType()));
483 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
484 // do all of the hard work of inserting PHI nodes as necessary. We convert
485 // the value into a stack object to get it to do this.
487 // Firstly, we create a stack object to hold the value...
490 if (I
.getType() != Type::VoidTy
) {
491 AI
= new AllocaInst(I
.getType(), 0, I
.getName(),
492 I
.getParent()->getParent()->getEntryBlock().begin());
496 // Secondly, insert load instructions for each use of the instruction
497 // outside of the loop.
498 while (!I
.use_empty()) {
499 Instruction
*U
= cast
<Instruction
>(I
.use_back());
501 // If the user is a PHI Node, we actually have to insert load instructions
502 // in all predecessor blocks, not in the PHI block itself!
503 if (PHINode
*UPN
= dyn_cast
<PHINode
>(U
)) {
504 // Only insert into each predecessor once, so that we don't have
505 // different incoming values from the same block!
506 std::map
<BasicBlock
*, Value
*> InsertedBlocks
;
507 for (unsigned i
= 0, e
= UPN
->getNumIncomingValues(); i
!= e
; ++i
)
508 if (UPN
->getIncomingValue(i
) == &I
) {
509 BasicBlock
*Pred
= UPN
->getIncomingBlock(i
);
510 Value
*&PredVal
= InsertedBlocks
[Pred
];
512 // Insert a new load instruction right before the terminator in
513 // the predecessor block.
514 PredVal
= new LoadInst(AI
, "", Pred
->getTerminator());
515 CurAST
->add(cast
<LoadInst
>(PredVal
));
518 UPN
->setIncomingValue(i
, PredVal
);
522 LoadInst
*L
= new LoadInst(AI
, "", U
);
523 U
->replaceUsesOfWith(&I
, L
);
528 // Thirdly, insert a copy of the instruction in each exit block of the loop
529 // that is dominated by the instruction, storing the result into the memory
530 // location. Be careful not to insert the instruction into any particular
531 // basic block more than once.
532 std::set
<BasicBlock
*> InsertedBlocks
;
533 BasicBlock
*InstOrigBB
= I
.getParent();
535 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
536 BasicBlock
*ExitBlock
= ExitBlocks
[i
];
538 if (isExitBlockDominatedByBlockInLoop(ExitBlock
, InstOrigBB
)) {
539 // If we haven't already processed this exit block, do so now.
540 if (InsertedBlocks
.insert(ExitBlock
).second
) {
541 // Insert the code after the last PHI node...
542 BasicBlock::iterator InsertPt
= ExitBlock
->begin();
543 while (isa
<PHINode
>(InsertPt
)) ++InsertPt
;
545 // If this is the first exit block processed, just move the original
546 // instruction, otherwise clone the original instruction and insert
549 if (InsertedBlocks
.size() == 1) {
550 I
.removeFromParent();
551 ExitBlock
->getInstList().insert(InsertPt
, &I
);
555 CurAST
->copyValue(&I
, New
);
556 if (!I
.getName().empty())
557 New
->setName(I
.getName()+".le");
558 ExitBlock
->getInstList().insert(InsertPt
, New
);
561 // Now that we have inserted the instruction, store it into the alloca
562 if (AI
) new StoreInst(New
, AI
, InsertPt
);
567 // If the instruction doesn't dominate any exit blocks, it must be dead.
568 if (InsertedBlocks
.empty()) {
569 CurAST
->deleteValue(&I
);
573 // Finally, promote the fine value to SSA form.
575 std::vector
<AllocaInst
*> Allocas
;
576 Allocas
.push_back(AI
);
577 PromoteMemToReg(Allocas
, *DT
, *DF
, CurAST
);
582 /// hoist - When an instruction is found to only use loop invariant operands
583 /// that is safe to hoist, this instruction is called to do the dirty work.
585 void LICM::hoist(Instruction
&I
) {
586 DOUT
<< "LICM hoisting to " << Preheader
->getName() << ": " << I
;
588 // Remove the instruction from its current basic block... but don't delete the
590 I
.removeFromParent();
592 // Insert the new node in Preheader, before the terminator.
593 Preheader
->getInstList().insert(Preheader
->getTerminator(), &I
);
595 if (isa
<LoadInst
>(I
)) ++NumMovedLoads
;
596 else if (isa
<CallInst
>(I
)) ++NumMovedCalls
;
601 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
602 /// not a trapping instruction or if it is a trapping instruction and is
603 /// guaranteed to execute.
605 bool LICM::isSafeToExecuteUnconditionally(Instruction
&Inst
) {
606 // If it is not a trapping instruction, it is always safe to hoist.
607 if (!Inst
.isTrapping()) return true;
609 // Otherwise we have to check to make sure that the instruction dominates all
610 // of the exit blocks. If it doesn't, then there is a path out of the loop
611 // which does not execute this instruction, so we can't hoist it.
613 // If the instruction is in the header block for the loop (which is very
614 // common), it is always guaranteed to dominate the exit blocks. Since this
615 // is a common case, and can save some work, check it now.
616 if (Inst
.getParent() == CurLoop
->getHeader())
619 // It's always safe to load from a global or alloca.
620 if (isa
<LoadInst
>(Inst
))
621 if (isa
<AllocationInst
>(Inst
.getOperand(0)) ||
622 isa
<GlobalVariable
>(Inst
.getOperand(0)))
625 // Get the exit blocks for the current loop.
626 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
627 CurLoop
->getExitBlocks(ExitBlocks
);
629 // For each exit block, get the DT node and walk up the DT until the
630 // instruction's basic block is found or we exit the loop.
631 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
)
632 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks
[i
], Inst
.getParent()))
639 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
640 /// stores out of the loop and moving loads to before the loop. We do this by
641 /// looping over the stores in the loop, looking for stores to Must pointers
642 /// which are loop invariant. We promote these memory locations to use allocas
643 /// instead. These allocas can easily be raised to register values by the
644 /// PromoteMem2Reg functionality.
646 void LICM::PromoteValuesInLoop() {
647 // PromotedValues - List of values that are promoted out of the loop. Each
648 // value has an alloca instruction for it, and a canonical version of the
650 std::vector
<std::pair
<AllocaInst
*, Value
*> > PromotedValues
;
651 std::map
<Value
*, AllocaInst
*> ValueToAllocaMap
; // Map of ptr to alloca
653 FindPromotableValuesInLoop(PromotedValues
, ValueToAllocaMap
);
654 if (ValueToAllocaMap
.empty()) return; // If there are values to promote.
657 NumPromoted
+= PromotedValues
.size();
659 std::vector
<Value
*> PointerValueNumbers
;
661 // Emit a copy from the value into the alloca'd value in the loop preheader
662 TerminatorInst
*LoopPredInst
= Preheader
->getTerminator();
663 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
) {
664 Value
*Ptr
= PromotedValues
[i
].second
;
666 // If we are promoting a pointer value, update alias information for the
668 Value
*LoadValue
= 0;
669 if (isa
<PointerType
>(cast
<PointerType
>(Ptr
->getType())->getElementType())) {
670 // Locate a load or store through the pointer, and assign the same value
671 // to LI as we are loading or storing. Since we know that the value is
672 // stored in this loop, this will always succeed.
673 for (Value::use_iterator UI
= Ptr
->use_begin(), E
= Ptr
->use_end();
675 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(*UI
)) {
678 } else if (StoreInst
*SI
= dyn_cast
<StoreInst
>(*UI
)) {
679 if (SI
->getOperand(1) == Ptr
) {
680 LoadValue
= SI
->getOperand(0);
684 assert(LoadValue
&& "No store through the pointer found!");
685 PointerValueNumbers
.push_back(LoadValue
); // Remember this for later.
688 // Load from the memory we are promoting.
689 LoadInst
*LI
= new LoadInst(Ptr
, Ptr
->getName()+".promoted", LoopPredInst
);
691 if (LoadValue
) CurAST
->copyValue(LoadValue
, LI
);
693 // Store into the temporary alloca.
694 new StoreInst(LI
, PromotedValues
[i
].first
, LoopPredInst
);
697 // Scan the basic blocks in the loop, replacing uses of our pointers with
698 // uses of the allocas in question.
700 const std::vector
<BasicBlock
*> &LoopBBs
= CurLoop
->getBlocks();
701 for (std::vector
<BasicBlock
*>::const_iterator I
= LoopBBs
.begin(),
702 E
= LoopBBs
.end(); I
!= E
; ++I
) {
703 // Rewrite all loads and stores in the block of the pointer...
704 for (BasicBlock::iterator II
= (*I
)->begin(), E
= (*I
)->end();
706 if (LoadInst
*L
= dyn_cast
<LoadInst
>(II
)) {
707 std::map
<Value
*, AllocaInst
*>::iterator
708 I
= ValueToAllocaMap
.find(L
->getOperand(0));
709 if (I
!= ValueToAllocaMap
.end())
710 L
->setOperand(0, I
->second
); // Rewrite load instruction...
711 } else if (StoreInst
*S
= dyn_cast
<StoreInst
>(II
)) {
712 std::map
<Value
*, AllocaInst
*>::iterator
713 I
= ValueToAllocaMap
.find(S
->getOperand(1));
714 if (I
!= ValueToAllocaMap
.end())
715 S
->setOperand(1, I
->second
); // Rewrite store instruction...
720 // Now that the body of the loop uses the allocas instead of the original
721 // memory locations, insert code to copy the alloca value back into the
722 // original memory location on all exits from the loop. Note that we only
723 // want to insert one copy of the code in each exit block, though the loop may
724 // exit to the same block more than once.
726 std::set
<BasicBlock
*> ProcessedBlocks
;
728 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
729 CurLoop
->getExitBlocks(ExitBlocks
);
730 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
)
731 if (ProcessedBlocks
.insert(ExitBlocks
[i
]).second
) {
732 // Copy all of the allocas into their memory locations.
733 BasicBlock::iterator BI
= ExitBlocks
[i
]->begin();
734 while (isa
<PHINode
>(*BI
))
735 ++BI
; // Skip over all of the phi nodes in the block.
736 Instruction
*InsertPos
= BI
;
738 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
) {
739 // Load from the alloca.
740 LoadInst
*LI
= new LoadInst(PromotedValues
[i
].first
, "", InsertPos
);
742 // If this is a pointer type, update alias info appropriately.
743 if (isa
<PointerType
>(LI
->getType()))
744 CurAST
->copyValue(PointerValueNumbers
[PVN
++], LI
);
746 // Store into the memory we promoted.
747 new StoreInst(LI
, PromotedValues
[i
].second
, InsertPos
);
751 // Now that we have done the deed, use the mem2reg functionality to promote
752 // all of the new allocas we just created into real SSA registers.
754 std::vector
<AllocaInst
*> PromotedAllocas
;
755 PromotedAllocas
.reserve(PromotedValues
.size());
756 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
)
757 PromotedAllocas
.push_back(PromotedValues
[i
].first
);
758 PromoteMemToReg(PromotedAllocas
, *DT
, *DF
, CurAST
);
761 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
762 /// pointers, which are not loaded and stored through may aliases and are safe
763 /// for promotion. If these are found, create an alloca for the value, add it
764 /// to the PromotedValues list, and keep track of the mapping from value to
766 void LICM::FindPromotableValuesInLoop(
767 std::vector
<std::pair
<AllocaInst
*, Value
*> > &PromotedValues
,
768 std::map
<Value
*, AllocaInst
*> &ValueToAllocaMap
) {
769 Instruction
*FnStart
= CurLoop
->getHeader()->getParent()->begin()->begin();
771 SmallVector
<Instruction
*, 4> LoopExits
;
772 SmallVector
<BasicBlock
*, 4> Blocks
;
773 CurLoop
->getExitingBlocks(Blocks
);
774 for (SmallVector
<BasicBlock
*, 4>::iterator BI
= Blocks
.begin(),
775 BE
= Blocks
.end(); BI
!= BE
; ++BI
) {
776 BasicBlock
*BB
= *BI
;
777 LoopExits
.push_back(BB
->getTerminator());
780 // Loop over all of the alias sets in the tracker object.
781 for (AliasSetTracker::iterator I
= CurAST
->begin(), E
= CurAST
->end();
784 // We can promote this alias set if it has a store, if it is a "Must" alias
785 // set, if the pointer is loop invariant, and if we are not eliminating any
786 // volatile loads or stores.
787 if (!AS
.isForwardingAliasSet() && AS
.isMod() && AS
.isMustAlias() &&
788 !AS
.isVolatile() && CurLoop
->isLoopInvariant(AS
.begin()->first
)) {
789 assert(AS
.begin() != AS
.end() &&
790 "Must alias set should have at least one pointer element in it!");
791 Value
*V
= AS
.begin()->first
;
793 // Check that all of the pointers in the alias set have the same type. We
794 // cannot (yet) promote a memory location that is loaded and stored in
796 bool PointerOk
= true;
797 for (AliasSet::iterator I
= AS
.begin(), E
= AS
.end(); I
!= E
; ++I
)
798 if (V
->getType() != I
->first
->getType()) {
803 // Do not promote null values because it may be unsafe to do so.
804 if (isa
<ConstantPointerNull
>(V
))
807 if (GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(V
)) {
808 // If GEP base is NULL then the calculated address used by Store or
809 // Load instruction is invalid. Do not promote this value because
810 // it may expose load and store instruction that are covered by
811 // condition which may not yet folded.
812 if (isa
<ConstantPointerNull
>(GEP
->getOperand(0)))
815 // If GEP is use is not dominating loop exit then promoting
816 // GEP may expose unsafe load and store instructions unconditinally.
818 for(Value::use_iterator UI
= V
->use_begin(), UE
= V
->use_end();
819 UI
!= UE
&& PointerOk
; ++UI
) {
820 Instruction
*Use
= dyn_cast
<Instruction
>(*UI
);
823 for (SmallVector
<Instruction
*, 4>::iterator
824 ExitI
= LoopExits
.begin(), ExitE
= LoopExits
.end();
825 ExitI
!= ExitE
; ++ExitI
) {
826 Instruction
*Ex
= *ExitI
;
827 if (!DT
->dominates(Use
, Ex
)){
839 const Type
*Ty
= cast
<PointerType
>(V
->getType())->getElementType();
840 AllocaInst
*AI
= new AllocaInst(Ty
, 0, V
->getName()+".tmp", FnStart
);
841 PromotedValues
.push_back(std::make_pair(AI
, V
));
843 // Update the AST and alias analysis.
844 CurAST
->copyValue(V
, AI
);
846 for (AliasSet::iterator I
= AS
.begin(), E
= AS
.end(); I
!= E
; ++I
)
847 ValueToAllocaMap
.insert(std::make_pair(I
->first
, AI
));
849 DOUT
<< "LICM: Promoting value: " << *V
<< "\n";
855 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
856 void LICM::cloneBasicBlockAnalysis(BasicBlock
*From
, BasicBlock
*To
, Loop
*L
) {
857 AliasSetTracker
*AST
= LoopToAliasMap
[L
];
861 AST
->copyValue(From
, To
);
864 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
866 void LICM::deleteAnalysisValue(Value
*V
, Loop
*L
) {
867 AliasSetTracker
*AST
= LoopToAliasMap
[L
];