blob: baa2594c755026b8e4493779d81f6fb97957f148 [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"
Philip Reamesb54c8e62016-03-09 22:59:30 +000044#include "llvm/Analysis/MemoryBuiltins.h"
Adam Nemet358433c2017-01-11 04:39:35 +000045#include "llvm/Analysis/OptimizationDiagnosticInfo.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 Carruth3bab7e12017-01-11 09:43:56 +000064#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000066#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000068#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000069#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000070using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "licm"
73
Dehao Chend55bc4c2016-05-05 00:54:54 +000074STATISTIC(NumSunk, "Number of instructions sunk out of loop");
75STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
77STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000078STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000079
Dan Gohmand78c4002008-05-13 00:00:25 +000080static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000081 DisablePromotion("disable-licm-promotion", cl::Hidden,
82 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000083
Hal Finkel3d4269a2015-02-22 18:35:32 +000084static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000085static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000086 const LoopSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000087static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +000088 const LoopSafetyInfo *SafetyInfo,
89 OptimizationRemarkEmitter *ORE);
Pete Cooper0cabcf22015-05-13 01:12:18 +000090static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000091 const Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet358433c2017-01-11 04:39:35 +000092 const LoopSafetyInfo *SafetyInfo,
93 OptimizationRemarkEmitter *ORE);
Adam Nemete2aaf3a2017-01-11 04:39:49 +000094static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +000095 const DominatorTree *DT,
96 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000097 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +000098 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +000099 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000100static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000101 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000102 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000103static Instruction *
104CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
105 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000106 const 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,
Adam Nemet358433c2017-01-11 04:39:35 +0000111 TargetLibraryInfo *TLI, ScalarEvolution *SE,
112 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000113
114 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
115 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000116 }
117
Dehao Chen9cba1f42016-07-12 22:37:48 +0000118private:
119 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
120
121 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
122 AliasAnalysis *AA);
123};
124
125struct LegacyLICMPass : public LoopPass {
126 static char ID; // Pass identification, replacement for typeid
127 LegacyLICMPass() : LoopPass(ID) {
128 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
129 }
130
131 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000132 if (skipLoop(L)) {
133 // If we have run LICM on a previous loop but now we are skipping
134 // (because we've hit the opt-bisect limit), we need to clear the
135 // loop alias information.
Davide Italianob9ff23a2016-12-23 15:02:35 +0000136 for (auto &LTAS : LICM.getLoopToAliasSetMap())
137 delete LTAS.second;
Davide Italiano34f94382016-12-23 13:12:50 +0000138 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000139 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000140 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000141
142 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Adam Nemet358433c2017-01-11 04:39:35 +0000143 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
144 // pass. Function analyses need to be preserved across loop transformations
145 // but ORE cannot be preserved (see comment before the pass definition).
146 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000147 return LICM.runOnLoop(L,
148 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
149 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
150 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
151 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Adam Nemet358433c2017-01-11 04:39:35 +0000152 SE ? &SE->getSE() : nullptr, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000153 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000154
Dehao Chend55bc4c2016-05-05 00:54:54 +0000155 /// This transformation requires natural loop information & requires that
156 /// loop preheaders be inserted into the CFG...
157 ///
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.setPreservesCFG();
160 AU.addRequired<TargetLibraryInfoWrapperPass>();
161 getLoopAnalysisUsage(AU);
162 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000163
Dehao Chend55bc4c2016-05-05 00:54:54 +0000164 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000165
Dehao Chend55bc4c2016-05-05 00:54:54 +0000166 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000167 assert(LICM.getLoopToAliasSetMap().empty() &&
168 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000169 return false;
170 }
Devang Patel69730c92007-03-07 04:41:30 +0000171
Dehao Chend55bc4c2016-05-05 00:54:54 +0000172private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000173 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000174
Dehao Chend55bc4c2016-05-05 00:54:54 +0000175 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
176 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
177 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000178
Dehao Chend55bc4c2016-05-05 00:54:54 +0000179 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
180 /// set.
181 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000182
Dehao Chend55bc4c2016-05-05 00:54:54 +0000183 /// Simple Analysis hook. Delete loop L from alias set map.
184 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000185};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000186}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000187
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000188PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
189 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000190 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000191 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000192 Function *F = L.getHeader()->getParent();
193
Adam Nemet358433c2017-01-11 04:39:35 +0000194 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000195 // FIXME: This should probably be optional rather than required.
196 if (!ORE)
197 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
198 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000199
200 LoopInvariantCodeMotion LICM;
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000201 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000202 return PreservedAnalyses::all();
203
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000204 auto PA = getLoopPassPreservedAnalyses();
205 PA.preserveSet<CFGAnalyses>();
206 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000207}
208
209char LegacyLICMPass::ID = 0;
210INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
211 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000212INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000213INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000214INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
215 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000216
Dehao Chen9cba1f42016-07-12 22:37:48 +0000217Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000218
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000219/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000220/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000221/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000222/// We should delete AST for inner loops in the new pass manager to avoid
223/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000224///
Dehao Chen9cba1f42016-07-12 22:37:48 +0000225bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
226 LoopInfo *LI, DominatorTree *DT,
227 TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +0000228 ScalarEvolution *SE,
229 OptimizationRemarkEmitter *ORE,
230 bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000231 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000232
Chandler Carruthfc258542014-02-11 12:52:27 +0000233 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
234
Dehao Chen9cba1f42016-07-12 22:37:48 +0000235 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000236
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000237 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000238 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000239
Hal Finkel3d4269a2015-02-22 18:35:32 +0000240 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000241 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000242 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000243
Chris Lattner6ec05f52002-05-10 22:44:58 +0000244 // We want to visit all of the instructions in this loop... that are not parts
245 // of our subloops (they have already had their invariants hoisted out of
246 // their loop, into this loop, so there is no need to process the BODIES of
247 // the subloops).
248 //
Chris Lattner64437692002-09-29 21:46:09 +0000249 // Traverse the body of the loop in depth first order on the dominator tree so
250 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000251 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000252 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000253 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000254 if (L->hasDedicatedExits())
Dehao Chen9cba1f42016-07-12 22:37:48 +0000255 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000256 CurAST, &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000257 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000258 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000259 CurAST, &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000260
Chris Lattner45d67d62003-02-24 03:52:32 +0000261 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000262 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000263 // Don't sink stores from loops without dedicated block exits. Exits
264 // containing indirect branches are not transformed by loop simplify,
265 // make sure we catch that. An additional load may be generated in the
266 // preheader for SSA updater, so also avoid sinking when no preheader
267 // is available.
268 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000269 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000270 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000271 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000272
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000273 // We can't insert into a catchswitch.
274 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
275 return isa<CatchSwitchInst>(Exit->getTerminator());
276 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000277
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000278 if (!HasCatchSwitch) {
279 SmallVector<Instruction *, 8> InsertPts;
280 InsertPts.reserve(ExitBlocks.size());
281 for (BasicBlock *ExitBlock : ExitBlocks)
282 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000283
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000284 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000285
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000286 bool Promoted = false;
287
288 // Loop over all of the alias sets in the tracker object.
289 for (AliasSet &AS : *CurAST)
290 Promoted |=
291 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT,
Adam Nemet358433c2017-01-11 04:39:35 +0000292 TLI, L, CurAST, &SafetyInfo, ORE);
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000293
294 // Once we have promoted values across the loop body we have to
295 // recursively reform LCSSA as any nested loop may now have values defined
296 // within the loop used in the outer loop.
297 // FIXME: This is really heavy handed. It would be a bit better to use an
298 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
299 // it as it went.
300 if (Promoted)
301 formLCSSARecursively(*L, *DT, LI, SE);
302
303 Changed |= Promoted;
304 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000305 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000306
Chandler Carruthfc258542014-02-11 12:52:27 +0000307 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
308 // specifically moving instructions across the loop boundary and so it is
309 // especially in need of sanity checking here.
310 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
311 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
312 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000313
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000314 // If this loop is nested inside of another one, save the alias information
315 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000316 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000317 LoopToAliasSetMap[L] = CurAST;
318 else
319 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000320
Dehao Chen9cba1f42016-07-12 22:37:48 +0000321 if (Changed && SE)
322 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000323 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000324}
325
Hal Finkel3d4269a2015-02-22 18:35:32 +0000326/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000327/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000328/// first order w.r.t the DominatorTree. This allows us to visit uses before
329/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000330///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
332 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000333 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
334 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000335
Hal Finkel3d4269a2015-02-22 18:35:32 +0000336 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000337 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
338 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
339 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000340
Hal Finkel3d4269a2015-02-22 18:35:32 +0000341 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000342 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000343 if (!CurLoop->contains(BB))
344 return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000345
Chris Lattner263f8042010-08-29 18:22:25 +0000346 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000347 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000348 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000349 for (DomTreeNode *Child : Children)
Adam Nemet358433c2017-01-11 04:39:35 +0000350 Changed |=
351 sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE);
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000352
Chris Lattner547192d62003-12-19 07:22:45 +0000353 // Only need to process the contents of this block if it is not part of a
354 // subloop (which would already have been processed).
Dehao Chend55bc4c2016-05-05 00:54:54 +0000355 if (inSubLoop(BB, CurLoop, LI))
356 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000357
Dehao Chend55bc4c2016-05-05 00:54:54 +0000358 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
Chris Lattner91846012003-12-19 08:18:16 +0000359 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000360
Chris Lattner263f8042010-08-29 18:22:25 +0000361 // If the instruction is dead, we would try to sink it because it isn't used
362 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000363 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000364 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000365 ++II;
366 CurAST->deleteValue(&I);
367 I.eraseFromParent();
368 Changed = true;
369 continue;
370 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000371
Chris Lattner547192d62003-12-19 07:22:45 +0000372 // Check to see if we can sink this instruction to the exit blocks
373 // of the loop. We can do this if the all users of the instruction are
374 // outside of the loop. In this case, it doesn't even matter if the
375 // operands of the instruction are loop invariant.
376 //
David Majnemer42a07302016-01-04 03:37:39 +0000377 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Adam Nemet81941b32017-01-11 04:39:45 +0000378 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
Chris Lattner91846012003-12-19 08:18:16 +0000379 ++II;
Adam Nemet358433c2017-01-11 04:39:35 +0000380 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo, ORE);
Chris Lattner91846012003-12-19 08:18:16 +0000381 }
Chris Lattner547192d62003-12-19 07:22:45 +0000382 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000383 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000384}
385
Hal Finkel3d4269a2015-02-22 18:35:32 +0000386/// Walk the specified region of the CFG (defined by all blocks dominated by
387/// the specified block, and that are in the current loop) in depth first
388/// order w.r.t the DominatorTree. This allows us to visit definitions before
389/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000390///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
392 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000393 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
394 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000395 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000396 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
397 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
398 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000399
Owen Andersonc24701e2007-04-24 06:40:39 +0000400 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000401
Chris Lattner05e86302002-09-29 22:26:07 +0000402 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000403 if (!CurLoop->contains(BB))
404 return false;
Sanjay Patel99133222016-01-13 23:01:57 +0000405
Chris Lattneraaaea512003-12-10 06:41:05 +0000406 // Only need to process the contents of this block if it is not part of a
407 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000408 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000409 if (!inSubLoop(BB, CurLoop, LI))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000410 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000411 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000412 // Try constant folding this instruction. If all the operands are
413 // constants, it is technically hoistable, but it would be better to just
414 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000415 if (Constant *C = ConstantFoldInstruction(
416 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000417 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
418 CurAST->copyValue(&I, C);
Chris Lattner030f0202010-08-31 23:00:16 +0000419 I.replaceAllUsesWith(C);
David Majnemer522a9112016-07-22 04:54:44 +0000420 if (isInstructionTriviallyDead(&I, TLI)) {
421 CurAST->deleteValue(&I);
422 I.eraseFromParent();
423 }
Andrew Kaylor7353cf42017-01-05 18:53:24 +0000424 Changed = true;
Chris Lattner030f0202010-08-31 23:00:16 +0000425 continue;
426 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000427
Chris Lattner547192d62003-12-19 07:22:45 +0000428 // Try hoisting the instruction out to the preheader. We can only do this
429 // if all of the operands of the instruction are loop invariant and if it
430 // is safe to hoist the instruction.
431 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 if (CurLoop->hasLoopInvariantOperands(&I) &&
Adam Nemet81941b32017-01-11 04:39:45 +0000433 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000434 isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000435 I, DT, CurLoop, SafetyInfo, ORE,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000436 CurLoop->getLoopPreheader()->getTerminator()))
Adam Nemet358433c2017-01-11 04:39:35 +0000437 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
Chris Lattner030f0202010-08-31 23:00:16 +0000438 }
Chris Lattner64437692002-09-29 21:46:09 +0000439
Dehao Chend55bc4c2016-05-05 00:54:54 +0000440 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000441 for (DomTreeNode *Child : Children)
Adam Nemet358433c2017-01-11 04:39:35 +0000442 Changed |=
443 hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000444 return Changed;
445}
446
447/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000448/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000449///
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000450void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000451 assert(CurLoop != nullptr && "CurLoop cant be null");
452 BasicBlock *Header = CurLoop->getHeader();
453 // Setting default safety values.
454 SafetyInfo->MayThrow = false;
455 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000456 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000457 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
458 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000459 SafetyInfo->HeaderMayThrow |=
460 !isGuaranteedToTransferExecutionToSuccessor(&*I);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000461
Hal Finkel3d4269a2015-02-22 18:35:32 +0000462 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000463 // Iterate over loop instructions and compute safety info.
464 for (Loop::block_iterator BB = CurLoop->block_begin(),
465 BBE = CurLoop->block_end();
466 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000467 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
468 (I != E) && !SafetyInfo->MayThrow; ++I)
Eli Friedmanf1da33e2016-06-11 21:48:25 +0000469 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
David Majnemer42a07302016-01-04 03:37:39 +0000470
471 // Compute funclet colors if we might sink/hoist in a function with a funclet
472 // personality routine.
473 Function *Fn = CurLoop->getHeader()->getParent();
474 if (Fn->hasPersonalityFn())
475 if (Constant *PersonalityFn = Fn->getPersonalityFn())
476 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
477 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000478}
479
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000480bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
481 Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet81941b32017-01-11 04:39:45 +0000482 LoopSafetyInfo *SafetyInfo,
483 OptimizationRemarkEmitter *ORE) {
Chris Lattner65c11932003-12-09 19:32:44 +0000484 // Loads have extra constraints we have to verify before we can hoist them.
485 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000486 if (!LI->isUnordered())
Dehao Chend55bc4c2016-05-05 00:54:54 +0000487 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000488
Chris Lattner8a8fb902008-07-23 05:06:28 +0000489 // Loads from constant memory are always safe to move, even if they end up
490 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000491 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000492 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000493 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000494 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000495
Chris Lattner65c11932003-12-09 19:32:44 +0000496 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000497 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000498 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000499 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000500
501 AAMDNodes AAInfo;
502 LI->getAAMetadata(AAInfo);
503
Adam Nemet81941b32017-01-11 04:39:45 +0000504 bool Invalidated =
505 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
506 // Check loop-invariant address because this may also be a sinkable load
507 // whose address is not necessarily loop-invariant.
508 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
509 ORE->emit(OptimizationRemarkMissed(
510 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
511 << "failed to move load with loop-invariant address "
512 "because the loop may invalidate its value");
513
514 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000515 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000516 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000517 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000518 return false;
519
David Majnemer42a07302016-01-04 03:37:39 +0000520 // Don't sink calls which can throw.
521 if (CI->mayThrow())
522 return false;
523
Eli Friedman942e1c12011-05-27 18:37:52 +0000524 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000525 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
526 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000527 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000528 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000529 // A readonly argmemonly function only reads from memory pointed to by
530 // it's arguments with arbitrary offsets. If we can prove there are no
531 // writes to this memory in the loop, we can hoist or sink.
532 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
533 for (Value *Op : CI->arg_operands())
534 if (Op->getType()->isPointerTy() &&
535 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
536 AAMDNodes(), CurAST))
537 return false;
538 return true;
539 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000540 // If this call only reads from memory and there are no writes to memory
541 // in the loop, we can hoist or sink the call as appropriate.
542 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000543 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000544 if (!AS.isForwardingAliasSet() && AS.isMod()) {
545 FoundMod = true;
546 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000547 }
Chris Lattner20cda262004-03-15 04:11:30 +0000548 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000549 if (!FoundMod)
550 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000551 }
552
Nadav Rotem03dcd852012-09-04 10:25:04 +0000553 // FIXME: This should use mod/ref information to see if we can hoist or
554 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000555
Chris Lattner20cda262004-03-15 04:11:30 +0000556 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000557 }
558
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000559 // Only these instructions are hoistable/sinkable.
560 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
561 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
562 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
563 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
564 !isa<InsertValueInst>(I))
565 return false;
566
Dehao Chen92abc7e2016-10-03 18:52:08 +0000567 // SafetyInfo is nullptr if we are checking for sinking from preheader to
568 // loop body. It will be always safe as there is no speculative execution.
569 if (!SafetyInfo)
570 return true;
571
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000572 // TODO: Plumb the context instruction through to make hoisting and sinking
573 // more powerful. Hoisting of loads already works due to the special casing
574 // above.
575 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000576}
577
Hal Finkel3d4269a2015-02-22 18:35:32 +0000578/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000579/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000580/// This is true when all incoming values are that instruction.
581/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000582///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000583static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000584 for (const Value *IncValue : PN.incoming_values())
585 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000586 return false;
587
588 return true;
589}
590
Hal Finkel3d4269a2015-02-22 18:35:32 +0000591/// Return true if the only users of this instruction are outside of
592/// the loop. If this is true, we can sink the instruction to the exit
593/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000594///
David Majnemer42a07302016-01-04 03:37:39 +0000595static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000596 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000597 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000598 for (const User *U : I.users()) {
599 const Instruction *UI = cast<Instruction>(U);
600 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000601 const BasicBlock *BB = PN->getParent();
602 // We cannot sink uses in catchswitches.
603 if (isa<CatchSwitchInst>(BB->getTerminator()))
604 return false;
605
606 // We need to sink a callsite to a unique funclet. Avoid sinking if the
607 // phi use is too muddled.
608 if (isa<CallInst>(I))
609 if (!BlockColors.empty() &&
610 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
611 return false;
612
Chandler Carruth8765cf72014-01-25 04:07:24 +0000613 // A PHI node where all of the incoming values are this instruction are
614 // special -- they can just be RAUW'ed with the instruction and thus
615 // don't require a use in the predecessor. This is a particular important
616 // special case because it is the pattern found in LCSSA form.
617 if (isTriviallyReplacablePHI(*PN, I)) {
618 if (CurLoop->contains(PN))
619 return false;
620 else
621 continue;
622 }
623
624 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
625 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000626 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
627 if (PN->getIncomingValue(i) == &I)
628 if (CurLoop->contains(PN->getIncomingBlock(i)))
629 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000630
631 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000632 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000633
Chandler Carruthcdf47882014-03-09 03:16:01 +0000634 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000635 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000636 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000637 return true;
638}
639
David Majnemer42a07302016-01-04 03:37:39 +0000640static Instruction *
641CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
642 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000643 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000644 Instruction *New;
645 if (auto *CI = dyn_cast<CallInst>(&I)) {
646 const auto &BlockColors = SafetyInfo->BlockColors;
647
648 // Sinking call-sites need to be handled differently from other
649 // instructions. The cloned call-site needs a funclet bundle operand
650 // appropriate for it's location in the CFG.
651 SmallVector<OperandBundleDef, 1> OpBundles;
652 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
653 BundleIdx != BundleEnd; ++BundleIdx) {
654 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
655 if (Bundle.getTagID() == LLVMContext::OB_funclet)
656 continue;
657
658 OpBundles.emplace_back(Bundle);
659 }
660
661 if (!BlockColors.empty()) {
662 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
663 assert(CV.size() == 1 && "non-unique color for exit block!");
664 BasicBlock *BBColor = CV.front();
665 Instruction *EHPad = BBColor->getFirstNonPHI();
666 if (EHPad->isEHPad())
667 OpBundles.emplace_back("funclet", EHPad);
668 }
669
670 New = CallInst::Create(CI, OpBundles);
671 } else {
672 New = I.clone();
673 }
674
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000675 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000676 if (!I.getName().empty())
677 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000678
679 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
680 // particularly cheap because we can rip off the PHI node that we're
681 // replacing for the number and blocks of the predecessors.
682 // OPT: If this shows up in a profile, we can instead finish sinking all
683 // invariant instructions, and then walk their operands to re-establish
684 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
685 // sinking bottom-up.
686 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
687 ++OI)
688 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
689 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
690 if (!OLoop->contains(&PN)) {
691 PHINode *OpPN =
692 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000693 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000694 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
695 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
696 *OI = OpPN;
697 }
698 return New;
699}
700
Hal Finkel3d4269a2015-02-22 18:35:32 +0000701/// When an instruction is found to only be used outside of the loop, this
702/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000703/// This method is guaranteed to remove the original instruction from its
704/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000705///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000706static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000707 const Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet358433c2017-01-11 04:39:35 +0000708 const LoopSafetyInfo *SafetyInfo,
709 OptimizationRemarkEmitter *ORE) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000710 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Adam Nemet358433c2017-01-11 04:39:35 +0000711 ORE->emit(OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
712 << "sinking " << ore::NV("Inst", &I));
Hal Finkel3d4269a2015-02-22 18:35:32 +0000713 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000714 if (isa<LoadInst>(I))
715 ++NumMovedLoads;
716 else if (isa<CallInst>(I))
717 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000718 ++NumSunk;
719 Changed = true;
720
Chandler Carruthfc258542014-02-11 12:52:27 +0000721#ifndef NDEBUG
722 SmallVector<BasicBlock *, 32> ExitBlocks;
723 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000724 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000725 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000726#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000727
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000728 // Clones of this instruction. Don't create more than one per exit block!
729 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
730
Chandler Carruthfc258542014-02-11 12:52:27 +0000731 // If this instruction is only used outside of the loop, then all users are
732 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
733 // the instruction.
734 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000735 Value::user_iterator UI = I.user_begin();
736 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000737 if (!DT->isReachableFromEntry(User->getParent())) {
738 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
739 continue;
740 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000741 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000742 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000743
David Majnemer6bc83e02015-07-12 03:53:05 +0000744 // Surprisingly, instructions can be used outside of loops without any
745 // exits. This can only happen in PHI nodes if the incoming block is
746 // unreachable.
747 Use &U = UI.getUse();
748 BasicBlock *BB = PN->getIncomingBlock(U);
749 if (!DT->isReachableFromEntry(BB)) {
750 U = UndefValue::get(I.getType());
751 continue;
752 }
753
Chandler Carruthfc258542014-02-11 12:52:27 +0000754 BasicBlock *ExitBlock = PN->getParent();
755 assert(ExitBlockSet.count(ExitBlock) &&
756 "The LCSSA PHI is not in an exit block!");
757
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000758 Instruction *New;
759 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000760 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000761 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000762 else
763 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000764 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000765
766 PN->replaceAllUsesWith(New);
767 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000768 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000769
Chris Lattner1a1ed692010-08-29 18:00:00 +0000770 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000771 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000772 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000773}
Chris Lattner64437692002-09-29 21:46:09 +0000774
Hal Finkel3d4269a2015-02-22 18:35:32 +0000775/// When an instruction is found to only use loop invariant operands that
776/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000777///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000778static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000779 const LoopSafetyInfo *SafetyInfo,
780 OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000781 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000782 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
783 << "\n");
Adam Nemet358433c2017-01-11 04:39:35 +0000784 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Hoisted", &I)
785 << "hosting " << ore::NV("Inst", &I));
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000786
787 // Metadata can be dependent on conditions we are hoisting above.
788 // Conservatively strip all metadata on the instruction unless we were
789 // guaranteed to execute I if we entered the loop, in which case the metadata
790 // is valid in the loop preheader.
791 if (I.hasMetadataOtherThanDebugLoc() &&
792 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
793 // time in isGuaranteedToExecute if we don't actually have anything to
794 // drop. It is a compile time optimization, not required for correctness.
795 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
796 I.dropUnknownNonDebugMetadata();
797
Chris Lattner6ac06592010-08-29 18:18:40 +0000798 // Move the new node to the Preheader, before its terminator.
799 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000800
Wolfgang Piebc17a2792017-01-06 18:38:57 +0000801 // Do not retain debug locations when we are moving instructions to different
802 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
803 // need to retain their debug locs because they may be inlined.
804 // FIXME: How do we retain source locations without causing poor debugging
805 // behavior?
806 if (!isa<CallInst>(I))
807 I.setDebugLoc(DebugLoc());
808
Dehao Chend55bc4c2016-05-05 00:54:54 +0000809 if (isa<LoadInst>(I))
810 ++NumMovedLoads;
811 else if (isa<CallInst>(I))
812 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000813 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000814 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000815}
816
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000817/// Only sink or hoist an instruction if it is not a trapping instruction,
818/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000819/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000820static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000821 const DominatorTree *DT,
822 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000823 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000824 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000825 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +0000826 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000827 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000828
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000829 bool GuaranteedToExecute =
830 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
831
832 if (!GuaranteedToExecute) {
833 auto *LI = dyn_cast<LoadInst>(&Inst);
834 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
835 ORE->emit(OptimizationRemarkMissed(
836 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
837 << "failed to hoist load with loop-invariant address "
838 "because load is conditionally executed");
839 }
840
841 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000842}
843
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000844namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000845class LoopPromoter : public LoadAndStorePromoter {
846 Value *SomePtr; // Designated pointer to store to.
847 SmallPtrSetImpl<Value *> &PointerMustAliases;
848 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
849 SmallVectorImpl<Instruction *> &LoopInsertPts;
850 PredIteratorCache &PredCache;
851 AliasSetTracker &AST;
852 LoopInfo &LI;
853 DebugLoc DL;
854 int Alignment;
855 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000856
Dehao Chend55bc4c2016-05-05 00:54:54 +0000857 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
858 if (Instruction *I = dyn_cast<Instruction>(V))
859 if (Loop *L = LI.getLoopFor(I->getParent()))
860 if (!L->contains(BB)) {
861 // We need to create an LCSSA PHI node for the incoming value and
862 // store that.
863 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
864 I->getName() + ".lcssa", &BB->front());
865 for (BasicBlock *Pred : PredCache.get(BB))
866 PN->addIncoming(I, Pred);
867 return PN;
868 }
869 return V;
870 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000871
Dehao Chend55bc4c2016-05-05 00:54:54 +0000872public:
873 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
874 SmallPtrSetImpl<Value *> &PMA,
875 SmallVectorImpl<BasicBlock *> &LEB,
876 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
877 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
878 const AAMDNodes &AATags)
879 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
880 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000881 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000882
Dehao Chend55bc4c2016-05-05 00:54:54 +0000883 bool isInstInList(Instruction *I,
884 const SmallVectorImpl<Instruction *> &) const override {
885 Value *Ptr;
886 if (LoadInst *LI = dyn_cast<LoadInst>(I))
887 Ptr = LI->getOperand(0);
888 else
889 Ptr = cast<StoreInst>(I)->getPointerOperand();
890 return PointerMustAliases.count(Ptr);
891 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000892
Dehao Chend55bc4c2016-05-05 00:54:54 +0000893 void doExtraRewritesBeforeFinalDeletion() const override {
894 // Insert stores after in the loop exit blocks. Each exit block gets a
895 // store of the live-out values that feed them. Since we've already told
896 // the SSA updater about the defs in the loop and the preheader
897 // definition, it is all set and we can start using it.
898 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
899 BasicBlock *ExitBlock = LoopExitBlocks[i];
900 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
901 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
902 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
903 Instruction *InsertPos = LoopInsertPts[i];
904 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
905 NewSI->setAlignment(Alignment);
906 NewSI->setDebugLoc(DL);
907 if (AATags)
908 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000909 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000910 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000911
Dehao Chend55bc4c2016-05-05 00:54:54 +0000912 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
913 // Update alias analysis.
914 AST.copyValue(LI, V);
915 }
916 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
917};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000918} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000919
Hal Finkel3d4269a2015-02-22 18:35:32 +0000920/// Try to promote memory values to scalars by sinking stores out of the
921/// loop and moving loads to before the loop. We do this by looping over
922/// the stores in the loop, looking for stores to Must pointers which are
923/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000924///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000925bool llvm::promoteLoopAccessesToScalars(
926 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
927 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
928 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +0000929 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
930 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000931 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000932 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
933 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +0000934 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000935
Chris Lattner1dc98b42010-08-29 06:43:52 +0000936 // We can promote this alias set if it has a store, if it is a "Must" alias
937 // set, if the pointer is loop invariant, and if we are not eliminating any
938 // volatile loads or stores.
939 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
940 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000941 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000942
Chris Lattner1dc98b42010-08-29 06:43:52 +0000943 assert(!AS.empty() &&
944 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000945
Chris Lattner1dc98b42010-08-29 06:43:52 +0000946 Value *SomePtr = AS.begin()->getValue();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000947 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000948
Chris Lattner1dc98b42010-08-29 06:43:52 +0000949 // It isn't safe to promote a load/store from the loop if the load/store is
950 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000951 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000952 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000953 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000954 // into:
955 //
956 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
957 //
958 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000959 //
Philip Reamesb54c8e62016-03-09 22:59:30 +0000960 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000961 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +0000962 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000963 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +0000964 // path which did not originally have one.
965 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000966 // If at least one store is guaranteed to execute, both properties are
967 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +0000968 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000969 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +0000970 // guaranteed to execute, we can still establish these properties.
971 // We can establish (p1) by proving that hoisting the load into the preheader
972 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000973 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +0000974 // since they're all must alias.
Michael Kupersteinc9acad12017-01-05 20:42:06 +0000975 //
976 // There are two ways establish (p2):
977 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000978 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +0000979 // b) Prove a store dominates every exit block. In this case, if an exit
980 // blocks is reached, the original dynamic path would have taken us through
981 // the store, so inserting a store into the exit block is safe. Note that this
982 // is different from the store being guaranteed to execute. For instance,
983 // if an exception is thrown on the first iteration of the loop, the original
984 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000985
986 bool DereferenceableInPH = false;
987 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000988
Dehao Chend55bc4c2016-05-05 00:54:54 +0000989 SmallVector<Instruction *, 64> LoopUses;
990 SmallPtrSet<Value *, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000991
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000992 // We start with an alignment of one and try to find instructions that allow
993 // us to prove better alignment.
994 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000995 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000996
Philip Reamesb54c8e62016-03-09 22:59:30 +0000997 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
998
Eli Friedmanee895052016-06-05 22:13:52 +0000999 if (SafetyInfo->MayThrow) {
1000 // If a loop can throw, we have to insert a store along each unwind edge.
1001 // That said, we can't actually make the unwind edge explicit. Therefore,
1002 // we have to prove that the store is dead along the unwind edge.
1003 //
1004 // Currently, this code just special-cases alloca instructions.
1005 if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
1006 return false;
1007 }
1008
Chris Lattner1dc98b42010-08-29 06:43:52 +00001009 // Check that all of the pointers in the alias set have the same type. We
1010 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001011 // different sizes. While we are at it, collect alignment and AA info.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001012 for (const auto &ASI : AS) {
1013 Value *ASIV = ASI.getValue();
Chris Lattner1dc98b42010-08-29 06:43:52 +00001014 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +00001015
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001016 // Check that all of the pointers in the alias set have the same type. We
1017 // cannot (yet) promote a memory location that is loaded and stored in
1018 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001019 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001020 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001021
Chandler Carruthcdf47882014-03-09 03:16:01 +00001022 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001023 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001024 Instruction *UI = dyn_cast<Instruction>(U);
1025 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001026 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001027
Chris Lattner1dc98b42010-08-29 06:43:52 +00001028 // If there is an non-load/store instruction in the loop, we can't promote
1029 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001030 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Sanjay Patel9f49b682016-01-08 22:05:03 +00001031 assert(!Load->isVolatile() && "AST broken");
1032 if (!Load->isSimple())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001033 return false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001034
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001035 if (!DereferenceableInPH)
1036 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001037 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001038 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001039 // Stores *of* the pointer are not interesting, only stores *to* the
1040 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001041 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001042 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +00001043 assert(!Store->isVolatile() && "AST broken");
1044 if (!Store->isSimple())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001045 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001046
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001047 // If the store is guaranteed to execute, both properties are satisfied.
1048 // We may want to check if a store is guaranteed to execute even if we
1049 // already know that promotion is safe, since it may have higher
1050 // alignment than any other guaranteed stores, in which case we can
1051 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001052 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001053 if (!InstAlignment)
1054 InstAlignment =
1055 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1056
1057 if (!DereferenceableInPH || !SafeToInsertStore ||
1058 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001059 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001060 DereferenceableInPH = true;
1061 SafeToInsertStore = true;
1062 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001063 }
Anna Thomas67151352016-06-24 12:38:45 +00001064 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001065
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001066 // If a store dominates all exit blocks, it is safe to sink.
1067 // As explained above, if an exit block was executed, a dominating
1068 // store must have been been executed at least once, so we are not
1069 // introducing stores on paths that did not have them.
1070 // Note that this only looks at explicit exit blocks. If we ever
1071 // start sinking stores into unwind edges (see above), this will break.
1072 if (!SafeToInsertStore)
1073 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1074 return DT->dominates(Store->getParent(), Exit);
1075 });
1076
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001077 // If the store is not guaranteed to execute, we may still get
1078 // deref info through it.
1079 if (!DereferenceableInPH) {
1080 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001081 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001082 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001083 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001084 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001085 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001086
Hal Finkelcc39b672014-07-24 12:16:19 +00001087 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001088 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001089 // On the first load/store, just take its AA tags.
1090 UI->getAAMetadata(AATags);
1091 } else if (AATags) {
1092 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001093 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001094
1095 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001096 }
1097 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001098
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001099
1100 // If we couldn't prove we can hoist the load, bail.
1101 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001102 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001103
1104 // We know we can hoist the load, but don't have a guaranteed store.
1105 // Check whether the location is thread-local. If it is, then we can insert
1106 // stores along paths which originally didn't have them without violating the
1107 // memory model.
1108 if (!SafeToInsertStore) {
Philip Reamesb54c8e62016-03-09 22:59:30 +00001109 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001110 SafeToInsertStore =
Michael Kuperstein76e06c82016-12-30 01:03:17 +00001111 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1112 !PointerMayBeCaptured(Object, true, true);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001113 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001114
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001115 // If we've still failed to prove we can sink the store, give up.
1116 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001117 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001118
Chris Lattner1dc98b42010-08-29 06:43:52 +00001119 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001120 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1121 << '\n');
Adam Nemet358433c2017-01-11 04:39:35 +00001122 ORE->emit(
1123 OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", LoopUses[0])
1124 << "Moving accesses to memory location out of the loop");
Chris Lattner1dc98b42010-08-29 06:43:52 +00001125 ++NumPromoted;
1126
Eli Friedmanddf7f552011-05-27 20:31:51 +00001127 // Grab a debug location for the inserted loads/stores; given that the
1128 // inserted loads/stores have little relation to the original loads/stores,
1129 // this code just arbitrarily picks a location from one, since any debug
1130 // location is better than none.
1131 DebugLoc DL = LoopUses[0]->getDebugLoc();
1132
Chris Lattner1dc98b42010-08-29 06:43:52 +00001133 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001134 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001135 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001136 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001137 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001138
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001139 // Set up the preheader to have a definition of the value. It is the live-out
1140 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001141 LoadInst *PreheaderLoad = new LoadInst(
1142 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001143 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001144 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001145 if (AATags)
1146 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001147 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1148
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001149 // Rewrite all the loads in the loop and remember all the definitions from
1150 // stores in the loop.
1151 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001152
1153 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1154 if (PreheaderLoad->use_empty())
1155 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001156
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001157 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001158}
Devang Patelb98a0972007-07-31 08:01:41 +00001159
Roman Gareev036c0882016-02-15 14:48:50 +00001160/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001161/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001162/// FIXME: In new pass manager, there is no helper function to handle loop
1163/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001164/// from scratch for every loop. Hook up with the helper functions when
1165/// available in the new pass manager to avoid redundant computation.
1166AliasSetTracker *
1167LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1168 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001169 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001170 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001171 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001172 auto MapI = LoopToAliasSetMap.find(InnerL);
1173 // If the AST for this inner loop is missing it may have been merged into
1174 // some other loop's AST and then that loop unrolled, and so we need to
1175 // recompute it.
1176 if (MapI == LoopToAliasSetMap.end()) {
1177 RecomputeLoops.push_back(InnerL);
1178 continue;
1179 }
1180 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001181
1182 if (CurAST != nullptr) {
1183 // What if InnerLoop was modified by other passes ?
1184 CurAST->add(*InnerAST);
1185
1186 // Once we've incorporated the inner loop's AST into ours, we don't need
1187 // the subloop's anymore.
1188 delete InnerAST;
1189 } else {
1190 CurAST = InnerAST;
1191 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001192 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001193 }
1194 if (CurAST == nullptr)
1195 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001196
1197 auto mergeLoop = [&](Loop *L) {
1198 // Loop over the body of this loop, looking for calls, invokes, and stores.
1199 // Because subloops have already been incorporated into AST, we skip blocks
1200 // in subloops.
1201 for (BasicBlock *BB : L->blocks())
1202 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1203 CurAST->add(*BB); // Incorporate the specified basic block
1204 };
1205
1206 // Add everything from the sub loops that are no longer directly available.
1207 for (Loop *InnerL : RecomputeLoops)
1208 mergeLoop(InnerL);
1209
1210 // And merge in this loop.
1211 mergeLoop(L);
1212
Roman Gareev036c0882016-02-15 14:48:50 +00001213 return CurAST;
1214}
1215
Ashutosh Nema47802622015-08-13 11:18:35 +00001216/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001217///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001218void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1219 Loop *L) {
1220 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001221 if (!AST)
1222 return;
1223
1224 AST->copyValue(From, To);
1225}
1226
Hal Finkel3d4269a2015-02-22 18:35:32 +00001227/// Simple Analysis hook. Delete value V from alias set
1228///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001229void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1230 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001231 if (!AST)
1232 return;
1233
1234 AST->deleteValue(V);
1235}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001236
1237/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001238///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001239void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1240 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001241 if (!AST)
1242 return;
1243
1244 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001245 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001246}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001247
Hal Finkel3d4269a2015-02-22 18:35:32 +00001248/// Return true if the body of this loop may store into the memory
1249/// location pointed to by V.
1250///
1251static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001252 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001253 AliasSetTracker *CurAST) {
1254 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1255 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1256}
1257
1258/// Little predicate that returns true if the specified basic block is in
1259/// a subloop of the current one, not the current one itself.
1260///
1261static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1262 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1263 return LI->getLoopFor(BB) != CurLoop;
1264}