blob: 5528a25864cc919b721b18d08ab6b14260fe1763 [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//
Chris Lattnerf3ebc3f2007-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 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
Chris Lattner1dc98b42010-08-29 06:43:52 +000029// the SSAUpdater to construct the appropriate SSA form for the value.
Chris Lattner6ec05f52002-05-10 22:44:58 +000030//
Chris Lattner6ec05f52002-05-10 22:44:58 +000031//===----------------------------------------------------------------------===//
32
33#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000035#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000036#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner030f0202010-08-31 23:00:16 +000037#include "llvm/Analysis/ConstantFolding.h"
38#include "llvm/Analysis/LoopInfo.h"
39#include "llvm/Analysis/LoopPass.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000040#include "llvm/Analysis/ScalarEvolution.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000041#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000042#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000046#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Instructions.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000050#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000051#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000055#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000057#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000059#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000060using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000061
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "licm"
63
Chris Lattner79a42ac2006-12-19 21:40:18 +000064STATISTIC(NumSunk , "Number of instructions sunk out of loop");
65STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
66STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
69
Dan Gohmand78c4002008-05-13 00:00:25 +000070static cl::opt<bool>
71DisablePromotion("disable-licm-promotion", cl::Hidden,
72 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000073
Hal Finkel3d4269a2015-02-22 18:35:32 +000074static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop);
76static bool hoist(Instruction &I, BasicBlock *Preheader);
77static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
78 Loop *CurLoop, AliasSetTracker *CurAST );
Mehdi Aminia28d91d2015-03-10 02:37:25 +000079static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
80 Loop *CurLoop, LICMSafetyInfo *SafetyInfo);
81static bool isSafeToExecuteUnconditionally(Instruction &Inst, DominatorTree *DT,
82 Loop *CurLoop,
83 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +000084static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
85 const AAMDNodes &AAInfo,
86 AliasSetTracker *CurAST);
87static Instruction *CloneInstructionInExitBlock(Instruction &I,
88 BasicBlock &ExitBlock,
89 PHINode &PN, LoopInfo *LI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +000090static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
91 DominatorTree *DT, Loop *CurLoop,
92 AliasSetTracker *CurAST,
93 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +000094
Dan Gohmand78c4002008-05-13 00:00:25 +000095namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000096 struct LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000097 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 LICM() : LoopPass(ID) {
99 initializeLICMPass(*PassRegistry::getPassRegistry());
100 }
Devang Patel09f162c2007-05-01 21:15:47 +0000101
Craig Topper3e4c6972014-03-05 09:10:37 +0000102 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000103
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000104 /// This transformation requires natural loop information & requires that
105 /// loop preheaders be inserted into the CFG...
106 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000107 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner820d9712002-10-21 20:00:28 +0000108 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000109 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000110 AU.addRequired<LoopInfoWrapperPass>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +0000111 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000112 AU.addPreservedID(LoopSimplifyID);
113 AU.addRequiredID(LCSSAID);
114 AU.addPreservedID(LCSSAID);
Chris Lattnera51fa882002-08-22 21:39:55 +0000115 AU.addRequired<AliasAnalysis>();
Chris Lattnerf94f6bb2010-08-29 07:02:56 +0000116 AU.addPreserved<AliasAnalysis>();
Chandler Carruthabfa3e52014-01-24 01:59:49 +0000117 AU.addPreserved<ScalarEvolution>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000118 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000119 }
120
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000121 using llvm::Pass::doFinalization;
122
Craig Topper3e4c6972014-03-05 09:10:37 +0000123 bool doFinalization() override {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000124 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
Devang Patel69730c92007-03-07 04:41:30 +0000125 return false;
126 }
127
Chris Lattner6ec05f52002-05-10 22:44:58 +0000128 private:
Chris Lattner45d67d62003-02-24 03:52:32 +0000129 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +0000130 LoopInfo *LI; // Current LoopInfo
Chris Lattnerabe61ef2010-08-29 06:49:44 +0000131 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000132
Chad Rosier43a33062011-12-02 01:26:24 +0000133 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
134
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000135 // State that is updated as we process loops.
Chris Lattner45d67d62003-02-24 03:52:32 +0000136 bool Changed; // Set to true when we change anything.
137 BasicBlock *Preheader; // The preheader block of the current loop...
138 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +0000139 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000140 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000141
Devang Patelb98a0972007-07-31 08:01:41 +0000142 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
Craig Topper3e4c6972014-03-05 09:10:37 +0000143 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
144 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000145
146 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
147 /// set.
Craig Topper3e4c6972014-03-05 09:10:37 +0000148 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000149
David Peixotto0d4d5e62014-09-24 16:48:31 +0000150 /// Simple Analysis hook. Delete loop L from alias set map.
151 void deleteAnalysisLoop(Loop *L) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000152 };
153}
154
Dan Gohmand78c4002008-05-13 00:00:25 +0000155char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000156INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000157INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000158INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000159INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000160INITIALIZE_PASS_DEPENDENCY(LCSSA)
161INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000162INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000163INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
164INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000165
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000166Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000167
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000168/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000169/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000170/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000171///
Devang Patel69730c92007-03-07 04:41:30 +0000172bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000173 if (skipOptnoneFunction(L))
174 return false;
175
Chris Lattner45d67d62003-02-24 03:52:32 +0000176 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000177
Chris Lattner45d67d62003-02-24 03:52:32 +0000178 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000179 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chris Lattnera51fa882002-08-22 21:39:55 +0000180 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +0000181 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000182
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000183 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +0000184
Chandler Carruthfc258542014-02-11 12:52:27 +0000185 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
186
Devang Patel69730c92007-03-07 04:41:30 +0000187 CurAST = new AliasSetTracker(*AA);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000188 // Collect Alias info from subloops.
Devang Patel69730c92007-03-07 04:41:30 +0000189 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
190 LoopItr != LoopItrE; ++LoopItr) {
191 Loop *InnerL = *LoopItr;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000192 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
193 assert(InnerAST && "Where is my AST?");
Devang Patel69730c92007-03-07 04:41:30 +0000194
195 // What if InnerLoop was modified by other passes ?
196 CurAST->add(*InnerAST);
Tobias Grossera3928f52011-07-06 19:20:02 +0000197
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000198 // Once we've incorporated the inner loop's AST into ours, we don't need the
199 // subloop's anymore.
200 delete InnerAST;
201 LoopToAliasSetMap.erase(InnerL);
Chris Lattner45d67d62003-02-24 03:52:32 +0000202 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000203
Chris Lattner6ec05f52002-05-10 22:44:58 +0000204 CurLoop = L;
205
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000206 // Get the preheader block to move instructions into...
207 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000208
Chris Lattner45d67d62003-02-24 03:52:32 +0000209 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000210 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000211 // subloops.
212 //
Dan Gohman90071072008-06-22 20:18:58 +0000213 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
214 I != E; ++I) {
215 BasicBlock *BB = *I;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000216 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
Dan Gohman90071072008-06-22 20:18:58 +0000217 CurAST->add(*BB); // Incorporate the specified basic block
218 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000219
Hal Finkel3d4269a2015-02-22 18:35:32 +0000220 // Compute loop safety information.
221 LICMSafetyInfo SafetyInfo;
222 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000223
Chris Lattner6ec05f52002-05-10 22:44:58 +0000224 // We want to visit all of the instructions in this loop... that are not parts
225 // of our subloops (they have already had their invariants hoisted out of
226 // their loop, into this loop, so there is no need to process the BODIES of
227 // the subloops).
228 //
Chris Lattner64437692002-09-29 21:46:09 +0000229 // Traverse the body of the loop in depth first order on the dominator tree so
230 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000231 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000232 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000233 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000234 if (L->hasDedicatedExits())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
236 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000237 if (Preheader)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000239 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000240
Chris Lattner45d67d62003-02-24 03:52:32 +0000241 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000242 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000243 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000244 SmallVector<BasicBlock *, 8> ExitBlocks;
245 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000246 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000247
Chris Lattner1dc98b42010-08-29 06:43:52 +0000248 // Loop over all of the alias sets in the tracker object.
249 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
250 I != E; ++I)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000251 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
252 PIC, LI, DT, CurLoop,
253 CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000254
255 // Once we have promoted values across the loop body we have to recursively
256 // reform LCSSA as any nested loop may now have values defined within the
257 // loop used in the outer loop.
258 // FIXME: This is really heavy handed. It would be a bit better to use an
259 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
260 // it as it went.
261 if (Changed)
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000262 formLCSSARecursively(*L, *DT, LI,
263 getAnalysisIfAvailable<ScalarEvolution>());
Chris Lattner1dc98b42010-08-29 06:43:52 +0000264 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000265
Chandler Carruthfc258542014-02-11 12:52:27 +0000266 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
267 // specifically moving instructions across the loop boundary and so it is
268 // especially in need of sanity checking here.
269 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
270 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
271 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000272
Chris Lattner6ec05f52002-05-10 22:44:58 +0000273 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000274 CurLoop = nullptr;
275 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000276
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000277 // If this loop is nested inside of another one, save the alias information
278 // for when we process the outer loop.
279 if (L->getParentLoop())
280 LoopToAliasSetMap[L] = CurAST;
281 else
282 delete CurAST;
Devang Patel69730c92007-03-07 04:41:30 +0000283 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000284}
285
Hal Finkel3d4269a2015-02-22 18:35:32 +0000286/// Walk the specified region of the CFG (defined by all blocks dominated by
287/// the specified block, and that are in the current loop) in reverse depth
288/// first order w.r.t the DominatorTree. This allows us to visit uses before
289/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000290///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000291bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
292 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
293 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000294
Hal Finkel3d4269a2015-02-22 18:35:32 +0000295 // Verify inputs.
296 assert(N != nullptr && AA != nullptr && LI != nullptr &&
297 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
298 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
299
300 // Set changed as false.
301 bool Changed = false;
302 // Get basic block
303 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000304 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000305 if (!CurLoop->contains(BB)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000306
Chris Lattner263f8042010-08-29 18:22:25 +0000307 // We are processing blocks in reverse dfo, so process children first.
Devang Patelbdd1aae2007-06-04 00:32:22 +0000308 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner547192d62003-12-19 07:22:45 +0000309 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310 Changed |=
311 sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Chris Lattner547192d62003-12-19 07:22:45 +0000312 // Only need to process the contents of this block if it is not part of a
313 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000314 if (inSubLoop(BB,CurLoop,LI)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000315
Chris Lattner91846012003-12-19 08:18:16 +0000316 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
317 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000318
Chris Lattner263f8042010-08-29 18:22:25 +0000319 // If the instruction is dead, we would try to sink it because it isn't used
320 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000321 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000322 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000323 ++II;
324 CurAST->deleteValue(&I);
325 I.eraseFromParent();
326 Changed = true;
327 continue;
328 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000329
Chris Lattner547192d62003-12-19 07:22:45 +0000330 // Check to see if we can sink this instruction to the exit blocks
331 // of the loop. We can do this if the all users of the instruction are
332 // outside of the loop. In this case, it doesn't even matter if the
333 // operands of the instruction are loop invariant.
334 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000335 if (isNotUsedInLoop(I, CurLoop) &&
336 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000337 ++II;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000338 Changed |= sink(I, LI, DT, CurLoop, CurAST);
Chris Lattner91846012003-12-19 08:18:16 +0000339 }
Chris Lattner547192d62003-12-19 07:22:45 +0000340 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000341 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000342}
343
Hal Finkel3d4269a2015-02-22 18:35:32 +0000344/// Walk the specified region of the CFG (defined by all blocks dominated by
345/// the specified block, and that are in the current loop) in depth first
346/// order w.r.t the DominatorTree. This allows us to visit definitions before
347/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000348///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
350 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
351 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000352 // Verify inputs.
353 assert(N != nullptr && AA != nullptr && LI != nullptr &&
354 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
355 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
356 // Set changed as false.
357 bool Changed = false;
358 // Get basic block
Owen Andersonc24701e2007-04-24 06:40:39 +0000359 BasicBlock *BB = N->getBlock();
Chris Lattner05e86302002-09-29 22:26:07 +0000360 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000361 if (!CurLoop->contains(BB)) return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000362 // Only need to process the contents of this block if it is not part of a
363 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000364 if (!inSubLoop(BB, CurLoop, LI))
Chris Lattneraaaea512003-12-10 06:41:05 +0000365 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
366 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000367 // Try constant folding this instruction. If all the operands are
368 // constants, it is technically hoistable, but it would be better to just
369 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000370 if (Constant *C = ConstantFoldInstruction(
371 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000372 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
373 CurAST->copyValue(&I, C);
374 CurAST->deleteValue(&I);
375 I.replaceAllUsesWith(C);
376 I.eraseFromParent();
377 continue;
378 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000379
Chris Lattner547192d62003-12-19 07:22:45 +0000380 // Try hoisting the instruction out to the preheader. We can only do this
381 // if all of the operands of the instruction are loop invariant and if it
382 // is safe to hoist the instruction.
383 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000384 if (CurLoop->hasLoopInvariantOperands(&I) &&
385 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo) &&
386 isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000387 Changed |= hoist(I, CurLoop->getLoopPreheader());
Chris Lattner030f0202010-08-31 23:00:16 +0000388 }
Chris Lattner64437692002-09-29 21:46:09 +0000389
Devang Patelbdd1aae2007-06-04 00:32:22 +0000390 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner64437692002-09-29 21:46:09 +0000391 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 Changed |=
393 hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000394 return Changed;
395}
396
397/// Computes loop safety information, checks loop body & header
398/// for the possiblity of may throw exception.
399///
400void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
401 assert(CurLoop != nullptr && "CurLoop cant be null");
402 BasicBlock *Header = CurLoop->getHeader();
403 // Setting default safety values.
404 SafetyInfo->MayThrow = false;
405 SafetyInfo->HeaderMayThrow = false;
406 // Iterate over header and compute dafety info.
407 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
408 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
409 SafetyInfo->HeaderMayThrow |= I->mayThrow();
410
411 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
412 // Iterate over loop instructions and compute safety info.
413 for (Loop::block_iterator BB = CurLoop->block_begin(),
414 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
415 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
416 (I != E) && !SafetyInfo->MayThrow; ++I)
417 SafetyInfo->MayThrow |= I->mayThrow();
Chris Lattner64437692002-09-29 21:46:09 +0000418}
419
Chris Lattneraaaea512003-12-10 06:41:05 +0000420/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
421/// instruction.
422///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
424 Loop *CurLoop, AliasSetTracker *CurAST,
425 LICMSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000426 // Loads have extra constraints we have to verify before we can hoist them.
427 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000428 if (!LI->isUnordered())
429 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000430
Chris Lattner8a8fb902008-07-23 05:06:28 +0000431 // Loads from constant memory are always safe to move, even if they end up
432 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000433 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000434 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000435 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000436 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000437
Chris Lattner65c11932003-12-09 19:32:44 +0000438 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000439 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000440 if (LI->getType()->isSized())
Dan Gohman43d19d62009-07-25 00:48:42 +0000441 Size = AA->getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000442
443 AAMDNodes AAInfo;
444 LI->getAAMetadata(AAInfo);
445
Hal Finkel3d4269a2015-02-22 18:35:32 +0000446 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000447 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000448 // Don't sink or hoist dbg info; it's legal, but not useful.
449 if (isa<DbgInfoIntrinsic>(I))
450 return false;
451
452 // Handle simple cases by querying alias analysis.
Duncan Sands68b6f502007-12-01 07:51:45 +0000453 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
454 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
455 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000456 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000457 // If this call only reads from memory and there are no writes to memory
458 // in the loop, we can hoist or sink the call as appropriate.
459 bool FoundMod = false;
460 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
461 I != E; ++I) {
462 AliasSet &AS = *I;
463 if (!AS.isForwardingAliasSet() && AS.isMod()) {
464 FoundMod = true;
465 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000466 }
Chris Lattner20cda262004-03-15 04:11:30 +0000467 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000468 if (!FoundMod) return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000469 }
470
Nadav Rotem03dcd852012-09-04 10:25:04 +0000471 // FIXME: This should use mod/ref information to see if we can hoist or
472 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000473
Chris Lattner20cda262004-03-15 04:11:30 +0000474 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000475 }
476
Nadav Rotem03dcd852012-09-04 10:25:04 +0000477 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000478 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
479 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
480 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
481 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
482 !isa<InsertValueInst>(I))
483 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000484
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo);
Chris Lattneraaaea512003-12-10 06:41:05 +0000486}
487
Hal Finkel3d4269a2015-02-22 18:35:32 +0000488/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000489/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000490/// This is true when all incoming values are that instruction.
491/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000492///
Chandler Carruth8765cf72014-01-25 04:07:24 +0000493static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
494 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
495 if (PN.getIncomingValue(i) != &I)
496 return false;
497
498 return true;
499}
500
Hal Finkel3d4269a2015-02-22 18:35:32 +0000501/// Return true if the only users of this instruction are outside of
502/// the loop. If this is true, we can sink the instruction to the exit
503/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000504///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000505static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000506 for (User *U : I.users()) {
507 Instruction *UI = cast<Instruction>(U);
508 if (PHINode *PN = dyn_cast<PHINode>(UI)) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000509 // A PHI node where all of the incoming values are this instruction are
510 // special -- they can just be RAUW'ed with the instruction and thus
511 // don't require a use in the predecessor. This is a particular important
512 // special case because it is the pattern found in LCSSA form.
513 if (isTriviallyReplacablePHI(*PN, I)) {
514 if (CurLoop->contains(PN))
515 return false;
516 else
517 continue;
518 }
519
520 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
521 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
523 if (PN->getIncomingValue(i) == &I)
524 if (CurLoop->contains(PN->getIncomingBlock(i)))
525 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000526
527 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000528 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000529
Chandler Carruthcdf47882014-03-09 03:16:01 +0000530 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000531 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000532 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000533 return true;
534}
535
Hal Finkel3d4269a2015-02-22 18:35:32 +0000536static Instruction *CloneInstructionInExitBlock(Instruction &I,
537 BasicBlock &ExitBlock,
538 PHINode &PN, LoopInfo *LI) {
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000539 Instruction *New = I.clone();
540 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
541 if (!I.getName().empty()) New->setName(I.getName() + ".le");
542
543 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
544 // particularly cheap because we can rip off the PHI node that we're
545 // replacing for the number and blocks of the predecessors.
546 // OPT: If this shows up in a profile, we can instead finish sinking all
547 // invariant instructions, and then walk their operands to re-establish
548 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
549 // sinking bottom-up.
550 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
551 ++OI)
552 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
553 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
554 if (!OLoop->contains(&PN)) {
555 PHINode *OpPN =
556 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
557 OInst->getName() + ".lcssa", ExitBlock.begin());
558 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
559 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
560 *OI = OpPN;
561 }
562 return New;
563}
564
Hal Finkel3d4269a2015-02-22 18:35:32 +0000565/// When an instruction is found to only be used outside of the loop, this
566/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000567/// This method is guaranteed to remove the original instruction from its
568/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000569///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000570static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
571 Loop *CurLoop, AliasSetTracker *CurAST ) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000572 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000573 bool Changed = false;
Chris Lattner55c21132003-12-10 20:43:29 +0000574 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000575 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000576 ++NumSunk;
577 Changed = true;
578
Chandler Carruthfc258542014-02-11 12:52:27 +0000579#ifndef NDEBUG
580 SmallVector<BasicBlock *, 32> ExitBlocks;
581 CurLoop->getUniqueExitBlocks(ExitBlocks);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000582 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
583 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000584#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000585
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000586 // Clones of this instruction. Don't create more than one per exit block!
587 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
588
Chandler Carruthfc258542014-02-11 12:52:27 +0000589 // If this instruction is only used outside of the loop, then all users are
590 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
591 // the instruction.
592 while (!I.use_empty()) {
David Majnemer49428102014-09-02 16:22:00 +0000593 Instruction *User = I.user_back();
594 if (!DT->isReachableFromEntry(User->getParent())) {
595 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
596 continue;
597 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000598 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000599 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000600
Chandler Carruthfc258542014-02-11 12:52:27 +0000601 BasicBlock *ExitBlock = PN->getParent();
602 assert(ExitBlockSet.count(ExitBlock) &&
603 "The LCSSA PHI is not in an exit block!");
604
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000605 Instruction *New;
606 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000607 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000608 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000609 else
610 New = SunkCopies[ExitBlock] =
Hal Finkel3d4269a2015-02-22 18:35:32 +0000611 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
Chandler Carruthfc258542014-02-11 12:52:27 +0000612
613 PN->replaceAllUsesWith(New);
614 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000615 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000616
Chris Lattner1a1ed692010-08-29 18:00:00 +0000617 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000618 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000619 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000620}
Chris Lattner64437692002-09-29 21:46:09 +0000621
Hal Finkel3d4269a2015-02-22 18:35:32 +0000622/// When an instruction is found to only use loop invariant operands that
623/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000624///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000625static bool hoist(Instruction &I, BasicBlock *Preheader) {
David Greene0fd86222010-01-05 01:27:30 +0000626 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
Evan Chengf8158612009-10-12 22:25:23 +0000627 << I << "\n");
Chris Lattner6ac06592010-08-29 18:18:40 +0000628 // Move the new node to the Preheader, before its terminator.
629 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000630
Chris Lattneraaaea512003-12-10 06:41:05 +0000631 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000632 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000633 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000634 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000635}
636
Hal Finkel3d4269a2015-02-22 18:35:32 +0000637/// Only sink or hoist an instruction if it is not a trapping instruction
638/// or if it is a trapping instruction and is guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000639///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000640static bool isSafeToExecuteUnconditionally(Instruction &Inst, DominatorTree *DT,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000641 Loop *CurLoop,
642 LICMSafetyInfo *SafetyInfo) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000643 // If it is not a trapping instruction, it is always safe to hoist.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644 if (isSafeToSpeculativelyExecute(&Inst))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000645 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000646
Hal Finkel3d4269a2015-02-22 18:35:32 +0000647 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000648}
649
Hal Finkel3d4269a2015-02-22 18:35:32 +0000650static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
651 Loop *CurLoop, LICMSafetyInfo * SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000652
Philip Reamesb35f46c2014-12-29 23:00:57 +0000653 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000654 // of the exit blocks. If it doesn't, then there is a path out of the loop
655 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000656
Chris Lattnerc0517682003-12-09 17:18:00 +0000657 // If the instruction is in the header block for the loop (which is very
658 // common), it is always guaranteed to dominate the exit blocks. Since this
659 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000660 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000661 // If there's a throw in the header block, we can't guarantee we'll reach
662 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000663 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000664
665 // Somewhere in this loop there is an instruction which may throw and make us
666 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000667 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000668 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000669
Chris Lattnerc0517682003-12-09 17:18:00 +0000670 // Get the exit blocks for the current loop.
Devang Patelb5933bb2007-08-21 00:31:24 +0000671 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000672 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000673
Chris Lattner27497ec2011-01-02 18:45:39 +0000674 // Verify that the block dominates each of the exit blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000675 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner27497ec2011-01-02 18:45:39 +0000676 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
Chris Lattneraaaea512003-12-10 06:41:05 +0000677 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000678
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000679 // As a degenerate case, if the loop is statically infinite then we haven't
680 // proven anything since there are no exit blocks.
681 if (ExitBlocks.empty())
682 return false;
683
Tanya Lattner57c03df2003-08-05 18:45:46 +0000684 return true;
685}
686
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000687namespace {
688 class LoopPromoter : public LoadAndStorePromoter {
689 Value *SomePtr; // Designated pointer to store to.
Craig Topper71b7b682014-08-21 05:55:13 +0000690 SmallPtrSetImpl<Value*> &PointerMustAliases;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000691 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
Dan Gohmanb9487362012-08-08 00:00:26 +0000692 SmallVectorImpl<Instruction*> &LoopInsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000693 PredIteratorCache &PredCache;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000694 AliasSetTracker &AST;
Chandler Carruthfc258542014-02-11 12:52:27 +0000695 LoopInfo &LI;
Eli Friedmanddf7f552011-05-27 20:31:51 +0000696 DebugLoc DL;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000697 int Alignment;
Hal Finkelcc39b672014-07-24 12:16:19 +0000698 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000699
700 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
701 if (Instruction *I = dyn_cast<Instruction>(V))
702 if (Loop *L = LI.getLoopFor(I->getParent()))
703 if (!L->contains(BB)) {
704 // We need to create an LCSSA PHI node for the incoming value and
705 // store that.
706 PHINode *PN = PHINode::Create(
707 I->getType(), PredCache.GetNumPreds(BB),
708 I->getName() + ".lcssa", BB->begin());
709 for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
710 PN->addIncoming(I, *PI);
711 return PN;
712 }
713 return V;
714 }
715
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000716 public:
Chandler Carruthfc258542014-02-11 12:52:27 +0000717 LoopPromoter(Value *SP, const SmallVectorImpl<Instruction *> &Insts,
Craig Topper71b7b682014-08-21 05:55:13 +0000718 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
Chandler Carruthfc258542014-02-11 12:52:27 +0000719 SmallVectorImpl<BasicBlock *> &LEB,
720 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
721 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Hal Finkelcc39b672014-07-24 12:16:19 +0000722 const AAMDNodes &AATags)
Chandler Carruthfc258542014-02-11 12:52:27 +0000723 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
724 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Hal Finkelcc39b672014-07-24 12:16:19 +0000725 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000726
Craig Topper3e4c6972014-03-05 09:10:37 +0000727 bool isInstInList(Instruction *I,
728 const SmallVectorImpl<Instruction*> &) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000729 Value *Ptr;
730 if (LoadInst *LI = dyn_cast<LoadInst>(I))
731 Ptr = LI->getOperand(0);
732 else
733 Ptr = cast<StoreInst>(I)->getPointerOperand();
734 return PointerMustAliases.count(Ptr);
735 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000736
Craig Topper3e4c6972014-03-05 09:10:37 +0000737 void doExtraRewritesBeforeFinalDeletion() const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000738 // Insert stores after in the loop exit blocks. Each exit block gets a
739 // store of the live-out values that feed them. Since we've already told
740 // the SSA updater about the defs in the loop and the preheader
741 // definition, it is all set and we can start using it.
742 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
743 BasicBlock *ExitBlock = LoopExitBlocks[i];
744 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
Chandler Carruthfc258542014-02-11 12:52:27 +0000745 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
746 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
Dan Gohmanb9487362012-08-08 00:00:26 +0000747 Instruction *InsertPos = LoopInsertPts[i];
Chandler Carruthfc258542014-02-11 12:52:27 +0000748 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000749 NewSI->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000750 NewSI->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000751 if (AATags) NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000752 }
753 }
754
Craig Topper3e4c6972014-03-05 09:10:37 +0000755 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000756 // Update alias analysis.
757 AST.copyValue(LI, V);
758 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000759 void instructionDeleted(Instruction *I) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000760 AST.deleteValue(I);
761 }
762 };
763} // end anon namespace
764
Hal Finkel3d4269a2015-02-22 18:35:32 +0000765/// Try to promote memory values to scalars by sinking stores out of the
766/// loop and moving loads to before the loop. We do this by looping over
767/// the stores in the loop, looking for stores to Must pointers which are
768/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000769///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000770bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
771 SmallVectorImpl<BasicBlock*>&ExitBlocks,
772 SmallVectorImpl<Instruction*>&InsertPts,
773 PredIteratorCache &PIC, LoopInfo *LI,
774 DominatorTree *DT, Loop *CurLoop,
775 AliasSetTracker *CurAST,
776 LICMSafetyInfo * SafetyInfo) {
777 // Verify inputs.
778 assert(LI != nullptr && DT != nullptr &&
779 CurLoop != nullptr && CurAST != nullptr &&
780 SafetyInfo != nullptr &&
781 "Unexpected Input to promoteLoopAccessesToScalars");
782 // Initially set Changed status to false.
783 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000784 // We can promote this alias set if it has a store, if it is a "Must" alias
785 // set, if the pointer is loop invariant, and if we are not eliminating any
786 // volatile loads or stores.
787 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
788 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000789 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000790
Chris Lattner1dc98b42010-08-29 06:43:52 +0000791 assert(!AS.empty() &&
792 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000793
Chris Lattner1dc98b42010-08-29 06:43:52 +0000794 Value *SomePtr = AS.begin()->getValue();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000795 BasicBlock * Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000796
Chris Lattner1dc98b42010-08-29 06:43:52 +0000797 // It isn't safe to promote a load/store from the loop if the load/store is
798 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000799 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000800 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000801 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000802 // into:
803 //
804 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
805 //
806 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000807 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000808 // It is safe to promote P if all uses are direct load/stores and if at
809 // least one is guaranteed to be executed.
810 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000811
Chris Lattner1dc98b42010-08-29 06:43:52 +0000812 SmallVector<Instruction*, 64> LoopUses;
813 SmallPtrSet<Value*, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000814
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000815 // We start with an alignment of one and try to find instructions that allow
816 // us to prove better alignment.
817 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000818 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000819 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000820
Chris Lattner1dc98b42010-08-29 06:43:52 +0000821 // Check that all of the pointers in the alias set have the same type. We
822 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000823 // different sizes. While we are at it, collect alignment and AA info.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000824 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
825 Value *ASIV = ASI->getValue();
826 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000827
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000828 // Check that all of the pointers in the alias set have the same type. We
829 // cannot (yet) promote a memory location that is loaded and stored in
830 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000831 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000832 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000833
Chandler Carruthcdf47882014-03-09 03:16:01 +0000834 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000835 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000836 Instruction *UI = dyn_cast<Instruction>(U);
837 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000838 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000839
Chris Lattner1dc98b42010-08-29 06:43:52 +0000840 // If there is an non-load/store instruction in the loop, we can't promote
841 // it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000842 if (LoadInst *load = dyn_cast<LoadInst>(UI)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000843 assert(!load->isVolatile() && "AST broken");
844 if (!load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000845 return Changed;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000846 } else if (StoreInst *store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000847 // Stores *of* the pointer are not interesting, only stores *to* the
848 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000849 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000850 continue;
Eli Friedman91386c72011-08-15 20:52:09 +0000851 assert(!store->isVolatile() && "AST broken");
852 if (!store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000853 return Changed;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000854 // Don't sink stores from loops without dedicated block exits. Exits
855 // containing indirect branches are not transformed by loop simplify,
Bruno Cardoso Lopesd035fbb2014-12-02 14:22:34 +0000856 // make sure we catch that. An additional load may be generated in the
857 // preheader for SSA updater, so also avoid sinking when no preheader
858 // is available.
859 if (!HasDedicatedExits || !Preheader)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000860 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000861
862 // Note that we only check GuaranteedToExecute inside the store case
863 // so that we do not introduce stores where they did not exist before
864 // (which would break the LLVM concurrency model).
865
866 // If the alignment of this instruction allows us to specify a more
867 // restrictive (and performant) alignment and if we are sure this
868 // instruction will be executed, update the alignment.
869 // Larger is better, with the exception of 0 being the best alignment.
Eli Friedman91386c72011-08-15 20:52:09 +0000870 unsigned InstAlignment = store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000871 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000872 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000873 GuaranteedToExecute = true;
874 Alignment = InstAlignment;
875 }
876
877 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000878 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
879 CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000880
Chris Lattnerbe901902010-09-06 05:11:24 +0000881 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000882 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000883
Hal Finkelcc39b672014-07-24 12:16:19 +0000884 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000885 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000886 // On the first load/store, just take its AA tags.
887 UI->getAAMetadata(AATags);
888 } else if (AATags) {
889 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +0000890 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000891
892 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000893 }
894 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000895
Chris Lattner1dc98b42010-08-29 06:43:52 +0000896 // If there isn't a guaranteed-to-execute instruction, we can't promote.
897 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000898 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000899
Chris Lattner1dc98b42010-08-29 06:43:52 +0000900 // Otherwise, this is safe to promote, lets do it!
Tobias Grossera3928f52011-07-06 19:20:02 +0000901 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +0000902 Changed = true;
903 ++NumPromoted;
904
Eli Friedmanddf7f552011-05-27 20:31:51 +0000905 // Grab a debug location for the inserted loads/stores; given that the
906 // inserted loads/stores have little relation to the original loads/stores,
907 // this code just arbitrarily picks a location from one, since any debug
908 // location is better than none.
909 DebugLoc DL = LoopUses[0]->getDebugLoc();
910
Dan Gohmanb9487362012-08-08 00:00:26 +0000911 // Figure out the loop exits and their insertion points, if this is the
912 // first promotion.
913 if (ExitBlocks.empty()) {
914 CurLoop->getUniqueExitBlocks(ExitBlocks);
915 InsertPts.resize(ExitBlocks.size());
916 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
917 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
918 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000919
Chris Lattner1dc98b42010-08-29 06:43:52 +0000920 // We use the SSAUpdater interface to insert phi nodes as required.
921 SmallVector<PHINode*, 16> NewPHIs;
922 SSAUpdater SSA(&NewPHIs);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000923 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +0000924 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +0000925
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000926 // Set up the preheader to have a definition of the value. It is the live-out
927 // value from the preheader that uses in the loop will use.
928 LoadInst *PreheaderLoad =
929 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
930 Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000931 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000932 PreheaderLoad->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000933 if (AATags) PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000934 SSA.AddAvailableValue(Preheader, PreheaderLoad);
935
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000936 // Rewrite all the loads in the loop and remember all the definitions from
937 // stores in the loop.
938 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +0000939
940 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
941 if (PreheaderLoad->use_empty())
942 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000943
944 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +0000945}
Devang Patelb98a0972007-07-31 08:01:41 +0000946
Hal Finkel3d4269a2015-02-22 18:35:32 +0000947/// Simple Analysis hook. Clone alias set info.
948///
Devang Patelb98a0972007-07-31 08:01:41 +0000949void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000950 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000951 if (!AST)
952 return;
953
954 AST->copyValue(From, To);
955}
956
Hal Finkel3d4269a2015-02-22 18:35:32 +0000957/// Simple Analysis hook. Delete value V from alias set
958///
Devang Patelb98a0972007-07-31 08:01:41 +0000959void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000960 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000961 if (!AST)
962 return;
963
964 AST->deleteValue(V);
965}
David Peixotto0d4d5e62014-09-24 16:48:31 +0000966
967/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000968///
David Peixotto0d4d5e62014-09-24 16:48:31 +0000969void LICM::deleteAnalysisLoop(Loop *L) {
970 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
971 if (!AST)
972 return;
973
974 delete AST;
975 LoopToAliasSetMap.erase(L);
976}
Hal Finkel3d4269a2015-02-22 18:35:32 +0000977
978
979/// Return true if the body of this loop may store into the memory
980/// location pointed to by V.
981///
982static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
983 const AAMDNodes &AAInfo,
984 AliasSetTracker *CurAST) {
985 // Check to see if any of the basic blocks in CurLoop invalidate *V.
986 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
987}
988
989/// Little predicate that returns true if the specified basic block is in
990/// a subloop of the current one, not the current one itself.
991///
992static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
993 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
994 return LI->getLoopFor(BB) != CurLoop;
995}
996