blob: 3b197e4ac2ca8bd9bde5acf3f99e2a177f29a0df [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000034#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000035#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000036#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000037#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner030f0202010-08-31 23:00:16 +000038#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000039#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamese0a54542016-03-09 23:07:53 +000040#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000041#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/LoopPass.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000043#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000044#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000045#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000047#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000048#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000056#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000057#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000058#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000061#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000063#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000064#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000065#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000066#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000067using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000068
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "licm"
70
Dehao Chend55bc4c2016-05-05 00:54:54 +000071STATISTIC(NumSunk, "Number of instructions sunk out of loop");
72STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000073STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
74STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000075STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076
Dan Gohmand78c4002008-05-13 00:00:25 +000077static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000078 DisablePromotion("disable-licm-promotion", cl::Hidden,
79 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000080
Hal Finkel3d4269a2015-02-22 18:35:32 +000081static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000082static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
83 const LICMSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000084static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
85 const LICMSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000086static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000087 const Loop *CurLoop, AliasSetTracker *CurAST,
88 const LICMSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000089static bool isGuaranteedToExecute(const Instruction &Inst,
Dehao Chend55bc4c2016-05-05 00:54:54 +000090 const DominatorTree *DT, const Loop *CurLoop,
Pete Cooper0cabcf22015-05-13 01:12:18 +000091 const LICMSafetyInfo *SafetyInfo);
92static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
93 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +000094 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +000095 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +000096 const LICMSafetyInfo *SafetyInfo,
97 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000098static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +000099 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000100 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000101static Instruction *
102CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
103 const LoopInfo *LI,
104 const LICMSafetyInfo *SafetyInfo);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000105static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000106 DominatorTree *DT, TargetLibraryInfo *TLI,
107 Loop *CurLoop, AliasSetTracker *CurAST,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000108 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000109
Dan Gohmand78c4002008-05-13 00:00:25 +0000110namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000111struct LICM : public LoopPass {
112 static char ID; // Pass identification, replacement for typeid
113 LICM() : LoopPass(ID) {
114 initializeLICMPass(*PassRegistry::getPassRegistry());
115 }
Devang Patel09f162c2007-05-01 21:15:47 +0000116
Dehao Chend55bc4c2016-05-05 00:54:54 +0000117 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000118
Dehao Chend55bc4c2016-05-05 00:54:54 +0000119 /// This transformation requires natural loop information & requires that
120 /// loop preheaders be inserted into the CFG...
121 ///
122 void getAnalysisUsage(AnalysisUsage &AU) const override {
123 AU.setPreservesCFG();
124 AU.addRequired<TargetLibraryInfoWrapperPass>();
125 getLoopAnalysisUsage(AU);
126 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000127
Dehao Chend55bc4c2016-05-05 00:54:54 +0000128 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000129
Dehao Chend55bc4c2016-05-05 00:54:54 +0000130 bool doFinalization() override {
131 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
132 return false;
133 }
Devang Patel69730c92007-03-07 04:41:30 +0000134
Dehao Chend55bc4c2016-05-05 00:54:54 +0000135private:
136 AliasAnalysis *AA; // Current AliasAnalysis information
137 LoopInfo *LI; // Current LoopInfo
138 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000139
Dehao Chend55bc4c2016-05-05 00:54:54 +0000140 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
Chad Rosier43a33062011-12-02 01:26:24 +0000141
Dehao Chend55bc4c2016-05-05 00:54:54 +0000142 // State that is updated as we process loops.
143 bool Changed; // Set to true when we change anything.
144 BasicBlock *Preheader; // The preheader block of the current loop...
145 Loop *CurLoop; // The current loop we are working on...
146 AliasSetTracker *CurAST; // AliasSet information for the current loop...
147 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000148
Dehao Chend55bc4c2016-05-05 00:54:54 +0000149 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
150 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
151 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000152
Dehao Chend55bc4c2016-05-05 00:54:54 +0000153 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
154 /// set.
155 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000156
Dehao Chend55bc4c2016-05-05 00:54:54 +0000157 /// Simple Analysis hook. Delete loop L from alias set map.
158 void deleteAnalysisLoop(Loop *L) override;
Roman Gareev036c0882016-02-15 14:48:50 +0000159
Dehao Chend55bc4c2016-05-05 00:54:54 +0000160 AliasSetTracker *collectAliasInfoForLoop(Loop *L);
161};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000162}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000163
Dan Gohmand78c4002008-05-13 00:00:25 +0000164char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000165INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000166INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000167INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000168INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000169
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000170Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000171
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000172/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000173/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000174/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000175///
Devang Patel69730c92007-03-07 04:41:30 +0000176bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000177 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000178 return false;
179
Chris Lattner45d67d62003-02-24 03:52:32 +0000180 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000181
Chris Lattner45d67d62003-02-24 03:52:32 +0000182 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000183 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000184 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth73523022014-01-13 13:07:17 +0000185 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000186
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000187 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +0000188
Chandler Carruthfc258542014-02-11 12:52:27 +0000189 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
190
Chandler Carruthad8cb382016-02-27 04:34:07 +0000191 CurAST = collectAliasInfoForLoop(L);
Tobias Grossera3928f52011-07-06 19:20:02 +0000192
Chris Lattner6ec05f52002-05-10 22:44:58 +0000193 CurLoop = L;
194
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000195 // Get the preheader block to move instructions into...
196 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000197
Hal Finkel3d4269a2015-02-22 18:35:32 +0000198 // Compute loop safety information.
199 LICMSafetyInfo SafetyInfo;
200 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000201
Chris Lattner6ec05f52002-05-10 22:44:58 +0000202 // We want to visit all of the instructions in this loop... that are not parts
203 // of our subloops (they have already had their invariants hoisted out of
204 // their loop, into this loop, so there is no need to process the BODIES of
205 // the subloops).
206 //
Chris Lattner64437692002-09-29 21:46:09 +0000207 // Traverse the body of the loop in depth first order on the dominator tree so
208 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000209 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000210 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000211 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000212 if (L->hasDedicatedExits())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000213 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
214 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000215 if (Preheader)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000216 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000217 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000218
Chris Lattner45d67d62003-02-24 03:52:32 +0000219 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000220 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000221 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000222 SmallVector<BasicBlock *, 8> ExitBlocks;
223 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000224 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000225
Chris Lattner1dc98b42010-08-29 06:43:52 +0000226 // Loop over all of the alias sets in the tracker object.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000227 for (AliasSet &AS : *CurAST)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000228 Changed |=
229 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT,
230 TLI, CurLoop, CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000231
232 // Once we have promoted values across the loop body we have to recursively
233 // reform LCSSA as any nested loop may now have values defined within the
234 // loop used in the outer loop.
235 // FIXME: This is really heavy handed. It would be a bit better to use an
236 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
237 // it as it went.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000238 if (Changed) {
239 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
240 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr);
241 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000242 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000243
Chandler Carruthfc258542014-02-11 12:52:27 +0000244 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
245 // specifically moving instructions across the loop boundary and so it is
246 // especially in need of sanity checking here.
247 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
248 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
249 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000250
Chris Lattner6ec05f52002-05-10 22:44:58 +0000251 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000252 CurLoop = nullptr;
253 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000254
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000255 // If this loop is nested inside of another one, save the alias information
256 // for when we process the outer loop.
257 if (L->getParentLoop())
258 LoopToAliasSetMap[L] = CurAST;
259 else
260 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000261
262 if (Changed)
263 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
264 SEWP->getSE().forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000265 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000266}
267
Hal Finkel3d4269a2015-02-22 18:35:32 +0000268/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000269/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000270/// first order w.r.t the DominatorTree. This allows us to visit uses before
271/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000272///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000273bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
274 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
275 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000276
Hal Finkel3d4269a2015-02-22 18:35:32 +0000277 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000278 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
279 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
280 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000281
Hal Finkel3d4269a2015-02-22 18:35:32 +0000282 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000283 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000284 if (!CurLoop->contains(BB))
285 return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000286
Chris Lattner263f8042010-08-29 18:22:25 +0000287 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000288 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000289 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000290 for (DomTreeNode *Child : Children)
291 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
292
Chris Lattner547192d62003-12-19 07:22:45 +0000293 // Only need to process the contents of this block if it is not part of a
294 // subloop (which would already have been processed).
Dehao Chend55bc4c2016-05-05 00:54:54 +0000295 if (inSubLoop(BB, CurLoop, LI))
296 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000297
Dehao Chend55bc4c2016-05-05 00:54:54 +0000298 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
Chris Lattner91846012003-12-19 08:18:16 +0000299 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000300
Chris Lattner263f8042010-08-29 18:22:25 +0000301 // If the instruction is dead, we would try to sink it because it isn't used
302 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000303 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000304 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000305 ++II;
306 CurAST->deleteValue(&I);
307 I.eraseFromParent();
308 Changed = true;
309 continue;
310 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000311
Chris Lattner547192d62003-12-19 07:22:45 +0000312 // Check to see if we can sink this instruction to the exit blocks
313 // of the loop. We can do this if the all users of the instruction are
314 // outside of the loop. In this case, it doesn't even matter if the
315 // operands of the instruction are loop invariant.
316 //
David Majnemer42a07302016-01-04 03:37:39 +0000317 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000318 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000319 ++II;
David Majnemer42a07302016-01-04 03:37:39 +0000320 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
Chris Lattner91846012003-12-19 08:18:16 +0000321 }
Chris Lattner547192d62003-12-19 07:22:45 +0000322 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000323 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000324}
325
Hal Finkel3d4269a2015-02-22 18:35:32 +0000326/// Walk the specified region of the CFG (defined by all blocks dominated by
327/// the specified block, and that are in the current loop) in depth first
328/// order w.r.t the DominatorTree. This allows us to visit definitions before
329/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000330///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
332 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
333 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000334 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000335 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
336 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
337 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000338
Owen Andersonc24701e2007-04-24 06:40:39 +0000339 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000340
Chris Lattner05e86302002-09-29 22:26:07 +0000341 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000342 if (!CurLoop->contains(BB))
343 return false;
Sanjay Patel99133222016-01-13 23:01:57 +0000344
Chris Lattneraaaea512003-12-10 06:41:05 +0000345 // Only need to process the contents of this block if it is not part of a
346 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000347 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000348 if (!inSubLoop(BB, CurLoop, LI))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000349 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000350 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000351 // Try constant folding this instruction. If all the operands are
352 // constants, it is technically hoistable, but it would be better to just
353 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000354 if (Constant *C = ConstantFoldInstruction(
355 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000356 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
357 CurAST->copyValue(&I, C);
358 CurAST->deleteValue(&I);
359 I.replaceAllUsesWith(C);
360 I.eraseFromParent();
361 continue;
362 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000363
Chris Lattner547192d62003-12-19 07:22:45 +0000364 // Try hoisting the instruction out to the preheader. We can only do this
365 // if all of the operands of the instruction are loop invariant and if it
366 // is safe to hoist the instruction.
367 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 if (CurLoop->hasLoopInvariantOperands(&I) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000369 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000370 isSafeToExecuteUnconditionally(
371 I, DT, TLI, CurLoop, SafetyInfo,
372 CurLoop->getLoopPreheader()->getTerminator()))
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000373 Changed |= hoist(I, DT, CurLoop, SafetyInfo);
Chris Lattner030f0202010-08-31 23:00:16 +0000374 }
Chris Lattner64437692002-09-29 21:46:09 +0000375
Dehao Chend55bc4c2016-05-05 00:54:54 +0000376 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000377 for (DomTreeNode *Child : Children)
378 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000379 return Changed;
380}
381
382/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000383/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000384///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000385void llvm::computeLICMSafetyInfo(LICMSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000386 assert(CurLoop != nullptr && "CurLoop cant be null");
387 BasicBlock *Header = CurLoop->getHeader();
388 // Setting default safety values.
389 SafetyInfo->MayThrow = false;
390 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000391 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000392 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
393 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
394 SafetyInfo->HeaderMayThrow |= I->mayThrow();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000395
Hal Finkel3d4269a2015-02-22 18:35:32 +0000396 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000397 // Iterate over loop instructions and compute safety info.
398 for (Loop::block_iterator BB = CurLoop->block_begin(),
399 BBE = CurLoop->block_end();
400 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000401 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
402 (I != E) && !SafetyInfo->MayThrow; ++I)
403 SafetyInfo->MayThrow |= I->mayThrow();
David Majnemer42a07302016-01-04 03:37:39 +0000404
405 // Compute funclet colors if we might sink/hoist in a function with a funclet
406 // personality routine.
407 Function *Fn = CurLoop->getHeader()->getParent();
408 if (Fn->hasPersonalityFn())
409 if (Constant *PersonalityFn = Fn->getPersonalityFn())
410 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
411 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000412}
413
Chris Lattneraaaea512003-12-10 06:41:05 +0000414/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
415/// instruction.
416///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000417bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000418 TargetLibraryInfo *TLI, Loop *CurLoop,
419 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000420 // Loads have extra constraints we have to verify before we can hoist them.
421 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000422 if (!LI->isUnordered())
Dehao Chend55bc4c2016-05-05 00:54:54 +0000423 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000424
Chris Lattner8a8fb902008-07-23 05:06:28 +0000425 // Loads from constant memory are always safe to move, even if they end up
426 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000427 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000428 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000429 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000430 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000431
Chris Lattner65c11932003-12-09 19:32:44 +0000432 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000433 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000434 if (LI->getType()->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000435 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000436
437 AAMDNodes AAInfo;
438 LI->getAAMetadata(AAInfo);
439
Hal Finkel3d4269a2015-02-22 18:35:32 +0000440 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000441 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000442 // Don't sink or hoist dbg info; it's legal, but not useful.
443 if (isa<DbgInfoIntrinsic>(I))
444 return false;
445
David Majnemer42a07302016-01-04 03:37:39 +0000446 // Don't sink calls which can throw.
447 if (CI->mayThrow())
448 return false;
449
Eli Friedman942e1c12011-05-27 18:37:52 +0000450 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000451 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
452 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000453 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000454 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000455 // A readonly argmemonly function only reads from memory pointed to by
456 // it's arguments with arbitrary offsets. If we can prove there are no
457 // writes to this memory in the loop, we can hoist or sink.
458 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
459 for (Value *Op : CI->arg_operands())
460 if (Op->getType()->isPointerTy() &&
461 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
462 AAMDNodes(), CurAST))
463 return false;
464 return true;
465 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000466 // If this call only reads from memory and there are no writes to memory
467 // in the loop, we can hoist or sink the call as appropriate.
468 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000469 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000470 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 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000475 if (!FoundMod)
476 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000477 }
478
Nadav Rotem03dcd852012-09-04 10:25:04 +0000479 // FIXME: This should use mod/ref information to see if we can hoist or
480 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000481
Chris Lattner20cda262004-03-15 04:11:30 +0000482 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000483 }
484
Nadav Rotem03dcd852012-09-04 10:25:04 +0000485 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000486 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
487 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
488 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
489 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
490 !isa<InsertValueInst>(I))
491 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000492
Philip Reamesb47b9c22015-05-22 02:14:05 +0000493 // TODO: Plumb the context instruction through to make hoisting and sinking
494 // more powerful. Hoisting of loads already works due to the special casing
Dehao Chend55bc4c2016-05-05 00:54:54 +0000495 // above.
Philip Reamesb47b9c22015-05-22 02:14:05 +0000496 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
497 nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000498}
499
Hal Finkel3d4269a2015-02-22 18:35:32 +0000500/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000501/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000502/// This is true when all incoming values are that instruction.
503/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000504///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000505static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000506 for (const Value *IncValue : PN.incoming_values())
507 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000508 return false;
509
510 return true;
511}
512
Hal Finkel3d4269a2015-02-22 18:35:32 +0000513/// Return true if the only users of this instruction are outside of
514/// the loop. If this is true, we can sink the instruction to the exit
515/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000516///
David Majnemer42a07302016-01-04 03:37:39 +0000517static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
518 const LICMSafetyInfo *SafetyInfo) {
519 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000520 for (const User *U : I.users()) {
521 const Instruction *UI = cast<Instruction>(U);
522 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000523 const BasicBlock *BB = PN->getParent();
524 // We cannot sink uses in catchswitches.
525 if (isa<CatchSwitchInst>(BB->getTerminator()))
526 return false;
527
528 // We need to sink a callsite to a unique funclet. Avoid sinking if the
529 // phi use is too muddled.
530 if (isa<CallInst>(I))
531 if (!BlockColors.empty() &&
532 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
533 return false;
534
Chandler Carruth8765cf72014-01-25 04:07:24 +0000535 // A PHI node where all of the incoming values are this instruction are
536 // special -- they can just be RAUW'ed with the instruction and thus
537 // don't require a use in the predecessor. This is a particular important
538 // special case because it is the pattern found in LCSSA form.
539 if (isTriviallyReplacablePHI(*PN, I)) {
540 if (CurLoop->contains(PN))
541 return false;
542 else
543 continue;
544 }
545
546 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
547 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000548 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
549 if (PN->getIncomingValue(i) == &I)
550 if (CurLoop->contains(PN->getIncomingBlock(i)))
551 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000552
553 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000554 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000555
Chandler Carruthcdf47882014-03-09 03:16:01 +0000556 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000557 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000558 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000559 return true;
560}
561
David Majnemer42a07302016-01-04 03:37:39 +0000562static Instruction *
563CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
564 const LoopInfo *LI,
565 const LICMSafetyInfo *SafetyInfo) {
566 Instruction *New;
567 if (auto *CI = dyn_cast<CallInst>(&I)) {
568 const auto &BlockColors = SafetyInfo->BlockColors;
569
570 // Sinking call-sites need to be handled differently from other
571 // instructions. The cloned call-site needs a funclet bundle operand
572 // appropriate for it's location in the CFG.
573 SmallVector<OperandBundleDef, 1> OpBundles;
574 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
575 BundleIdx != BundleEnd; ++BundleIdx) {
576 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
577 if (Bundle.getTagID() == LLVMContext::OB_funclet)
578 continue;
579
580 OpBundles.emplace_back(Bundle);
581 }
582
583 if (!BlockColors.empty()) {
584 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
585 assert(CV.size() == 1 && "non-unique color for exit block!");
586 BasicBlock *BBColor = CV.front();
587 Instruction *EHPad = BBColor->getFirstNonPHI();
588 if (EHPad->isEHPad())
589 OpBundles.emplace_back("funclet", EHPad);
590 }
591
592 New = CallInst::Create(CI, OpBundles);
593 } else {
594 New = I.clone();
595 }
596
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000597 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000598 if (!I.getName().empty())
599 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000600
601 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
602 // particularly cheap because we can rip off the PHI node that we're
603 // replacing for the number and blocks of the predecessors.
604 // OPT: If this shows up in a profile, we can instead finish sinking all
605 // invariant instructions, and then walk their operands to re-establish
606 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
607 // sinking bottom-up.
608 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
609 ++OI)
610 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
611 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
612 if (!OLoop->contains(&PN)) {
613 PHINode *OpPN =
614 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000615 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000616 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
617 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
618 *OI = OpPN;
619 }
620 return New;
621}
622
Hal Finkel3d4269a2015-02-22 18:35:32 +0000623/// When an instruction is found to only be used outside of the loop, this
624/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000625/// This method is guaranteed to remove the original instruction from its
626/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000627///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000628static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000629 const Loop *CurLoop, AliasSetTracker *CurAST,
630 const LICMSafetyInfo *SafetyInfo) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000631 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000632 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000633 if (isa<LoadInst>(I))
634 ++NumMovedLoads;
635 else if (isa<CallInst>(I))
636 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000637 ++NumSunk;
638 Changed = true;
639
Chandler Carruthfc258542014-02-11 12:52:27 +0000640#ifndef NDEBUG
641 SmallVector<BasicBlock *, 32> ExitBlocks;
642 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000643 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000644 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000645#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000646
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000647 // Clones of this instruction. Don't create more than one per exit block!
648 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
649
Chandler Carruthfc258542014-02-11 12:52:27 +0000650 // If this instruction is only used outside of the loop, then all users are
651 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
652 // the instruction.
653 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000654 Value::user_iterator UI = I.user_begin();
655 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000656 if (!DT->isReachableFromEntry(User->getParent())) {
657 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
658 continue;
659 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000660 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000661 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000662
David Majnemer6bc83e02015-07-12 03:53:05 +0000663 // Surprisingly, instructions can be used outside of loops without any
664 // exits. This can only happen in PHI nodes if the incoming block is
665 // unreachable.
666 Use &U = UI.getUse();
667 BasicBlock *BB = PN->getIncomingBlock(U);
668 if (!DT->isReachableFromEntry(BB)) {
669 U = UndefValue::get(I.getType());
670 continue;
671 }
672
Chandler Carruthfc258542014-02-11 12:52:27 +0000673 BasicBlock *ExitBlock = PN->getParent();
674 assert(ExitBlockSet.count(ExitBlock) &&
675 "The LCSSA PHI is not in an exit block!");
676
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000677 Instruction *New;
678 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000679 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000680 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000681 else
682 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000683 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000684
685 PN->replaceAllUsesWith(New);
686 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000687 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000688
Chris Lattner1a1ed692010-08-29 18:00:00 +0000689 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000690 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000691 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000692}
Chris Lattner64437692002-09-29 21:46:09 +0000693
Hal Finkel3d4269a2015-02-22 18:35:32 +0000694/// When an instruction is found to only use loop invariant operands that
695/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000696///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000697static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
698 const LICMSafetyInfo *SafetyInfo) {
699 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000700 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
701 << "\n");
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000702
703 // Metadata can be dependent on conditions we are hoisting above.
704 // Conservatively strip all metadata on the instruction unless we were
705 // guaranteed to execute I if we entered the loop, in which case the metadata
706 // is valid in the loop preheader.
707 if (I.hasMetadataOtherThanDebugLoc() &&
708 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
709 // time in isGuaranteedToExecute if we don't actually have anything to
710 // drop. It is a compile time optimization, not required for correctness.
711 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
712 I.dropUnknownNonDebugMetadata();
713
Chris Lattner6ac06592010-08-29 18:18:40 +0000714 // Move the new node to the Preheader, before its terminator.
715 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000716
Dehao Chend55bc4c2016-05-05 00:54:54 +0000717 if (isa<LoadInst>(I))
718 ++NumMovedLoads;
719 else if (isa<CallInst>(I))
720 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000721 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000722 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000723}
724
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000725/// Only sink or hoist an instruction if it is not a trapping instruction,
726/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000727/// or if it is a trapping instruction and is guaranteed to execute.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000728static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000729 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000730 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000731 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000732 const LICMSafetyInfo *SafetyInfo,
733 const Instruction *CtxI) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000734 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000735 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000736
Hal Finkel3d4269a2015-02-22 18:35:32 +0000737 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000738}
739
Pete Cooper0cabcf22015-05-13 01:12:18 +0000740static bool isGuaranteedToExecute(const Instruction &Inst,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000741 const DominatorTree *DT, const Loop *CurLoop,
742 const LICMSafetyInfo *SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000743
Philip Reamesb35f46c2014-12-29 23:00:57 +0000744 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000745 // of the exit blocks. If it doesn't, then there is a path out of the loop
746 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000747
Chris Lattnerc0517682003-12-09 17:18:00 +0000748 // If the instruction is in the header block for the loop (which is very
749 // common), it is always guaranteed to dominate the exit blocks. Since this
750 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000751 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000752 // If there's a throw in the header block, we can't guarantee we'll reach
753 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000754 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000755
756 // Somewhere in this loop there is an instruction which may throw and make us
757 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000758 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000759 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000760
Chris Lattnerc0517682003-12-09 17:18:00 +0000761 // Get the exit blocks for the current loop.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000762 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000763 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000764
Chris Lattner27497ec2011-01-02 18:45:39 +0000765 // Verify that the block dominates each of the exit blocks of the loop.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000766 for (BasicBlock *ExitBlock : ExitBlocks)
767 if (!DT->dominates(Inst.getParent(), ExitBlock))
Chris Lattneraaaea512003-12-10 06:41:05 +0000768 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000769
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000770 // As a degenerate case, if the loop is statically infinite then we haven't
771 // proven anything since there are no exit blocks.
772 if (ExitBlocks.empty())
773 return false;
774
Tanya Lattner57c03df2003-08-05 18:45:46 +0000775 return true;
776}
777
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000778namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000779class LoopPromoter : public LoadAndStorePromoter {
780 Value *SomePtr; // Designated pointer to store to.
781 SmallPtrSetImpl<Value *> &PointerMustAliases;
782 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
783 SmallVectorImpl<Instruction *> &LoopInsertPts;
784 PredIteratorCache &PredCache;
785 AliasSetTracker &AST;
786 LoopInfo &LI;
787 DebugLoc DL;
788 int Alignment;
789 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000790
Dehao Chend55bc4c2016-05-05 00:54:54 +0000791 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
792 if (Instruction *I = dyn_cast<Instruction>(V))
793 if (Loop *L = LI.getLoopFor(I->getParent()))
794 if (!L->contains(BB)) {
795 // We need to create an LCSSA PHI node for the incoming value and
796 // store that.
797 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
798 I->getName() + ".lcssa", &BB->front());
799 for (BasicBlock *Pred : PredCache.get(BB))
800 PN->addIncoming(I, Pred);
801 return PN;
802 }
803 return V;
804 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000805
Dehao Chend55bc4c2016-05-05 00:54:54 +0000806public:
807 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
808 SmallPtrSetImpl<Value *> &PMA,
809 SmallVectorImpl<BasicBlock *> &LEB,
810 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
811 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
812 const AAMDNodes &AATags)
813 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
814 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000815 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000816
Dehao Chend55bc4c2016-05-05 00:54:54 +0000817 bool isInstInList(Instruction *I,
818 const SmallVectorImpl<Instruction *> &) const override {
819 Value *Ptr;
820 if (LoadInst *LI = dyn_cast<LoadInst>(I))
821 Ptr = LI->getOperand(0);
822 else
823 Ptr = cast<StoreInst>(I)->getPointerOperand();
824 return PointerMustAliases.count(Ptr);
825 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000826
Dehao Chend55bc4c2016-05-05 00:54:54 +0000827 void doExtraRewritesBeforeFinalDeletion() const override {
828 // Insert stores after in the loop exit blocks. Each exit block gets a
829 // store of the live-out values that feed them. Since we've already told
830 // the SSA updater about the defs in the loop and the preheader
831 // definition, it is all set and we can start using it.
832 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
833 BasicBlock *ExitBlock = LoopExitBlocks[i];
834 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
835 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
836 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
837 Instruction *InsertPos = LoopInsertPts[i];
838 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
839 NewSI->setAlignment(Alignment);
840 NewSI->setDebugLoc(DL);
841 if (AATags)
842 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000843 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000844 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000845
Dehao Chend55bc4c2016-05-05 00:54:54 +0000846 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
847 // Update alias analysis.
848 AST.copyValue(LI, V);
849 }
850 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
851};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000852} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000853
Hal Finkel3d4269a2015-02-22 18:35:32 +0000854/// Try to promote memory values to scalars by sinking stores out of the
855/// loop and moving loads to before the loop. We do this by looping over
856/// the stores in the loop, looking for stores to Must pointers which are
857/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000858///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000859bool llvm::promoteLoopAccessesToScalars(
860 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
861 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
862 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
863 Loop *CurLoop, AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000864 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000865 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
866 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +0000867 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000868
Chris Lattner1dc98b42010-08-29 06:43:52 +0000869 // We can promote this alias set if it has a store, if it is a "Must" alias
870 // set, if the pointer is loop invariant, and if we are not eliminating any
871 // volatile loads or stores.
872 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
873 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000874 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000875
Chris Lattner1dc98b42010-08-29 06:43:52 +0000876 assert(!AS.empty() &&
877 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000878
Chris Lattner1dc98b42010-08-29 06:43:52 +0000879 Value *SomePtr = AS.begin()->getValue();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000880 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000881
Chris Lattner1dc98b42010-08-29 06:43:52 +0000882 // It isn't safe to promote a load/store from the loop if the load/store is
883 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000884 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000885 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000886 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000887 // into:
888 //
889 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
890 //
891 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000892 //
Philip Reamesb54c8e62016-03-09 22:59:30 +0000893 // The safety property divides into two parts:
894 // 1) The memory may not be dereferenceable on entry to the loop. In this
895 // case, we can't insert the required load in the preheader.
896 // 2) The memory model does not allow us to insert a store along any dynamic
897 // path which did not originally have one.
898 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000899 // It is safe to promote P if all uses are direct load/stores and if at
900 // least one is guaranteed to be executed.
901 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000902
Philip Reamesb54c8e62016-03-09 22:59:30 +0000903 // It is also safe to promote P if we can prove that speculating a load into
904 // the preheader is safe (i.e. proving dereferenceability on all
905 // paths through the loop), and that the memory can be proven thread local
906 // (so that the memory model requirement doesn't apply.) We first establish
907 // the former, and then run a capture analysis below to establish the later.
908 // We can use any access within the alias set to prove dereferenceability
909 // since they're all must alias.
910 bool CanSpeculateLoad = false;
911
Dehao Chend55bc4c2016-05-05 00:54:54 +0000912 SmallVector<Instruction *, 64> LoopUses;
913 SmallPtrSet<Value *, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000914
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000915 // We start with an alignment of one and try to find instructions that allow
916 // us to prove better alignment.
917 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000918 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000919 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000920
Philip Reamesb54c8e62016-03-09 22:59:30 +0000921 // Don't sink stores from loops without dedicated block exits. Exits
922 // containing indirect branches are not transformed by loop simplify,
923 // make sure we catch that. An additional load may be generated in the
924 // preheader for SSA updater, so also avoid sinking when no preheader
925 // is available.
926 if (!HasDedicatedExits || !Preheader)
927 return false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000928
Philip Reamesb54c8e62016-03-09 22:59:30 +0000929 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
930
Chris Lattner1dc98b42010-08-29 06:43:52 +0000931 // Check that all of the pointers in the alias set have the same type. We
932 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000933 // different sizes. While we are at it, collect alignment and AA info.
Sanjay Patel99133222016-01-13 23:01:57 +0000934 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000935 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
936 Value *ASIV = ASI->getValue();
937 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000938
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000939 // Check that all of the pointers in the alias set have the same type. We
940 // cannot (yet) promote a memory location that is loaded and stored in
941 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000942 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000943 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000944
Chandler Carruthcdf47882014-03-09 03:16:01 +0000945 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000946 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000947 Instruction *UI = dyn_cast<Instruction>(U);
948 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000949 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000950
Chris Lattner1dc98b42010-08-29 06:43:52 +0000951 // If there is an non-load/store instruction in the loop, we can't promote
952 // it.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000953 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
954 assert(!Load->isVolatile() && "AST broken");
955 if (!Load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000956 return Changed;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000957
958 if (!GuaranteedToExecute && !CanSpeculateLoad)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000959 CanSpeculateLoad = isSafeToExecuteUnconditionally(
960 *Load, DT, TLI, CurLoop, SafetyInfo, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +0000961 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000962 // Stores *of* the pointer are not interesting, only stores *to* the
963 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000964 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000965 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000966 assert(!Store->isVolatile() && "AST broken");
967 if (!Store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000968 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000969
970 // Note that we only check GuaranteedToExecute inside the store case
971 // so that we do not introduce stores where they did not exist before
972 // (which would break the LLVM concurrency model).
973
974 // If the alignment of this instruction allows us to specify a more
975 // restrictive (and performant) alignment and if we are sure this
976 // instruction will be executed, update the alignment.
977 // Larger is better, with the exception of 0 being the best alignment.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000978 unsigned InstAlignment = Store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000979 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000980 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000981 GuaranteedToExecute = true;
982 Alignment = InstAlignment;
983 }
984
985 if (!GuaranteedToExecute)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000986 GuaranteedToExecute =
987 isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
Philip Reamesb54c8e62016-03-09 22:59:30 +0000988
989 if (!GuaranteedToExecute && !CanSpeculateLoad) {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000990 CanSpeculateLoad = isDereferenceableAndAlignedPointer(
991 Store->getPointerOperand(), Store->getAlignment(), MDL,
992 Preheader->getTerminator(), DT, TLI);
Philip Reamesb54c8e62016-03-09 22:59:30 +0000993 }
Chris Lattnerbe901902010-09-06 05:11:24 +0000994 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000995 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000996
Hal Finkelcc39b672014-07-24 12:16:19 +0000997 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000998 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000999 // On the first load/store, just take its AA tags.
1000 UI->getAAMetadata(AATags);
1001 } else if (AATags) {
1002 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001003 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001004
1005 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001006 }
1007 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001008
Philip Reamesb54c8e62016-03-09 22:59:30 +00001009 // Check legality per comment above. Otherwise, we can't promote.
1010 bool PromotionIsLegal = GuaranteedToExecute;
1011 if (!PromotionIsLegal && CanSpeculateLoad) {
1012 // If this is a thread local location, then we can insert stores along
1013 // paths which originally didn't have them without violating the memory
Dehao Chend55bc4c2016-05-05 00:54:54 +00001014 // model.
Philip Reamesb54c8e62016-03-09 22:59:30 +00001015 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001016 PromotionIsLegal =
1017 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001018 }
1019 if (!PromotionIsLegal)
Hal Finkel3d4269a2015-02-22 18:35:32 +00001020 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +00001021
David Majnemer219055f2016-01-04 17:42:19 +00001022 // Figure out the loop exits and their insertion points, if this is the
1023 // first promotion.
1024 if (ExitBlocks.empty()) {
1025 CurLoop->getUniqueExitBlocks(ExitBlocks);
1026 InsertPts.clear();
1027 InsertPts.reserve(ExitBlocks.size());
David Majnemerb33f3a22016-01-04 23:16:22 +00001028 for (BasicBlock *ExitBlock : ExitBlocks)
David Majnemer219055f2016-01-04 17:42:19 +00001029 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
David Majnemer219055f2016-01-04 17:42:19 +00001030 }
1031
David Majnemerb33f3a22016-01-04 23:16:22 +00001032 // Can't insert into a catchswitch.
1033 for (BasicBlock *ExitBlock : ExitBlocks)
1034 if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1035 return Changed;
1036
Chris Lattner1dc98b42010-08-29 06:43:52 +00001037 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001038 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1039 << '\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +00001040 Changed = true;
1041 ++NumPromoted;
1042
Eli Friedmanddf7f552011-05-27 20:31:51 +00001043 // Grab a debug location for the inserted loads/stores; given that the
1044 // inserted loads/stores have little relation to the original loads/stores,
1045 // this code just arbitrarily picks a location from one, since any debug
1046 // location is better than none.
1047 DebugLoc DL = LoopUses[0]->getDebugLoc();
1048
Chris Lattner1dc98b42010-08-29 06:43:52 +00001049 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001050 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001051 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001052 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001053 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001054
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001055 // Set up the preheader to have a definition of the value. It is the live-out
1056 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001057 LoadInst *PreheaderLoad = new LoadInst(
1058 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001059 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001060 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001061 if (AATags)
1062 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001063 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1064
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001065 // Rewrite all the loads in the loop and remember all the definitions from
1066 // stores in the loop.
1067 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001068
1069 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1070 if (PreheaderLoad->use_empty())
1071 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001072
1073 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +00001074}
Devang Patelb98a0972007-07-31 08:01:41 +00001075
Roman Gareev036c0882016-02-15 14:48:50 +00001076/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001077/// from L and all subloops of L.
1078AliasSetTracker *LICM::collectAliasInfoForLoop(Loop *L) {
Roman Gareev036c0882016-02-15 14:48:50 +00001079 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001080 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001081 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001082 auto MapI = LoopToAliasSetMap.find(InnerL);
1083 // If the AST for this inner loop is missing it may have been merged into
1084 // some other loop's AST and then that loop unrolled, and so we need to
1085 // recompute it.
1086 if (MapI == LoopToAliasSetMap.end()) {
1087 RecomputeLoops.push_back(InnerL);
1088 continue;
1089 }
1090 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001091
1092 if (CurAST != nullptr) {
1093 // What if InnerLoop was modified by other passes ?
1094 CurAST->add(*InnerAST);
1095
1096 // Once we've incorporated the inner loop's AST into ours, we don't need
1097 // the subloop's anymore.
1098 delete InnerAST;
1099 } else {
1100 CurAST = InnerAST;
1101 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001102 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001103 }
1104 if (CurAST == nullptr)
1105 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001106
1107 auto mergeLoop = [&](Loop *L) {
1108 // Loop over the body of this loop, looking for calls, invokes, and stores.
1109 // Because subloops have already been incorporated into AST, we skip blocks
1110 // in subloops.
1111 for (BasicBlock *BB : L->blocks())
1112 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1113 CurAST->add(*BB); // Incorporate the specified basic block
1114 };
1115
1116 // Add everything from the sub loops that are no longer directly available.
1117 for (Loop *InnerL : RecomputeLoops)
1118 mergeLoop(InnerL);
1119
1120 // And merge in this loop.
1121 mergeLoop(L);
1122
Roman Gareev036c0882016-02-15 14:48:50 +00001123 return CurAST;
1124}
1125
Ashutosh Nema47802622015-08-13 11:18:35 +00001126/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001127///
Devang Patelb98a0972007-07-31 08:01:41 +00001128void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001129 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001130 if (!AST)
1131 return;
1132
1133 AST->copyValue(From, To);
1134}
1135
Hal Finkel3d4269a2015-02-22 18:35:32 +00001136/// Simple Analysis hook. Delete value V from alias set
1137///
Devang Patelb98a0972007-07-31 08:01:41 +00001138void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001139 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001140 if (!AST)
1141 return;
1142
1143 AST->deleteValue(V);
1144}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001145
1146/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001147///
David Peixotto0d4d5e62014-09-24 16:48:31 +00001148void LICM::deleteAnalysisLoop(Loop *L) {
1149 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1150 if (!AST)
1151 return;
1152
1153 delete AST;
1154 LoopToAliasSetMap.erase(L);
1155}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001156
Hal Finkel3d4269a2015-02-22 18:35:32 +00001157/// Return true if the body of this loop may store into the memory
1158/// location pointed to by V.
1159///
1160static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001161 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001162 AliasSetTracker *CurAST) {
1163 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1164 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1165}
1166
1167/// Little predicate that returns true if the specified basic block is in
1168/// a subloop of the current one, not the current one itself.
1169///
1170static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1171 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1172 return LI->getLoopFor(BB) != CurLoop;
1173}