blob: 99d7e2e1f0bd9e915c713036ee2587a2e934fa76 [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
Dehao Chen9cba1f42016-07-12 22:37:48 +000033#include "llvm/Transforms/Scalar/LICM.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"
Chandler Carruth7b560d42015-09-09 17:55:00 +000037#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000038#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner030f0202010-08-31 23:00:16 +000039#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000040#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamese0a54542016-03-09 23:07:53 +000041#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000042#include "llvm/Analysis/LoopInfo.h"
43#include "llvm/Analysis/LoopPass.h"
Dehao Chen9cba1f42016-07-12 22:37:48 +000044#include "llvm/Analysis/LoopPassManager.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000045#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000046#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000047#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000049#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000050#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Constants.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Instructions.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000058#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000059#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000060#include "llvm/Support/CommandLine.h"
61#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000063#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000064#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000065#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000067#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000068#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000069using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "licm"
72
Dehao Chend55bc4c2016-05-05 00:54:54 +000073STATISTIC(NumSunk, "Number of instructions sunk out of loop");
74STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000075STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
76STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000077STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000078
Dan Gohmand78c4002008-05-13 00:00:25 +000079static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000080 DisablePromotion("disable-licm-promotion", cl::Hidden,
81 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000082
Hal Finkel3d4269a2015-02-22 18:35:32 +000083static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000084static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000085 const LoopSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000086static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000087 const LoopSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000088static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000089 const Loop *CurLoop, AliasSetTracker *CurAST,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000090 const LoopSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000091static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
92 const DominatorTree *DT,
93 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000094 const LoopSafetyInfo *SafetyInfo,
Philip Reamesb47b9c22015-05-22 02:14:05 +000095 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000096static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +000097 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +000098 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +000099static Instruction *
100CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
101 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000102 const LoopSafetyInfo *SafetyInfo);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000103static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000104 DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000105 Loop *CurLoop, AliasSetTracker *CurAST,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000106 LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000107
Dan Gohmand78c4002008-05-13 00:00:25 +0000108namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000109struct LoopInvariantCodeMotion {
110 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
111 TargetLibraryInfo *TLI, ScalarEvolution *SE, bool DeleteAST);
112
113 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
114 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000115 }
116
Dehao Chen9cba1f42016-07-12 22:37:48 +0000117private:
118 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
119
120 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
121 AliasAnalysis *AA);
122};
123
124struct LegacyLICMPass : public LoopPass {
125 static char ID; // Pass identification, replacement for typeid
126 LegacyLICMPass() : LoopPass(ID) {
127 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
128 }
129
130 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
131 if (skipLoop(L))
132 return false;
133
134 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
135 return LICM.runOnLoop(L,
136 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
137 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
138 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
139 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
140 SE ? &SE->getSE() : nullptr, false);
141 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000142
Dehao Chend55bc4c2016-05-05 00:54:54 +0000143 /// This transformation requires natural loop information & requires that
144 /// loop preheaders be inserted into the CFG...
145 ///
146 void getAnalysisUsage(AnalysisUsage &AU) const override {
147 AU.setPreservesCFG();
148 AU.addRequired<TargetLibraryInfoWrapperPass>();
149 getLoopAnalysisUsage(AU);
150 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000151
Dehao Chend55bc4c2016-05-05 00:54:54 +0000152 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000153
Dehao Chend55bc4c2016-05-05 00:54:54 +0000154 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000155 assert(LICM.getLoopToAliasSetMap().empty() &&
156 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000157 return false;
158 }
Devang Patel69730c92007-03-07 04:41:30 +0000159
Dehao Chend55bc4c2016-05-05 00:54:54 +0000160private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000161 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000162
Dehao Chend55bc4c2016-05-05 00:54:54 +0000163 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
164 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
165 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000166
Dehao Chend55bc4c2016-05-05 00:54:54 +0000167 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
168 /// set.
169 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000170
Dehao Chend55bc4c2016-05-05 00:54:54 +0000171 /// Simple Analysis hook. Delete loop L from alias set map.
172 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000173};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000174}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000175
Sean Silva0746f3b2016-08-09 00:28:52 +0000176PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000177 const auto &FAM =
178 AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
179 Function *F = L.getHeader()->getParent();
180
181 auto *AA = FAM.getCachedResult<AAManager>(*F);
182 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
183 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
184 auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
185 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
186 assert((AA && LI && DT && TLI && SE) && "Analyses for LICM not available");
187
188 LoopInvariantCodeMotion LICM;
189
190 if (!LICM.runOnLoop(&L, AA, LI, DT, TLI, SE, true))
191 return PreservedAnalyses::all();
192
193 // FIXME: There is no setPreservesCFG in the new PM. When that becomes
194 // available, it should be used here.
195 return getLoopPassPreservedAnalyses();
196}
197
198char LegacyLICMPass::ID = 0;
199INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
200 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000201INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000202INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000203INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
204 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000205
Dehao Chen9cba1f42016-07-12 22:37:48 +0000206Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000207
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000208/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000209/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000210/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000211/// We should delete AST for inner loops in the new pass manager to avoid
212/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000213///
Dehao Chen9cba1f42016-07-12 22:37:48 +0000214bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
215 LoopInfo *LI, DominatorTree *DT,
216 TargetLibraryInfo *TLI,
217 ScalarEvolution *SE, bool DeleteAST) {
218 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000219
Chandler Carruthfc258542014-02-11 12:52:27 +0000220 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
221
Dehao Chen9cba1f42016-07-12 22:37:48 +0000222 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000223
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000224 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000225 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000226
Hal Finkel3d4269a2015-02-22 18:35:32 +0000227 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000228 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000229 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000230
Chris Lattner6ec05f52002-05-10 22:44:58 +0000231 // We want to visit all of the instructions in this loop... that are not parts
232 // of our subloops (they have already had their invariants hoisted out of
233 // their loop, into this loop, so there is no need to process the BODIES of
234 // the subloops).
235 //
Chris Lattner64437692002-09-29 21:46:09 +0000236 // Traverse the body of the loop in depth first order on the dominator tree so
237 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000238 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000239 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000240 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000241 if (L->hasDedicatedExits())
Dehao Chen9cba1f42016-07-12 22:37:48 +0000242 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000244 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000245 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
246 CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000247
Chris Lattner45d67d62003-02-24 03:52:32 +0000248 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000249 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000250 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000251 SmallVector<BasicBlock *, 8> ExitBlocks;
252 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000253 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000254
Chris Lattner1dc98b42010-08-29 06:43:52 +0000255 // Loop over all of the alias sets in the tracker object.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000256 for (AliasSet &AS : *CurAST)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000257 Changed |= promoteLoopAccessesToScalars(
258 AS, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L, CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000259
260 // Once we have promoted values across the loop body we have to recursively
261 // reform LCSSA as any nested loop may now have values defined within the
262 // loop used in the outer loop.
263 // FIXME: This is really heavy handed. It would be a bit better to use an
264 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
265 // it as it went.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000266 if (Changed) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000267 formLCSSARecursively(*L, *DT, LI, SE);
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000268 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000269 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000270
Chandler Carruthfc258542014-02-11 12:52:27 +0000271 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
272 // specifically moving instructions across the loop boundary and so it is
273 // especially in need of sanity checking here.
274 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
275 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
276 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000277
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000278 // If this loop is nested inside of another one, save the alias information
279 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000280 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000281 LoopToAliasSetMap[L] = CurAST;
282 else
283 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000284
Dehao Chen9cba1f42016-07-12 22:37:48 +0000285 if (Changed && SE)
286 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000287 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000288}
289
Hal Finkel3d4269a2015-02-22 18:35:32 +0000290/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000291/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000292/// first order w.r.t the DominatorTree. This allows us to visit uses before
293/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000294///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
296 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000297 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000298
Hal Finkel3d4269a2015-02-22 18:35:32 +0000299 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000300 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
301 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
302 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000303
Hal Finkel3d4269a2015-02-22 18:35:32 +0000304 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000305 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000306 if (!CurLoop->contains(BB))
307 return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000308
Chris Lattner263f8042010-08-29 18:22:25 +0000309 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000310 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000311 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000312 for (DomTreeNode *Child : Children)
313 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
314
Chris Lattner547192d62003-12-19 07:22:45 +0000315 // Only need to process the contents of this block if it is not part of a
316 // subloop (which would already have been processed).
Dehao Chend55bc4c2016-05-05 00:54:54 +0000317 if (inSubLoop(BB, CurLoop, LI))
318 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000319
Dehao Chend55bc4c2016-05-05 00:54:54 +0000320 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
Chris Lattner91846012003-12-19 08:18:16 +0000321 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000322
Chris Lattner263f8042010-08-29 18:22:25 +0000323 // If the instruction is dead, we would try to sink it because it isn't used
324 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000325 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000326 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000327 ++II;
328 CurAST->deleteValue(&I);
329 I.eraseFromParent();
330 Changed = true;
331 continue;
332 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000333
Chris Lattner547192d62003-12-19 07:22:45 +0000334 // Check to see if we can sink this instruction to the exit blocks
335 // of the loop. We can do this if the all users of the instruction are
336 // outside of the loop. In this case, it doesn't even matter if the
337 // operands of the instruction are loop invariant.
338 //
David Majnemer42a07302016-01-04 03:37:39 +0000339 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000340 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000341 ++II;
David Majnemer42a07302016-01-04 03:37:39 +0000342 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
Chris Lattner91846012003-12-19 08:18:16 +0000343 }
Chris Lattner547192d62003-12-19 07:22:45 +0000344 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000345 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000346}
347
Hal Finkel3d4269a2015-02-22 18:35:32 +0000348/// Walk the specified region of the CFG (defined by all blocks dominated by
349/// the specified block, and that are in the current loop) in depth first
350/// order w.r.t the DominatorTree. This allows us to visit definitions before
351/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000352///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000355 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000356 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000357 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
358 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
359 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000360
Owen Andersonc24701e2007-04-24 06:40:39 +0000361 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000362
Chris Lattner05e86302002-09-29 22:26:07 +0000363 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000364 if (!CurLoop->contains(BB))
365 return false;
Sanjay Patel99133222016-01-13 23:01:57 +0000366
Chris Lattneraaaea512003-12-10 06:41:05 +0000367 // Only need to process the contents of this block if it is not part of a
368 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000369 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000370 if (!inSubLoop(BB, CurLoop, LI))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000371 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000372 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);
Chris Lattner030f0202010-08-31 23:00:16 +0000380 I.replaceAllUsesWith(C);
David Majnemer522a9112016-07-22 04:54:44 +0000381 if (isInstructionTriviallyDead(&I, TLI)) {
382 CurAST->deleteValue(&I);
383 I.eraseFromParent();
384 }
Chris Lattner030f0202010-08-31 23:00:16 +0000385 continue;
386 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000387
Chris Lattner547192d62003-12-19 07:22:45 +0000388 // Try hoisting the instruction out to the preheader. We can only do this
389 // if all of the operands of the instruction are loop invariant and if it
390 // is safe to hoist the instruction.
391 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 if (CurLoop->hasLoopInvariantOperands(&I) &&
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000393 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo) &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000394 isSafeToExecuteUnconditionally(
Sean Silva45835e72016-07-02 23:47:27 +0000395 I, DT, CurLoop, SafetyInfo,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000396 CurLoop->getLoopPreheader()->getTerminator()))
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000397 Changed |= hoist(I, DT, CurLoop, SafetyInfo);
Chris Lattner030f0202010-08-31 23:00:16 +0000398 }
Chris Lattner64437692002-09-29 21:46:09 +0000399
Dehao Chend55bc4c2016-05-05 00:54:54 +0000400 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000401 for (DomTreeNode *Child : Children)
402 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000403 return Changed;
404}
405
406/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000407/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000408///
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000409void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000410 assert(CurLoop != nullptr && "CurLoop cant be null");
411 BasicBlock *Header = CurLoop->getHeader();
412 // Setting default safety values.
413 SafetyInfo->MayThrow = false;
414 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000415 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000416 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
417 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000418 SafetyInfo->HeaderMayThrow |=
419 !isGuaranteedToTransferExecutionToSuccessor(&*I);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000420
Hal Finkel3d4269a2015-02-22 18:35:32 +0000421 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000422 // Iterate over loop instructions and compute safety info.
423 for (Loop::block_iterator BB = CurLoop->block_begin(),
424 BBE = CurLoop->block_end();
425 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000426 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
427 (I != E) && !SafetyInfo->MayThrow; ++I)
Eli Friedmanf1da33e2016-06-11 21:48:25 +0000428 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
David Majnemer42a07302016-01-04 03:37:39 +0000429
430 // Compute funclet colors if we might sink/hoist in a function with a funclet
431 // personality routine.
432 Function *Fn = CurLoop->getHeader()->getParent();
433 if (Fn->hasPersonalityFn())
434 if (Constant *PersonalityFn = Fn->getPersonalityFn())
435 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
436 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000437}
438
Chris Lattneraaaea512003-12-10 06:41:05 +0000439/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
440/// instruction.
441///
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000442bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
443 Loop *CurLoop, AliasSetTracker *CurAST,
444 LoopSafetyInfo *SafetyInfo) {
445 if (!isa<LoadInst>(I) && !isa<CallInst>(I) &&
446 !isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
447 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
448 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
449 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
450 !isa<InsertValueInst>(I))
451 return false;
452
Chris Lattner65c11932003-12-09 19:32:44 +0000453 // Loads have extra constraints we have to verify before we can hoist them.
454 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000455 if (!LI->isUnordered())
Dehao Chend55bc4c2016-05-05 00:54:54 +0000456 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000457
Chris Lattner8a8fb902008-07-23 05:06:28 +0000458 // Loads from constant memory are always safe to move, even if they end up
459 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000460 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000461 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000462 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000463 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000464
Chris Lattner65c11932003-12-09 19:32:44 +0000465 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000466 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000467 if (LI->getType()->isSized())
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000468 Size = LI->getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000469
470 AAMDNodes AAInfo;
471 LI->getAAMetadata(AAInfo);
472
Hal Finkel3d4269a2015-02-22 18:35:32 +0000473 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000474 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000475 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000476 if (isa<DbgInfoIntrinsic>(*CI))
Eli Friedman942e1c12011-05-27 18:37:52 +0000477 return false;
478
David Majnemer42a07302016-01-04 03:37:39 +0000479 // Don't sink calls which can throw.
480 if (CI->mayThrow())
481 return false;
482
Eli Friedman942e1c12011-05-27 18:37:52 +0000483 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000484 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
485 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000486 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000487 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000488 // A readonly argmemonly function only reads from memory pointed to by
489 // it's arguments with arbitrary offsets. If we can prove there are no
490 // writes to this memory in the loop, we can hoist or sink.
491 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
492 for (Value *Op : CI->arg_operands())
493 if (Op->getType()->isPointerTy() &&
494 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
495 AAMDNodes(), CurAST))
496 return false;
497 return true;
498 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000499 // If this call only reads from memory and there are no writes to memory
500 // in the loop, we can hoist or sink the call as appropriate.
501 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000502 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000503 if (!AS.isForwardingAliasSet() && AS.isMod()) {
504 FoundMod = true;
505 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000506 }
Chris Lattner20cda262004-03-15 04:11:30 +0000507 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000508 if (!FoundMod)
509 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000510 }
511
Nadav Rotem03dcd852012-09-04 10:25:04 +0000512 // FIXME: This should use mod/ref information to see if we can hoist or
513 // sink the call.
Chris Lattner20cda262004-03-15 04:11:30 +0000514 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000515 }
516
Dehao Chenbc4e5bb2016-09-01 23:15:50 +0000517 if (SafetyInfo)
518 // TODO: Plumb the context instruction through to make hoisting and sinking
519 // more powerful. Hoisting of loads already works due to the special casing
520 // above.
521 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
522 else
523 return true;
Chris Lattneraaaea512003-12-10 06:41:05 +0000524}
525
Hal Finkel3d4269a2015-02-22 18:35:32 +0000526/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000527/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000528/// This is true when all incoming values are that instruction.
529/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000530///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000531static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000532 for (const Value *IncValue : PN.incoming_values())
533 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000534 return false;
535
536 return true;
537}
538
Hal Finkel3d4269a2015-02-22 18:35:32 +0000539/// Return true if the only users of this instruction are outside of
540/// the loop. If this is true, we can sink the instruction to the exit
541/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000542///
David Majnemer42a07302016-01-04 03:37:39 +0000543static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000544 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000545 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000546 for (const User *U : I.users()) {
547 const Instruction *UI = cast<Instruction>(U);
548 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000549 const BasicBlock *BB = PN->getParent();
550 // We cannot sink uses in catchswitches.
551 if (isa<CatchSwitchInst>(BB->getTerminator()))
552 return false;
553
554 // We need to sink a callsite to a unique funclet. Avoid sinking if the
555 // phi use is too muddled.
556 if (isa<CallInst>(I))
557 if (!BlockColors.empty() &&
558 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
559 return false;
560
Chandler Carruth8765cf72014-01-25 04:07:24 +0000561 // A PHI node where all of the incoming values are this instruction are
562 // special -- they can just be RAUW'ed with the instruction and thus
563 // don't require a use in the predecessor. This is a particular important
564 // special case because it is the pattern found in LCSSA form.
565 if (isTriviallyReplacablePHI(*PN, I)) {
566 if (CurLoop->contains(PN))
567 return false;
568 else
569 continue;
570 }
571
572 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
573 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000574 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
575 if (PN->getIncomingValue(i) == &I)
576 if (CurLoop->contains(PN->getIncomingBlock(i)))
577 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000578
579 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000580 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000581
Chandler Carruthcdf47882014-03-09 03:16:01 +0000582 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000583 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000584 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000585 return true;
586}
587
David Majnemer42a07302016-01-04 03:37:39 +0000588static Instruction *
589CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
590 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000591 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000592 Instruction *New;
593 if (auto *CI = dyn_cast<CallInst>(&I)) {
594 const auto &BlockColors = SafetyInfo->BlockColors;
595
596 // Sinking call-sites need to be handled differently from other
597 // instructions. The cloned call-site needs a funclet bundle operand
598 // appropriate for it's location in the CFG.
599 SmallVector<OperandBundleDef, 1> OpBundles;
600 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
601 BundleIdx != BundleEnd; ++BundleIdx) {
602 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
603 if (Bundle.getTagID() == LLVMContext::OB_funclet)
604 continue;
605
606 OpBundles.emplace_back(Bundle);
607 }
608
609 if (!BlockColors.empty()) {
610 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
611 assert(CV.size() == 1 && "non-unique color for exit block!");
612 BasicBlock *BBColor = CV.front();
613 Instruction *EHPad = BBColor->getFirstNonPHI();
614 if (EHPad->isEHPad())
615 OpBundles.emplace_back("funclet", EHPad);
616 }
617
618 New = CallInst::Create(CI, OpBundles);
619 } else {
620 New = I.clone();
621 }
622
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000623 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000624 if (!I.getName().empty())
625 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000626
627 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
628 // particularly cheap because we can rip off the PHI node that we're
629 // replacing for the number and blocks of the predecessors.
630 // OPT: If this shows up in a profile, we can instead finish sinking all
631 // invariant instructions, and then walk their operands to re-establish
632 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
633 // sinking bottom-up.
634 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
635 ++OI)
636 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
637 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
638 if (!OLoop->contains(&PN)) {
639 PHINode *OpPN =
640 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000641 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000642 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
643 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
644 *OI = OpPN;
645 }
646 return New;
647}
648
Hal Finkel3d4269a2015-02-22 18:35:32 +0000649/// When an instruction is found to only be used outside of the loop, this
650/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000651/// This method is guaranteed to remove the original instruction from its
652/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000653///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000654static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000655 const Loop *CurLoop, AliasSetTracker *CurAST,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000656 const LoopSafetyInfo *SafetyInfo) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000657 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000658 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000659 if (isa<LoadInst>(I))
660 ++NumMovedLoads;
661 else if (isa<CallInst>(I))
662 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000663 ++NumSunk;
664 Changed = true;
665
Chandler Carruthfc258542014-02-11 12:52:27 +0000666#ifndef NDEBUG
667 SmallVector<BasicBlock *, 32> ExitBlocks;
668 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000669 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000670 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000671#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000672
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000673 // Clones of this instruction. Don't create more than one per exit block!
674 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
675
Chandler Carruthfc258542014-02-11 12:52:27 +0000676 // If this instruction is only used outside of the loop, then all users are
677 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
678 // the instruction.
679 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000680 Value::user_iterator UI = I.user_begin();
681 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000682 if (!DT->isReachableFromEntry(User->getParent())) {
683 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
684 continue;
685 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000686 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000687 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000688
David Majnemer6bc83e02015-07-12 03:53:05 +0000689 // Surprisingly, instructions can be used outside of loops without any
690 // exits. This can only happen in PHI nodes if the incoming block is
691 // unreachable.
692 Use &U = UI.getUse();
693 BasicBlock *BB = PN->getIncomingBlock(U);
694 if (!DT->isReachableFromEntry(BB)) {
695 U = UndefValue::get(I.getType());
696 continue;
697 }
698
Chandler Carruthfc258542014-02-11 12:52:27 +0000699 BasicBlock *ExitBlock = PN->getParent();
700 assert(ExitBlockSet.count(ExitBlock) &&
701 "The LCSSA PHI is not in an exit block!");
702
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000703 Instruction *New;
704 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000705 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000706 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000707 else
708 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000709 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000710
711 PN->replaceAllUsesWith(New);
712 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000713 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000714
Chris Lattner1a1ed692010-08-29 18:00:00 +0000715 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000716 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000717 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000718}
Chris Lattner64437692002-09-29 21:46:09 +0000719
Hal Finkel3d4269a2015-02-22 18:35:32 +0000720/// When an instruction is found to only use loop invariant operands that
721/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000722///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000723static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000724 const LoopSafetyInfo *SafetyInfo) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000725 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000726 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
727 << "\n");
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000728
729 // Metadata can be dependent on conditions we are hoisting above.
730 // Conservatively strip all metadata on the instruction unless we were
731 // guaranteed to execute I if we entered the loop, in which case the metadata
732 // is valid in the loop preheader.
733 if (I.hasMetadataOtherThanDebugLoc() &&
734 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
735 // time in isGuaranteedToExecute if we don't actually have anything to
736 // drop. It is a compile time optimization, not required for correctness.
737 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
738 I.dropUnknownNonDebugMetadata();
739
Chris Lattner6ac06592010-08-29 18:18:40 +0000740 // Move the new node to the Preheader, before its terminator.
741 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000742
Dehao Chend55bc4c2016-05-05 00:54:54 +0000743 if (isa<LoadInst>(I))
744 ++NumMovedLoads;
745 else if (isa<CallInst>(I))
746 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000747 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000748 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000749}
750
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000751/// Only sink or hoist an instruction if it is not a trapping instruction,
752/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000753/// or if it is a trapping instruction and is guaranteed to execute.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000754static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000755 const DominatorTree *DT,
756 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000757 const LoopSafetyInfo *SafetyInfo,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000758 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +0000759 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000760 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000761
Hal Finkel3d4269a2015-02-22 18:35:32 +0000762 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000763}
764
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000765namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000766class LoopPromoter : public LoadAndStorePromoter {
767 Value *SomePtr; // Designated pointer to store to.
768 SmallPtrSetImpl<Value *> &PointerMustAliases;
769 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
770 SmallVectorImpl<Instruction *> &LoopInsertPts;
771 PredIteratorCache &PredCache;
772 AliasSetTracker &AST;
773 LoopInfo &LI;
774 DebugLoc DL;
775 int Alignment;
776 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000777
Dehao Chend55bc4c2016-05-05 00:54:54 +0000778 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
779 if (Instruction *I = dyn_cast<Instruction>(V))
780 if (Loop *L = LI.getLoopFor(I->getParent()))
781 if (!L->contains(BB)) {
782 // We need to create an LCSSA PHI node for the incoming value and
783 // store that.
784 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
785 I->getName() + ".lcssa", &BB->front());
786 for (BasicBlock *Pred : PredCache.get(BB))
787 PN->addIncoming(I, Pred);
788 return PN;
789 }
790 return V;
791 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000792
Dehao Chend55bc4c2016-05-05 00:54:54 +0000793public:
794 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
795 SmallPtrSetImpl<Value *> &PMA,
796 SmallVectorImpl<BasicBlock *> &LEB,
797 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
798 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
799 const AAMDNodes &AATags)
800 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
801 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000802 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000803
Dehao Chend55bc4c2016-05-05 00:54:54 +0000804 bool isInstInList(Instruction *I,
805 const SmallVectorImpl<Instruction *> &) const override {
806 Value *Ptr;
807 if (LoadInst *LI = dyn_cast<LoadInst>(I))
808 Ptr = LI->getOperand(0);
809 else
810 Ptr = cast<StoreInst>(I)->getPointerOperand();
811 return PointerMustAliases.count(Ptr);
812 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000813
Dehao Chend55bc4c2016-05-05 00:54:54 +0000814 void doExtraRewritesBeforeFinalDeletion() const override {
815 // Insert stores after in the loop exit blocks. Each exit block gets a
816 // store of the live-out values that feed them. Since we've already told
817 // the SSA updater about the defs in the loop and the preheader
818 // definition, it is all set and we can start using it.
819 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
820 BasicBlock *ExitBlock = LoopExitBlocks[i];
821 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
822 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
823 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
824 Instruction *InsertPos = LoopInsertPts[i];
825 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
826 NewSI->setAlignment(Alignment);
827 NewSI->setDebugLoc(DL);
828 if (AATags)
829 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000830 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000831 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000832
Dehao Chend55bc4c2016-05-05 00:54:54 +0000833 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
834 // Update alias analysis.
835 AST.copyValue(LI, V);
836 }
837 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
838};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000839} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000840
Hal Finkel3d4269a2015-02-22 18:35:32 +0000841/// Try to promote memory values to scalars by sinking stores out of the
842/// loop and moving loads to before the loop. We do this by looping over
843/// the stores in the loop, looking for stores to Must pointers which are
844/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000845///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000846bool llvm::promoteLoopAccessesToScalars(
847 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
848 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
849 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000850 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000851 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000852 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
853 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +0000854 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000855
Chris Lattner1dc98b42010-08-29 06:43:52 +0000856 // We can promote this alias set if it has a store, if it is a "Must" alias
857 // set, if the pointer is loop invariant, and if we are not eliminating any
858 // volatile loads or stores.
859 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
860 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000861 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000862
Chris Lattner1dc98b42010-08-29 06:43:52 +0000863 assert(!AS.empty() &&
864 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000865
Chris Lattner1dc98b42010-08-29 06:43:52 +0000866 Value *SomePtr = AS.begin()->getValue();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000867 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000868
Chris Lattner1dc98b42010-08-29 06:43:52 +0000869 // It isn't safe to promote a load/store from the loop if the load/store is
870 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000871 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000872 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000873 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000874 // into:
875 //
876 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
877 //
878 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000879 //
Philip Reamesb54c8e62016-03-09 22:59:30 +0000880 // The safety property divides into two parts:
881 // 1) The memory may not be dereferenceable on entry to the loop. In this
882 // case, we can't insert the required load in the preheader.
883 // 2) The memory model does not allow us to insert a store along any dynamic
884 // path which did not originally have one.
885 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000886 // It is safe to promote P if all uses are direct load/stores and if at
887 // least one is guaranteed to be executed.
888 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000889
Philip Reamesb54c8e62016-03-09 22:59:30 +0000890 // It is also safe to promote P if we can prove that speculating a load into
891 // the preheader is safe (i.e. proving dereferenceability on all
892 // paths through the loop), and that the memory can be proven thread local
893 // (so that the memory model requirement doesn't apply.) We first establish
894 // the former, and then run a capture analysis below to establish the later.
895 // We can use any access within the alias set to prove dereferenceability
896 // since they're all must alias.
897 bool CanSpeculateLoad = false;
898
Dehao Chend55bc4c2016-05-05 00:54:54 +0000899 SmallVector<Instruction *, 64> LoopUses;
900 SmallPtrSet<Value *, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000901
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000902 // We start with an alignment of one and try to find instructions that allow
903 // us to prove better alignment.
904 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000905 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000906 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000907
Philip Reamesb54c8e62016-03-09 22:59:30 +0000908 // Don't sink stores from loops without dedicated block exits. Exits
909 // containing indirect branches are not transformed by loop simplify,
910 // make sure we catch that. An additional load may be generated in the
911 // preheader for SSA updater, so also avoid sinking when no preheader
912 // is available.
913 if (!HasDedicatedExits || !Preheader)
914 return false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000915
Philip Reamesb54c8e62016-03-09 22:59:30 +0000916 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
917
Eli Friedmanee895052016-06-05 22:13:52 +0000918 if (SafetyInfo->MayThrow) {
919 // If a loop can throw, we have to insert a store along each unwind edge.
920 // That said, we can't actually make the unwind edge explicit. Therefore,
921 // we have to prove that the store is dead along the unwind edge.
922 //
923 // Currently, this code just special-cases alloca instructions.
924 if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
925 return false;
926 }
927
Chris Lattner1dc98b42010-08-29 06:43:52 +0000928 // Check that all of the pointers in the alias set have the same type. We
929 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000930 // different sizes. While we are at it, collect alignment and AA info.
Sanjay Patel99133222016-01-13 23:01:57 +0000931 bool Changed = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000932 for (const auto &ASI : AS) {
933 Value *ASIV = ASI.getValue();
Chris Lattner1dc98b42010-08-29 06:43:52 +0000934 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000935
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000936 // Check that all of the pointers in the alias set have the same type. We
937 // cannot (yet) promote a memory location that is loaded and stored in
938 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000939 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000940 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000941
Chandler Carruthcdf47882014-03-09 03:16:01 +0000942 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000943 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000944 Instruction *UI = dyn_cast<Instruction>(U);
945 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000946 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000947
Chris Lattner1dc98b42010-08-29 06:43:52 +0000948 // If there is an non-load/store instruction in the loop, we can't promote
949 // it.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000950 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
951 assert(!Load->isVolatile() && "AST broken");
952 if (!Load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000953 return Changed;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000954
955 if (!GuaranteedToExecute && !CanSpeculateLoad)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000956 CanSpeculateLoad = isSafeToExecuteUnconditionally(
Sean Silva45835e72016-07-02 23:47:27 +0000957 *Load, DT, CurLoop, SafetyInfo, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +0000958 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000959 // Stores *of* the pointer are not interesting, only stores *to* the
960 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000961 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000962 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000963 assert(!Store->isVolatile() && "AST broken");
964 if (!Store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000965 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000966
967 // Note that we only check GuaranteedToExecute inside the store case
968 // so that we do not introduce stores where they did not exist before
969 // (which would break the LLVM concurrency model).
970
971 // If the alignment of this instruction allows us to specify a more
972 // restrictive (and performant) alignment and if we are sure this
973 // instruction will be executed, update the alignment.
974 // Larger is better, with the exception of 0 being the best alignment.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000975 unsigned InstAlignment = Store->getAlignment();
Anna Thomas67151352016-06-24 12:38:45 +0000976 if ((InstAlignment > Alignment || InstAlignment == 0) &&
977 Alignment != 0) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000978 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000979 GuaranteedToExecute = true;
980 Alignment = InstAlignment;
981 }
Anna Thomas67151352016-06-24 12:38:45 +0000982 } else if (!GuaranteedToExecute) {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000983 GuaranteedToExecute =
984 isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
Anna Thomas67151352016-06-24 12:38:45 +0000985 }
Philip Reamesb54c8e62016-03-09 22:59:30 +0000986
987 if (!GuaranteedToExecute && !CanSpeculateLoad) {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000988 CanSpeculateLoad = isDereferenceableAndAlignedPointer(
989 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +0000990 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +0000991 }
Chris Lattnerbe901902010-09-06 05:11:24 +0000992 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000993 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000994
Hal Finkelcc39b672014-07-24 12:16:19 +0000995 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000996 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000997 // On the first load/store, just take its AA tags.
998 UI->getAAMetadata(AATags);
999 } else if (AATags) {
1000 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001001 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001002
1003 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001004 }
1005 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001006
Philip Reamesb54c8e62016-03-09 22:59:30 +00001007 // Check legality per comment above. Otherwise, we can't promote.
1008 bool PromotionIsLegal = GuaranteedToExecute;
1009 if (!PromotionIsLegal && CanSpeculateLoad) {
1010 // If this is a thread local location, then we can insert stores along
1011 // paths which originally didn't have them without violating the memory
Dehao Chend55bc4c2016-05-05 00:54:54 +00001012 // model.
Philip Reamesb54c8e62016-03-09 22:59:30 +00001013 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001014 PromotionIsLegal =
1015 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001016 }
1017 if (!PromotionIsLegal)
Hal Finkel3d4269a2015-02-22 18:35:32 +00001018 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +00001019
David Majnemer219055f2016-01-04 17:42:19 +00001020 // Figure out the loop exits and their insertion points, if this is the
1021 // first promotion.
1022 if (ExitBlocks.empty()) {
1023 CurLoop->getUniqueExitBlocks(ExitBlocks);
1024 InsertPts.clear();
1025 InsertPts.reserve(ExitBlocks.size());
David Majnemerb33f3a22016-01-04 23:16:22 +00001026 for (BasicBlock *ExitBlock : ExitBlocks)
David Majnemer219055f2016-01-04 17:42:19 +00001027 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
David Majnemer219055f2016-01-04 17:42:19 +00001028 }
1029
David Majnemerb33f3a22016-01-04 23:16:22 +00001030 // Can't insert into a catchswitch.
1031 for (BasicBlock *ExitBlock : ExitBlocks)
1032 if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1033 return Changed;
1034
Chris Lattner1dc98b42010-08-29 06:43:52 +00001035 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001036 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1037 << '\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +00001038 Changed = true;
1039 ++NumPromoted;
1040
Eli Friedmanddf7f552011-05-27 20:31:51 +00001041 // Grab a debug location for the inserted loads/stores; given that the
1042 // inserted loads/stores have little relation to the original loads/stores,
1043 // this code just arbitrarily picks a location from one, since any debug
1044 // location is better than none.
1045 DebugLoc DL = LoopUses[0]->getDebugLoc();
1046
Chris Lattner1dc98b42010-08-29 06:43:52 +00001047 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001048 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001049 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001050 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001051 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001052
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001053 // Set up the preheader to have a definition of the value. It is the live-out
1054 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001055 LoadInst *PreheaderLoad = new LoadInst(
1056 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001057 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001058 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001059 if (AATags)
1060 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001061 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1062
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001063 // Rewrite all the loads in the loop and remember all the definitions from
1064 // stores in the loop.
1065 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001066
1067 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1068 if (PreheaderLoad->use_empty())
1069 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001070
1071 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +00001072}
Devang Patelb98a0972007-07-31 08:01:41 +00001073
Roman Gareev036c0882016-02-15 14:48:50 +00001074/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001075/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001076/// FIXME: In new pass manager, there is no helper function to handle loop
1077/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001078/// from scratch for every loop. Hook up with the helper functions when
1079/// available in the new pass manager to avoid redundant computation.
1080AliasSetTracker *
1081LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1082 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001083 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001084 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001085 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001086 auto MapI = LoopToAliasSetMap.find(InnerL);
1087 // If the AST for this inner loop is missing it may have been merged into
1088 // some other loop's AST and then that loop unrolled, and so we need to
1089 // recompute it.
1090 if (MapI == LoopToAliasSetMap.end()) {
1091 RecomputeLoops.push_back(InnerL);
1092 continue;
1093 }
1094 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001095
1096 if (CurAST != nullptr) {
1097 // What if InnerLoop was modified by other passes ?
1098 CurAST->add(*InnerAST);
1099
1100 // Once we've incorporated the inner loop's AST into ours, we don't need
1101 // the subloop's anymore.
1102 delete InnerAST;
1103 } else {
1104 CurAST = InnerAST;
1105 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001106 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001107 }
1108 if (CurAST == nullptr)
1109 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001110
1111 auto mergeLoop = [&](Loop *L) {
1112 // Loop over the body of this loop, looking for calls, invokes, and stores.
1113 // Because subloops have already been incorporated into AST, we skip blocks
1114 // in subloops.
1115 for (BasicBlock *BB : L->blocks())
1116 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1117 CurAST->add(*BB); // Incorporate the specified basic block
1118 };
1119
1120 // Add everything from the sub loops that are no longer directly available.
1121 for (Loop *InnerL : RecomputeLoops)
1122 mergeLoop(InnerL);
1123
1124 // And merge in this loop.
1125 mergeLoop(L);
1126
Roman Gareev036c0882016-02-15 14:48:50 +00001127 return CurAST;
1128}
1129
Ashutosh Nema47802622015-08-13 11:18:35 +00001130/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001131///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001132void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1133 Loop *L) {
1134 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001135 if (!AST)
1136 return;
1137
1138 AST->copyValue(From, To);
1139}
1140
Hal Finkel3d4269a2015-02-22 18:35:32 +00001141/// Simple Analysis hook. Delete value V from alias set
1142///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001143void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1144 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001145 if (!AST)
1146 return;
1147
1148 AST->deleteValue(V);
1149}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001150
1151/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001152///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001153void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1154 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001155 if (!AST)
1156 return;
1157
1158 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001159 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001160}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001161
Hal Finkel3d4269a2015-02-22 18:35:32 +00001162/// Return true if the body of this loop may store into the memory
1163/// location pointed to by V.
1164///
1165static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001166 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001167 AliasSetTracker *CurAST) {
1168 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1169 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1170}
1171
1172/// Little predicate that returns true if the specified basic block is in
1173/// a subloop of the current one, not the current one itself.
1174///
1175static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1176 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1177 return LI->getLoopFor(BB) != CurLoop;
1178}