blob: 76848c76a851fc946bb51bf1cca76e97cb40f8ba [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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000042#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000043#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000047#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Instructions.h"
49#include "llvm/IR/IntrinsicInst.h"
50#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000051#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000052#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000053#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/Support/raw_ostream.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);
Pete Cooper0cabcf22015-05-13 01:12:18 +000075static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop);
Hal Finkel3d4269a2015-02-22 18:35:32 +000076static bool hoist(Instruction &I, BasicBlock *Preheader);
Pete Cooper0cabcf22015-05-13 01:12:18 +000077static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
78 const Loop *CurLoop, AliasSetTracker *CurAST );
79static bool isGuaranteedToExecute(const Instruction &Inst,
80 const DominatorTree *DT,
81 const Loop *CurLoop,
82 const LICMSafetyInfo *SafetyInfo);
83static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
84 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +000085 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +000086 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +000087 const LICMSafetyInfo *SafetyInfo,
88 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000089static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
90 const AAMDNodes &AAInfo,
91 AliasSetTracker *CurAST);
Pete Cooper0cabcf22015-05-13 01:12:18 +000092static Instruction *CloneInstructionInExitBlock(const Instruction &I,
Hal Finkel3d4269a2015-02-22 18:35:32 +000093 BasicBlock &ExitBlock,
Pete Cooper0cabcf22015-05-13 01:12:18 +000094 PHINode &PN,
95 const LoopInfo *LI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +000096static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +000097 DominatorTree *DT, TargetLibraryInfo *TLI,
98 Loop *CurLoop, AliasSetTracker *CurAST,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000099 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000100
Dan Gohmand78c4002008-05-13 00:00:25 +0000101namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000102 struct LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000103 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000104 LICM() : LoopPass(ID) {
105 initializeLICMPass(*PassRegistry::getPassRegistry());
106 }
Devang Patel09f162c2007-05-01 21:15:47 +0000107
Craig Topper3e4c6972014-03-05 09:10:37 +0000108 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000109
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000110 /// This transformation requires natural loop information & requires that
111 /// loop preheaders be inserted into the CFG...
112 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000113 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner820d9712002-10-21 20:00:28 +0000114 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000115 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000116 AU.addRequired<LoopInfoWrapperPass>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +0000117 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000118 AU.addPreservedID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
120 AU.addPreservedID(LCSSAID);
Chris Lattnera51fa882002-08-22 21:39:55 +0000121 AU.addRequired<AliasAnalysis>();
Chris Lattnerf94f6bb2010-08-29 07:02:56 +0000122 AU.addPreserved<AliasAnalysis>();
Chandler Carruthabfa3e52014-01-24 01:59:49 +0000123 AU.addPreserved<ScalarEvolution>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000124 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000125 }
126
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000127 using llvm::Pass::doFinalization;
128
Craig Topper3e4c6972014-03-05 09:10:37 +0000129 bool doFinalization() override {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000130 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
Devang Patel69730c92007-03-07 04:41:30 +0000131 return false;
132 }
133
Chris Lattner6ec05f52002-05-10 22:44:58 +0000134 private:
Chris Lattner45d67d62003-02-24 03:52:32 +0000135 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +0000136 LoopInfo *LI; // Current LoopInfo
Chris Lattnerabe61ef2010-08-29 06:49:44 +0000137 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000138
Chad Rosier43a33062011-12-02 01:26:24 +0000139 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
140
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000141 // State that is updated as we process loops.
Chris Lattner45d67d62003-02-24 03:52:32 +0000142 bool Changed; // Set to true when we change anything.
143 BasicBlock *Preheader; // The preheader block of the current loop...
144 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +0000145 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000146 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000147
Devang Patelb98a0972007-07-31 08:01:41 +0000148 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
Craig Topper3e4c6972014-03-05 09:10:37 +0000149 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
150 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000151
152 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
153 /// set.
Craig Topper3e4c6972014-03-05 09:10:37 +0000154 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000155
David Peixotto0d4d5e62014-09-24 16:48:31 +0000156 /// Simple Analysis hook. Delete loop L from alias set map.
157 void deleteAnalysisLoop(Loop *L) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000158 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000159}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000160
Dan Gohmand78c4002008-05-13 00:00:25 +0000161char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000162INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000163INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000164INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000165INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000166INITIALIZE_PASS_DEPENDENCY(LCSSA)
167INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000168INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000169INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000171
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000172Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000173
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000174/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000175/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000176/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000177///
Devang Patel69730c92007-03-07 04:41:30 +0000178bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000179 if (skipOptnoneFunction(L))
180 return false;
181
Chris Lattner45d67d62003-02-24 03:52:32 +0000182 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000183
Chris Lattner45d67d62003-02-24 03:52:32 +0000184 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000185 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chris Lattnera51fa882002-08-22 21:39:55 +0000186 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +0000187 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000188
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000189 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +0000190
Chandler Carruthfc258542014-02-11 12:52:27 +0000191 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
192
Devang Patel69730c92007-03-07 04:41:30 +0000193 CurAST = new AliasSetTracker(*AA);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000194 // Collect Alias info from subloops.
Devang Patel69730c92007-03-07 04:41:30 +0000195 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
196 LoopItr != LoopItrE; ++LoopItr) {
197 Loop *InnerL = *LoopItr;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000198 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
199 assert(InnerAST && "Where is my AST?");
Devang Patel69730c92007-03-07 04:41:30 +0000200
201 // What if InnerLoop was modified by other passes ?
202 CurAST->add(*InnerAST);
Tobias Grossera3928f52011-07-06 19:20:02 +0000203
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000204 // Once we've incorporated the inner loop's AST into ours, we don't need the
205 // subloop's anymore.
206 delete InnerAST;
207 LoopToAliasSetMap.erase(InnerL);
Chris Lattner45d67d62003-02-24 03:52:32 +0000208 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000209
Chris Lattner6ec05f52002-05-10 22:44:58 +0000210 CurLoop = L;
211
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000212 // Get the preheader block to move instructions into...
213 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000214
Chris Lattner45d67d62003-02-24 03:52:32 +0000215 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000216 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000217 // subloops.
218 //
Dan Gohman90071072008-06-22 20:18:58 +0000219 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
220 I != E; ++I) {
221 BasicBlock *BB = *I;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000222 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
Dan Gohman90071072008-06-22 20:18:58 +0000223 CurAST->add(*BB); // Incorporate the specified basic block
224 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000225
Hal Finkel3d4269a2015-02-22 18:35:32 +0000226 // Compute loop safety information.
227 LICMSafetyInfo SafetyInfo;
228 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000229
Chris Lattner6ec05f52002-05-10 22:44:58 +0000230 // We want to visit all of the instructions in this loop... that are not parts
231 // of our subloops (they have already had their invariants hoisted out of
232 // their loop, into this loop, so there is no need to process the BODIES of
233 // the subloops).
234 //
Chris Lattner64437692002-09-29 21:46:09 +0000235 // Traverse the body of the loop in depth first order on the dominator tree so
236 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000237 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000238 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000239 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000240 if (L->hasDedicatedExits())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000241 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
242 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000243 if (Preheader)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000244 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000245 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000246
Chris Lattner45d67d62003-02-24 03:52:32 +0000247 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000248 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000249 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000250 SmallVector<BasicBlock *, 8> ExitBlocks;
251 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000252 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000253
Chris Lattner1dc98b42010-08-29 06:43:52 +0000254 // Loop over all of the alias sets in the tracker object.
255 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
256 I != E; ++I)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000257 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
258 PIC, LI, DT, CurLoop,
259 CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000260
261 // Once we have promoted values across the loop body we have to recursively
262 // reform LCSSA as any nested loop may now have values defined within the
263 // loop used in the outer loop.
264 // FIXME: This is really heavy handed. It would be a bit better to use an
265 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
266 // it as it went.
267 if (Changed)
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000268 formLCSSARecursively(*L, *DT, LI,
269 getAnalysisIfAvailable<ScalarEvolution>());
Chris Lattner1dc98b42010-08-29 06:43:52 +0000270 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000271
Chandler Carruthfc258542014-02-11 12:52:27 +0000272 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
273 // specifically moving instructions across the loop boundary and so it is
274 // especially in need of sanity checking here.
275 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
276 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
277 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000278
Chris Lattner6ec05f52002-05-10 22:44:58 +0000279 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000280 CurLoop = nullptr;
281 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000282
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000283 // If this loop is nested inside of another one, save the alias information
284 // for when we process the outer loop.
285 if (L->getParentLoop())
286 LoopToAliasSetMap[L] = CurAST;
287 else
288 delete CurAST;
Devang Patel69730c92007-03-07 04:41:30 +0000289 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000290}
291
Hal Finkel3d4269a2015-02-22 18:35:32 +0000292/// Walk the specified region of the CFG (defined by all blocks dominated by
293/// the specified block, and that are in the current loop) in reverse depth
294/// first order w.r.t the DominatorTree. This allows us to visit uses before
295/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000296///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
298 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
299 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000300
Hal Finkel3d4269a2015-02-22 18:35:32 +0000301 // Verify inputs.
302 assert(N != nullptr && AA != nullptr && LI != nullptr &&
303 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
304 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
305
306 // Set changed as false.
307 bool Changed = false;
308 // Get basic block
309 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000310 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000311 if (!CurLoop->contains(BB)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000312
Chris Lattner263f8042010-08-29 18:22:25 +0000313 // We are processing blocks in reverse dfo, so process children first.
Devang Patelbdd1aae2007-06-04 00:32:22 +0000314 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner547192d62003-12-19 07:22:45 +0000315 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 Changed |=
317 sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Chris Lattner547192d62003-12-19 07:22:45 +0000318 // Only need to process the contents of this block if it is not part of a
319 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000320 if (inSubLoop(BB,CurLoop,LI)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000321
Chris Lattner91846012003-12-19 08:18:16 +0000322 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
323 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000324
Chris Lattner263f8042010-08-29 18:22:25 +0000325 // If the instruction is dead, we would try to sink it because it isn't used
326 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000327 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000328 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000329 ++II;
330 CurAST->deleteValue(&I);
331 I.eraseFromParent();
332 Changed = true;
333 continue;
334 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000335
Chris Lattner547192d62003-12-19 07:22:45 +0000336 // Check to see if we can sink this instruction to the exit blocks
337 // of the loop. We can do this if the all users of the instruction are
338 // outside of the loop. In this case, it doesn't even matter if the
339 // operands of the instruction are loop invariant.
340 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000341 if (isNotUsedInLoop(I, CurLoop) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000342 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000343 ++II;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000344 Changed |= sink(I, LI, DT, CurLoop, CurAST);
Chris Lattner91846012003-12-19 08:18:16 +0000345 }
Chris Lattner547192d62003-12-19 07:22:45 +0000346 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000347 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000348}
349
Hal Finkel3d4269a2015-02-22 18:35:32 +0000350/// Walk the specified region of the CFG (defined by all blocks dominated by
351/// the specified block, and that are in the current loop) in depth first
352/// order w.r.t the DominatorTree. This allows us to visit definitions before
353/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000354///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000355bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
356 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
357 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000358 // Verify inputs.
359 assert(N != nullptr && AA != nullptr && LI != nullptr &&
360 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
361 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
362 // Set changed as false.
363 bool Changed = false;
364 // Get basic block
Owen Andersonc24701e2007-04-24 06:40:39 +0000365 BasicBlock *BB = N->getBlock();
Chris Lattner05e86302002-09-29 22:26:07 +0000366 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000367 if (!CurLoop->contains(BB)) return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000368 // Only need to process the contents of this block if it is not part of a
369 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000370 if (!inSubLoop(BB, CurLoop, LI))
Chris Lattneraaaea512003-12-10 06:41:05 +0000371 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
372 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000373 // Try constant folding this instruction. If all the operands are
374 // constants, it is technically hoistable, but it would be better to just
375 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000376 if (Constant *C = ConstantFoldInstruction(
377 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000378 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
379 CurAST->copyValue(&I, C);
380 CurAST->deleteValue(&I);
381 I.replaceAllUsesWith(C);
382 I.eraseFromParent();
383 continue;
384 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000385
Chris Lattner547192d62003-12-19 07:22:45 +0000386 // Try hoisting the instruction out to the preheader. We can only do this
387 // if all of the operands of the instruction are loop invariant and if it
388 // is safe to hoist the instruction.
389 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000390 if (CurLoop->hasLoopInvariantOperands(&I) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000391 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
Philip Reamesb47b9c22015-05-22 02:14:05 +0000392 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
393 CurLoop->getLoopPreheader()->getTerminator()))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000394 Changed |= hoist(I, CurLoop->getLoopPreheader());
Chris Lattner030f0202010-08-31 23:00:16 +0000395 }
Chris Lattner64437692002-09-29 21:46:09 +0000396
Devang Patelbdd1aae2007-06-04 00:32:22 +0000397 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner64437692002-09-29 21:46:09 +0000398 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000399 Changed |=
400 hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000401 return Changed;
402}
403
404/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000405/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000406///
407void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
408 assert(CurLoop != nullptr && "CurLoop cant be null");
409 BasicBlock *Header = CurLoop->getHeader();
410 // Setting default safety values.
411 SafetyInfo->MayThrow = false;
412 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000413 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000414 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
415 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
416 SafetyInfo->HeaderMayThrow |= I->mayThrow();
417
418 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
419 // Iterate over loop instructions and compute safety info.
420 for (Loop::block_iterator BB = CurLoop->block_begin(),
421 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
422 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
423 (I != E) && !SafetyInfo->MayThrow; ++I)
424 SafetyInfo->MayThrow |= I->mayThrow();
Chris Lattner64437692002-09-29 21:46:09 +0000425}
426
Chris Lattneraaaea512003-12-10 06:41:05 +0000427/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
428/// instruction.
429///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000430bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000431 TargetLibraryInfo *TLI, Loop *CurLoop,
432 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000433 // Loads have extra constraints we have to verify before we can hoist them.
434 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000435 if (!LI->isUnordered())
436 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000437
Chris Lattner8a8fb902008-07-23 05:06:28 +0000438 // Loads from constant memory are always safe to move, even if they end up
439 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000440 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000441 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000442 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000443 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000444
Chris Lattner65c11932003-12-09 19:32:44 +0000445 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000446 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000447 if (LI->getType()->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000448 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000449
450 AAMDNodes AAInfo;
451 LI->getAAMetadata(AAInfo);
452
Hal Finkel3d4269a2015-02-22 18:35:32 +0000453 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000454 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000455 // Don't sink or hoist dbg info; it's legal, but not useful.
456 if (isa<DbgInfoIntrinsic>(I))
457 return false;
458
459 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000460 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
461 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000462 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000463 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000464 // If this call only reads from memory and there are no writes to memory
465 // in the loop, we can hoist or sink the call as appropriate.
466 bool FoundMod = false;
467 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
468 I != E; ++I) {
469 AliasSet &AS = *I;
470 if (!AS.isForwardingAliasSet() && AS.isMod()) {
471 FoundMod = true;
472 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000473 }
Chris Lattner20cda262004-03-15 04:11:30 +0000474 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000475 if (!FoundMod) return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000476 }
477
Nadav Rotem03dcd852012-09-04 10:25:04 +0000478 // FIXME: This should use mod/ref information to see if we can hoist or
479 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000480
Chris Lattner20cda262004-03-15 04:11:30 +0000481 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000482 }
483
Nadav Rotem03dcd852012-09-04 10:25:04 +0000484 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000485 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
486 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
487 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
488 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
489 !isa<InsertValueInst>(I))
490 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000491
Philip Reamesb47b9c22015-05-22 02:14:05 +0000492 // TODO: Plumb the context instruction through to make hoisting and sinking
493 // more powerful. Hoisting of loads already works due to the special casing
494 // above.
495 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
496 nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000497}
498
Hal Finkel3d4269a2015-02-22 18:35:32 +0000499/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000500/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000501/// This is true when all incoming values are that instruction.
502/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000503///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000504static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000505 for (const Value *IncValue : PN.incoming_values())
506 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000507 return false;
508
509 return true;
510}
511
Hal Finkel3d4269a2015-02-22 18:35:32 +0000512/// Return true if the only users of this instruction are outside of
513/// the loop. If this is true, we can sink the instruction to the exit
514/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000515///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000516static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) {
517 for (const User *U : I.users()) {
518 const Instruction *UI = cast<Instruction>(U);
519 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000520 // A PHI node where all of the incoming values are this instruction are
521 // special -- they can just be RAUW'ed with the instruction and thus
522 // don't require a use in the predecessor. This is a particular important
523 // special case because it is the pattern found in LCSSA form.
524 if (isTriviallyReplacablePHI(*PN, I)) {
525 if (CurLoop->contains(PN))
526 return false;
527 else
528 continue;
529 }
530
531 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
532 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000533 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
534 if (PN->getIncomingValue(i) == &I)
535 if (CurLoop->contains(PN->getIncomingBlock(i)))
536 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000537
538 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000539 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000540
Chandler Carruthcdf47882014-03-09 03:16:01 +0000541 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000542 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000543 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000544 return true;
545}
546
Pete Cooper0cabcf22015-05-13 01:12:18 +0000547static Instruction *CloneInstructionInExitBlock(const Instruction &I,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000548 BasicBlock &ExitBlock,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000549 PHINode &PN,
550 const LoopInfo *LI) {
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000551 Instruction *New = I.clone();
552 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
553 if (!I.getName().empty()) New->setName(I.getName() + ".le");
554
555 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
556 // particularly cheap because we can rip off the PHI node that we're
557 // replacing for the number and blocks of the predecessors.
558 // OPT: If this shows up in a profile, we can instead finish sinking all
559 // invariant instructions, and then walk their operands to re-establish
560 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
561 // sinking bottom-up.
562 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
563 ++OI)
564 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
565 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
566 if (!OLoop->contains(&PN)) {
567 PHINode *OpPN =
568 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
569 OInst->getName() + ".lcssa", ExitBlock.begin());
570 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
571 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
572 *OI = OpPN;
573 }
574 return New;
575}
576
Hal Finkel3d4269a2015-02-22 18:35:32 +0000577/// When an instruction is found to only be used outside of the loop, this
578/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000579/// This method is guaranteed to remove the original instruction from its
580/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000581///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000582static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
583 const Loop *CurLoop, AliasSetTracker *CurAST ) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000584 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000585 bool Changed = false;
Chris Lattner55c21132003-12-10 20:43:29 +0000586 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000587 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000588 ++NumSunk;
589 Changed = true;
590
Chandler Carruthfc258542014-02-11 12:52:27 +0000591#ifndef NDEBUG
592 SmallVector<BasicBlock *, 32> ExitBlocks;
593 CurLoop->getUniqueExitBlocks(ExitBlocks);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000594 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
595 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000596#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000597
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000598 // Clones of this instruction. Don't create more than one per exit block!
599 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
600
Chandler Carruthfc258542014-02-11 12:52:27 +0000601 // If this instruction is only used outside of the loop, then all users are
602 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
603 // the instruction.
604 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000605 Value::user_iterator UI = I.user_begin();
606 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000607 if (!DT->isReachableFromEntry(User->getParent())) {
608 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
609 continue;
610 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000611 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000612 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000613
David Majnemer6bc83e02015-07-12 03:53:05 +0000614 // Surprisingly, instructions can be used outside of loops without any
615 // exits. This can only happen in PHI nodes if the incoming block is
616 // unreachable.
617 Use &U = UI.getUse();
618 BasicBlock *BB = PN->getIncomingBlock(U);
619 if (!DT->isReachableFromEntry(BB)) {
620 U = UndefValue::get(I.getType());
621 continue;
622 }
623
Chandler Carruthfc258542014-02-11 12:52:27 +0000624 BasicBlock *ExitBlock = PN->getParent();
625 assert(ExitBlockSet.count(ExitBlock) &&
626 "The LCSSA PHI is not in an exit block!");
627
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000628 Instruction *New;
629 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000630 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000631 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000632 else
633 New = SunkCopies[ExitBlock] =
Hal Finkel3d4269a2015-02-22 18:35:32 +0000634 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
Chandler Carruthfc258542014-02-11 12:52:27 +0000635
636 PN->replaceAllUsesWith(New);
637 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000638 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000639
Chris Lattner1a1ed692010-08-29 18:00:00 +0000640 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000641 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000642 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000643}
Chris Lattner64437692002-09-29 21:46:09 +0000644
Hal Finkel3d4269a2015-02-22 18:35:32 +0000645/// When an instruction is found to only use loop invariant operands that
646/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000647///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000648static bool hoist(Instruction &I, BasicBlock *Preheader) {
David Greene0fd86222010-01-05 01:27:30 +0000649 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
Evan Chengf8158612009-10-12 22:25:23 +0000650 << I << "\n");
Chris Lattner6ac06592010-08-29 18:18:40 +0000651 // Move the new node to the Preheader, before its terminator.
652 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000653
Chris Lattneraaaea512003-12-10 06:41:05 +0000654 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000655 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000656 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000657 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000658}
659
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000660/// Only sink or hoist an instruction if it is not a trapping instruction,
661/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000662/// or if it is a trapping instruction and is guaranteed to execute.
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000663static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000664 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000665 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000666 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000667 const LICMSafetyInfo *SafetyInfo,
668 const Instruction *CtxI) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000669 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000670 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000671
Hal Finkel3d4269a2015-02-22 18:35:32 +0000672 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000673}
674
Pete Cooper0cabcf22015-05-13 01:12:18 +0000675static bool isGuaranteedToExecute(const Instruction &Inst,
676 const DominatorTree *DT,
677 const Loop *CurLoop,
678 const LICMSafetyInfo * SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000679
Philip Reamesb35f46c2014-12-29 23:00:57 +0000680 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000681 // of the exit blocks. If it doesn't, then there is a path out of the loop
682 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000683
Chris Lattnerc0517682003-12-09 17:18:00 +0000684 // If the instruction is in the header block for the loop (which is very
685 // common), it is always guaranteed to dominate the exit blocks. Since this
686 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000687 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000688 // If there's a throw in the header block, we can't guarantee we'll reach
689 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000690 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000691
692 // Somewhere in this loop there is an instruction which may throw and make us
693 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000694 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000695 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000696
Chris Lattnerc0517682003-12-09 17:18:00 +0000697 // Get the exit blocks for the current loop.
Devang Patelb5933bb2007-08-21 00:31:24 +0000698 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000699 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000700
Chris Lattner27497ec2011-01-02 18:45:39 +0000701 // Verify that the block dominates each of the exit blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000702 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner27497ec2011-01-02 18:45:39 +0000703 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
Chris Lattneraaaea512003-12-10 06:41:05 +0000704 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000705
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000706 // As a degenerate case, if the loop is statically infinite then we haven't
707 // proven anything since there are no exit blocks.
708 if (ExitBlocks.empty())
709 return false;
710
Tanya Lattner57c03df2003-08-05 18:45:46 +0000711 return true;
712}
713
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000714namespace {
715 class LoopPromoter : public LoadAndStorePromoter {
716 Value *SomePtr; // Designated pointer to store to.
Craig Topper71b7b682014-08-21 05:55:13 +0000717 SmallPtrSetImpl<Value*> &PointerMustAliases;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000718 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
Dan Gohmanb9487362012-08-08 00:00:26 +0000719 SmallVectorImpl<Instruction*> &LoopInsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000720 PredIteratorCache &PredCache;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000721 AliasSetTracker &AST;
Chandler Carruthfc258542014-02-11 12:52:27 +0000722 LoopInfo &LI;
Eli Friedmanddf7f552011-05-27 20:31:51 +0000723 DebugLoc DL;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000724 int Alignment;
Hal Finkelcc39b672014-07-24 12:16:19 +0000725 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000726
727 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
728 if (Instruction *I = dyn_cast<Instruction>(V))
729 if (Loop *L = LI.getLoopFor(I->getParent()))
730 if (!L->contains(BB)) {
731 // We need to create an LCSSA PHI node for the incoming value and
732 // store that.
733 PHINode *PN = PHINode::Create(
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000734 I->getType(), PredCache.size(BB),
Chandler Carruthfc258542014-02-11 12:52:27 +0000735 I->getName() + ".lcssa", BB->begin());
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000736 for (BasicBlock *Pred : PredCache.get(BB))
737 PN->addIncoming(I, Pred);
Chandler Carruthfc258542014-02-11 12:52:27 +0000738 return PN;
739 }
740 return V;
741 }
742
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000743 public:
Pete Cooper41e0ee32015-05-13 01:12:16 +0000744 LoopPromoter(Value *SP,
745 ArrayRef<const Instruction *> Insts,
Craig Topper71b7b682014-08-21 05:55:13 +0000746 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
Chandler Carruthfc258542014-02-11 12:52:27 +0000747 SmallVectorImpl<BasicBlock *> &LEB,
748 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
749 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Hal Finkelcc39b672014-07-24 12:16:19 +0000750 const AAMDNodes &AATags)
Chandler Carruthfc258542014-02-11 12:52:27 +0000751 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
752 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Hal Finkelcc39b672014-07-24 12:16:19 +0000753 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000754
Craig Topper3e4c6972014-03-05 09:10:37 +0000755 bool isInstInList(Instruction *I,
756 const SmallVectorImpl<Instruction*> &) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000757 Value *Ptr;
758 if (LoadInst *LI = dyn_cast<LoadInst>(I))
759 Ptr = LI->getOperand(0);
760 else
761 Ptr = cast<StoreInst>(I)->getPointerOperand();
762 return PointerMustAliases.count(Ptr);
763 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000764
Craig Topper3e4c6972014-03-05 09:10:37 +0000765 void doExtraRewritesBeforeFinalDeletion() const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000766 // Insert stores after in the loop exit blocks. Each exit block gets a
767 // store of the live-out values that feed them. Since we've already told
768 // the SSA updater about the defs in the loop and the preheader
769 // definition, it is all set and we can start using it.
770 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
771 BasicBlock *ExitBlock = LoopExitBlocks[i];
772 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
Chandler Carruthfc258542014-02-11 12:52:27 +0000773 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
774 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
Dan Gohmanb9487362012-08-08 00:00:26 +0000775 Instruction *InsertPos = LoopInsertPts[i];
Chandler Carruthfc258542014-02-11 12:52:27 +0000776 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000777 NewSI->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000778 NewSI->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000779 if (AATags) NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000780 }
781 }
782
Craig Topper3e4c6972014-03-05 09:10:37 +0000783 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000784 // Update alias analysis.
785 AST.copyValue(LI, V);
786 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000787 void instructionDeleted(Instruction *I) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000788 AST.deleteValue(I);
789 }
790 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000791} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000792
Hal Finkel3d4269a2015-02-22 18:35:32 +0000793/// Try to promote memory values to scalars by sinking stores out of the
794/// loop and moving loads to before the loop. We do this by looping over
795/// the stores in the loop, looking for stores to Must pointers which are
796/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000797///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000798bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
799 SmallVectorImpl<BasicBlock*>&ExitBlocks,
800 SmallVectorImpl<Instruction*>&InsertPts,
801 PredIteratorCache &PIC, LoopInfo *LI,
802 DominatorTree *DT, Loop *CurLoop,
803 AliasSetTracker *CurAST,
804 LICMSafetyInfo * SafetyInfo) {
805 // Verify inputs.
806 assert(LI != nullptr && DT != nullptr &&
807 CurLoop != nullptr && CurAST != nullptr &&
808 SafetyInfo != nullptr &&
809 "Unexpected Input to promoteLoopAccessesToScalars");
810 // Initially set Changed status to false.
811 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000812 // We can promote this alias set if it has a store, if it is a "Must" alias
813 // set, if the pointer is loop invariant, and if we are not eliminating any
814 // volatile loads or stores.
815 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
816 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000817 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000818
Chris Lattner1dc98b42010-08-29 06:43:52 +0000819 assert(!AS.empty() &&
820 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000821
Chris Lattner1dc98b42010-08-29 06:43:52 +0000822 Value *SomePtr = AS.begin()->getValue();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000823 BasicBlock * Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000824
Chris Lattner1dc98b42010-08-29 06:43:52 +0000825 // It isn't safe to promote a load/store from the loop if the load/store is
826 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000827 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000828 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000829 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000830 // into:
831 //
832 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
833 //
834 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000835 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000836 // It is safe to promote P if all uses are direct load/stores and if at
837 // least one is guaranteed to be executed.
838 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000839
Chris Lattner1dc98b42010-08-29 06:43:52 +0000840 SmallVector<Instruction*, 64> LoopUses;
841 SmallPtrSet<Value*, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000842
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000843 // We start with an alignment of one and try to find instructions that allow
844 // us to prove better alignment.
845 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000846 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000847 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000848
Chris Lattner1dc98b42010-08-29 06:43:52 +0000849 // Check that all of the pointers in the alias set have the same type. We
850 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000851 // different sizes. While we are at it, collect alignment and AA info.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000852 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
853 Value *ASIV = ASI->getValue();
854 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000855
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000856 // Check that all of the pointers in the alias set have the same type. We
857 // cannot (yet) promote a memory location that is loaded and stored in
858 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000859 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000860 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000861
Chandler Carruthcdf47882014-03-09 03:16:01 +0000862 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000863 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000864 Instruction *UI = dyn_cast<Instruction>(U);
865 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000866 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000867
Chris Lattner1dc98b42010-08-29 06:43:52 +0000868 // If there is an non-load/store instruction in the loop, we can't promote
869 // it.
Pete Cooper0cabcf22015-05-13 01:12:18 +0000870 if (const LoadInst *load = dyn_cast<LoadInst>(UI)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000871 assert(!load->isVolatile() && "AST broken");
872 if (!load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000873 return Changed;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000874 } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000875 // Stores *of* the pointer are not interesting, only stores *to* the
876 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000877 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000878 continue;
Eli Friedman91386c72011-08-15 20:52:09 +0000879 assert(!store->isVolatile() && "AST broken");
880 if (!store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000881 return Changed;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000882 // Don't sink stores from loops without dedicated block exits. Exits
883 // containing indirect branches are not transformed by loop simplify,
Bruno Cardoso Lopesd035fbb2014-12-02 14:22:34 +0000884 // make sure we catch that. An additional load may be generated in the
885 // preheader for SSA updater, so also avoid sinking when no preheader
886 // is available.
887 if (!HasDedicatedExits || !Preheader)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000888 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000889
890 // Note that we only check GuaranteedToExecute inside the store case
891 // so that we do not introduce stores where they did not exist before
892 // (which would break the LLVM concurrency model).
893
894 // If the alignment of this instruction allows us to specify a more
895 // restrictive (and performant) alignment and if we are sure this
896 // instruction will be executed, update the alignment.
897 // Larger is better, with the exception of 0 being the best alignment.
Eli Friedman91386c72011-08-15 20:52:09 +0000898 unsigned InstAlignment = store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000899 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000900 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000901 GuaranteedToExecute = true;
902 Alignment = InstAlignment;
903 }
904
905 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000906 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
907 CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000908
Chris Lattnerbe901902010-09-06 05:11:24 +0000909 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000910 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000911
Hal Finkelcc39b672014-07-24 12:16:19 +0000912 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000913 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000914 // On the first load/store, just take its AA tags.
915 UI->getAAMetadata(AATags);
916 } else if (AATags) {
917 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +0000918 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000919
920 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000921 }
922 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000923
Chris Lattner1dc98b42010-08-29 06:43:52 +0000924 // If there isn't a guaranteed-to-execute instruction, we can't promote.
925 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000926 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000927
Chris Lattner1dc98b42010-08-29 06:43:52 +0000928 // Otherwise, this is safe to promote, lets do it!
Tobias Grossera3928f52011-07-06 19:20:02 +0000929 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +0000930 Changed = true;
931 ++NumPromoted;
932
Eli Friedmanddf7f552011-05-27 20:31:51 +0000933 // Grab a debug location for the inserted loads/stores; given that the
934 // inserted loads/stores have little relation to the original loads/stores,
935 // this code just arbitrarily picks a location from one, since any debug
936 // location is better than none.
937 DebugLoc DL = LoopUses[0]->getDebugLoc();
938
Dan Gohmanb9487362012-08-08 00:00:26 +0000939 // Figure out the loop exits and their insertion points, if this is the
940 // first promotion.
941 if (ExitBlocks.empty()) {
942 CurLoop->getUniqueExitBlocks(ExitBlocks);
943 InsertPts.resize(ExitBlocks.size());
944 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
945 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
946 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000947
Chris Lattner1dc98b42010-08-29 06:43:52 +0000948 // We use the SSAUpdater interface to insert phi nodes as required.
949 SmallVector<PHINode*, 16> NewPHIs;
950 SSAUpdater SSA(&NewPHIs);
Pete Cooper7c4d7b82015-05-13 22:43:09 +0000951 LoopPromoter Promoter(SomePtr, LoopUses, SSA,
Pete Cooper41e0ee32015-05-13 01:12:16 +0000952 PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +0000953 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +0000954
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000955 // Set up the preheader to have a definition of the value. It is the live-out
956 // value from the preheader that uses in the loop will use.
957 LoadInst *PreheaderLoad =
958 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
959 Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000960 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000961 PreheaderLoad->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000962 if (AATags) PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000963 SSA.AddAvailableValue(Preheader, PreheaderLoad);
964
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000965 // Rewrite all the loads in the loop and remember all the definitions from
966 // stores in the loop.
967 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +0000968
969 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
970 if (PreheaderLoad->use_empty())
971 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000972
973 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +0000974}
Devang Patelb98a0972007-07-31 08:01:41 +0000975
Hal Finkel3d4269a2015-02-22 18:35:32 +0000976/// Simple Analysis hook. Clone alias set info.
977///
Devang Patelb98a0972007-07-31 08:01:41 +0000978void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000979 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000980 if (!AST)
981 return;
982
983 AST->copyValue(From, To);
984}
985
Hal Finkel3d4269a2015-02-22 18:35:32 +0000986/// Simple Analysis hook. Delete value V from alias set
987///
Devang Patelb98a0972007-07-31 08:01:41 +0000988void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000989 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000990 if (!AST)
991 return;
992
993 AST->deleteValue(V);
994}
David Peixotto0d4d5e62014-09-24 16:48:31 +0000995
996/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000997///
David Peixotto0d4d5e62014-09-24 16:48:31 +0000998void LICM::deleteAnalysisLoop(Loop *L) {
999 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1000 if (!AST)
1001 return;
1002
1003 delete AST;
1004 LoopToAliasSetMap.erase(L);
1005}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001006
1007
1008/// Return true if the body of this loop may store into the memory
1009/// location pointed to by V.
1010///
1011static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1012 const AAMDNodes &AAInfo,
1013 AliasSetTracker *CurAST) {
1014 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1015 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1016}
1017
1018/// Little predicate that returns true if the specified basic block is in
1019/// a subloop of the current one, not the current one itself.
1020///
1021static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1022 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1023 return LI->getLoopFor(BB) != CurLoop;
1024}
1025