blob: 669afa33ac9463f33672ebb04c8f4fa7727b86ec [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6ec05f52002-05-10 22:44:58 +00009//
Chris Lattnerc0517682003-12-09 17:18:00 +000010// 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
Chris Lattner547192d62003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattnerc0517682003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner45d67d62003-02-24 03:52:32 +000017//
Chris Lattner289ba2a2004-05-23 21:20:19 +000018// 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.
Chris Lattner45d67d62003-02-24 03:52:32 +000021// 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.
Chris Lattner6ec05f52002-05-10 22:44:58 +000031//
Chris Lattner6ec05f52002-05-10 22:44:58 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1c790bf2005-03-23 21:00:12 +000034#define DEBUG_TYPE "licm"
Chris Lattner6ec05f52002-05-10 22:44:58 +000035#include "llvm/Transforms/Scalar.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000036#include "llvm/Constants.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000037#include "llvm/DerivedTypes.h"
38#include "llvm/Instructions.h"
39#include "llvm/Target/TargetData.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000040#include "llvm/Analysis/LoopInfo.h"
Devang Patel69730c92007-03-07 04:41:30 +000041#include "llvm/Analysis/LoopPass.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000042#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000043#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner64437692002-09-29 21:46:09 +000044#include "llvm/Analysis/Dominators.h"
Devang Patelbb97ac42007-07-30 20:19:59 +000045#include "llvm/Analysis/ScalarEvolution.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000046#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Reid Spencer557ab152007-02-05 23:32:05 +000047#include "llvm/Support/CFG.h"
48#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000052#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000053using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chris Lattner79a42ac2006-12-19 21:40:18 +000055STATISTIC(NumSunk , "Number of instructions sunk out of loop");
56STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
57STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
58STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
59STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
60
Chris Lattner6ec05f52002-05-10 22:44:58 +000061namespace {
Chris Lattner17895702003-10-13 05:04:27 +000062 cl::opt<bool>
63 DisablePromotion("disable-licm-promotion", cl::Hidden,
64 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000065
Devang Patel69730c92007-03-07 04:41:30 +000066 struct VISIBILITY_HIDDEN LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000068 LICM() : LoopPass((intptr_t)&ID) {}
69
Devang Patel69730c92007-03-07 04:41:30 +000070 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner6ec05f52002-05-10 22:44:58 +000071
Chris Lattnerf64f2d32002-09-26 16:52:07 +000072 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
74 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +000075 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000076 AU.setPreservesCFG();
Chris Lattner72272a72003-10-12 21:52:28 +000077 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000078 AU.addRequired<LoopInfo>();
Owen Andersonc24701e2007-04-24 06:40:39 +000079 AU.addRequired<DominatorTree>();
Chris Lattner0592bb72003-03-03 23:32:45 +000080 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnera51fa882002-08-22 21:39:55 +000081 AU.addRequired<AliasAnalysis>();
Devang Patelbb97ac42007-07-30 20:19:59 +000082 AU.addPreserved<ScalarEvolution>();
83 AU.addPreserved<DominanceFrontier>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000084 }
85
Dan Gohman2ce11162007-04-17 18:21:36 +000086 bool doFinalization() {
Devang Patel69730c92007-03-07 04:41:30 +000087 LoopToAliasMap.clear();
88 return false;
89 }
90
Chris Lattner6ec05f52002-05-10 22:44:58 +000091 private:
Chris Lattnerc0517682003-12-09 17:18:00 +000092 // Various analyses that we use...
Chris Lattner45d67d62003-02-24 03:52:32 +000093 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +000094 LoopInfo *LI; // Current LoopInfo
Owen Andersonc24701e2007-04-24 06:40:39 +000095 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattnera906bac2003-10-05 21:20:13 +000096 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattnerc0517682003-12-09 17:18:00 +000097
98 // State that is updated as we process loops
Chris Lattner45d67d62003-02-24 03:52:32 +000099 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...
Chris Lattner0592bb72003-03-03 23:32:45 +0000102 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel69730c92007-03-07 04:41:30 +0000103 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000104
Devang Patelb98a0972007-07-31 08:01:41 +0000105 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
106 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
107
108 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
109 /// set.
110 void deleteAnalysisValue(Value *V, Loop *L);
111
Chris Lattner547192d62003-12-19 07:22:45 +0000112 /// 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
Owen Andersonc24701e2007-04-24 06:40:39 +0000114 /// reverse depth first order w.r.t the DominatorTree. This allows us to
Chris Lattner547192d62003-12-19 07:22:45 +0000115 /// visit uses before definitions, allowing us to sink a loop body in one
116 /// pass without iteration.
117 ///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000118 void SinkRegion(DomTreeNode *N);
Chris Lattner547192d62003-12-19 07:22:45 +0000119
Chris Lattner64437692002-09-29 21:46:09 +0000120 /// HoistRegion - Walk the specified region of the CFG (defined by all
121 /// blocks dominated by the specified block, and that are in the current
Owen Andersonc24701e2007-04-24 06:40:39 +0000122 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000123 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner64437692002-09-29 21:46:09 +0000124 /// pass without iteration.
125 ///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000126 void HoistRegion(DomTreeNode *N);
Chris Lattner64437692002-09-29 21:46:09 +0000127
Chris Lattner05e86302002-09-29 22:26:07 +0000128 /// 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.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000130 ///
Chris Lattner05e86302002-09-29 22:26:07 +0000131 bool inSubLoop(BasicBlock *BB) {
132 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000133 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
134 if ((*I)->contains(BB))
Chris Lattner05e86302002-09-29 22:26:07 +0000135 return true; // A subloop actually contains this block!
136 return false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000137 }
138
Chris Lattneraaaea512003-12-10 06:41:05 +0000139 /// 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
143 /// searched.
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)
149 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000150
Devang Patelbdd1aae2007-06-04 00:32:22 +0000151 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
152 DomTreeNode *IDom = DT->getNode(ExitBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000153
Chris Lattneraaaea512003-12-10 06:41:05 +0000154 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner289ba2a2004-05-23 21:20:19 +0000155 // least_ its immediate dominator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000156 do {
157 // Get next Immediate Dominator.
Owen Andersonc24701e2007-04-24 06:40:39 +0000158 IDom = IDom->getIDom();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000159
Chris Lattneraaaea512003-12-10 06:41:05 +0000160 // 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.
Owen Andersonc24701e2007-04-24 06:40:39 +0000162 if (IDom->getBlock() == LoopHeader)
Chris Lattneraaaea512003-12-10 06:41:05 +0000163 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000164
Owen Andersonc24701e2007-04-24 06:40:39 +0000165 } while (IDom != BlockInLoopNode);
Chris Lattneraaaea512003-12-10 06:41:05 +0000166
167 return true;
168 }
169
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
172 /// needed.
173 ///
174 void sink(Instruction &I);
175
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000176 /// 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.
178 ///
Chris Lattner113f4f42002-06-25 16:13:24 +0000179 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000180
Chris Lattneraaaea512003-12-10 06:41:05 +0000181 /// 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.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000184 ///
Chris Lattneraaaea512003-12-10 06:41:05 +0000185 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000186
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000187 /// pointerInvalidatedByLoop - Return true if the body of this loop may
188 /// store into the memory location pointed to by V.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000189 ///
Chris Lattnerb1374092004-11-26 21:20:09 +0000190 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000191 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerb1374092004-11-26 21:20:09 +0000192 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner45d67d62003-02-24 03:52:32 +0000193 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000194
Chris Lattneraaaea512003-12-10 06:41:05 +0000195 bool canSinkOrHoistInst(Instruction &I);
196 bool isLoopInvariantInst(Instruction &I);
197 bool isNotUsedInLoop(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000198
Chris Lattner45d67d62003-02-24 03:52:32 +0000199 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
200 /// to scalars as we can.
201 ///
202 void PromoteValuesInLoop();
203
Chris Lattnera3465782004-09-15 01:04:07 +0000204 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman9b8d3392003-09-11 15:32:37 +0000205 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner45d67d62003-02-24 03:52:32 +0000206 /// 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
208 /// alloca...
209 ///
Chris Lattnera3465782004-09-15 01:04:07 +0000210 void FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000211 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
212 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000213 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000214
Devang Patel8c78a0b2007-05-03 01:11:54 +0000215 char LICM::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000216 RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000217}
218
Devang Patel69730c92007-03-07 04:41:30 +0000219LoopPass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000220
Devang Patel69730c92007-03-07 04:41:30 +0000221/// Hoist expressions out of the specified loop...
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000222///
Devang Patel69730c92007-03-07 04:41:30 +0000223bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000224 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000225
Chris Lattner45d67d62003-02-24 03:52:32 +0000226 // Get our Loop and Alias Analysis information...
227 LI = &getAnalysis<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000228 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000229 DF = &getAnalysis<DominanceFrontier>();
Owen Andersonc24701e2007-04-24 06:40:39 +0000230 DT = &getAnalysis<DominatorTree>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000231
Devang Patel69730c92007-03-07 04:41:30 +0000232 CurAST = new AliasSetTracker(*AA);
Devang Patel9b3b35d2007-05-30 15:29:37 +0000233 // Collect Alias info from subloops
Devang Patel69730c92007-03-07 04:41:30 +0000234 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
235 LoopItr != LoopItrE; ++LoopItr) {
236 Loop *InnerL = *LoopItr;
237 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
238 assert (InnerAST && "Where is my AST?");
239
240 // What if InnerLoop was modified by other passes ?
241 CurAST->add(*InnerAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000242 }
Devang Patel69730c92007-03-07 04:41:30 +0000243
Chris Lattner6ec05f52002-05-10 22:44:58 +0000244 CurLoop = L;
245
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000246 // Get the preheader block to move instructions into...
247 Preheader = L->getLoopPreheader();
248 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
249
Chris Lattner45d67d62003-02-24 03:52:32 +0000250 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000251 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000252 // subloops.
253 //
Chris Lattneraaaea512003-12-10 06:41:05 +0000254 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
255 E = L->getBlocks().end(); I != E; ++I)
Chris Lattner45d67d62003-02-24 03:52:32 +0000256 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
Chris Lattner28d921d2007-04-14 23:32:02 +0000257 CurAST->add(**I); // Incorporate the specified basic block
Chris Lattner45d67d62003-02-24 03:52:32 +0000258
Chris Lattner6ec05f52002-05-10 22:44:58 +0000259 // 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 //
Chris Lattner64437692002-09-29 21:46:09 +0000264 // 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
Chris Lattner547192d62003-12-19 07:22:45 +0000266 // us to sink instructions in one pass, without iteration. AFter sinking
267 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000268 //
Owen Andersonc24701e2007-04-24 06:40:39 +0000269 SinkRegion(DT->getNode(L->getHeader()));
270 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattner6ec05f52002-05-10 22:44:58 +0000271
Chris Lattner45d67d62003-02-24 03:52:32 +0000272 // 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
Chris Lattner6ec05f52002-05-10 22:44:58 +0000277 // Clear out loops state information for the next iteration
278 CurLoop = 0;
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000279 Preheader = 0;
Devang Patel69730c92007-03-07 04:41:30 +0000280
281 LoopToAliasMap[L] = CurAST;
282 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000283}
284
Chris Lattner547192d62003-12-19 07:22:45 +0000285/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
286/// dominated by the specified block, and that are in the current loop) in
Owen Andersonc24701e2007-04-24 06:40:39 +0000287/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
Chris Lattner547192d62003-12-19 07:22:45 +0000288/// uses before definitions, allowing us to sink a loop body in one pass without
289/// iteration.
290///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000291void LICM::SinkRegion(DomTreeNode *N) {
Owen Andersonc24701e2007-04-24 06:40:39 +0000292 assert(N != 0 && "Null dominator tree node?");
293 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000294
295 // If this subregion is not in the top level loop at all, exit.
296 if (!CurLoop->contains(BB)) return;
297
298 // We are processing blocks in reverse dfo, so process children first...
Devang Patelbdd1aae2007-06-04 00:32:22 +0000299 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner547192d62003-12-19 07:22:45 +0000300 for (unsigned i = 0, e = Children.size(); i != e; ++i)
301 SinkRegion(Children[i]);
302
303 // Only need to process the contents of this block if it is not part of a
304 // subloop (which would already have been processed).
305 if (inSubLoop(BB)) return;
306
Chris Lattner91846012003-12-19 08:18:16 +0000307 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
308 Instruction &I = *--II;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000309
Chris Lattner547192d62003-12-19 07:22:45 +0000310 // Check to see if we can sink this instruction to the exit blocks
311 // of the loop. We can do this if the all users of the instruction are
312 // outside of the loop. In this case, it doesn't even matter if the
313 // operands of the instruction are loop invariant.
314 //
Chris Lattnerfaf77912005-03-25 00:22:36 +0000315 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattner91846012003-12-19 08:18:16 +0000316 ++II;
Chris Lattner547192d62003-12-19 07:22:45 +0000317 sink(I);
Chris Lattner91846012003-12-19 08:18:16 +0000318 }
Chris Lattner547192d62003-12-19 07:22:45 +0000319 }
320}
321
322
Chris Lattner64437692002-09-29 21:46:09 +0000323/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
324/// dominated by the specified block, and that are in the current loop) in depth
Owen Andersonc24701e2007-04-24 06:40:39 +0000325/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner64437692002-09-29 21:46:09 +0000326/// before uses, allowing us to hoist a loop body in one pass without iteration.
327///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000328void LICM::HoistRegion(DomTreeNode *N) {
Owen Andersonc24701e2007-04-24 06:40:39 +0000329 assert(N != 0 && "Null dominator tree node?");
330 BasicBlock *BB = N->getBlock();
Chris Lattner64437692002-09-29 21:46:09 +0000331
Chris Lattner05e86302002-09-29 22:26:07 +0000332 // If this subregion is not in the top level loop at all, exit.
Chris Lattner65c11932003-12-09 19:32:44 +0000333 if (!CurLoop->contains(BB)) return;
Chris Lattner64437692002-09-29 21:46:09 +0000334
Chris Lattneraaaea512003-12-10 06:41:05 +0000335 // Only need to process the contents of this block if it is not part of a
336 // subloop (which would already have been processed).
Chris Lattner65c11932003-12-09 19:32:44 +0000337 if (!inSubLoop(BB))
Chris Lattneraaaea512003-12-10 06:41:05 +0000338 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
339 Instruction &I = *II++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000340
Chris Lattner547192d62003-12-19 07:22:45 +0000341 // Try hoisting the instruction out to the preheader. We can only do this
342 // if all of the operands of the instruction are loop invariant and if it
343 // is safe to hoist the instruction.
344 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000345 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattner547192d62003-12-19 07:22:45 +0000346 isSafeToExecuteUnconditionally(I))
Chris Lattner49771a02006-06-26 19:10:05 +0000347 hoist(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000348 }
Chris Lattner64437692002-09-29 21:46:09 +0000349
Devang Patelbdd1aae2007-06-04 00:32:22 +0000350 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner64437692002-09-29 21:46:09 +0000351 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner42ad6462004-06-19 20:23:35 +0000352 HoistRegion(Children[i]);
Chris Lattner64437692002-09-29 21:46:09 +0000353}
354
Chris Lattneraaaea512003-12-10 06:41:05 +0000355/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
356/// instruction.
357///
358bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattner65c11932003-12-09 19:32:44 +0000359 // Loads have extra constraints we have to verify before we can hoist them.
360 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
361 if (LI->isVolatile())
362 return false; // Don't hoist volatile loads!
363
364 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerb1374092004-11-26 21:20:09 +0000365 unsigned Size = 0;
366 if (LI->getType()->isSized())
367 Size = AA->getTargetData().getTypeSize(LI->getType());
368 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner20cda262004-03-15 04:11:30 +0000369 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
370 // Handle obvious cases efficiently.
371 if (Function *Callee = CI->getCalledFunction()) {
Chris Lattnerb17f3e12004-12-15 07:22:25 +0000372 AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
373 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
Chris Lattner20cda262004-03-15 04:11:30 +0000374 return true;
Chris Lattnerb17f3e12004-12-15 07:22:25 +0000375 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
Chris Lattner20cda262004-03-15 04:11:30 +0000376 // If this call only reads from memory and there are no writes to memory
377 // in the loop, we can hoist or sink the call as appropriate.
378 bool FoundMod = false;
379 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
380 I != E; ++I) {
381 AliasSet &AS = *I;
382 if (!AS.isForwardingAliasSet() && AS.isMod()) {
383 FoundMod = true;
384 break;
385 }
386 }
387 if (!FoundMod) return true;
388 }
389 }
390
391 // FIXME: This should use mod/ref information to see if we can hoist or sink
392 // the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000393
Chris Lattner20cda262004-03-15 04:11:30 +0000394 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000395 }
396
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397 // Otherwise these instructions are hoistable/sinkable
Reid Spencer2341c222007-02-02 02:16:23 +0000398 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Dan Gohman151169d2007-06-05 16:05:55 +0000399 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
400 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
401 isa<ShuffleVectorInst>(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000402}
403
404/// isNotUsedInLoop - Return true if the only users of this instruction are
405/// outside of the loop. If this is true, we can sink the instruction to the
406/// exit blocks of the loop.
407///
408bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattner34399dd2003-12-11 22:23:32 +0000409 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
410 Instruction *User = cast<Instruction>(*UI);
411 if (PHINode *PN = dyn_cast<PHINode>(User)) {
412 // PHI node uses occur in predecessor blocks!
413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
414 if (PN->getIncomingValue(i) == &I)
415 if (CurLoop->contains(PN->getIncomingBlock(i)))
416 return false;
417 } else if (CurLoop->contains(User->getParent())) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000418 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000419 }
420 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000421 return true;
422}
423
424
425/// isLoopInvariantInst - Return true if all operands of this instruction are
426/// loop invariant. We also filter out non-hoistable instructions here just for
427/// efficiency.
428///
429bool LICM::isLoopInvariantInst(Instruction &I) {
430 // The instruction is loop invariant if all of its operands are loop-invariant
431 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattnerfc44a252004-04-18 22:46:08 +0000432 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattneraaaea512003-12-10 06:41:05 +0000433 return false;
434
Chris Lattner65c11932003-12-09 19:32:44 +0000435 // If we got this far, the instruction is loop invariant!
436 return true;
437}
438
Chris Lattneraaaea512003-12-10 06:41:05 +0000439/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattner91846012003-12-19 08:18:16 +0000440/// this function moves it to the exit blocks and patches up SSA form as needed.
441/// This method is guaranteed to remove the original instruction from its
442/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000443///
444void LICM::sink(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000445 DOUT << "LICM sinking instruction: " << I;
Chris Lattneraaaea512003-12-10 06:41:05 +0000446
Chris Lattner35eaa552004-04-18 22:15:13 +0000447 std::vector<BasicBlock*> ExitBlocks;
448 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner55c21132003-12-10 20:43:29 +0000449
450 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000451 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000452 ++NumSunk;
453 Changed = true;
454
Chris Lattneraaaea512003-12-10 06:41:05 +0000455 // The case where there is only a single exit node of this loop is common
456 // enough that we handle it as a special (more efficient) case. It is more
457 // efficient to handle because there are no PHI nodes that need to be placed.
458 if (ExitBlocks.size() == 1) {
459 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
460 // Instruction is not used, just delete it.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000461 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000462 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
463 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000464 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000465 } else {
466 // Move the instruction to the start of the exit block, after any PHI
467 // nodes in it.
Chris Lattner49771a02006-06-26 19:10:05 +0000468 I.removeFromParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000469
Chris Lattneraaaea512003-12-10 06:41:05 +0000470 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
471 while (isa<PHINode>(InsertPt)) ++InsertPt;
472 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
473 }
474 } else if (ExitBlocks.size() == 0) {
475 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000476 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000477 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
478 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000479 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000480 } else {
481 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
482 // do all of the hard work of inserting PHI nodes as necessary. We convert
483 // the value into a stack object to get it to do this.
484
485 // Firstly, we create a stack object to hold the value...
Chris Lattner50eb7712004-07-27 07:38:32 +0000486 AllocaInst *AI = 0;
Chris Lattneraaaea512003-12-10 06:41:05 +0000487
Devang Patelac54a622007-06-01 22:15:31 +0000488 if (I.getType() != Type::VoidTy) {
Chris Lattner50eb7712004-07-27 07:38:32 +0000489 AI = new AllocaInst(I.getType(), 0, I.getName(),
Dan Gohmandcb291f2007-03-22 16:38:57 +0000490 I.getParent()->getParent()->getEntryBlock().begin());
Devang Patelac54a622007-06-01 22:15:31 +0000491 CurAST->add(AI);
492 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000493
Chris Lattneraaaea512003-12-10 06:41:05 +0000494 // Secondly, insert load instructions for each use of the instruction
495 // outside of the loop.
496 while (!I.use_empty()) {
497 Instruction *U = cast<Instruction>(I.use_back());
498
499 // If the user is a PHI Node, we actually have to insert load instructions
500 // in all predecessor blocks, not in the PHI block itself!
501 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
502 // Only insert into each predecessor once, so that we don't have
503 // different incoming values from the same block!
504 std::map<BasicBlock*, Value*> InsertedBlocks;
505 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
506 if (UPN->getIncomingValue(i) == &I) {
507 BasicBlock *Pred = UPN->getIncomingBlock(i);
508 Value *&PredVal = InsertedBlocks[Pred];
509 if (!PredVal) {
510 // Insert a new load instruction right before the terminator in
511 // the predecessor block.
512 PredVal = new LoadInst(AI, "", Pred->getTerminator());
Devang Patelac54a622007-06-01 22:15:31 +0000513 CurAST->add(cast<LoadInst>(PredVal));
Chris Lattneraaaea512003-12-10 06:41:05 +0000514 }
515
516 UPN->setIncomingValue(i, PredVal);
517 }
518
519 } else {
520 LoadInst *L = new LoadInst(AI, "", U);
521 U->replaceUsesOfWith(&I, L);
Devang Patelac54a622007-06-01 22:15:31 +0000522 CurAST->add(L);
Chris Lattneraaaea512003-12-10 06:41:05 +0000523 }
524 }
525
526 // Thirdly, insert a copy of the instruction in each exit block of the loop
527 // that is dominated by the instruction, storing the result into the memory
528 // location. Be careful not to insert the instruction into any particular
529 // basic block more than once.
530 std::set<BasicBlock*> InsertedBlocks;
531 BasicBlock *InstOrigBB = I.getParent();
532
533 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
534 BasicBlock *ExitBlock = ExitBlocks[i];
535
536 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000537 // If we haven't already processed this exit block, do so now.
Chris Lattner63643142003-12-10 16:58:24 +0000538 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000539 // Insert the code after the last PHI node...
540 BasicBlock::iterator InsertPt = ExitBlock->begin();
541 while (isa<PHINode>(InsertPt)) ++InsertPt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000542
Chris Lattneraaaea512003-12-10 06:41:05 +0000543 // If this is the first exit block processed, just move the original
544 // instruction, otherwise clone the original instruction and insert
545 // the copy.
546 Instruction *New;
Chris Lattner6281fd32003-12-10 22:35:56 +0000547 if (InsertedBlocks.size() == 1) {
Chris Lattner49771a02006-06-26 19:10:05 +0000548 I.removeFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000549 ExitBlock->getInstList().insert(InsertPt, &I);
550 New = &I;
551 } else {
552 New = I.clone();
Chris Lattnerfaf77912005-03-25 00:22:36 +0000553 CurAST->copyValue(&I, New);
Chris Lattner50eb7712004-07-27 07:38:32 +0000554 if (!I.getName().empty())
555 New->setName(I.getName()+".le");
Chris Lattneraaaea512003-12-10 06:41:05 +0000556 ExitBlock->getInstList().insert(InsertPt, New);
557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattneraaaea512003-12-10 06:41:05 +0000559 // Now that we have inserted the instruction, store it into the alloca
Chris Lattner50eb7712004-07-27 07:38:32 +0000560 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattneraaaea512003-12-10 06:41:05 +0000561 }
562 }
563 }
Chris Lattner91846012003-12-19 08:18:16 +0000564
565 // If the instruction doesn't dominate any exit blocks, it must be dead.
566 if (InsertedBlocks.empty()) {
Chris Lattner289ba2a2004-05-23 21:20:19 +0000567 CurAST->deleteValue(&I);
Chris Lattner49771a02006-06-26 19:10:05 +0000568 I.eraseFromParent();
Chris Lattner91846012003-12-19 08:18:16 +0000569 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000570
Chris Lattneraaaea512003-12-10 06:41:05 +0000571 // Finally, promote the fine value to SSA form.
Chris Lattner50eb7712004-07-27 07:38:32 +0000572 if (AI) {
573 std::vector<AllocaInst*> Allocas;
574 Allocas.push_back(AI);
Devang Patelfc7fdef2007-06-07 21:57:03 +0000575 PromoteMemToReg(Allocas, *DT, *DF, CurAST);
Chris Lattner50eb7712004-07-27 07:38:32 +0000576 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000577 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000578}
Chris Lattner64437692002-09-29 21:46:09 +0000579
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000580/// hoist - When an instruction is found to only use loop invariant operands
581/// that is safe to hoist, this instruction is called to do the dirty work.
582///
Chris Lattneraaaea512003-12-10 06:41:05 +0000583void LICM::hoist(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000584 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
Chris Lattner65c11932003-12-09 19:32:44 +0000585
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000586 // Remove the instruction from its current basic block... but don't delete the
587 // instruction.
Chris Lattner49771a02006-06-26 19:10:05 +0000588 I.removeFromParent();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000589
Chris Lattner718b2212002-09-26 16:38:03 +0000590 // Insert the new node in Preheader, before the terminator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000591 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000592
Chris Lattneraaaea512003-12-10 06:41:05 +0000593 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000594 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000595 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000596 Changed = true;
597}
598
Chris Lattneraaaea512003-12-10 06:41:05 +0000599/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
600/// not a trapping instruction or if it is a trapping instruction and is
601/// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000602///
Chris Lattneraaaea512003-12-10 06:41:05 +0000603bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000604 // If it is not a trapping instruction, it is always safe to hoist.
605 if (!Inst.isTrapping()) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000606
Chris Lattnerc0517682003-12-09 17:18:00 +0000607 // Otherwise we have to check to make sure that the instruction dominates all
608 // of the exit blocks. If it doesn't, then there is a path out of the loop
609 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000610
Chris Lattnerc0517682003-12-09 17:18:00 +0000611 // If the instruction is in the header block for the loop (which is very
612 // common), it is always guaranteed to dominate the exit blocks. Since this
613 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000614 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattnerc0517682003-12-09 17:18:00 +0000615 return true;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000616
Chris Lattner6e455602004-11-29 21:26:12 +0000617 // It's always safe to load from a global or alloca.
618 if (isa<LoadInst>(Inst))
619 if (isa<AllocationInst>(Inst.getOperand(0)) ||
620 isa<GlobalVariable>(Inst.getOperand(0)))
621 return true;
622
Chris Lattnerc0517682003-12-09 17:18:00 +0000623 // Get the exit blocks for the current loop.
Chris Lattner35eaa552004-04-18 22:15:13 +0000624 std::vector<BasicBlock*> ExitBlocks;
625 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000626
Owen Andersonc24701e2007-04-24 06:40:39 +0000627 // For each exit block, get the DT node and walk up the DT until the
Chris Lattnerc0517682003-12-09 17:18:00 +0000628 // instruction's basic block is found or we exit the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000629 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
630 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
631 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000632
Tanya Lattner57c03df2003-08-05 18:45:46 +0000633 return true;
634}
635
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000636
Chris Lattner45d67d62003-02-24 03:52:32 +0000637/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
638/// stores out of the loop and moving loads to before the loop. We do this by
639/// looping over the stores in the loop, looking for stores to Must pointers
640/// which are loop invariant. We promote these memory locations to use allocas
641/// instead. These allocas can easily be raised to register values by the
642/// PromoteMem2Reg functionality.
643///
644void LICM::PromoteValuesInLoop() {
645 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner216c7b82003-09-10 05:29:43 +0000646 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner45d67d62003-02-24 03:52:32 +0000647 // pointer.
648 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
649 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
650
Chris Lattnera3465782004-09-15 01:04:07 +0000651 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
652 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner45d67d62003-02-24 03:52:32 +0000653
654 Changed = true;
655 NumPromoted += PromotedValues.size();
656
Chris Lattnera3465782004-09-15 01:04:07 +0000657 std::vector<Value*> PointerValueNumbers;
658
Chris Lattner45d67d62003-02-24 03:52:32 +0000659 // Emit a copy from the value into the alloca'd value in the loop preheader
660 TerminatorInst *LoopPredInst = Preheader->getTerminator();
661 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000662 Value *Ptr = PromotedValues[i].second;
663
664 // If we are promoting a pointer value, update alias information for the
665 // inserted load.
666 Value *LoadValue = 0;
667 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
668 // Locate a load or store through the pointer, and assign the same value
669 // to LI as we are loading or storing. Since we know that the value is
670 // stored in this loop, this will always succeed.
671 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
672 UI != E; ++UI)
673 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
674 LoadValue = LI;
675 break;
676 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerf11216d2004-09-15 02:34:40 +0000677 if (SI->getOperand(1) == Ptr) {
Chris Lattnera3465782004-09-15 01:04:07 +0000678 LoadValue = SI->getOperand(0);
679 break;
680 }
681 }
682 assert(LoadValue && "No store through the pointer found!");
683 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
684 }
685
686 // Load from the memory we are promoting.
687 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
688
689 if (LoadValue) CurAST->copyValue(LoadValue, LI);
690
691 // Store into the temporary alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000692 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
693 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000694
Chris Lattner45d67d62003-02-24 03:52:32 +0000695 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattneredda1af2003-12-10 15:56:24 +0000696 // uses of the allocas in question.
Chris Lattner45d67d62003-02-24 03:52:32 +0000697 //
698 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
699 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
700 E = LoopBBs.end(); I != E; ++I) {
701 // Rewrite all loads and stores in the block of the pointer...
702 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
703 II != E; ++II) {
Chris Lattner889f6202003-04-23 16:37:45 +0000704 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000705 std::map<Value*, AllocaInst*>::iterator
706 I = ValueToAllocaMap.find(L->getOperand(0));
707 if (I != ValueToAllocaMap.end())
708 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattner889f6202003-04-23 16:37:45 +0000709 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000710 std::map<Value*, AllocaInst*>::iterator
711 I = ValueToAllocaMap.find(S->getOperand(1));
712 if (I != ValueToAllocaMap.end())
713 S->setOperand(1, I->second); // Rewrite store instruction...
714 }
715 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000716 }
717
Chris Lattneredda1af2003-12-10 15:56:24 +0000718 // Now that the body of the loop uses the allocas instead of the original
719 // memory locations, insert code to copy the alloca value back into the
720 // original memory location on all exits from the loop. Note that we only
721 // want to insert one copy of the code in each exit block, though the loop may
722 // exit to the same block more than once.
723 //
724 std::set<BasicBlock*> ProcessedBlocks;
725
Chris Lattner35eaa552004-04-18 22:15:13 +0000726 std::vector<BasicBlock*> ExitBlocks;
727 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattneredda1af2003-12-10 15:56:24 +0000728 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner48b4b852003-12-10 16:57:24 +0000729 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
Chris Lattnera3465782004-09-15 01:04:07 +0000730 // Copy all of the allocas into their memory locations.
Chris Lattneredda1af2003-12-10 15:56:24 +0000731 BasicBlock::iterator BI = ExitBlocks[i]->begin();
732 while (isa<PHINode>(*BI))
Chris Lattnera3465782004-09-15 01:04:07 +0000733 ++BI; // Skip over all of the phi nodes in the block.
Chris Lattneredda1af2003-12-10 15:56:24 +0000734 Instruction *InsertPos = BI;
Chris Lattnera3465782004-09-15 01:04:07 +0000735 unsigned PVN = 0;
Chris Lattneredda1af2003-12-10 15:56:24 +0000736 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000737 // Load from the alloca.
Chris Lattneredda1af2003-12-10 15:56:24 +0000738 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnera3465782004-09-15 01:04:07 +0000739
740 // If this is a pointer type, update alias info appropriately.
741 if (isa<PointerType>(LI->getType()))
742 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
743
744 // Store into the memory we promoted.
Chris Lattneredda1af2003-12-10 15:56:24 +0000745 new StoreInst(LI, PromotedValues[i].second, InsertPos);
746 }
747 }
748
Chris Lattner45d67d62003-02-24 03:52:32 +0000749 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnera3465782004-09-15 01:04:07 +0000750 // all of the new allocas we just created into real SSA registers.
Chris Lattner45d67d62003-02-24 03:52:32 +0000751 //
752 std::vector<AllocaInst*> PromotedAllocas;
753 PromotedAllocas.reserve(PromotedValues.size());
754 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
755 PromotedAllocas.push_back(PromotedValues[i].first);
Devang Patelfc7fdef2007-06-07 21:57:03 +0000756 PromoteMemToReg(PromotedAllocas, *DT, *DF, CurAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000757}
758
Chris Lattnera3465782004-09-15 01:04:07 +0000759/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Chris Lattner45d67d62003-02-24 03:52:32 +0000760/// pointers, which are not loaded and stored through may aliases. If these are
761/// found, create an alloca for the value, add it to the PromotedValues list,
Chris Lattnera3465782004-09-15 01:04:07 +0000762/// and keep track of the mapping from value to alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000763///
Chris Lattnera3465782004-09-15 01:04:07 +0000764void LICM::FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000765 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
766 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
767 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
768
Chris Lattnera3465782004-09-15 01:04:07 +0000769 // Loop over all of the alias sets in the tracker object.
Chris Lattner0592bb72003-03-03 23:32:45 +0000770 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
771 I != E; ++I) {
772 AliasSet &AS = *I;
773 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnera3465782004-09-15 01:04:07 +0000774 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner20cda262004-03-15 04:11:30 +0000775 // volatile loads or stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000776 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
Chris Lattnerfc44a252004-04-18 22:46:08 +0000777 !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000778 assert(AS.begin() != AS.end() &&
779 "Must alias set should have at least one pointer element in it!");
780 Value *V = AS.begin()->first;
Chris Lattner45d67d62003-02-24 03:52:32 +0000781
Chris Lattner0592bb72003-03-03 23:32:45 +0000782 // Check that all of the pointers in the alias set have the same type. We
783 // cannot (yet) promote a memory location that is loaded and stored in
784 // different sizes.
785 bool PointerOk = true;
786 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
787 if (V->getType() != I->first->getType()) {
788 PointerOk = false;
789 break;
Chris Lattner45d67d62003-02-24 03:52:32 +0000790 }
Chris Lattner0592bb72003-03-03 23:32:45 +0000791
792 if (PointerOk) {
793 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
794 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
795 PromotedValues.push_back(std::make_pair(AI, V));
Chris Lattnera3465782004-09-15 01:04:07 +0000796
797 // Update the AST and alias analysis.
798 CurAST->copyValue(V, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000799
Chris Lattner0592bb72003-03-03 23:32:45 +0000800 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
801 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000802
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000803 DOUT << "LICM: Promoting value: " << *V << "\n";
Chris Lattner45d67d62003-02-24 03:52:32 +0000804 }
805 }
806 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000807}
Devang Patelb98a0972007-07-31 08:01:41 +0000808
809/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
810void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
811 AliasSetTracker *AST = LoopToAliasMap[L];
812 if (!AST)
813 return;
814
815 AST->copyValue(From, To);
816}
817
818/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
819/// set.
820void LICM::deleteAnalysisValue(Value *V, Loop *L) {
821 AliasSetTracker *AST = LoopToAliasMap[L];
822 if (!AST)
823 return;
824
825 AST->deleteValue(V);
826}