blob: e3df80b19aad9f4949c4ef72b67449beb1298a7f [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"
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +000045#include "llvm/Analysis/MemorySSA.h"
Adam Nemet0965da22017-10-09 23:19:02 +000046#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000050#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000051#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
54#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000055#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/Instructions.h"
57#include "llvm/IR/IntrinsicInst.h"
58#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000059#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000060#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000061#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000064#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000065#include "llvm/Transforms/Scalar/LoopPassManager.h"
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000068#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000069#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000070#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000071#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000072using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "licm"
75
Dehao Chend55bc4c2016-05-05 00:54:54 +000076STATISTIC(NumSunk, "Number of instructions sunk out of loop");
77STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000078STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
79STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000080STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000081
Xin Tongccee0e02017-02-21 20:53:48 +000082/// Memory promotion is enabled by default.
Dan Gohmand78c4002008-05-13 00:00:25 +000083static cl::opt<bool>
Xin Tongccee0e02017-02-21 20:53:48 +000084 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
Dehao Chend55bc4c2016-05-05 00:54:54 +000085 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000086
Anna Thomas7f4b26e2017-02-02 13:22:03 +000087static cl::opt<uint32_t> MaxNumUsesTraversed(
88 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
89 cl::desc("Max num uses visited for identifying load "
90 "invariance in loop using invariant start (default = 8)"));
91
Hal Finkel3d4269a2015-02-22 18:35:32 +000092static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
Jun Bum Lim44c58d32017-12-15 20:33:24 +000093static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
94 const LoopSafetyInfo *SafetyInfo,
95 TargetTransformInfo *TTI, bool &FreeInLoop);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000096static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +000097 const LoopSafetyInfo *SafetyInfo,
98 OptimizationRemarkEmitter *ORE);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000099static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000100 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000101 OptimizationRemarkEmitter *ORE, bool FreeInLoop);
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000102static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000103 const DominatorTree *DT,
104 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000105 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000106 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000107 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000108static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000109 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000110 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000111static Instruction *
112CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
113 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000114 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000115
Dan Gohmand78c4002008-05-13 00:00:25 +0000116namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000117struct LoopInvariantCodeMotion {
118 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000119 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
120 ScalarEvolution *SE, MemorySSA *MSSA,
Adam Nemet358433c2017-01-11 04:39:35 +0000121 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000122
123 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
124 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000125 }
126
Dehao Chen9cba1f42016-07-12 22:37:48 +0000127private:
128 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
129
130 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
131 AliasAnalysis *AA);
132};
133
134struct LegacyLICMPass : public LoopPass {
135 static char ID; // Pass identification, replacement for typeid
136 LegacyLICMPass() : LoopPass(ID) {
137 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
138 }
139
140 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000141 if (skipLoop(L)) {
142 // If we have run LICM on a previous loop but now we are skipping
143 // (because we've hit the opt-bisect limit), we need to clear the
144 // loop alias information.
Davide Italianob9ff23a2016-12-23 15:02:35 +0000145 for (auto &LTAS : LICM.getLoopToAliasSetMap())
146 delete LTAS.second;
Davide Italiano34f94382016-12-23 13:12:50 +0000147 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000148 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000149 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000150
151 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000152 MemorySSA *MSSA = EnableMSSALoopDependency
153 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
154 : nullptr;
Adam Nemet358433c2017-01-11 04:39:35 +0000155 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
156 // pass. Function analyses need to be preserved across loop transformations
157 // but ORE cannot be preserved (see comment before the pass definition).
158 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000159 return LICM.runOnLoop(L,
160 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
161 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
162 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
163 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000164 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
165 *L->getHeader()->getParent()),
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000166 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000167 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000168
Dehao Chend55bc4c2016-05-05 00:54:54 +0000169 /// This transformation requires natural loop information & requires that
170 /// loop preheaders be inserted into the CFG...
171 ///
172 void getAnalysisUsage(AnalysisUsage &AU) const override {
173 AU.setPreservesCFG();
174 AU.addRequired<TargetLibraryInfoWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000175 if (EnableMSSALoopDependency)
176 AU.addRequired<MemorySSAWrapperPass>();
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000177 AU.addRequired<TargetTransformInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000178 getLoopAnalysisUsage(AU);
179 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000180
Dehao Chend55bc4c2016-05-05 00:54:54 +0000181 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000182
Dehao Chend55bc4c2016-05-05 00:54:54 +0000183 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000184 assert(LICM.getLoopToAliasSetMap().empty() &&
185 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000186 return false;
187 }
Devang Patel69730c92007-03-07 04:41:30 +0000188
Dehao Chend55bc4c2016-05-05 00:54:54 +0000189private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000190 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000191
Dehao Chend55bc4c2016-05-05 00:54:54 +0000192 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
193 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
194 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000195
Dehao Chend55bc4c2016-05-05 00:54:54 +0000196 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
197 /// set.
198 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000199
Dehao Chend55bc4c2016-05-05 00:54:54 +0000200 /// Simple Analysis hook. Delete loop L from alias set map.
201 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000202};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000203} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000204
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000205PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
206 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000207 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000208 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000209 Function *F = L.getHeader()->getParent();
210
Adam Nemet358433c2017-01-11 04:39:35 +0000211 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000212 // FIXME: This should probably be optional rather than required.
213 if (!ORE)
214 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
215 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000216
217 LoopInvariantCodeMotion LICM;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000218 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
219 AR.MSSA, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000220 return PreservedAnalyses::all();
221
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000222 auto PA = getLoopPassPreservedAnalyses();
223 PA.preserveSet<CFGAnalyses>();
224 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000225}
226
227char LegacyLICMPass::ID = 0;
228INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
229 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000230INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000231INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000232INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000233INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000234INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
235 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000236
Dehao Chen9cba1f42016-07-12 22:37:48 +0000237Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000238
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000239/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000240/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000241/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000242/// We should delete AST for inner loops in the new pass manager to avoid
243/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000244///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000245bool LoopInvariantCodeMotion::runOnLoop(
246 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
247 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
248 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000249 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000250
Chandler Carruthfc258542014-02-11 12:52:27 +0000251 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
252
Dehao Chen9cba1f42016-07-12 22:37:48 +0000253 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000254
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000255 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000256 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000257
Hal Finkel3d4269a2015-02-22 18:35:32 +0000258 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000259 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000260 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000261
Chris Lattner6ec05f52002-05-10 22:44:58 +0000262 // We want to visit all of the instructions in this loop... that are not parts
263 // of our subloops (they have already had their invariants hoisted out of
264 // their loop, into this loop, so there is no need to process the BODIES of
265 // the subloops).
266 //
Chris Lattner64437692002-09-29 21:46:09 +0000267 // Traverse the body of the loop in depth first order on the dominator tree so
268 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000269 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000270 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000271 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000272 if (L->hasDedicatedExits())
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000273 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000274 CurAST, &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000275 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000276 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000277 CurAST, &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000278
Chris Lattner45d67d62003-02-24 03:52:32 +0000279 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000280 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000281 // Don't sink stores from loops without dedicated block exits. Exits
282 // containing indirect branches are not transformed by loop simplify,
283 // make sure we catch that. An additional load may be generated in the
284 // preheader for SSA updater, so also avoid sinking when no preheader
285 // is available.
286 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000287 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000288 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000289 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000290
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000291 // We can't insert into a catchswitch.
292 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
293 return isa<CatchSwitchInst>(Exit->getTerminator());
294 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000295
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000296 if (!HasCatchSwitch) {
297 SmallVector<Instruction *, 8> InsertPts;
298 InsertPts.reserve(ExitBlocks.size());
299 for (BasicBlock *ExitBlock : ExitBlocks)
300 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000301
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000302 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000303
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000304 bool Promoted = false;
305
306 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000307 for (AliasSet &AS : *CurAST) {
308 // We can promote this alias set if it has a store, if it is a "Must"
309 // alias set, if the pointer is loop invariant, and if we are not
310 // eliminating any volatile loads or stores.
311 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
312 AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
313 continue;
314
315 assert(
316 !AS.empty() &&
317 "Must alias set should have at least one pointer element in it!");
318
319 SmallSetVector<Value *, 8> PointerMustAliases;
320 for (const auto &ASI : AS)
321 PointerMustAliases.insert(ASI.getValue());
322
323 Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
324 InsertPts, PIC, LI, DT, TLI, L,
325 CurAST, &SafetyInfo, ORE);
326 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000327
328 // Once we have promoted values across the loop body we have to
329 // recursively reform LCSSA as any nested loop may now have values defined
330 // within the loop used in the outer loop.
331 // FIXME: This is really heavy handed. It would be a bit better to use an
332 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
333 // it as it went.
334 if (Promoted)
335 formLCSSARecursively(*L, *DT, LI, SE);
336
337 Changed |= Promoted;
338 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000339 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000340
Chandler Carruthfc258542014-02-11 12:52:27 +0000341 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
342 // specifically moving instructions across the loop boundary and so it is
343 // especially in need of sanity checking here.
344 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
345 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
346 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000347
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000348 // If this loop is nested inside of another one, save the alias information
349 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000350 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000351 LoopToAliasSetMap[L] = CurAST;
352 else
353 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000354
Dehao Chen9cba1f42016-07-12 22:37:48 +0000355 if (Changed && SE)
356 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000357 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000358}
359
Hal Finkel3d4269a2015-02-22 18:35:32 +0000360/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000361/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000362/// first order w.r.t the DominatorTree. This allows us to visit uses before
363/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000364///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000365bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000366 DominatorTree *DT, TargetLibraryInfo *TLI,
367 TargetTransformInfo *TTI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000368 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
369 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000370
Hal Finkel3d4269a2015-02-22 18:35:32 +0000371 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000372 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
373 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
374 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000375
David Majnemere6bb8952017-07-20 03:27:02 +0000376 // We want to visit children before parents. We will enque all the parents
377 // before their children in the worklist and process the worklist in reverse
378 // order.
379 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000380
Sanjay Patel99133222016-01-13 23:01:57 +0000381 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000382 for (DomTreeNode *DTN : reverse(Worklist)) {
383 BasicBlock *BB = DTN->getBlock();
384 // Only need to process the contents of this block if it is not part of a
385 // subloop (which would already have been processed).
386 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000387 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000388
David Majnemere6bb8952017-07-20 03:27:02 +0000389 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
390 Instruction &I = *--II;
391
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000392 // If the instruction is dead, we would try to sink it because it isn't
393 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000394 if (isInstructionTriviallyDead(&I, TLI)) {
395 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
396 ++II;
397 CurAST->deleteValue(&I);
398 I.eraseFromParent();
399 Changed = true;
400 continue;
401 }
402
403 // Check to see if we can sink this instruction to the exit blocks
404 // of the loop. We can do this if the all users of the instruction are
405 // outside of the loop. In this case, it doesn't even matter if the
406 // operands of the instruction are loop invariant.
407 //
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000408 bool FreeInLoop = false;
409 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
David Majnemere6bb8952017-07-20 03:27:02 +0000410 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000411 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
412 if (!FreeInLoop) {
413 ++II;
414 CurAST->deleteValue(&I);
415 I.eraseFromParent();
416 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000417 Changed = true;
418 }
David Majnemere6bb8952017-07-20 03:27:02 +0000419 }
Chris Lattner91846012003-12-19 08:18:16 +0000420 }
Chris Lattner547192d62003-12-19 07:22:45 +0000421 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000422 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000423}
424
Hal Finkel3d4269a2015-02-22 18:35:32 +0000425/// Walk the specified region of the CFG (defined by all blocks dominated by
426/// the specified block, and that are in the current loop) in depth first
427/// order w.r.t the DominatorTree. This allows us to visit definitions before
428/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000429///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000430bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
431 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000432 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
433 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000434 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000435 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
436 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
437 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000438
David Majnemere6bb8952017-07-20 03:27:02 +0000439 // We want to visit parents before children. We will enque all the parents
440 // before their children in the worklist and process the worklist in order.
441 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000442
Sanjay Patel99133222016-01-13 23:01:57 +0000443 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000444 for (DomTreeNode *DTN : Worklist) {
445 BasicBlock *BB = DTN->getBlock();
446 // Only need to process the contents of this block if it is not part of a
447 // subloop (which would already have been processed).
448 if (!inSubLoop(BB, CurLoop, LI))
449 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
450 Instruction &I = *II++;
451 // Try constant folding this instruction. If all the operands are
452 // constants, it is technically hoistable, but it would be better to
453 // just fold it.
454 if (Constant *C = ConstantFoldInstruction(
455 &I, I.getModule()->getDataLayout(), TLI)) {
456 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
457 CurAST->copyValue(&I, C);
458 I.replaceAllUsesWith(C);
459 if (isInstructionTriviallyDead(&I, TLI)) {
460 CurAST->deleteValue(&I);
461 I.eraseFromParent();
462 }
463 Changed = true;
464 continue;
David Majnemer522a9112016-07-22 04:54:44 +0000465 }
David Majnemere6bb8952017-07-20 03:27:02 +0000466
467 // Attempt to remove floating point division out of the loop by
468 // converting it to a reciprocal multiplication.
469 if (I.getOpcode() == Instruction::FDiv &&
470 CurLoop->isLoopInvariant(I.getOperand(1)) &&
471 I.hasAllowReciprocal()) {
472 auto Divisor = I.getOperand(1);
473 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
474 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
475 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
476 ReciprocalDivisor->insertBefore(&I);
477
478 auto Product =
479 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
480 Product->setFastMathFlags(I.getFastMathFlags());
481 Product->insertAfter(&I);
482 I.replaceAllUsesWith(Product);
483 I.eraseFromParent();
484
485 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
486 Changed = true;
487 continue;
488 }
489
490 // Try hoisting the instruction out to the preheader. We can only do
491 // this if all of the operands of the instruction are loop invariant and
492 // if it is safe to hoist the instruction.
493 //
494 if (CurLoop->hasLoopInvariantOperands(&I) &&
495 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
496 isSafeToExecuteUnconditionally(
497 I, DT, CurLoop, SafetyInfo, ORE,
498 CurLoop->getLoopPreheader()->getTerminator()))
499 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
Chris Lattner030f0202010-08-31 23:00:16 +0000500 }
David Majnemere6bb8952017-07-20 03:27:02 +0000501 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000502
Hal Finkel3d4269a2015-02-22 18:35:32 +0000503 return Changed;
504}
505
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000506// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000507// CurLoop is dominated by an invariant.start representing the same memory
508// location and size as the memory location LI loads from, and also the
509// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000510static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
511 Loop *CurLoop) {
512 Value *Addr = LI->getOperand(0);
513 const DataLayout &DL = LI->getModule()->getDataLayout();
514 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
515 cast<PointerType>(Addr->getType())->getElementType());
516
517 // if the type is i8 addrspace(x)*, we know this is the type of
518 // llvm.invariant.start operand
519 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
520 LI->getPointerAddressSpace());
521 unsigned BitcastsVisited = 0;
522 // Look through bitcasts until we reach the i8* type (this is invariant.start
523 // operand type).
524 while (Addr->getType() != PtrInt8Ty) {
525 auto *BC = dyn_cast<BitCastInst>(Addr);
526 // Avoid traversing high number of bitcast uses.
527 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
528 return false;
529 Addr = BC->getOperand(0);
530 }
531
532 unsigned UsesVisited = 0;
533 // Traverse all uses of the load operand value, to see if invariant.start is
534 // one of the uses, and whether it dominates the load instruction.
535 for (auto *U : Addr->users()) {
536 // Avoid traversing for Load operand with high number of users.
537 if (++UsesVisited > MaxNumUsesTraversed)
538 return false;
539 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
540 // If there are escaping uses of invariant.start instruction, the load maybe
541 // non-invariant.
542 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000543 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000544 continue;
545 unsigned InvariantSizeInBits =
546 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
547 // Confirm the invariant.start location size contains the load operand size
548 // in bits. Also, the invariant.start should dominate the load, and we
549 // should not hoist the load out of a loop that contains this dominating
550 // invariant.start.
551 if (LocSizeInBits <= InvariantSizeInBits &&
552 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
553 return true;
554 }
555
556 return false;
557}
558
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000559bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
560 Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet81941b32017-01-11 04:39:45 +0000561 LoopSafetyInfo *SafetyInfo,
562 OptimizationRemarkEmitter *ORE) {
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000563 // SafetyInfo is nullptr if we are checking for sinking from preheader to
564 // loop body.
565 const bool SinkingToLoopBody = !SafetyInfo;
Chris Lattner65c11932003-12-09 19:32:44 +0000566 // Loads have extra constraints we have to verify before we can hoist them.
567 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000568 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000569 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000570
Chris Lattner8a8fb902008-07-23 05:06:28 +0000571 // Loads from constant memory are always safe to move, even if they end up
572 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000573 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000574 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000575 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000576 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000577
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000578 if (LI->isAtomic() && SinkingToLoopBody)
579 return false; // Don't sink unordered atomic loads to loop body.
580
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000581 // This checks for an invariant.start dominating the load.
582 if (isLoadInvariantInLoop(LI, DT, CurLoop))
583 return true;
584
Chris Lattner65c11932003-12-09 19:32:44 +0000585 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000586 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000587 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000588 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000589
590 AAMDNodes AAInfo;
591 LI->getAAMetadata(AAInfo);
592
Adam Nemet81941b32017-01-11 04:39:45 +0000593 bool Invalidated =
594 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
595 // Check loop-invariant address because this may also be a sinkable load
596 // whose address is not necessarily loop-invariant.
597 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +0000598 ORE->emit([&]() {
599 return OptimizationRemarkMissed(
600 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
601 << "failed to move load with loop-invariant address "
602 "because the loop may invalidate its value";
603 });
Adam Nemet81941b32017-01-11 04:39:45 +0000604
605 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000606 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000607 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000608 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000609 return false;
610
David Majnemer42a07302016-01-04 03:37:39 +0000611 // Don't sink calls which can throw.
612 if (CI->mayThrow())
613 return false;
614
Eli Friedman942e1c12011-05-27 18:37:52 +0000615 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000616 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
617 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000618 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000619 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000620 // A readonly argmemonly function only reads from memory pointed to by
621 // it's arguments with arbitrary offsets. If we can prove there are no
622 // writes to this memory in the loop, we can hoist or sink.
623 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
624 for (Value *Op : CI->arg_operands())
625 if (Op->getType()->isPointerTy() &&
626 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
627 AAMDNodes(), CurAST))
628 return false;
629 return true;
630 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000631 // If this call only reads from memory and there are no writes to memory
632 // in the loop, we can hoist or sink the call as appropriate.
633 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000634 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000635 if (!AS.isForwardingAliasSet() && AS.isMod()) {
636 FoundMod = true;
637 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000638 }
Chris Lattner20cda262004-03-15 04:11:30 +0000639 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000640 if (!FoundMod)
641 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000642 }
643
Nadav Rotem03dcd852012-09-04 10:25:04 +0000644 // FIXME: This should use mod/ref information to see if we can hoist or
645 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000646
Chris Lattner20cda262004-03-15 04:11:30 +0000647 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000648 }
649
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000650 // Only these instructions are hoistable/sinkable.
651 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
652 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
653 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
654 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
655 !isa<InsertValueInst>(I))
656 return false;
657
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000658 // If we are checking for sinking from preheader to loop body it will be
659 // always safe as there is no speculative execution.
660 if (SinkingToLoopBody)
Dehao Chen92abc7e2016-10-03 18:52:08 +0000661 return true;
662
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000663 // TODO: Plumb the context instruction through to make hoisting and sinking
664 // more powerful. Hoisting of loads already works due to the special casing
665 // above.
666 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000667}
668
Hal Finkel3d4269a2015-02-22 18:35:32 +0000669/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000670/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000671/// This is true when all incoming values are that instruction.
672/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000673///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000674static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000675 for (const Value *IncValue : PN.incoming_values())
676 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000677 return false;
678
679 return true;
680}
681
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000682/// Return true if the instruction is free in the loop.
683static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
684 const TargetTransformInfo *TTI) {
685
686 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
687 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
688 return false;
689 // For a GEP, we cannot simply use getUserCost because currently it
690 // optimistically assume that a GEP will fold into addressing mode
691 // regardless of its users.
692 const BasicBlock *BB = GEP->getParent();
693 for (const User *U : GEP->users()) {
694 const Instruction *UI = cast<Instruction>(U);
695 if (CurLoop->contains(UI) &&
696 (BB != UI->getParent() ||
697 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
698 return false;
699 }
700 return true;
701 } else
702 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
703}
704
Hal Finkel3d4269a2015-02-22 18:35:32 +0000705/// Return true if the only users of this instruction are outside of
706/// the loop. If this is true, we can sink the instruction to the exit
707/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000708///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000709/// We also return true if the instruction could be folded away in lowering.
710/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
711static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
712 const LoopSafetyInfo *SafetyInfo,
713 TargetTransformInfo *TTI, bool &FreeInLoop) {
David Majnemer42a07302016-01-04 03:37:39 +0000714 const auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000715 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
Pete Cooper0cabcf22015-05-13 01:12:18 +0000716 for (const User *U : I.users()) {
717 const Instruction *UI = cast<Instruction>(U);
718 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000719 const BasicBlock *BB = PN->getParent();
720 // We cannot sink uses in catchswitches.
721 if (isa<CatchSwitchInst>(BB->getTerminator()))
722 return false;
723
724 // We need to sink a callsite to a unique funclet. Avoid sinking if the
725 // phi use is too muddled.
726 if (isa<CallInst>(I))
727 if (!BlockColors.empty() &&
728 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
729 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000730 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000731
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000732 if (CurLoop->contains(UI)) {
733 if (IsFree) {
734 FreeInLoop = true;
735 continue;
736 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000737 return false;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000738 }
Chris Lattner34399dd2003-12-11 22:23:32 +0000739 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000740 return true;
741}
742
David Majnemer42a07302016-01-04 03:37:39 +0000743static Instruction *
744CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
745 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000746 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000747 Instruction *New;
748 if (auto *CI = dyn_cast<CallInst>(&I)) {
749 const auto &BlockColors = SafetyInfo->BlockColors;
750
751 // Sinking call-sites need to be handled differently from other
752 // instructions. The cloned call-site needs a funclet bundle operand
753 // appropriate for it's location in the CFG.
754 SmallVector<OperandBundleDef, 1> OpBundles;
755 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
756 BundleIdx != BundleEnd; ++BundleIdx) {
757 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
758 if (Bundle.getTagID() == LLVMContext::OB_funclet)
759 continue;
760
761 OpBundles.emplace_back(Bundle);
762 }
763
764 if (!BlockColors.empty()) {
765 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
766 assert(CV.size() == 1 && "non-unique color for exit block!");
767 BasicBlock *BBColor = CV.front();
768 Instruction *EHPad = BBColor->getFirstNonPHI();
769 if (EHPad->isEHPad())
770 OpBundles.emplace_back("funclet", EHPad);
771 }
772
773 New = CallInst::Create(CI, OpBundles);
774 } else {
775 New = I.clone();
776 }
777
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000778 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000779 if (!I.getName().empty())
780 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000781
782 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
783 // particularly cheap because we can rip off the PHI node that we're
784 // replacing for the number and blocks of the predecessors.
785 // OPT: If this shows up in a profile, we can instead finish sinking all
786 // invariant instructions, and then walk their operands to re-establish
787 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
788 // sinking bottom-up.
789 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
790 ++OI)
791 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
792 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
793 if (!OLoop->contains(&PN)) {
794 PHINode *OpPN =
795 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000796 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000797 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
798 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
799 *OI = OpPN;
800 }
801 return New;
802}
803
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000804static Instruction *sinkThroughTriviallyReplacablePHI(
805 PHINode *TPN, Instruction *I, LoopInfo *LI,
806 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
807 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
808 assert(isTriviallyReplacablePHI(*TPN, *I) &&
809 "Expect only trivially replacalbe PHI");
810 BasicBlock *ExitBlock = TPN->getParent();
811 Instruction *New;
812 auto It = SunkCopies.find(ExitBlock);
813 if (It != SunkCopies.end())
814 New = It->second;
815 else
816 New = SunkCopies[ExitBlock] =
817 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
818 return New;
819}
820
Jun Bum Lim144eb592018-02-12 17:56:55 +0000821static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000822 BasicBlock *BB = PN->getParent();
823 if (!BB->canSplitPredecessors())
824 return false;
Jun Bum Lim144eb592018-02-12 17:56:55 +0000825 // It's not impossible to split EHPad blocks, but if BlockColors already exist
826 // it require updating BlockColors for all offspring blocks accordingly. By
827 // skipping such corner case, we can make updating BlockColors after splitting
828 // predecessor fairly simple.
829 if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad())
830 return false;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000831 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
832 BasicBlock *BBPred = *PI;
833 if (isa<IndirectBrInst>(BBPred->getTerminator()))
834 return false;
835 }
836 return true;
837}
838
839static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000840 LoopInfo *LI, const Loop *CurLoop,
841 LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000842#ifndef NDEBUG
843 SmallVector<BasicBlock *, 32> ExitBlocks;
844 CurLoop->getUniqueExitBlocks(ExitBlocks);
845 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
846 ExitBlocks.end());
847#endif
848 BasicBlock *ExitBB = PN->getParent();
849 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
850
851 // Split predecessors of the loop exit to make instructions in the loop are
852 // exposed to exit blocks through trivially replacable PHIs while keeping the
853 // loop in the canonical form where each predecessor of each exit block should
854 // be contained within the loop. For example, this will convert the loop below
855 // from
856 //
857 // LB1:
858 // %v1 =
859 // br %LE, %LB2
860 // LB2:
861 // %v2 =
862 // br %LE, %LB1
863 // LE:
864 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replacable
865 //
866 // to
867 //
868 // LB1:
869 // %v1 =
870 // br %LE.split, %LB2
871 // LB2:
872 // %v2 =
873 // br %LE.split2, %LB1
874 // LE.split:
875 // %p1 = phi [%v1, %LB1] <-- trivially replacable
876 // br %LE
877 // LE.split2:
878 // %p2 = phi [%v2, %LB2] <-- trivially replacable
879 // br %LE
880 // LE:
881 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
882 //
Jun Bum Lim144eb592018-02-12 17:56:55 +0000883 auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000884 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
885 while (!PredBBs.empty()) {
886 BasicBlock *PredBB = *PredBBs.begin();
887 assert(CurLoop->contains(PredBB) &&
888 "Expect all predecessors are in the loop");
Jun Bum Lim144eb592018-02-12 17:56:55 +0000889 if (PN->getBasicBlockIndex(PredBB) >= 0) {
890 BasicBlock *NewPred = SplitBlockPredecessors(
891 ExitBB, PredBB, ".split.loop.exit", DT, LI, true);
892 // Since we do not allow splitting EH-block with BlockColors in
893 // canSplitPredecessors(), we can simply assign predecessor's color to
894 // the new block.
895 if (!BlockColors.empty())
896 BlockColors[NewPred] = BlockColors[PredBB];
897 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000898 PredBBs.remove(PredBB);
899 }
900}
901
Hal Finkel3d4269a2015-02-22 18:35:32 +0000902/// When an instruction is found to only be used outside of the loop, this
903/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000904/// This method is guaranteed to remove the original instruction from its
905/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000906///
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000907static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000908 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000909 OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000910 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000911 ORE->emit([&]() {
912 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
913 << "sinking " << ore::NV("Inst", &I);
914 });
Hal Finkel3d4269a2015-02-22 18:35:32 +0000915 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000916 if (isa<LoadInst>(I))
917 ++NumMovedLoads;
918 else if (isa<CallInst>(I))
919 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000920 ++NumSunk;
Chris Lattner55c21132003-12-10 20:43:29 +0000921
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000922 // Iterate over users to be ready for actual sinking. Replace users via
923 // unrechable blocks with undef and make all user PHIs trivially replcable.
924 SmallPtrSet<Instruction *, 8> VisitedUsers;
925 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
926 auto *User = cast<Instruction>(*UI);
927 Use &U = UI.getUse();
928 ++UI;
929
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000930 if (VisitedUsers.count(User) || CurLoop->contains(User))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000931 continue;
932
933 if (!DT->isReachableFromEntry(User->getParent())) {
Jun Bum Lim0f906722017-11-17 20:38:25 +0000934 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000935 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000936 continue;
937 }
938
939 // The user must be a PHI node.
940 PHINode *PN = cast<PHINode>(User);
941
942 // Surprisingly, instructions can be used outside of loops without any
943 // exits. This can only happen in PHI nodes if the incoming block is
944 // unreachable.
945 BasicBlock *BB = PN->getIncomingBlock(U);
946 if (!DT->isReachableFromEntry(BB)) {
947 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000948 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000949 continue;
950 }
951
952 VisitedUsers.insert(PN);
953 if (isTriviallyReplacablePHI(*PN, I))
954 continue;
955
Jun Bum Lim144eb592018-02-12 17:56:55 +0000956 if (!canSplitPredecessors(PN, SafetyInfo))
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000957 return Changed;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000958
959 // Split predecessors of the PHI so that we can make users trivially
960 // replacable.
Jun Bum Lim144eb592018-02-12 17:56:55 +0000961 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000962
963 // Should rebuild the iterators, as they may be invalidated by
964 // splitPredecessorsOfLoopExit().
965 UI = I.user_begin();
966 UE = I.user_end();
967 }
968
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000969 if (VisitedUsers.empty())
970 return Changed;
971
Chandler Carruthfc258542014-02-11 12:52:27 +0000972#ifndef NDEBUG
973 SmallVector<BasicBlock *, 32> ExitBlocks;
974 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000975 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000976 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000977#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000978
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000979 // Clones of this instruction. Don't create more than one per exit block!
980 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
981
Chandler Carruthfc258542014-02-11 12:52:27 +0000982 // If this instruction is only used outside of the loop, then all users are
983 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
984 // the instruction.
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000985 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
986 for (auto *UI : Users) {
987 auto *User = cast<Instruction>(UI);
988
989 if (CurLoop->contains(User))
990 continue;
991
992 PHINode *PN = cast<PHINode>(User);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000993 assert(ExitBlockSet.count(PN->getParent()) &&
Chandler Carruthfc258542014-02-11 12:52:27 +0000994 "The LCSSA PHI is not in an exit block!");
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000995 // The PHI must be trivially replacable.
996 Instruction *New = sinkThroughTriviallyReplacablePHI(PN, &I, LI, SunkCopies,
997 SafetyInfo, CurLoop);
Chandler Carruthfc258542014-02-11 12:52:27 +0000998 PN->replaceAllUsesWith(New);
999 PN->eraseFromParent();
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001000 Changed = true;
Chris Lattnercd96b4d2010-08-29 04:28:20 +00001001 }
Hal Finkel3d4269a2015-02-22 18:35:32 +00001002 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +00001003}
Chris Lattner64437692002-09-29 21:46:09 +00001004
Hal Finkel3d4269a2015-02-22 18:35:32 +00001005/// When an instruction is found to only use loop invariant operands that
1006/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +00001007///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001008static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +00001009 const LoopSafetyInfo *SafetyInfo,
1010 OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001011 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001012 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1013 << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001014 ORE->emit([&]() {
1015 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1016 << ore::NV("Inst", &I);
1017 });
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001018
1019 // Metadata can be dependent on conditions we are hoisting above.
1020 // Conservatively strip all metadata on the instruction unless we were
1021 // guaranteed to execute I if we entered the loop, in which case the metadata
1022 // is valid in the loop preheader.
1023 if (I.hasMetadataOtherThanDebugLoc() &&
1024 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1025 // time in isGuaranteedToExecute if we don't actually have anything to
1026 // drop. It is a compile time optimization, not required for correctness.
1027 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1028 I.dropUnknownNonDebugMetadata();
1029
Chris Lattner6ac06592010-08-29 18:18:40 +00001030 // Move the new node to the Preheader, before its terminator.
1031 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001032
Wolfgang Piebc17a2792017-01-06 18:38:57 +00001033 // Do not retain debug locations when we are moving instructions to different
1034 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1035 // need to retain their debug locs because they may be inlined.
1036 // FIXME: How do we retain source locations without causing poor debugging
1037 // behavior?
1038 if (!isa<CallInst>(I))
1039 I.setDebugLoc(DebugLoc());
1040
Dehao Chend55bc4c2016-05-05 00:54:54 +00001041 if (isa<LoadInst>(I))
1042 ++NumMovedLoads;
1043 else if (isa<CallInst>(I))
1044 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +00001045 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +00001046 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +00001047}
1048
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00001049/// Only sink or hoist an instruction if it is not a trapping instruction,
1050/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001051/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001052static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +00001053 const DominatorTree *DT,
1054 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001055 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001056 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +00001057 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +00001058 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +00001059 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001060
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001061 bool GuaranteedToExecute =
1062 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1063
1064 if (!GuaranteedToExecute) {
1065 auto *LI = dyn_cast<LoadInst>(&Inst);
1066 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +00001067 ORE->emit([&]() {
1068 return OptimizationRemarkMissed(
1069 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1070 << "failed to hoist load with loop-invariant address "
1071 "because load is conditionally executed";
1072 });
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001073 }
1074
1075 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001076}
1077
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001078namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +00001079class LoopPromoter : public LoadAndStorePromoter {
1080 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001081 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001082 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1083 SmallVectorImpl<Instruction *> &LoopInsertPts;
1084 PredIteratorCache &PredCache;
1085 AliasSetTracker &AST;
1086 LoopInfo &LI;
1087 DebugLoc DL;
1088 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001089 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001090 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +00001091
Dehao Chend55bc4c2016-05-05 00:54:54 +00001092 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1093 if (Instruction *I = dyn_cast<Instruction>(V))
1094 if (Loop *L = LI.getLoopFor(I->getParent()))
1095 if (!L->contains(BB)) {
1096 // We need to create an LCSSA PHI node for the incoming value and
1097 // store that.
1098 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1099 I->getName() + ".lcssa", &BB->front());
1100 for (BasicBlock *Pred : PredCache.get(BB))
1101 PN->addIncoming(I, Pred);
1102 return PN;
1103 }
1104 return V;
1105 }
Chandler Carruthfc258542014-02-11 12:52:27 +00001106
Dehao Chend55bc4c2016-05-05 00:54:54 +00001107public:
1108 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001109 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001110 SmallVectorImpl<BasicBlock *> &LEB,
1111 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1112 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001113 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +00001114 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1115 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001116 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001117 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +00001118
Dehao Chend55bc4c2016-05-05 00:54:54 +00001119 bool isInstInList(Instruction *I,
1120 const SmallVectorImpl<Instruction *> &) const override {
1121 Value *Ptr;
1122 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1123 Ptr = LI->getOperand(0);
1124 else
1125 Ptr = cast<StoreInst>(I)->getPointerOperand();
1126 return PointerMustAliases.count(Ptr);
1127 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001128
Dehao Chend55bc4c2016-05-05 00:54:54 +00001129 void doExtraRewritesBeforeFinalDeletion() const override {
1130 // Insert stores after in the loop exit blocks. Each exit block gets a
1131 // store of the live-out values that feed them. Since we've already told
1132 // the SSA updater about the defs in the loop and the preheader
1133 // definition, it is all set and we can start using it.
1134 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1135 BasicBlock *ExitBlock = LoopExitBlocks[i];
1136 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1137 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1138 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1139 Instruction *InsertPos = LoopInsertPts[i];
1140 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001141 if (UnorderedAtomic)
1142 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001143 NewSI->setAlignment(Alignment);
1144 NewSI->setDebugLoc(DL);
1145 if (AATags)
1146 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001147 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001148 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001149
Dehao Chend55bc4c2016-05-05 00:54:54 +00001150 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1151 // Update alias analysis.
1152 AST.copyValue(LI, V);
1153 }
1154 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1155};
Philip Reames21cc2fa2017-10-26 21:00:15 +00001156
1157
1158/// Return true iff we can prove that a caller of this function can not inspect
1159/// the contents of the provided object in a well defined program.
1160bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1161 if (isa<AllocaInst>(Object))
1162 // Since the alloca goes out of scope, we know the caller can't retain a
1163 // reference to it and be well defined. Thus, we don't need to check for
1164 // capture.
1165 return true;
1166
1167 // For all other objects we need to know that the caller can't possibly
1168 // have gotten a reference to the object. There are two components of
1169 // that:
1170 // 1) Object can't be escaped by this function. This is what
1171 // PointerMayBeCaptured checks.
1172 // 2) Object can't have been captured at definition site. For this, we
1173 // need to know the return value is noalias. At the moment, we use a
1174 // weaker condition and handle only AllocLikeFunctions (which are
1175 // known to be noalias). TODO
1176 return isAllocLikeFn(Object, TLI) &&
1177 !PointerMayBeCaptured(Object, true, true);
1178}
1179
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001180} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001181
Hal Finkel3d4269a2015-02-22 18:35:32 +00001182/// Try to promote memory values to scalars by sinking stores out of the
1183/// loop and moving loads to before the loop. We do this by looping over
1184/// the stores in the loop, looking for stores to Must pointers which are
1185/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001186///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001187bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001188 const SmallSetVector<Value *, 8> &PointerMustAliases,
1189 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001190 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1191 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001192 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1193 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001194 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001195 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1196 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001197 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001198
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001199 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001200 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001201
Anna Thomas5ac72f92018-03-13 19:38:45 +00001202 // It is not safe to promote a load/store from the loop if the load/store is
Chris Lattner1dc98b42010-08-29 06:43:52 +00001203 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001204 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001205 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001206 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001207 // into:
1208 //
1209 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1210 //
1211 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001212 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001213 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001214 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001215 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001216 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001217 // path which did not originally have one.
1218 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001219 // If at least one store is guaranteed to execute, both properties are
1220 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001221 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001222 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001223 // guaranteed to execute, we can still establish these properties.
1224 // We can establish (p1) by proving that hoisting the load into the preheader
1225 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001226 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001227 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001228 //
1229 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001230 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001231 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001232 // b) Prove a store dominates every exit block. In this case, if an exit
1233 // blocks is reached, the original dynamic path would have taken us through
1234 // the store, so inserting a store into the exit block is safe. Note that this
1235 // is different from the store being guaranteed to execute. For instance,
1236 // if an exception is thrown on the first iteration of the loop, the original
1237 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001238
1239 bool DereferenceableInPH = false;
1240 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001241
Dehao Chend55bc4c2016-05-05 00:54:54 +00001242 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001243
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001244 // We start with an alignment of one and try to find instructions that allow
1245 // us to prove better alignment.
1246 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001247 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001248 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001249 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001250 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001251
Philip Reamesb54c8e62016-03-09 22:59:30 +00001252 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1253
Philip Reames21cc2fa2017-10-26 21:00:15 +00001254 bool IsKnownThreadLocalObject = false;
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001255 if (SafetyInfo->MayThrow) {
Eli Friedmanee895052016-06-05 22:13:52 +00001256 // If a loop can throw, we have to insert a store along each unwind edge.
1257 // That said, we can't actually make the unwind edge explicit. Therefore,
Philip Reames21cc2fa2017-10-26 21:00:15 +00001258 // we have to prove that the store is dead along the unwind edge. We do
1259 // this by proving that the caller can't have a reference to the object
1260 // after return and thus can't possibly load from the object.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001261 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Philip Reames21cc2fa2017-10-26 21:00:15 +00001262 if (!isKnownNonEscaping(Object, TLI))
1263 return false;
1264 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1265 // visible to other threads if captured and used during their lifetimes.
1266 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
Eli Friedmanee895052016-06-05 22:13:52 +00001267 }
1268
Chris Lattner1dc98b42010-08-29 06:43:52 +00001269 // Check that all of the pointers in the alias set have the same type. We
1270 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001271 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001272 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001273 // Check that all of the pointers in the alias set have the same type. We
1274 // cannot (yet) promote a memory location that is loaded and stored in
1275 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001276 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001277 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001278
Chandler Carruthcdf47882014-03-09 03:16:01 +00001279 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001280 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001281 Instruction *UI = dyn_cast<Instruction>(U);
1282 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001283 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001284
Chris Lattner1dc98b42010-08-29 06:43:52 +00001285 // If there is an non-load/store instruction in the loop, we can't promote
1286 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001287 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Sanjay Patel9f49b682016-01-08 22:05:03 +00001288 assert(!Load->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001289 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001290 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001291
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001292 SawUnorderedAtomic |= Load->isAtomic();
1293 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001294
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001295 if (!DereferenceableInPH)
1296 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001297 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001298 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001299 // Stores *of* the pointer are not interesting, only stores *to* the
1300 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001301 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001302 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +00001303 assert(!Store->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001304 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001305 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001306
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001307 SawUnorderedAtomic |= Store->isAtomic();
1308 SawNotAtomic |= !Store->isAtomic();
1309
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001310 // If the store is guaranteed to execute, both properties are satisfied.
1311 // We may want to check if a store is guaranteed to execute even if we
1312 // already know that promotion is safe, since it may have higher
1313 // alignment than any other guaranteed stores, in which case we can
1314 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001315 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001316 if (!InstAlignment)
1317 InstAlignment =
1318 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1319
1320 if (!DereferenceableInPH || !SafeToInsertStore ||
1321 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001322 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001323 DereferenceableInPH = true;
1324 SafeToInsertStore = true;
1325 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001326 }
Anna Thomas67151352016-06-24 12:38:45 +00001327 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001328
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001329 // If a store dominates all exit blocks, it is safe to sink.
1330 // As explained above, if an exit block was executed, a dominating
1331 // store must have been been executed at least once, so we are not
1332 // introducing stores on paths that did not have them.
1333 // Note that this only looks at explicit exit blocks. If we ever
1334 // start sinking stores into unwind edges (see above), this will break.
1335 if (!SafeToInsertStore)
1336 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1337 return DT->dominates(Store->getParent(), Exit);
1338 });
1339
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001340 // If the store is not guaranteed to execute, we may still get
1341 // deref info through it.
1342 if (!DereferenceableInPH) {
1343 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001344 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001345 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001346 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001347 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001348 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001349
Hal Finkelcc39b672014-07-24 12:16:19 +00001350 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001351 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001352 // On the first load/store, just take its AA tags.
1353 UI->getAAMetadata(AATags);
1354 } else if (AATags) {
1355 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001356 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001357
1358 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001359 }
1360 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001361
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001362 // If we found both an unordered atomic instruction and a non-atomic memory
1363 // access, bail. We can't blindly promote non-atomic to atomic since we
1364 // might not be able to lower the result. We can't downgrade since that
1365 // would violate memory model. Also, align 0 is an error for atomics.
1366 if (SawUnorderedAtomic && SawNotAtomic)
1367 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001368
1369 // If we couldn't prove we can hoist the load, bail.
1370 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001371 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001372
1373 // We know we can hoist the load, but don't have a guaranteed store.
1374 // Check whether the location is thread-local. If it is, then we can insert
1375 // stores along paths which originally didn't have them without violating the
1376 // memory model.
1377 if (!SafeToInsertStore) {
Philip Reames21cc2fa2017-10-26 21:00:15 +00001378 if (IsKnownThreadLocalObject)
Xin Tong5ee40ba2017-01-19 19:31:40 +00001379 SafeToInsertStore = true;
1380 else {
1381 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1382 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001383 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1384 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001385 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001386 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001387
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001388 // If we've still failed to prove we can sink the store, give up.
1389 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001390 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001391
Chris Lattner1dc98b42010-08-29 06:43:52 +00001392 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001393 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1394 << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +00001395 ORE->emit([&]() {
1396 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1397 LoopUses[0])
1398 << "Moving accesses to memory location out of the loop";
1399 });
Chris Lattner1dc98b42010-08-29 06:43:52 +00001400 ++NumPromoted;
1401
Eli Friedmanddf7f552011-05-27 20:31:51 +00001402 // Grab a debug location for the inserted loads/stores; given that the
1403 // inserted loads/stores have little relation to the original loads/stores,
1404 // this code just arbitrarily picks a location from one, since any debug
1405 // location is better than none.
1406 DebugLoc DL = LoopUses[0]->getDebugLoc();
1407
Chris Lattner1dc98b42010-08-29 06:43:52 +00001408 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001409 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001410 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001411 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001412 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1413 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001414
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001415 // Set up the preheader to have a definition of the value. It is the live-out
1416 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001417 LoadInst *PreheaderLoad = new LoadInst(
1418 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001419 if (SawUnorderedAtomic)
1420 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001421 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001422 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001423 if (AATags)
1424 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001425 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1426
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001427 // Rewrite all the loads in the loop and remember all the definitions from
1428 // stores in the loop.
1429 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001430
1431 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1432 if (PreheaderLoad->use_empty())
1433 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001434
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001435 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001436}
Devang Patelb98a0972007-07-31 08:01:41 +00001437
Roman Gareev036c0882016-02-15 14:48:50 +00001438/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001439/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001440/// FIXME: In new pass manager, there is no helper function to handle loop
1441/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001442/// from scratch for every loop. Hook up with the helper functions when
1443/// available in the new pass manager to avoid redundant computation.
1444AliasSetTracker *
1445LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1446 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001447 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001448 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001449 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001450 auto MapI = LoopToAliasSetMap.find(InnerL);
1451 // If the AST for this inner loop is missing it may have been merged into
1452 // some other loop's AST and then that loop unrolled, and so we need to
1453 // recompute it.
1454 if (MapI == LoopToAliasSetMap.end()) {
1455 RecomputeLoops.push_back(InnerL);
1456 continue;
1457 }
1458 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001459
1460 if (CurAST != nullptr) {
1461 // What if InnerLoop was modified by other passes ?
1462 CurAST->add(*InnerAST);
1463
1464 // Once we've incorporated the inner loop's AST into ours, we don't need
1465 // the subloop's anymore.
1466 delete InnerAST;
1467 } else {
1468 CurAST = InnerAST;
1469 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001470 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001471 }
1472 if (CurAST == nullptr)
1473 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001474
1475 auto mergeLoop = [&](Loop *L) {
1476 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chandler Carruthad8cb382016-02-27 04:34:07 +00001477 for (BasicBlock *BB : L->blocks())
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001478 CurAST->add(*BB); // Incorporate the specified basic block
Chandler Carruthad8cb382016-02-27 04:34:07 +00001479 };
1480
1481 // Add everything from the sub loops that are no longer directly available.
1482 for (Loop *InnerL : RecomputeLoops)
1483 mergeLoop(InnerL);
1484
1485 // And merge in this loop.
1486 mergeLoop(L);
1487
Roman Gareev036c0882016-02-15 14:48:50 +00001488 return CurAST;
1489}
1490
Ashutosh Nema47802622015-08-13 11:18:35 +00001491/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001492///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001493void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1494 Loop *L) {
1495 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001496 if (!AST)
1497 return;
1498
1499 AST->copyValue(From, To);
1500}
1501
Hal Finkel3d4269a2015-02-22 18:35:32 +00001502/// Simple Analysis hook. Delete value V from alias set
1503///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001504void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1505 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001506 if (!AST)
1507 return;
1508
1509 AST->deleteValue(V);
1510}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001511
1512/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001513///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001514void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1515 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001516 if (!AST)
1517 return;
1518
1519 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001520 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001521}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001522
Hal Finkel3d4269a2015-02-22 18:35:32 +00001523/// Return true if the body of this loop may store into the memory
1524/// location pointed to by V.
1525///
1526static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001527 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001528 AliasSetTracker *CurAST) {
1529 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1530 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1531}
1532
1533/// Little predicate that returns true if the specified basic block is in
1534/// a subloop of the current one, not the current one itself.
1535///
1536static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1537 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1538 return LI->getLoopFor(BB) != CurLoop;
1539}