blob: 0512bcb2f5a252207bdce36cf53c0fea0554c853 [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2//
Chris Lattner45d67d62003-02-24 03:52:32 +00003// This pass is a simple loop invariant code motion pass. An interesting aspect
4// of this pass is that it uses alias analysis for two purposes:
5//
6// 1. Moving loop invariant loads out of loops. If we can determine that a
7// load inside of a loop never aliases anything stored to, we can hoist it
8// like any other instruction.
9// 2. Scalar Promotion of Memory - If there is a store instruction inside of
10// the loop, we try to move the store to happen AFTER the loop instead of
11// inside of the loop. This can only happen if a few conditions are true:
12// A. The pointer stored through is loop invariant
13// B. There are no stores or loads in the loop which _may_ alias the
14// pointer. There are no calls in the loop which mod/ref the pointer.
15// If these conditions are true, we can promote the loads and stores in the
16// loop of the pointer to use a temporary alloca'd variable. We then use
17// the mem2reg functionality to construct the appropriate SSA form for the
18// variable.
Chris Lattner6ec05f52002-05-10 22:44:58 +000019//
Chris Lattner6ec05f52002-05-10 22:44:58 +000020//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chris Lattner45d67d62003-02-24 03:52:32 +000023#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000024#include "llvm/Transforms/Utils/Local.h"
25#include "llvm/Analysis/LoopInfo.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000026#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000027#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner64437692002-09-29 21:46:09 +000028#include "llvm/Analysis/Dominators.h"
Chris Lattner45d67d62003-02-24 03:52:32 +000029#include "llvm/Instructions.h"
30#include "llvm/DerivedTypes.h"
Chris Lattnere27406e2003-03-03 17:25:18 +000031#include "llvm/Target/TargetData.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000032#include "llvm/Support/InstVisitor.h"
Chris Lattner45d67d62003-02-24 03:52:32 +000033#include "llvm/Support/CFG.h"
Chris Lattner45d67d62003-02-24 03:52:32 +000034#include "Support/CommandLine.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000035#include "Support/Debug.h"
36#include "Support/Statistic.h"
Chris Lattner05e86302002-09-29 22:26:07 +000037#include "llvm/Assembly/Writer.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000038#include <algorithm>
39
Chris Lattner6ec05f52002-05-10 22:44:58 +000040namespace {
Chris Lattner17895702003-10-13 05:04:27 +000041 cl::opt<bool>
42 DisablePromotion("disable-licm-promotion", cl::Hidden,
43 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000044
Chris Lattnerbf3a0992002-10-01 22:38:41 +000045 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
46 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
Chris Lattner17895702003-10-13 05:04:27 +000047 Statistic<> NumPromoted("licm",
48 "Number of memory locations promoted to registers");
Chris Lattner718b2212002-09-26 16:38:03 +000049
Chris Lattner6ec05f52002-05-10 22:44:58 +000050 struct LICM : public FunctionPass, public InstVisitor<LICM> {
Chris Lattner113f4f42002-06-25 16:13:24 +000051 virtual bool runOnFunction(Function &F);
Chris Lattner6ec05f52002-05-10 22:44:58 +000052
Chris Lattnerf64f2d32002-09-26 16:52:07 +000053 /// This transformation requires natural loop information & requires that
54 /// loop preheaders be inserted into the CFG...
55 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000057 AU.setPreservesCFG();
Chris Lattner72272a72003-10-12 21:52:28 +000058 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000059 AU.addRequired<LoopInfo>();
Chris Lattner64437692002-09-29 21:46:09 +000060 AU.addRequired<DominatorTree>();
Chris Lattner0592bb72003-03-03 23:32:45 +000061 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnera51fa882002-08-22 21:39:55 +000062 AU.addRequired<AliasAnalysis>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000063 }
64
65 private:
Chris Lattner45d67d62003-02-24 03:52:32 +000066 LoopInfo *LI; // Current LoopInfo
67 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnera906bac2003-10-05 21:20:13 +000068 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattner45d67d62003-02-24 03:52:32 +000069 bool Changed; // Set to true when we change anything.
70 BasicBlock *Preheader; // The preheader block of the current loop...
71 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +000072 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +000073 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattner6ec05f52002-05-10 22:44:58 +000074
Chris Lattnerf64f2d32002-09-26 16:52:07 +000075 /// visitLoop - Hoist expressions out of the specified loop...
76 ///
Chris Lattner0592bb72003-03-03 23:32:45 +000077 void visitLoop(Loop *L, AliasSetTracker &AST);
Chris Lattner6ec05f52002-05-10 22:44:58 +000078
Chris Lattner64437692002-09-29 21:46:09 +000079 /// HoistRegion - Walk the specified region of the CFG (defined by all
80 /// blocks dominated by the specified block, and that are in the current
81 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000082 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner64437692002-09-29 21:46:09 +000083 /// pass without iteration.
84 ///
85 void HoistRegion(DominatorTree::Node *N);
86
Chris Lattner05e86302002-09-29 22:26:07 +000087 /// inSubLoop - Little predicate that returns true if the specified basic
88 /// block is in a subloop of the current one, not the current one itself.
Chris Lattnerf64f2d32002-09-26 16:52:07 +000089 ///
Chris Lattner05e86302002-09-29 22:26:07 +000090 bool inSubLoop(BasicBlock *BB) {
91 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner6ec05f52002-05-10 22:44:58 +000092 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
93 if (CurLoop->getSubLoops()[i]->contains(BB))
Chris Lattner05e86302002-09-29 22:26:07 +000094 return true; // A subloop actually contains this block!
95 return false;
Chris Lattner6ec05f52002-05-10 22:44:58 +000096 }
97
Chris Lattnerf64f2d32002-09-26 16:52:07 +000098 /// hoist - When an instruction is found to only use loop invariant operands
99 /// that is safe to hoist, this instruction is called to do the dirty work.
100 ///
Chris Lattner113f4f42002-06-25 16:13:24 +0000101 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000102
Chris Lattner17895702003-10-13 05:04:27 +0000103 /// SafeToHoist - Only hoist an instruction if it is not a trapping
104 /// instruction or if it is a trapping instruction and is guaranteed to
105 /// execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000106 ///
107 bool SafeToHoist(Instruction &I);
108
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000109 /// pointerInvalidatedByLoop - Return true if the body of this loop may
110 /// store into the memory location pointed to by V.
111 ///
Chris Lattner45d67d62003-02-24 03:52:32 +0000112 bool pointerInvalidatedByLoop(Value *V) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000113 // Check to see if any of the basic blocks in CurLoop invalidate *V.
114 return CurAST->getAliasSetForPointer(V, 0).isMod();
Chris Lattner45d67d62003-02-24 03:52:32 +0000115 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000116
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000117 /// isLoopInvariant - Return true if the specified value is loop invariant
118 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +0000119 inline bool isLoopInvariant(Value *V) {
120 if (Instruction *I = dyn_cast<Instruction>(V))
121 return !CurLoop->contains(I->getParent());
122 return true; // All non-instructions are loop invariant
123 }
124
Chris Lattner45d67d62003-02-24 03:52:32 +0000125 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
126 /// to scalars as we can.
127 ///
128 void PromoteValuesInLoop();
129
130 /// findPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman9b8d3392003-09-11 15:32:37 +0000131 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner45d67d62003-02-24 03:52:32 +0000132 /// If these are found, create an alloca for the value, add it to the
133 /// PromotedValues list, and keep track of the mapping from value to
134 /// alloca...
135 ///
136 void findPromotableValuesInLoop(
137 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
138 std::map<Value*, AllocaInst*> &Val2AlMap);
139
140
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000141 /// Instruction visitation handlers... these basically control whether or
142 /// not the specified instruction types are hoisted.
143 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +0000144 friend class InstVisitor<LICM>;
Chris Lattner113f4f42002-06-25 16:13:24 +0000145 void visitBinaryOperator(Instruction &I) {
Chris Lattner17895702003-10-13 05:04:27 +0000146 if (isLoopInvariant(I.getOperand(0)) &&
147 isLoopInvariant(I.getOperand(1)) && SafeToHoist(I))
Chris Lattner6ec05f52002-05-10 22:44:58 +0000148 hoist(I);
149 }
Chris Lattnerb80b69c2002-08-14 18:22:19 +0000150 void visitCastInst(CastInst &CI) {
151 Instruction &I = (Instruction&)CI;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000152 if (isLoopInvariant(I.getOperand(0)) && SafeToHoist(CI)) hoist(I);
Chris Lattnerb193ff82002-08-14 18:18:02 +0000153 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000154 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000155
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000156 void visitLoadInst(LoadInst &LI);
Chris Lattnera51fa882002-08-22 21:39:55 +0000157
Chris Lattner113f4f42002-06-25 16:13:24 +0000158 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
159 Instruction &I = (Instruction&)GEPI;
160 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
161 if (!isLoopInvariant(I.getOperand(i))) return;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000162 if(SafeToHoist(GEPI))
163 hoist(I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000164 }
165 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000166
Chris Lattnerc8b70922002-07-26 21:12:46 +0000167 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000168}
169
170Pass *createLICMPass() { return new LICM(); }
171
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000172/// runOnFunction - For LICM, this simply traverses the loop structure of the
173/// function, hoisting expressions out of loops if possible.
174///
Chris Lattner113f4f42002-06-25 16:13:24 +0000175bool LICM::runOnFunction(Function &) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000176 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000177
Chris Lattner45d67d62003-02-24 03:52:32 +0000178 // Get our Loop and Alias Analysis information...
179 LI = &getAnalysis<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000180 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000181 DF = &getAnalysis<DominanceFrontier>();
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000182 DT = &getAnalysis<DominatorTree>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000183
Chris Lattner45d67d62003-02-24 03:52:32 +0000184 // Hoist expressions out of all of the top-level loops.
185 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
186 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
187 E = TopLevelLoops.end(); I != E; ++I) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000188 AliasSetTracker AST(*AA);
189 LICM::visitLoop(*I, AST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000190 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000191 return Changed;
192}
193
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000194
195/// visitLoop - Hoist expressions out of the specified loop...
196///
Chris Lattner0592bb72003-03-03 23:32:45 +0000197void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
Chris Lattner6ec05f52002-05-10 22:44:58 +0000198 // Recurse through all subloops before we process this loop...
Chris Lattner45d67d62003-02-24 03:52:32 +0000199 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
200 E = L->getSubLoops().end(); I != E; ++I) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000201 AliasSetTracker SubAST(*AA);
202 LICM::visitLoop(*I, SubAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000203
204 // Incorporate information about the subloops into this loop...
Chris Lattner0592bb72003-03-03 23:32:45 +0000205 AST.add(SubAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000206 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000207 CurLoop = L;
Chris Lattner0592bb72003-03-03 23:32:45 +0000208 CurAST = &AST;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000209
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000210 // Get the preheader block to move instructions into...
211 Preheader = L->getLoopPreheader();
212 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
213
Chris Lattner45d67d62003-02-24 03:52:32 +0000214 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000215 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000216 // subloops.
217 //
218 const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
219 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
220 E = LoopBBs.end(); I != E; ++I)
221 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
Chris Lattner0592bb72003-03-03 23:32:45 +0000222 AST.add(**I); // Incorporate the specified basic block
Chris Lattner45d67d62003-02-24 03:52:32 +0000223
Chris Lattner6ec05f52002-05-10 22:44:58 +0000224 // We want to visit all of the instructions in this loop... that are not parts
225 // of our subloops (they have already had their invariants hoisted out of
226 // their loop, into this loop, so there is no need to process the BODIES of
227 // the subloops).
228 //
Chris Lattner64437692002-09-29 21:46:09 +0000229 // Traverse the body of the loop in depth first order on the dominator tree so
230 // that we are guaranteed to see definitions before we see uses. This allows
231 // us to perform the LICM transformation in one pass, without iteration.
232 //
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000233 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattner6ec05f52002-05-10 22:44:58 +0000234
Chris Lattner45d67d62003-02-24 03:52:32 +0000235 // Now that all loop invariants have been removed from the loop, promote any
236 // memory references to scalars that we can...
237 if (!DisablePromotion)
238 PromoteValuesInLoop();
239
Chris Lattner6ec05f52002-05-10 22:44:58 +0000240 // Clear out loops state information for the next iteration
241 CurLoop = 0;
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000242 Preheader = 0;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000243}
244
Chris Lattner64437692002-09-29 21:46:09 +0000245/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
246/// dominated by the specified block, and that are in the current loop) in depth
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000247/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner64437692002-09-29 21:46:09 +0000248/// before uses, allowing us to hoist a loop body in one pass without iteration.
249///
250void LICM::HoistRegion(DominatorTree::Node *N) {
251 assert(N != 0 && "Null dominator tree node?");
252
Chris Lattner05e86302002-09-29 22:26:07 +0000253 // If this subregion is not in the top level loop at all, exit.
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000254 if (!CurLoop->contains(N->getBlock())) return;
Chris Lattner64437692002-09-29 21:46:09 +0000255
Chris Lattner05e86302002-09-29 22:26:07 +0000256 // Only need to hoist the contents of this block if it is not part of a
257 // subloop (which would already have been hoisted)
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000258 if (!inSubLoop(N->getBlock()))
259 visit(*N->getBlock());
Chris Lattner64437692002-09-29 21:46:09 +0000260
261 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
262 for (unsigned i = 0, e = Children.size(); i != e; ++i)
263 HoistRegion(Children[i]);
264}
265
266
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000267/// hoist - When an instruction is found to only use loop invariant operands
268/// that is safe to hoist, this instruction is called to do the dirty work.
269///
Chris Lattner113f4f42002-06-25 16:13:24 +0000270void LICM::hoist(Instruction &Inst) {
Chris Lattner05e86302002-09-29 22:26:07 +0000271 DEBUG(std::cerr << "LICM hoisting to";
272 WriteAsOperand(std::cerr, Preheader, false);
273 std::cerr << ": " << Inst);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000274
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000275 // Remove the instruction from its current basic block... but don't delete the
276 // instruction.
277 Inst.getParent()->getInstList().remove(&Inst);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000278
Chris Lattner718b2212002-09-26 16:38:03 +0000279 // Insert the new node in Preheader, before the terminator.
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000280 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
Chris Lattner718b2212002-09-26 16:38:03 +0000281
Chris Lattner718b2212002-09-26 16:38:03 +0000282 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000283 Changed = true;
284}
285
Tanya Lattner57c03df2003-08-05 18:45:46 +0000286/// SafeToHoist - Only hoist an instruction if it is not a trapping instruction
287/// or if it is a trapping instruction and is guaranteed to execute
288///
289bool LICM::SafeToHoist(Instruction &Inst) {
290
291 //If it is a trapping instruction, then check if its guaranteed to execute.
292 if(Inst.isTrapping()) {
293
294 //Get the instruction's basic block.
295 BasicBlock *InstBB = Inst.getParent();
296
297 //Get the Dominator Tree Node for the instruction's basic block/
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000298 DominatorTree::Node *InstDTNode = DT->getNode(InstBB);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000299
300 //Get the exit blocks for the current loop.
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000301 const std::vector<BasicBlock* > &ExitBlocks = CurLoop->getExitBlocks();
Tanya Lattner57c03df2003-08-05 18:45:46 +0000302
303 //For each exit block, get the DT node and walk up the DT until
304 //the instruction's basic block is found or we exit the loop.
305 for(unsigned i=0; i < ExitBlocks.size(); ++i) {
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000306 DominatorTree::Node *IDom = DT->getNode(ExitBlocks[i]);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000307
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000308 while(IDom != InstDTNode) {
Tanya Lattner57c03df2003-08-05 18:45:46 +0000309
Tanya Lattner57c03df2003-08-05 18:45:46 +0000310 //Get next Immediate Dominator.
311 IDom = IDom->getIDom();
312
313 //See if we exited the loop.
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000314 if(!CurLoop->contains(IDom->getBlock()))
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000315 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000316 }
Tanya Lattner57c03df2003-08-05 18:45:46 +0000317 }
318 }
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000319
Tanya Lattner57c03df2003-08-05 18:45:46 +0000320 return true;
321}
322
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000323
324void LICM::visitLoadInst(LoadInst &LI) {
Chris Lattner01a83912003-09-08 18:17:14 +0000325 if (isLoopInvariant(LI.getOperand(0)) && !LI.isVolatile() &&
Tanya Lattner57c03df2003-08-05 18:45:46 +0000326 !pointerInvalidatedByLoop(LI.getOperand(0)) && SafeToHoist(LI)) {
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000327 hoist(LI);
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000328 ++NumHoistedLoads;
329 }
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000330}
331
Chris Lattner45d67d62003-02-24 03:52:32 +0000332/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
333/// stores out of the loop and moving loads to before the loop. We do this by
334/// looping over the stores in the loop, looking for stores to Must pointers
335/// which are loop invariant. We promote these memory locations to use allocas
336/// instead. These allocas can easily be raised to register values by the
337/// PromoteMem2Reg functionality.
338///
339void LICM::PromoteValuesInLoop() {
340 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner216c7b82003-09-10 05:29:43 +0000341 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner45d67d62003-02-24 03:52:32 +0000342 // pointer.
343 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
344 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
345
346 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
347 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
348
349 Changed = true;
350 NumPromoted += PromotedValues.size();
351
352 // Emit a copy from the value into the alloca'd value in the loop preheader
353 TerminatorInst *LoopPredInst = Preheader->getTerminator();
354 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
355 // Load from the memory we are promoting...
356 LoadInst *LI = new LoadInst(PromotedValues[i].second,
357 PromotedValues[i].second->getName()+".promoted",
358 LoopPredInst);
359 // Store into the temporary alloca...
360 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
361 }
362
363 // Scan the basic blocks in the loop, replacing uses of our pointers with
364 // uses of the allocas in question. If we find a branch that exits the
365 // loop, make sure to put reload code into all of the successors of the
366 // loop.
367 //
368 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
369 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
370 E = LoopBBs.end(); I != E; ++I) {
371 // Rewrite all loads and stores in the block of the pointer...
372 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
373 II != E; ++II) {
Chris Lattner889f6202003-04-23 16:37:45 +0000374 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000375 std::map<Value*, AllocaInst*>::iterator
376 I = ValueToAllocaMap.find(L->getOperand(0));
377 if (I != ValueToAllocaMap.end())
378 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattner889f6202003-04-23 16:37:45 +0000379 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000380 std::map<Value*, AllocaInst*>::iterator
381 I = ValueToAllocaMap.find(S->getOperand(1));
382 if (I != ValueToAllocaMap.end())
383 S->setOperand(1, I->second); // Rewrite store instruction...
384 }
385 }
386
387 // Check to see if any successors of this block are outside of the loop.
388 // If so, we need to copy the value from the alloca back into the memory
389 // location...
390 //
391 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
392 if (!CurLoop->contains(*SI)) {
393 // Copy all of the allocas into their memory locations...
Chris Lattner1ad80e22003-02-27 21:59:36 +0000394 BasicBlock::iterator BI = (*SI)->begin();
395 while (isa<PHINode>(*BI))
396 ++BI; // Skip over all of the phi nodes in the block...
397 Instruction *InsertPos = BI;
Chris Lattner45d67d62003-02-24 03:52:32 +0000398 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
399 // Load from the alloca...
400 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
401 // Store into the memory we promoted...
402 new StoreInst(LI, PromotedValues[i].second, InsertPos);
403 }
404 }
405 }
406
407 // Now that we have done the deed, use the mem2reg functionality to promote
408 // all of the new allocas we just created into real SSA registers...
409 //
410 std::vector<AllocaInst*> PromotedAllocas;
411 PromotedAllocas.reserve(PromotedValues.size());
412 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
413 PromotedAllocas.push_back(PromotedValues[i].first);
Chris Lattnera906bac2003-10-05 21:20:13 +0000414 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData());
Chris Lattner45d67d62003-02-24 03:52:32 +0000415}
416
Misha Brukman9b8d3392003-09-11 15:32:37 +0000417/// findPromotableValuesInLoop - Check the current loop for stores to definite
Chris Lattner45d67d62003-02-24 03:52:32 +0000418/// pointers, which are not loaded and stored through may aliases. If these are
419/// found, create an alloca for the value, add it to the PromotedValues list,
420/// and keep track of the mapping from value to alloca...
421///
422void LICM::findPromotableValuesInLoop(
423 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
424 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
425 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
426
Chris Lattner0592bb72003-03-03 23:32:45 +0000427 // Loop over all of the alias sets in the tracker object...
428 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
429 I != E; ++I) {
430 AliasSet &AS = *I;
431 // We can promote this alias set if it has a store, if it is a "Must" alias
432 // set, and if the pointer is loop invariant.
433 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
434 isLoopInvariant(AS.begin()->first)) {
435 assert(AS.begin() != AS.end() &&
436 "Must alias set should have at least one pointer element in it!");
437 Value *V = AS.begin()->first;
Chris Lattner45d67d62003-02-24 03:52:32 +0000438
Chris Lattner0592bb72003-03-03 23:32:45 +0000439 // Check that all of the pointers in the alias set have the same type. We
440 // cannot (yet) promote a memory location that is loaded and stored in
441 // different sizes.
442 bool PointerOk = true;
443 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
444 if (V->getType() != I->first->getType()) {
445 PointerOk = false;
446 break;
Chris Lattner45d67d62003-02-24 03:52:32 +0000447 }
Chris Lattner0592bb72003-03-03 23:32:45 +0000448
449 if (PointerOk) {
450 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
451 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
452 PromotedValues.push_back(std::make_pair(AI, V));
453
454 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
455 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
456
457 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
Chris Lattner45d67d62003-02-24 03:52:32 +0000458 }
459 }
460 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000461}