blob: 104c8739c0e36c8d332215e6a2fbb22e92f4592d [file] [log] [blame]
Chris Lattnere0e734e2002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere0e734e2002-05-10 22:44:58 +00009//
Chris Lattner92094b42003-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 Lattnere4365b22003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattner92094b42003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner2e6e7412003-02-24 03:52:32 +000017//
Chris Lattner2741c972004-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 Lattner2e6e7412003-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 Lattnere0e734e2002-05-10 22:44:58 +000031//
Chris Lattnere0e734e2002-05-10 22:44:58 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1f309c12005-03-23 21:00:12 +000034#define DEBUG_TYPE "licm"
Chris Lattnere0e734e2002-05-10 22:44:58 +000035#include "llvm/Transforms/Scalar.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Constants.h"
Chris Lattner2741c972004-05-23 21:20:19 +000037#include "llvm/DerivedTypes.h"
Torok Edwin9289ae82009-10-11 19:15:54 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner2741c972004-05-23 21:20:19 +000039#include "llvm/Instructions.h"
40#include "llvm/Target/TargetData.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000041#include "llvm/Analysis/LoopInfo.h"
Devang Patel54959d62007-03-07 04:41:30 +000042#include "llvm/Analysis/LoopPass.h"
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000043#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0252e492003-03-03 23:32:45 +000044#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner952eaee2002-09-29 21:46:09 +000045#include "llvm/Analysis/Dominators.h"
Devang Patel96b651c2007-07-30 20:19:59 +000046#include "llvm/Analysis/ScalarEvolution.h"
Chris Lattner2741c972004-05-23 21:20:19 +000047#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000048#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000050#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/Support/Debug.h"
52#include "llvm/ADT/Statistic.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000053#include <algorithm>
Chris Lattner92094b42003-12-09 17:18:00 +000054using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumSunk , "Number of instructions sunk out of loop");
57STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
58STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
59STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
60STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
61
Dan Gohman844731a2008-05-13 00:00:25 +000062static cl::opt<bool>
63DisablePromotion("disable-licm-promotion", cl::Hidden,
64 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner2e6e7412003-02-24 03:52:32 +000065
Chris Lattnerd7168dd2009-03-09 05:11:09 +000066// This feature is currently disabled by default because CodeGen is not yet
67// capable of rematerializing these constants in PIC mode, so it can lead to
68// degraded performance. Compile test/CodeGen/X86/remat-constant.ll with
Dan Gohman3eee6542008-07-24 23:57:25 +000069// -relocation-model=pic to see an example of this.
70static cl::opt<bool>
71EnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden,
72 cl::desc("Enable hoisting/sinking of constant "
73 "global variables"));
74
Dan Gohman844731a2008-05-13 00:00:25 +000075namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000076 struct LICM : public LoopPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000077 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000078 LICM() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000079
Devang Patel54959d62007-03-07 04:41:30 +000080 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnere0e734e2002-05-10 22:44:58 +000081
Chris Lattner94170592002-09-26 16:52:07 +000082 /// This transformation requires natural loop information & requires that
83 /// loop preheaders be inserted into the CFG...
84 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +000085 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000086 AU.setPreservesCFG();
Chris Lattner98bf4362003-10-12 21:52:28 +000087 AU.addRequiredID(LoopSimplifyID);
Chris Lattner5f0eb8d2002-08-08 19:01:30 +000088 AU.addRequired<LoopInfo>();
Owen Anderson3a2b58f2007-04-24 06:40:39 +000089 AU.addRequired<DominatorTree>();
Chris Lattner0252e492003-03-03 23:32:45 +000090 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000091 AU.addRequired<AliasAnalysis>();
Devang Patel96b651c2007-07-30 20:19:59 +000092 AU.addPreserved<ScalarEvolution>();
93 AU.addPreserved<DominanceFrontier>();
Dan Gohman5c89b522009-09-08 15:45:00 +000094 AU.addPreservedID(LoopSimplifyID);
Chris Lattnere0e734e2002-05-10 22:44:58 +000095 }
96
Dan Gohman747603e2007-04-17 18:21:36 +000097 bool doFinalization() {
Anton Korobeynikovfd94dd52007-11-25 23:52:02 +000098 // Free the values stored in the map
99 for (std::map<Loop *, AliasSetTracker *>::iterator
100 I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
101 delete I->second;
102
Devang Patel54959d62007-03-07 04:41:30 +0000103 LoopToAliasMap.clear();
104 return false;
105 }
106
Chris Lattnere0e734e2002-05-10 22:44:58 +0000107 private:
Chris Lattner92094b42003-12-09 17:18:00 +0000108 // Various analyses that we use...
Chris Lattner2e6e7412003-02-24 03:52:32 +0000109 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattner92094b42003-12-09 17:18:00 +0000110 LoopInfo *LI; // Current LoopInfo
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000111 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattner43f820d2003-10-05 21:20:13 +0000112 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattner92094b42003-12-09 17:18:00 +0000113
114 // State that is updated as we process loops
Chris Lattner2e6e7412003-02-24 03:52:32 +0000115 bool Changed; // Set to true when we change anything.
116 BasicBlock *Preheader; // The preheader block of the current loop...
117 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0252e492003-03-03 23:32:45 +0000118 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel54959d62007-03-07 04:41:30 +0000119 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000120
Devang Patel91d22c82007-07-31 08:01:41 +0000121 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
122 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
123
124 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
125 /// set.
126 void deleteAnalysisValue(Value *V, Loop *L);
127
Chris Lattnere4365b22003-12-19 07:22:45 +0000128 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
129 /// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000130 /// reverse depth first order w.r.t the DominatorTree. This allows us to
Chris Lattnere4365b22003-12-19 07:22:45 +0000131 /// visit uses before definitions, allowing us to sink a loop body in one
132 /// pass without iteration.
133 ///
Devang Patel26042422007-06-04 00:32:22 +0000134 void SinkRegion(DomTreeNode *N);
Chris Lattnere4365b22003-12-19 07:22:45 +0000135
Chris Lattner952eaee2002-09-29 21:46:09 +0000136 /// HoistRegion - Walk the specified region of the CFG (defined by all
137 /// blocks dominated by the specified block, and that are in the current
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000138 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000139 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner952eaee2002-09-29 21:46:09 +0000140 /// pass without iteration.
141 ///
Devang Patel26042422007-06-04 00:32:22 +0000142 void HoistRegion(DomTreeNode *N);
Chris Lattner952eaee2002-09-29 21:46:09 +0000143
Chris Lattnerb4613732002-09-29 22:26:07 +0000144 /// inSubLoop - Little predicate that returns true if the specified basic
145 /// block is in a subloop of the current one, not the current one itself.
Chris Lattner94170592002-09-26 16:52:07 +0000146 ///
Chris Lattnerb4613732002-09-29 22:26:07 +0000147 bool inSubLoop(BasicBlock *BB) {
148 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner329c1c62004-01-08 00:09:44 +0000149 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
150 if ((*I)->contains(BB))
Chris Lattnerb4613732002-09-29 22:26:07 +0000151 return true; // A subloop actually contains this block!
152 return false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000153 }
154
Chris Lattnera2706512003-12-10 06:41:05 +0000155 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
156 /// specified exit block of the loop is dominated by the specified block
157 /// that is in the body of the loop. We use these constraints to
158 /// dramatically limit the amount of the dominator tree that needs to be
159 /// searched.
160 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
161 BasicBlock *BlockInLoop) const {
162 // If the block in the loop is the loop header, it must be dominated!
163 BasicBlock *LoopHeader = CurLoop->getHeader();
164 if (BlockInLoop == LoopHeader)
165 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000166
Devang Patel26042422007-06-04 00:32:22 +0000167 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
168 DomTreeNode *IDom = DT->getNode(ExitBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000169
Chris Lattnera2706512003-12-10 06:41:05 +0000170 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner2741c972004-05-23 21:20:19 +0000171 // least_ its immediate dominator.
Chris Lattnera2706512003-12-10 06:41:05 +0000172 do {
173 // Get next Immediate Dominator.
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000174 IDom = IDom->getIDom();
Misha Brukmanfd939082005-04-21 23:48:37 +0000175
Chris Lattnera2706512003-12-10 06:41:05 +0000176 // If we have got to the header of the loop, then the instructions block
177 // did not dominate the exit node, so we can't hoist it.
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000178 if (IDom->getBlock() == LoopHeader)
Chris Lattnera2706512003-12-10 06:41:05 +0000179 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000180
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000181 } while (IDom != BlockInLoopNode);
Chris Lattnera2706512003-12-10 06:41:05 +0000182
183 return true;
184 }
185
186 /// sink - When an instruction is found to only be used outside of the loop,
187 /// this function moves it to the exit blocks and patches up SSA form as
188 /// needed.
189 ///
190 void sink(Instruction &I);
191
Chris Lattner94170592002-09-26 16:52:07 +0000192 /// hoist - When an instruction is found to only use loop invariant operands
193 /// that is safe to hoist, this instruction is called to do the dirty work.
194 ///
Chris Lattner7e708292002-06-25 16:13:24 +0000195 void hoist(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000196
Chris Lattnera2706512003-12-10 06:41:05 +0000197 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
198 /// is not a trapping instruction or if it is a trapping instruction and is
199 /// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000200 ///
Chris Lattnera2706512003-12-10 06:41:05 +0000201 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner9966c032003-08-05 18:45:46 +0000202
Chris Lattner94170592002-09-26 16:52:07 +0000203 /// pointerInvalidatedByLoop - Return true if the body of this loop may
204 /// store into the memory location pointed to by V.
Misha Brukmanfd939082005-04-21 23:48:37 +0000205 ///
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000206 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0252e492003-03-03 23:32:45 +0000207 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000208 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000209 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000210
Chris Lattnera2706512003-12-10 06:41:05 +0000211 bool canSinkOrHoistInst(Instruction &I);
212 bool isLoopInvariantInst(Instruction &I);
213 bool isNotUsedInLoop(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000214
Chris Lattner2e6e7412003-02-24 03:52:32 +0000215 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
216 /// to scalars as we can.
217 ///
218 void PromoteValuesInLoop();
219
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000220 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman352361b2003-09-11 15:32:37 +0000221 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000222 /// If these are found, create an alloca for the value, add it to the
223 /// PromotedValues list, and keep track of the mapping from value to
224 /// alloca...
225 ///
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000226 void FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000227 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
228 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000229 };
230}
231
Dan Gohman844731a2008-05-13 00:00:25 +0000232char LICM::ID = 0;
233static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
234
Daniel Dunbar394f0442008-10-22 23:32:42 +0000235Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000236
Devang Patel8d246f02007-07-31 16:52:25 +0000237/// Hoist expressions out of the specified loop. Note, alias info for inner
238/// loop is not preserved so it is not a good idea to run LICM multiple
239/// times on one loop.
Chris Lattner94170592002-09-26 16:52:07 +0000240///
Devang Patel54959d62007-03-07 04:41:30 +0000241bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000242 Changed = false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000243
Chris Lattner2e6e7412003-02-24 03:52:32 +0000244 // Get our Loop and Alias Analysis information...
245 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000246 AA = &getAnalysis<AliasAnalysis>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000247 DF = &getAnalysis<DominanceFrontier>();
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000248 DT = &getAnalysis<DominatorTree>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000249
Devang Patel54959d62007-03-07 04:41:30 +0000250 CurAST = new AliasSetTracker(*AA);
Devang Patelf38ac5d2007-05-30 15:29:37 +0000251 // Collect Alias info from subloops
Devang Patel54959d62007-03-07 04:41:30 +0000252 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
253 LoopItr != LoopItrE; ++LoopItr) {
254 Loop *InnerL = *LoopItr;
255 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
256 assert (InnerAST && "Where is my AST?");
257
258 // What if InnerLoop was modified by other passes ?
259 CurAST->add(*InnerAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000260 }
Devang Patel54959d62007-03-07 04:41:30 +0000261
Chris Lattnere0e734e2002-05-10 22:44:58 +0000262 CurLoop = L;
263
Chris Lattner99a57212002-09-26 19:40:25 +0000264 // Get the preheader block to move instructions into...
265 Preheader = L->getLoopPreheader();
Chris Lattner99a57212002-09-26 19:40:25 +0000266
Chris Lattner2e6e7412003-02-24 03:52:32 +0000267 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0252e492003-03-03 23:32:45 +0000268 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner2e6e7412003-02-24 03:52:32 +0000269 // subloops.
270 //
Dan Gohman9b787632008-06-22 20:18:58 +0000271 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
272 I != E; ++I) {
273 BasicBlock *BB = *I;
274 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops...
275 CurAST->add(*BB); // Incorporate the specified basic block
276 }
Chris Lattner2e6e7412003-02-24 03:52:32 +0000277
Chris Lattnere0e734e2002-05-10 22:44:58 +0000278 // We want to visit all of the instructions in this loop... that are not parts
279 // of our subloops (they have already had their invariants hoisted out of
280 // their loop, into this loop, so there is no need to process the BODIES of
281 // the subloops).
282 //
Chris Lattner952eaee2002-09-29 21:46:09 +0000283 // Traverse the body of the loop in depth first order on the dominator tree so
284 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckyaf5cbc82007-08-18 15:08:56 +0000285 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattnere4365b22003-12-19 07:22:45 +0000286 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner952eaee2002-09-29 21:46:09 +0000287 //
Dan Gohman03e896b2009-11-05 21:11:53 +0000288 if (L->hasDedicatedExits())
289 SinkRegion(DT->getNode(L->getHeader()));
290 if (Preheader)
291 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattnere0e734e2002-05-10 22:44:58 +0000292
Chris Lattner2e6e7412003-02-24 03:52:32 +0000293 // Now that all loop invariants have been removed from the loop, promote any
294 // memory references to scalars that we can...
Dan Gohman03e896b2009-11-05 21:11:53 +0000295 if (!DisablePromotion && Preheader && L->hasDedicatedExits())
Chris Lattner2e6e7412003-02-24 03:52:32 +0000296 PromoteValuesInLoop();
297
Chris Lattnere0e734e2002-05-10 22:44:58 +0000298 // Clear out loops state information for the next iteration
299 CurLoop = 0;
Chris Lattner99a57212002-09-26 19:40:25 +0000300 Preheader = 0;
Devang Patel54959d62007-03-07 04:41:30 +0000301
302 LoopToAliasMap[L] = CurAST;
303 return Changed;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000304}
305
Chris Lattnere4365b22003-12-19 07:22:45 +0000306/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
307/// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000308/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
Chris Lattnere4365b22003-12-19 07:22:45 +0000309/// uses before definitions, allowing us to sink a loop body in one pass without
310/// iteration.
311///
Devang Patel26042422007-06-04 00:32:22 +0000312void LICM::SinkRegion(DomTreeNode *N) {
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000313 assert(N != 0 && "Null dominator tree node?");
314 BasicBlock *BB = N->getBlock();
Chris Lattnere4365b22003-12-19 07:22:45 +0000315
316 // If this subregion is not in the top level loop at all, exit.
317 if (!CurLoop->contains(BB)) return;
318
319 // We are processing blocks in reverse dfo, so process children first...
Devang Patel26042422007-06-04 00:32:22 +0000320 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattnere4365b22003-12-19 07:22:45 +0000321 for (unsigned i = 0, e = Children.size(); i != e; ++i)
322 SinkRegion(Children[i]);
323
324 // Only need to process the contents of this block if it is not part of a
325 // subloop (which would already have been processed).
326 if (inSubLoop(BB)) return;
327
Chris Lattnera3df8a92003-12-19 08:18:16 +0000328 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
329 Instruction &I = *--II;
Misha Brukmanfd939082005-04-21 23:48:37 +0000330
Chris Lattnere4365b22003-12-19 07:22:45 +0000331 // Check to see if we can sink this instruction to the exit blocks
332 // of the loop. We can do this if the all users of the instruction are
333 // outside of the loop. In this case, it doesn't even matter if the
334 // operands of the instruction are loop invariant.
335 //
Chris Lattner70ac2dc2005-03-25 00:22:36 +0000336 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattnera3df8a92003-12-19 08:18:16 +0000337 ++II;
Chris Lattnere4365b22003-12-19 07:22:45 +0000338 sink(I);
Chris Lattnera3df8a92003-12-19 08:18:16 +0000339 }
Chris Lattnere4365b22003-12-19 07:22:45 +0000340 }
341}
342
Chris Lattner952eaee2002-09-29 21:46:09 +0000343/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
344/// dominated by the specified block, and that are in the current loop) in depth
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000345/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner952eaee2002-09-29 21:46:09 +0000346/// before uses, allowing us to hoist a loop body in one pass without iteration.
347///
Devang Patel26042422007-06-04 00:32:22 +0000348void LICM::HoistRegion(DomTreeNode *N) {
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000349 assert(N != 0 && "Null dominator tree node?");
350 BasicBlock *BB = N->getBlock();
Chris Lattner952eaee2002-09-29 21:46:09 +0000351
Chris Lattnerb4613732002-09-29 22:26:07 +0000352 // If this subregion is not in the top level loop at all, exit.
Chris Lattnered6dfc22003-12-09 19:32:44 +0000353 if (!CurLoop->contains(BB)) return;
Chris Lattner952eaee2002-09-29 21:46:09 +0000354
Chris Lattnera2706512003-12-10 06:41:05 +0000355 // Only need to process the contents of this block if it is not part of a
356 // subloop (which would already have been processed).
Chris Lattnered6dfc22003-12-09 19:32:44 +0000357 if (!inSubLoop(BB))
Chris Lattnera2706512003-12-10 06:41:05 +0000358 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
359 Instruction &I = *II++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000360
Chris Lattnere4365b22003-12-19 07:22:45 +0000361 // Try hoisting the instruction out to the preheader. We can only do this
362 // if all of the operands of the instruction are loop invariant and if it
363 // is safe to hoist the instruction.
364 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000365 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattnere4365b22003-12-19 07:22:45 +0000366 isSafeToExecuteUnconditionally(I))
Chris Lattner3c80a512006-06-26 19:10:05 +0000367 hoist(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000368 }
Chris Lattner952eaee2002-09-29 21:46:09 +0000369
Devang Patel26042422007-06-04 00:32:22 +0000370 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner952eaee2002-09-29 21:46:09 +0000371 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner56b7ee22004-06-19 20:23:35 +0000372 HoistRegion(Children[i]);
Chris Lattner952eaee2002-09-29 21:46:09 +0000373}
374
Chris Lattnera2706512003-12-10 06:41:05 +0000375/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
376/// instruction.
377///
378bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattnered6dfc22003-12-09 19:32:44 +0000379 // Loads have extra constraints we have to verify before we can hoist them.
380 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
381 if (LI->isVolatile())
382 return false; // Don't hoist volatile loads!
383
Chris Lattner967948b2008-07-23 05:06:28 +0000384 // Loads from constant memory are always safe to move, even if they end up
385 // in the same alias set as something that ends up being modified.
Dan Gohman3eee6542008-07-24 23:57:25 +0000386 if (EnableLICMConstantMotion &&
387 AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner967948b2008-07-23 05:06:28 +0000388 return true;
389
Chris Lattnered6dfc22003-12-09 19:32:44 +0000390 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000391 unsigned Size = 0;
392 if (LI->getType()->isSized())
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000393 Size = AA->getTypeStoreSize(LI->getType());
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000394 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner118dd0c2004-03-15 04:11:30 +0000395 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Torok Edwin9289ae82009-10-11 19:15:54 +0000396 if (isa<DbgStopPointInst>(CI)) {
397 // Don't hoist/sink dbgstoppoints, we handle them separately
398 return false;
399 }
Chris Lattner118dd0c2004-03-15 04:11:30 +0000400 // Handle obvious cases efficiently.
Duncan Sandsdff67102007-12-01 07:51:45 +0000401 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
402 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
403 return true;
404 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
405 // If this call only reads from memory and there are no writes to memory
406 // in the loop, we can hoist or sink the call as appropriate.
407 bool FoundMod = false;
408 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
409 I != E; ++I) {
410 AliasSet &AS = *I;
411 if (!AS.isForwardingAliasSet() && AS.isMod()) {
412 FoundMod = true;
413 break;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000414 }
Chris Lattner118dd0c2004-03-15 04:11:30 +0000415 }
Duncan Sandsdff67102007-12-01 07:51:45 +0000416 if (!FoundMod) return true;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000417 }
418
419 // FIXME: This should use mod/ref information to see if we can hoist or sink
420 // the call.
Misha Brukmanfd939082005-04-21 23:48:37 +0000421
Chris Lattner118dd0c2004-03-15 04:11:30 +0000422 return false;
Chris Lattnered6dfc22003-12-09 19:32:44 +0000423 }
424
Reid Spencer3da59db2006-11-27 01:05:10 +0000425 // Otherwise these instructions are hoistable/sinkable
Reid Spencer832254e2007-02-02 02:16:23 +0000426 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Dan Gohmand8af90c2007-06-05 16:05:55 +0000427 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
428 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
429 isa<ShuffleVectorInst>(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000430}
431
432/// isNotUsedInLoop - Return true if the only users of this instruction are
433/// outside of the loop. If this is true, we can sink the instruction to the
434/// exit blocks of the loop.
435///
436bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattnerea9403f2003-12-11 22:23:32 +0000437 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
438 Instruction *User = cast<Instruction>(*UI);
439 if (PHINode *PN = dyn_cast<PHINode>(User)) {
440 // PHI node uses occur in predecessor blocks!
441 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
442 if (PN->getIncomingValue(i) == &I)
443 if (CurLoop->contains(PN->getIncomingBlock(i)))
444 return false;
445 } else if (CurLoop->contains(User->getParent())) {
Chris Lattnera2706512003-12-10 06:41:05 +0000446 return false;
Chris Lattnerea9403f2003-12-11 22:23:32 +0000447 }
448 }
Chris Lattnera2706512003-12-10 06:41:05 +0000449 return true;
450}
451
452
453/// isLoopInvariantInst - Return true if all operands of this instruction are
454/// loop invariant. We also filter out non-hoistable instructions here just for
455/// efficiency.
456///
457bool LICM::isLoopInvariantInst(Instruction &I) {
458 // The instruction is loop invariant if all of its operands are loop-invariant
459 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3280f7b2004-04-18 22:46:08 +0000460 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattnera2706512003-12-10 06:41:05 +0000461 return false;
462
Chris Lattnered6dfc22003-12-09 19:32:44 +0000463 // If we got this far, the instruction is loop invariant!
464 return true;
465}
466
Chris Lattnera2706512003-12-10 06:41:05 +0000467/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattnera3df8a92003-12-19 08:18:16 +0000468/// this function moves it to the exit blocks and patches up SSA form as needed.
469/// This method is guaranteed to remove the original instruction from its
470/// position, and may either delete it or move it to outside of the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000471///
472void LICM::sink(Instruction &I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000473 DEBUG(errs() << "LICM sinking instruction: " << I);
Chris Lattnera2706512003-12-10 06:41:05 +0000474
Devang Patelb7211a22007-08-21 00:31:24 +0000475 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner5fa802f2004-04-18 22:15:13 +0000476 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000477
478 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000479 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000480 ++NumSunk;
481 Changed = true;
482
Chris Lattnera2706512003-12-10 06:41:05 +0000483 // The case where there is only a single exit node of this loop is common
484 // enough that we handle it as a special (more efficient) case. It is more
485 // efficient to handle because there are no PHI nodes that need to be placed.
486 if (ExitBlocks.size() == 1) {
487 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
488 // Instruction is not used, just delete it.
Chris Lattner2741c972004-05-23 21:20:19 +0000489 CurAST->deleteValue(&I);
Devang Patel1bf5ebc2009-10-13 21:41:20 +0000490 // If I has users in unreachable blocks, eliminate.
Devang Patel228ebd02009-10-13 22:56:32 +0000491 // If I is not void type then replaceAllUsesWith undef.
492 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +0000493 if (!I.getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +0000494 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000495 I.eraseFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000496 } else {
497 // Move the instruction to the start of the exit block, after any PHI
498 // nodes in it.
Chris Lattner3c80a512006-06-26 19:10:05 +0000499 I.removeFromParent();
Dan Gohman02dea8b2008-05-23 21:05:58 +0000500 BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
Chris Lattnera2706512003-12-10 06:41:05 +0000501 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
502 }
Dan Gohman30359592008-01-29 13:02:09 +0000503 } else if (ExitBlocks.empty()) {
Chris Lattnera2706512003-12-10 06:41:05 +0000504 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner2741c972004-05-23 21:20:19 +0000505 CurAST->deleteValue(&I);
Devang Patel1bf5ebc2009-10-13 21:41:20 +0000506 // If I has users in unreachable blocks, eliminate.
Devang Patel228ebd02009-10-13 22:56:32 +0000507 // If I is not void type then replaceAllUsesWith undef.
508 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +0000509 if (!I.getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +0000510 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000511 I.eraseFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000512 } else {
513 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
514 // do all of the hard work of inserting PHI nodes as necessary. We convert
515 // the value into a stack object to get it to do this.
516
517 // Firstly, we create a stack object to hold the value...
Chris Lattnereaa24302004-07-27 07:38:32 +0000518 AllocaInst *AI = 0;
Chris Lattnera2706512003-12-10 06:41:05 +0000519
Devang Patel9674d152009-10-14 17:29:00 +0000520 if (!I.getType()->isVoidTy()) {
Owen Anderson50dead02009-07-15 23:53:25 +0000521 AI = new AllocaInst(I.getType(), 0, I.getName(),
Dan Gohmanecb7a772007-03-22 16:38:57 +0000522 I.getParent()->getParent()->getEntryBlock().begin());
Devang Patele7ae1a92007-06-01 22:15:31 +0000523 CurAST->add(AI);
524 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000525
Chris Lattnera2706512003-12-10 06:41:05 +0000526 // Secondly, insert load instructions for each use of the instruction
527 // outside of the loop.
528 while (!I.use_empty()) {
529 Instruction *U = cast<Instruction>(I.use_back());
530
531 // If the user is a PHI Node, we actually have to insert load instructions
532 // in all predecessor blocks, not in the PHI block itself!
533 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
534 // Only insert into each predecessor once, so that we don't have
535 // different incoming values from the same block!
536 std::map<BasicBlock*, Value*> InsertedBlocks;
537 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
538 if (UPN->getIncomingValue(i) == &I) {
539 BasicBlock *Pred = UPN->getIncomingBlock(i);
540 Value *&PredVal = InsertedBlocks[Pred];
541 if (!PredVal) {
542 // Insert a new load instruction right before the terminator in
543 // the predecessor block.
544 PredVal = new LoadInst(AI, "", Pred->getTerminator());
Devang Patele7ae1a92007-06-01 22:15:31 +0000545 CurAST->add(cast<LoadInst>(PredVal));
Chris Lattnera2706512003-12-10 06:41:05 +0000546 }
547
548 UPN->setIncomingValue(i, PredVal);
549 }
550
551 } else {
552 LoadInst *L = new LoadInst(AI, "", U);
553 U->replaceUsesOfWith(&I, L);
Devang Patele7ae1a92007-06-01 22:15:31 +0000554 CurAST->add(L);
Chris Lattnera2706512003-12-10 06:41:05 +0000555 }
556 }
557
558 // Thirdly, insert a copy of the instruction in each exit block of the loop
559 // that is dominated by the instruction, storing the result into the memory
560 // location. Be careful not to insert the instruction into any particular
561 // basic block more than once.
562 std::set<BasicBlock*> InsertedBlocks;
563 BasicBlock *InstOrigBB = I.getParent();
564
565 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
566 BasicBlock *ExitBlock = ExitBlocks[i];
567
568 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattnera2706512003-12-10 06:41:05 +0000569 // If we haven't already processed this exit block, do so now.
Chris Lattnere3cfe8d2003-12-10 16:58:24 +0000570 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattnera2706512003-12-10 06:41:05 +0000571 // Insert the code after the last PHI node...
Dan Gohman02dea8b2008-05-23 21:05:58 +0000572 BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
Misha Brukmanfd939082005-04-21 23:48:37 +0000573
Chris Lattnera2706512003-12-10 06:41:05 +0000574 // If this is the first exit block processed, just move the original
575 // instruction, otherwise clone the original instruction and insert
576 // the copy.
577 Instruction *New;
Chris Lattner7d3ced92003-12-10 22:35:56 +0000578 if (InsertedBlocks.size() == 1) {
Chris Lattner3c80a512006-06-26 19:10:05 +0000579 I.removeFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000580 ExitBlock->getInstList().insert(InsertPt, &I);
581 New = &I;
582 } else {
Nick Lewycky67760642009-09-27 07:38:41 +0000583 New = I.clone();
Chris Lattner70ac2dc2005-03-25 00:22:36 +0000584 CurAST->copyValue(&I, New);
Chris Lattnereaa24302004-07-27 07:38:32 +0000585 if (!I.getName().empty())
586 New->setName(I.getName()+".le");
Chris Lattnera2706512003-12-10 06:41:05 +0000587 ExitBlock->getInstList().insert(InsertPt, New);
588 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000589
Chris Lattnera2706512003-12-10 06:41:05 +0000590 // Now that we have inserted the instruction, store it into the alloca
Chris Lattnereaa24302004-07-27 07:38:32 +0000591 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattnera2706512003-12-10 06:41:05 +0000592 }
593 }
594 }
Chris Lattnera3df8a92003-12-19 08:18:16 +0000595
596 // If the instruction doesn't dominate any exit blocks, it must be dead.
597 if (InsertedBlocks.empty()) {
Chris Lattner2741c972004-05-23 21:20:19 +0000598 CurAST->deleteValue(&I);
Chris Lattner3c80a512006-06-26 19:10:05 +0000599 I.eraseFromParent();
Chris Lattnera3df8a92003-12-19 08:18:16 +0000600 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000601
Chris Lattnera2706512003-12-10 06:41:05 +0000602 // Finally, promote the fine value to SSA form.
Chris Lattnereaa24302004-07-27 07:38:32 +0000603 if (AI) {
604 std::vector<AllocaInst*> Allocas;
605 Allocas.push_back(AI);
Dan Gohmanf37cfed2009-09-27 16:10:30 +0000606 PromoteMemToReg(Allocas, *DT, *DF, AI->getContext(), CurAST);
Chris Lattnereaa24302004-07-27 07:38:32 +0000607 }
Chris Lattnera2706512003-12-10 06:41:05 +0000608 }
Chris Lattnera2706512003-12-10 06:41:05 +0000609}
Chris Lattner952eaee2002-09-29 21:46:09 +0000610
Chris Lattner94170592002-09-26 16:52:07 +0000611/// hoist - When an instruction is found to only use loop invariant operands
612/// that is safe to hoist, this instruction is called to do the dirty work.
613///
Chris Lattnera2706512003-12-10 06:41:05 +0000614void LICM::hoist(Instruction &I) {
Evan Cheng67d1d1f2009-10-12 22:25:23 +0000615 DEBUG(errs() << "LICM hoisting to " << Preheader->getName() << ": "
616 << I << "\n");
Chris Lattnered6dfc22003-12-09 19:32:44 +0000617
Chris Lattner99a57212002-09-26 19:40:25 +0000618 // Remove the instruction from its current basic block... but don't delete the
619 // instruction.
Chris Lattner3c80a512006-06-26 19:10:05 +0000620 I.removeFromParent();
Chris Lattnere0e734e2002-05-10 22:44:58 +0000621
Chris Lattner9646e6b2002-09-26 16:38:03 +0000622 // Insert the new node in Preheader, before the terminator.
Chris Lattnera2706512003-12-10 06:41:05 +0000623 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000624
Chris Lattnera2706512003-12-10 06:41:05 +0000625 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000626 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner9646e6b2002-09-26 16:38:03 +0000627 ++NumHoisted;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000628 Changed = true;
629}
630
Chris Lattnera2706512003-12-10 06:41:05 +0000631/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
632/// not a trapping instruction or if it is a trapping instruction and is
633/// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000634///
Chris Lattnera2706512003-12-10 06:41:05 +0000635bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattner92094b42003-12-09 17:18:00 +0000636 // If it is not a trapping instruction, it is always safe to hoist.
Eli Friedman0b79a772009-07-17 04:28:42 +0000637 if (Inst.isSafeToSpeculativelyExecute())
638 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000639
Chris Lattner92094b42003-12-09 17:18:00 +0000640 // Otherwise we have to check to make sure that the instruction dominates all
641 // of the exit blocks. If it doesn't, then there is a path out of the loop
642 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner9966c032003-08-05 18:45:46 +0000643
Chris Lattner92094b42003-12-09 17:18:00 +0000644 // If the instruction is in the header block for the loop (which is very
645 // common), it is always guaranteed to dominate the exit blocks. Since this
646 // is a common case, and can save some work, check it now.
Chris Lattnera2706512003-12-10 06:41:05 +0000647 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattner92094b42003-12-09 17:18:00 +0000648 return true;
Tanya Lattner9966c032003-08-05 18:45:46 +0000649
Chris Lattner92094b42003-12-09 17:18:00 +0000650 // Get the exit blocks for the current loop.
Devang Patelb7211a22007-08-21 00:31:24 +0000651 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner5fa802f2004-04-18 22:15:13 +0000652 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner92094b42003-12-09 17:18:00 +0000653
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000654 // For each exit block, get the DT node and walk up the DT until the
Chris Lattner92094b42003-12-09 17:18:00 +0000655 // instruction's basic block is found or we exit the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000656 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
657 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
658 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000659
Tanya Lattner9966c032003-08-05 18:45:46 +0000660 return true;
661}
662
Chris Lattnereb53ae42002-09-26 16:19:31 +0000663
Chris Lattner2e6e7412003-02-24 03:52:32 +0000664/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
665/// stores out of the loop and moving loads to before the loop. We do this by
666/// looping over the stores in the loop, looking for stores to Must pointers
667/// which are loop invariant. We promote these memory locations to use allocas
668/// instead. These allocas can easily be raised to register values by the
669/// PromoteMem2Reg functionality.
670///
671void LICM::PromoteValuesInLoop() {
672 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner065a6162003-09-10 05:29:43 +0000673 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner2e6e7412003-02-24 03:52:32 +0000674 // pointer.
675 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
676 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
677
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000678 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
679 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000680
681 Changed = true;
682 NumPromoted += PromotedValues.size();
683
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000684 std::vector<Value*> PointerValueNumbers;
685
Chris Lattner2e6e7412003-02-24 03:52:32 +0000686 // Emit a copy from the value into the alloca'd value in the loop preheader
687 TerminatorInst *LoopPredInst = Preheader->getTerminator();
688 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000689 Value *Ptr = PromotedValues[i].second;
690
691 // If we are promoting a pointer value, update alias information for the
692 // inserted load.
693 Value *LoadValue = 0;
694 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
695 // Locate a load or store through the pointer, and assign the same value
696 // to LI as we are loading or storing. Since we know that the value is
697 // stored in this loop, this will always succeed.
698 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
699 UI != E; ++UI)
700 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
701 LoadValue = LI;
702 break;
703 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerbdacd872004-09-15 02:34:40 +0000704 if (SI->getOperand(1) == Ptr) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000705 LoadValue = SI->getOperand(0);
706 break;
707 }
708 }
709 assert(LoadValue && "No store through the pointer found!");
710 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
711 }
712
713 // Load from the memory we are promoting.
714 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
715
716 if (LoadValue) CurAST->copyValue(LoadValue, LI);
717
718 // Store into the temporary alloca.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000719 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
720 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000721
Chris Lattner2e6e7412003-02-24 03:52:32 +0000722 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattner0ed2da92003-12-10 15:56:24 +0000723 // uses of the allocas in question.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000724 //
Dan Gohman9b787632008-06-22 20:18:58 +0000725 for (Loop::block_iterator I = CurLoop->block_begin(),
726 E = CurLoop->block_end(); I != E; ++I) {
727 BasicBlock *BB = *I;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000728 // Rewrite all loads and stores in the block of the pointer...
Dan Gohman9b787632008-06-22 20:18:58 +0000729 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
Chris Lattnere408e252003-04-23 16:37:45 +0000730 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000731 std::map<Value*, AllocaInst*>::iterator
732 I = ValueToAllocaMap.find(L->getOperand(0));
733 if (I != ValueToAllocaMap.end())
734 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattnere408e252003-04-23 16:37:45 +0000735 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000736 std::map<Value*, AllocaInst*>::iterator
737 I = ValueToAllocaMap.find(S->getOperand(1));
738 if (I != ValueToAllocaMap.end())
739 S->setOperand(1, I->second); // Rewrite store instruction...
740 }
741 }
Chris Lattner2e6e7412003-02-24 03:52:32 +0000742 }
743
Chris Lattner0ed2da92003-12-10 15:56:24 +0000744 // Now that the body of the loop uses the allocas instead of the original
745 // memory locations, insert code to copy the alloca value back into the
746 // original memory location on all exits from the loop. Note that we only
747 // want to insert one copy of the code in each exit block, though the loop may
748 // exit to the same block more than once.
749 //
Chris Lattner19d9d432008-05-22 03:22:42 +0000750 SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
Chris Lattner0ed2da92003-12-10 15:56:24 +0000751
Devang Patelb7211a22007-08-21 00:31:24 +0000752 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner5fa802f2004-04-18 22:15:13 +0000753 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner19d9d432008-05-22 03:22:42 +0000754 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
755 if (!ProcessedBlocks.insert(ExitBlocks[i]))
756 continue;
757
758 // Copy all of the allocas into their memory locations.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000759 BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
Chris Lattner19d9d432008-05-22 03:22:42 +0000760 Instruction *InsertPos = BI;
761 unsigned PVN = 0;
762 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
763 // Load from the alloca.
764 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000765
Chris Lattner19d9d432008-05-22 03:22:42 +0000766 // If this is a pointer type, update alias info appropriately.
767 if (isa<PointerType>(LI->getType()))
768 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000769
Chris Lattner19d9d432008-05-22 03:22:42 +0000770 // Store into the memory we promoted.
771 new StoreInst(LI, PromotedValues[i].second, InsertPos);
Chris Lattner0ed2da92003-12-10 15:56:24 +0000772 }
Chris Lattner19d9d432008-05-22 03:22:42 +0000773 }
Chris Lattner0ed2da92003-12-10 15:56:24 +0000774
Chris Lattner2e6e7412003-02-24 03:52:32 +0000775 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000776 // all of the new allocas we just created into real SSA registers.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000777 //
778 std::vector<AllocaInst*> PromotedAllocas;
779 PromotedAllocas.reserve(PromotedValues.size());
780 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
781 PromotedAllocas.push_back(PromotedValues[i].first);
Owen Andersone922c022009-07-22 00:24:57 +0000782 PromoteMemToReg(PromotedAllocas, *DT, *DF, Preheader->getContext(), CurAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000783}
784
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000785/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Devang Patelf2038b12007-09-19 20:18:51 +0000786/// pointers, which are not loaded and stored through may aliases and are safe
787/// for promotion. If these are found, create an alloca for the value, add it
788/// to the PromotedValues list, and keep track of the mapping from value to
789/// alloca.
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000790void LICM::FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000791 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
792 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
793 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
794
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000795 // Loop over all of the alias sets in the tracker object.
Chris Lattner0252e492003-03-03 23:32:45 +0000796 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
797 I != E; ++I) {
798 AliasSet &AS = *I;
799 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000800 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner118dd0c2004-03-15 04:11:30 +0000801 // volatile loads or stores.
Chris Lattner29d92932008-05-22 00:53:38 +0000802 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000803 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Chris Lattner29d92932008-05-22 00:53:38 +0000804 continue;
805
806 assert(!AS.empty() &&
807 "Must alias set should have at least one pointer element in it!");
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000808 Value *V = AS.begin()->getValue();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000809
Chris Lattner29d92932008-05-22 00:53:38 +0000810 // Check that all of the pointers in the alias set have the same type. We
811 // cannot (yet) promote a memory location that is loaded and stored in
812 // different sizes.
813 {
Chris Lattner0252e492003-03-03 23:32:45 +0000814 bool PointerOk = true;
815 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000816 if (V->getType() != I->getValue()->getType()) {
Chris Lattner0252e492003-03-03 23:32:45 +0000817 PointerOk = false;
818 break;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000819 }
Chris Lattner29d92932008-05-22 00:53:38 +0000820 if (!PointerOk)
821 continue;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000822 }
Chris Lattner29d92932008-05-22 00:53:38 +0000823
Chris Lattner19d9d432008-05-22 03:22:42 +0000824 // It isn't safe to promote a load/store from the loop if the load/store is
825 // conditional. For example, turning:
826 //
827 // for () { if (c) *P += 1; }
828 //
829 // into:
830 //
831 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
832 //
833 // is not safe, because *P may only be valid to access if 'c' is true.
834 //
835 // It is safe to promote P if all uses are direct load/stores and if at
836 // least one is guaranteed to be executed.
837 bool GuaranteedToExecute = false;
838 bool InvalidInst = false;
839 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
840 UI != UE; ++UI) {
841 // Ignore instructions not in this loop.
Chris Lattner29d92932008-05-22 00:53:38 +0000842 Instruction *Use = dyn_cast<Instruction>(*UI);
843 if (!Use || !CurLoop->contains(Use->getParent()))
844 continue;
Chris Lattner29d92932008-05-22 00:53:38 +0000845
Chris Lattner19d9d432008-05-22 03:22:42 +0000846 if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
847 InvalidInst = true;
Chris Lattner29d92932008-05-22 00:53:38 +0000848 break;
Chris Lattner19d9d432008-05-22 03:22:42 +0000849 }
850
851 if (!GuaranteedToExecute)
852 GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
Chris Lattner29d92932008-05-22 00:53:38 +0000853 }
854
Chris Lattner19d9d432008-05-22 03:22:42 +0000855 // If there is an non-load/store instruction in the loop, we can't promote
856 // it. If there isn't a guaranteed-to-execute instruction, we can't
857 // promote.
858 if (InvalidInst || !GuaranteedToExecute)
Chris Lattner29d92932008-05-22 00:53:38 +0000859 continue;
860
861 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
Owen Anderson50dead02009-07-15 23:53:25 +0000862 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
Chris Lattner29d92932008-05-22 00:53:38 +0000863 PromotedValues.push_back(std::make_pair(AI, V));
864
865 // Update the AST and alias analysis.
866 CurAST->copyValue(V, AI);
867
868 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000869 ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI));
Chris Lattner29d92932008-05-22 00:53:38 +0000870
Chris Lattnerbdff5482009-08-23 04:37:46 +0000871 DEBUG(errs() << "LICM: Promoting value: " << *V << "\n");
Chris Lattner2e6e7412003-02-24 03:52:32 +0000872 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000873}
Devang Patel91d22c82007-07-31 08:01:41 +0000874
875/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
876void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
877 AliasSetTracker *AST = LoopToAliasMap[L];
878 if (!AST)
879 return;
880
881 AST->copyValue(From, To);
882}
883
884/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
885/// set.
886void LICM::deleteAnalysisValue(Value *V, Loop *L) {
887 AliasSetTracker *AST = LoopToAliasMap[L];
888 if (!AST)
889 return;
890
891 AST->deleteValue(V);
892}