blob: 1cbe3ef10a09baea9a0bf44e1513590340f97673 [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"
David Blaikie31b98d22018-06-04 21:23:21 +000050#include "llvm/Transforms/Utils/Local.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000051#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000052#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Instructions.h"
58#include "llvm/IR/IntrinsicInst.h"
59#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000060#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000061#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000062#include "llvm/Support/CommandLine.h"
63#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000064#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000065#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000066#include "llvm/Transforms/Scalar/LoopPassManager.h"
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000067#include "llvm/Transforms/Utils/BasicBlockUtils.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 {
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000173 AU.addPreserved<DominatorTreeWrapperPass>();
174 AU.addPreserved<LoopInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000175 AU.addRequired<TargetLibraryInfoWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000176 if (EnableMSSALoopDependency)
177 AU.addRequired<MemorySSAWrapperPass>();
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000178 AU.addRequired<TargetTransformInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000179 getLoopAnalysisUsage(AU);
180 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000181
Dehao Chend55bc4c2016-05-05 00:54:54 +0000182 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000183
Dehao Chend55bc4c2016-05-05 00:54:54 +0000184 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000185 assert(LICM.getLoopToAliasSetMap().empty() &&
186 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000187 return false;
188 }
Devang Patel69730c92007-03-07 04:41:30 +0000189
Dehao Chend55bc4c2016-05-05 00:54:54 +0000190private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000191 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000192
Dehao Chend55bc4c2016-05-05 00:54:54 +0000193 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
194 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
195 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000196
Dehao Chend55bc4c2016-05-05 00:54:54 +0000197 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
198 /// set.
199 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000200
Dehao Chend55bc4c2016-05-05 00:54:54 +0000201 /// Simple Analysis hook. Delete loop L from alias set map.
202 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000203};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000204} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000205
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000206PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
207 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000208 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000209 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000210 Function *F = L.getHeader()->getParent();
211
Adam Nemet358433c2017-01-11 04:39:35 +0000212 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000213 // FIXME: This should probably be optional rather than required.
214 if (!ORE)
215 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
216 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000217
218 LoopInvariantCodeMotion LICM;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000219 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
220 AR.MSSA, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000221 return PreservedAnalyses::all();
222
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000223 auto PA = getLoopPassPreservedAnalyses();
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000224
225 PA.preserve<DominatorTreeAnalysis>();
226 PA.preserve<LoopAnalysis>();
227
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000228 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000229}
230
231char LegacyLICMPass::ID = 0;
232INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
233 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000234INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000235INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000236INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000237INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000238INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
239 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000240
Dehao Chen9cba1f42016-07-12 22:37:48 +0000241Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000242
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000243/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000244/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000245/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000246/// We should delete AST for inner loops in the new pass manager to avoid
247/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000248///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000249bool LoopInvariantCodeMotion::runOnLoop(
250 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
251 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
252 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000253 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000254
Chandler Carruthfc258542014-02-11 12:52:27 +0000255 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
256
Dehao Chen9cba1f42016-07-12 22:37:48 +0000257 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000258
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000259 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000260 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000261
Hal Finkel3d4269a2015-02-22 18:35:32 +0000262 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000263 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000264 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000265
Chris Lattner6ec05f52002-05-10 22:44:58 +0000266 // We want to visit all of the instructions in this loop... that are not parts
267 // of our subloops (they have already had their invariants hoisted out of
268 // their loop, into this loop, so there is no need to process the BODIES of
269 // the subloops).
270 //
Chris Lattner64437692002-09-29 21:46:09 +0000271 // Traverse the body of the loop in depth first order on the dominator tree so
272 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000273 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000274 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000275 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000276 if (L->hasDedicatedExits())
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000277 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000278 CurAST, &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000279 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000280 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000281 CurAST, &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000282
Chris Lattner45d67d62003-02-24 03:52:32 +0000283 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000284 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000285 // Don't sink stores from loops without dedicated block exits. Exits
286 // containing indirect branches are not transformed by loop simplify,
287 // make sure we catch that. An additional load may be generated in the
288 // preheader for SSA updater, so also avoid sinking when no preheader
289 // is available.
290 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000291 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000292 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000293 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000294
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000295 // We can't insert into a catchswitch.
296 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
297 return isa<CatchSwitchInst>(Exit->getTerminator());
298 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000299
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000300 if (!HasCatchSwitch) {
301 SmallVector<Instruction *, 8> InsertPts;
302 InsertPts.reserve(ExitBlocks.size());
303 for (BasicBlock *ExitBlock : ExitBlocks)
304 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000305
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000306 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000307
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000308 bool Promoted = false;
309
310 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000311 for (AliasSet &AS : *CurAST) {
312 // We can promote this alias set if it has a store, if it is a "Must"
313 // alias set, if the pointer is loop invariant, and if we are not
314 // eliminating any volatile loads or stores.
315 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
316 AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
317 continue;
318
319 assert(
320 !AS.empty() &&
321 "Must alias set should have at least one pointer element in it!");
322
323 SmallSetVector<Value *, 8> PointerMustAliases;
324 for (const auto &ASI : AS)
325 PointerMustAliases.insert(ASI.getValue());
326
327 Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
328 InsertPts, PIC, LI, DT, TLI, L,
329 CurAST, &SafetyInfo, ORE);
330 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000331
332 // Once we have promoted values across the loop body we have to
333 // recursively reform LCSSA as any nested loop may now have values defined
334 // within the loop used in the outer loop.
335 // FIXME: This is really heavy handed. It would be a bit better to use an
336 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
337 // it as it went.
338 if (Promoted)
339 formLCSSARecursively(*L, *DT, LI, SE);
340
341 Changed |= Promoted;
342 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000343 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000344
Chandler Carruthfc258542014-02-11 12:52:27 +0000345 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
346 // specifically moving instructions across the loop boundary and so it is
347 // especially in need of sanity checking here.
348 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
349 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
350 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000351
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000352 // If this loop is nested inside of another one, save the alias information
353 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000354 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000355 LoopToAliasSetMap[L] = CurAST;
356 else
357 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000358
Dehao Chen9cba1f42016-07-12 22:37:48 +0000359 if (Changed && SE)
360 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000361 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000362}
363
Hal Finkel3d4269a2015-02-22 18:35:32 +0000364/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000365/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000366/// first order w.r.t the DominatorTree. This allows us to visit uses before
367/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000368///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000369bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000370 DominatorTree *DT, TargetLibraryInfo *TLI,
371 TargetTransformInfo *TTI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000372 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
373 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000374
Hal Finkel3d4269a2015-02-22 18:35:32 +0000375 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000376 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
377 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
378 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000379
David Majnemere6bb8952017-07-20 03:27:02 +0000380 // We want to visit children before parents. We will enque all the parents
381 // before their children in the worklist and process the worklist in reverse
382 // order.
383 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000384
Sanjay Patel99133222016-01-13 23:01:57 +0000385 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000386 for (DomTreeNode *DTN : reverse(Worklist)) {
387 BasicBlock *BB = DTN->getBlock();
388 // Only need to process the contents of this block if it is not part of a
389 // subloop (which would already have been processed).
390 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000391 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000392
David Majnemere6bb8952017-07-20 03:27:02 +0000393 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
394 Instruction &I = *--II;
395
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000396 // If the instruction is dead, we would try to sink it because it isn't
397 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000398 if (isInstructionTriviallyDead(&I, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Anastasis Grammenos3a589102018-03-18 15:59:19 +0000400 salvageDebugInfo(I);
David Majnemere6bb8952017-07-20 03:27:02 +0000401 ++II;
402 CurAST->deleteValue(&I);
403 I.eraseFromParent();
404 Changed = true;
405 continue;
406 }
407
408 // Check to see if we can sink this instruction to the exit blocks
409 // of the loop. We can do this if the all users of the instruction are
410 // outside of the loop. In this case, it doesn't even matter if the
411 // operands of the instruction are loop invariant.
412 //
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000413 bool FreeInLoop = false;
414 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
Philip Reames59373682018-08-03 00:21:56 +0000415 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE)) {
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000416 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
417 if (!FreeInLoop) {
418 ++II;
419 CurAST->deleteValue(&I);
420 I.eraseFromParent();
421 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000422 Changed = true;
423 }
David Majnemere6bb8952017-07-20 03:27:02 +0000424 }
Chris Lattner91846012003-12-19 08:18:16 +0000425 }
Chris Lattner547192d62003-12-19 07:22:45 +0000426 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000427 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000428}
429
Hal Finkel3d4269a2015-02-22 18:35:32 +0000430/// Walk the specified region of the CFG (defined by all blocks dominated by
431/// the specified block, and that are in the current loop) in depth first
432/// order w.r.t the DominatorTree. This allows us to visit definitions before
433/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000434///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000435bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
436 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000437 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
438 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000439 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000440 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
441 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
442 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000443
David Majnemere6bb8952017-07-20 03:27:02 +0000444 // We want to visit parents before children. We will enque all the parents
445 // before their children in the worklist and process the worklist in order.
446 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000447
Sanjay Patel99133222016-01-13 23:01:57 +0000448 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000449 for (DomTreeNode *DTN : Worklist) {
450 BasicBlock *BB = DTN->getBlock();
451 // Only need to process the contents of this block if it is not part of a
452 // subloop (which would already have been processed).
Philip Reames5a648242018-04-27 20:58:30 +0000453 if (inSubLoop(BB, CurLoop, LI))
454 continue;
David Majnemere6bb8952017-07-20 03:27:02 +0000455
Philip Reames5b39acd2018-05-04 21:35:00 +0000456 // Keep track of whether the prefix of instructions visited so far are such
457 // that the next instruction visited is guaranteed to execute if the loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000458 // is entered.
Philip Reames5b39acd2018-05-04 21:35:00 +0000459 bool IsMustExecute = CurLoop->getHeader() == BB;
460
Philip Reames5a648242018-04-27 20:58:30 +0000461 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
462 Instruction &I = *II++;
463 // Try constant folding this instruction. If all the operands are
464 // constants, it is technically hoistable, but it would be better to
465 // just fold it.
466 if (Constant *C = ConstantFoldInstruction(
467 &I, I.getModule()->getDataLayout(), TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C
469 << '\n');
Philip Reames5a648242018-04-27 20:58:30 +0000470 CurAST->copyValue(&I, C);
471 I.replaceAllUsesWith(C);
472 if (isInstructionTriviallyDead(&I, TLI)) {
473 CurAST->deleteValue(&I);
David Majnemere6bb8952017-07-20 03:27:02 +0000474 I.eraseFromParent();
David Majnemere6bb8952017-07-20 03:27:02 +0000475 }
Philip Reames5a648242018-04-27 20:58:30 +0000476 Changed = true;
477 continue;
Chris Lattner030f0202010-08-31 23:00:16 +0000478 }
Philip Reames5a648242018-04-27 20:58:30 +0000479
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000480 // Try hoisting the instruction out to the preheader. We can only do
481 // this if all of the operands of the instruction are loop invariant and
482 // if it is safe to hoist the instruction.
483 //
484 if (CurLoop->hasLoopInvariantOperands(&I) &&
Philip Reames32cb80b2018-08-02 04:08:04 +0000485 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000486 (IsMustExecute ||
487 isSafeToExecuteUnconditionally(
488 I, DT, CurLoop, SafetyInfo, ORE,
489 CurLoop->getLoopPreheader()->getTerminator()))) {
490 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
491 continue;
492 }
493
Philip Reames5a648242018-04-27 20:58:30 +0000494 // Attempt to remove floating point division out of the loop by
495 // converting it to a reciprocal multiplication.
496 if (I.getOpcode() == Instruction::FDiv &&
497 CurLoop->isLoopInvariant(I.getOperand(1)) &&
498 I.hasAllowReciprocal()) {
499 auto Divisor = I.getOperand(1);
500 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
501 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
502 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
503 ReciprocalDivisor->insertBefore(&I);
504
505 auto Product =
506 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
507 Product->setFastMathFlags(I.getFastMathFlags());
508 Product->insertAfter(&I);
509 I.replaceAllUsesWith(Product);
510 I.eraseFromParent();
511
512 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
513 Changed = true;
514 continue;
515 }
516
Philip Reames5b39acd2018-05-04 21:35:00 +0000517 if (IsMustExecute)
518 IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I);
Philip Reames5a648242018-04-27 20:58:30 +0000519 }
David Majnemere6bb8952017-07-20 03:27:02 +0000520 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000521
Hal Finkel3d4269a2015-02-22 18:35:32 +0000522 return Changed;
523}
524
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000525// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000526// CurLoop is dominated by an invariant.start representing the same memory
527// location and size as the memory location LI loads from, and also the
528// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000529static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
530 Loop *CurLoop) {
531 Value *Addr = LI->getOperand(0);
532 const DataLayout &DL = LI->getModule()->getDataLayout();
533 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
534 cast<PointerType>(Addr->getType())->getElementType());
535
536 // if the type is i8 addrspace(x)*, we know this is the type of
537 // llvm.invariant.start operand
538 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
539 LI->getPointerAddressSpace());
540 unsigned BitcastsVisited = 0;
541 // Look through bitcasts until we reach the i8* type (this is invariant.start
542 // operand type).
543 while (Addr->getType() != PtrInt8Ty) {
544 auto *BC = dyn_cast<BitCastInst>(Addr);
545 // Avoid traversing high number of bitcast uses.
546 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
547 return false;
548 Addr = BC->getOperand(0);
549 }
550
551 unsigned UsesVisited = 0;
552 // Traverse all uses of the load operand value, to see if invariant.start is
553 // one of the uses, and whether it dominates the load instruction.
554 for (auto *U : Addr->users()) {
555 // Avoid traversing for Load operand with high number of users.
556 if (++UsesVisited > MaxNumUsesTraversed)
557 return false;
558 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
559 // If there are escaping uses of invariant.start instruction, the load maybe
560 // non-invariant.
561 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000562 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000563 continue;
564 unsigned InvariantSizeInBits =
565 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
566 // Confirm the invariant.start location size contains the load operand size
567 // in bits. Also, the invariant.start should dominate the load, and we
568 // should not hoist the load out of a loop that contains this dominating
569 // invariant.start.
570 if (LocSizeInBits <= InvariantSizeInBits &&
571 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
572 return true;
573 }
574
575 return false;
576}
577
Philip Reames09de4702018-08-02 00:54:14 +0000578namespace {
579/// Return true if-and-only-if we know how to (mechanically) both hoist and
580/// sink a given instruction out of a loop. Does not address legality
581/// concerns such as aliasing or speculation safety.
582bool isHoistableAndSinkableInst(Instruction &I) {
583 // Only these instructions are hoistable/sinkable.
584 return (isa<LoadInst>(I) || isa<CallInst>(I) ||
585 isa<BinaryOperator>(I) || isa<CastInst>(I) ||
586 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) ||
587 isa<CmpInst>(I) || isa<InsertElementInst>(I) ||
588 isa<ExtractElementInst>(I) || isa<ShuffleVectorInst>(I) ||
589 isa<ExtractValueInst>(I) || isa<InsertValueInst>(I));
590}
Philip Reames3b35aaa2018-08-06 22:07:37 +0000591/// Return true if all of the alias sets within this AST are known not to
592/// contain a Mod.
593bool isReadOnly(AliasSetTracker *CurAST) {
594 for (AliasSet &AS : *CurAST) {
595 if (!AS.isForwardingAliasSet() && AS.isMod()) {
596 return false;
597 }
598 }
599 return true;
600}
Philip Reames09de4702018-08-02 00:54:14 +0000601}
602
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000603bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
604 Loop *CurLoop, AliasSetTracker *CurAST,
Philip Reames32cb80b2018-08-02 04:08:04 +0000605 bool TargetExecutesOncePerLoop,
Adam Nemet81941b32017-01-11 04:39:45 +0000606 OptimizationRemarkEmitter *ORE) {
Philip Reames09de4702018-08-02 00:54:14 +0000607 // If we don't understand the instruction, bail early.
608 if (!isHoistableAndSinkableInst(I))
609 return false;
610
Chris Lattner65c11932003-12-09 19:32:44 +0000611 // Loads have extra constraints we have to verify before we can hoist them.
612 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000613 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000614 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000615
Chris Lattner8a8fb902008-07-23 05:06:28 +0000616 // Loads from constant memory are always safe to move, even if they end up
617 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000618 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000619 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000620 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000621 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000622
Philip Reames32cb80b2018-08-02 04:08:04 +0000623 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
624 return false; // Don't risk duplicating unordered loads
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000625
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000626 // This checks for an invariant.start dominating the load.
627 if (isLoadInvariantInLoop(LI, DT, CurLoop))
628 return true;
629
Chris Lattner65c11932003-12-09 19:32:44 +0000630 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000631 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000632 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000633 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000634
635 AAMDNodes AAInfo;
636 LI->getAAMetadata(AAInfo);
637
Adam Nemet81941b32017-01-11 04:39:45 +0000638 bool Invalidated =
639 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
640 // Check loop-invariant address because this may also be a sinkable load
641 // whose address is not necessarily loop-invariant.
642 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +0000643 ORE->emit([&]() {
644 return OptimizationRemarkMissed(
645 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
646 << "failed to move load with loop-invariant address "
647 "because the loop may invalidate its value";
648 });
Adam Nemet81941b32017-01-11 04:39:45 +0000649
650 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000651 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000652 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000653 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000654 return false;
655
David Majnemer42a07302016-01-04 03:37:39 +0000656 // Don't sink calls which can throw.
657 if (CI->mayThrow())
658 return false;
659
Eli Friedman942e1c12011-05-27 18:37:52 +0000660 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000661 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
662 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000663 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000664 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000665 // A readonly argmemonly function only reads from memory pointed to by
666 // it's arguments with arbitrary offsets. If we can prove there are no
667 // writes to this memory in the loop, we can hoist or sink.
668 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
669 for (Value *Op : CI->arg_operands())
670 if (Op->getType()->isPointerTy() &&
671 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
672 AAMDNodes(), CurAST))
673 return false;
674 return true;
675 }
Philip Reames3b35aaa2018-08-06 22:07:37 +0000676
Duncan Sands68b6f502007-12-01 07:51:45 +0000677 // If this call only reads from memory and there are no writes to memory
678 // in the loop, we can hoist or sink the call as appropriate.
Philip Reames3b35aaa2018-08-06 22:07:37 +0000679 if (isReadOnly(CurAST))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000680 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000681 }
682
Nadav Rotem03dcd852012-09-04 10:25:04 +0000683 // FIXME: This should use mod/ref information to see if we can hoist or
684 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000685
Chris Lattner20cda262004-03-15 04:11:30 +0000686 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000687 }
688
Philip Reames32cb80b2018-08-02 04:08:04 +0000689 // We've established mechanical ability and aliasing, it's up to the caller
690 // to check fault safety
691 return true;
Chris Lattneraaaea512003-12-10 06:41:05 +0000692}
693
Hal Finkel3d4269a2015-02-22 18:35:32 +0000694/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000695/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000696/// This is true when all incoming values are that instruction.
697/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000698///
Alina Sbirlea0e155012018-07-02 18:53:40 +0000699static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000700 for (const Value *IncValue : PN.incoming_values())
701 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000702 return false;
703
704 return true;
705}
706
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000707/// Return true if the instruction is free in the loop.
708static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
709 const TargetTransformInfo *TTI) {
710
711 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
712 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
713 return false;
714 // For a GEP, we cannot simply use getUserCost because currently it
715 // optimistically assume that a GEP will fold into addressing mode
716 // regardless of its users.
717 const BasicBlock *BB = GEP->getParent();
718 for (const User *U : GEP->users()) {
719 const Instruction *UI = cast<Instruction>(U);
720 if (CurLoop->contains(UI) &&
721 (BB != UI->getParent() ||
722 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
723 return false;
724 }
725 return true;
726 } else
727 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
728}
729
Hal Finkel3d4269a2015-02-22 18:35:32 +0000730/// Return true if the only users of this instruction are outside of
731/// the loop. If this is true, we can sink the instruction to the exit
732/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000733///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000734/// We also return true if the instruction could be folded away in lowering.
735/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
736static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
737 const LoopSafetyInfo *SafetyInfo,
738 TargetTransformInfo *TTI, bool &FreeInLoop) {
David Majnemer42a07302016-01-04 03:37:39 +0000739 const auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000740 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
Pete Cooper0cabcf22015-05-13 01:12:18 +0000741 for (const User *U : I.users()) {
742 const Instruction *UI = cast<Instruction>(U);
743 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000744 const BasicBlock *BB = PN->getParent();
745 // We cannot sink uses in catchswitches.
746 if (isa<CatchSwitchInst>(BB->getTerminator()))
747 return false;
748
749 // We need to sink a callsite to a unique funclet. Avoid sinking if the
750 // phi use is too muddled.
751 if (isa<CallInst>(I))
752 if (!BlockColors.empty() &&
753 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
754 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000755 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000756
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000757 if (CurLoop->contains(UI)) {
758 if (IsFree) {
759 FreeInLoop = true;
760 continue;
761 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000762 return false;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000763 }
Chris Lattner34399dd2003-12-11 22:23:32 +0000764 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000765 return true;
766}
767
David Majnemer42a07302016-01-04 03:37:39 +0000768static Instruction *
769CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
770 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000771 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000772 Instruction *New;
773 if (auto *CI = dyn_cast<CallInst>(&I)) {
774 const auto &BlockColors = SafetyInfo->BlockColors;
775
776 // Sinking call-sites need to be handled differently from other
777 // instructions. The cloned call-site needs a funclet bundle operand
778 // appropriate for it's location in the CFG.
779 SmallVector<OperandBundleDef, 1> OpBundles;
780 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
781 BundleIdx != BundleEnd; ++BundleIdx) {
782 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
783 if (Bundle.getTagID() == LLVMContext::OB_funclet)
784 continue;
785
786 OpBundles.emplace_back(Bundle);
787 }
788
789 if (!BlockColors.empty()) {
790 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
791 assert(CV.size() == 1 && "non-unique color for exit block!");
792 BasicBlock *BBColor = CV.front();
793 Instruction *EHPad = BBColor->getFirstNonPHI();
794 if (EHPad->isEHPad())
795 OpBundles.emplace_back("funclet", EHPad);
796 }
797
798 New = CallInst::Create(CI, OpBundles);
799 } else {
800 New = I.clone();
801 }
802
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000803 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000804 if (!I.getName().empty())
805 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000806
807 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
808 // particularly cheap because we can rip off the PHI node that we're
809 // replacing for the number and blocks of the predecessors.
810 // OPT: If this shows up in a profile, we can instead finish sinking all
811 // invariant instructions, and then walk their operands to re-establish
812 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
813 // sinking bottom-up.
814 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
815 ++OI)
816 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
817 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
818 if (!OLoop->contains(&PN)) {
819 PHINode *OpPN =
820 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000821 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000822 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
823 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
824 *OI = OpPN;
825 }
826 return New;
827}
828
Alina Sbirlea0e155012018-07-02 18:53:40 +0000829static Instruction *sinkThroughTriviallyReplaceablePHI(
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000830 PHINode *TPN, Instruction *I, LoopInfo *LI,
831 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
832 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
Alina Sbirlea0e155012018-07-02 18:53:40 +0000833 assert(isTriviallyReplaceablePHI(*TPN, *I) &&
834 "Expect only trivially replaceable PHI");
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000835 BasicBlock *ExitBlock = TPN->getParent();
836 Instruction *New;
837 auto It = SunkCopies.find(ExitBlock);
838 if (It != SunkCopies.end())
839 New = It->second;
840 else
841 New = SunkCopies[ExitBlock] =
842 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
843 return New;
844}
845
Jun Bum Lim144eb592018-02-12 17:56:55 +0000846static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000847 BasicBlock *BB = PN->getParent();
848 if (!BB->canSplitPredecessors())
849 return false;
Jun Bum Lim144eb592018-02-12 17:56:55 +0000850 // It's not impossible to split EHPad blocks, but if BlockColors already exist
851 // it require updating BlockColors for all offspring blocks accordingly. By
852 // skipping such corner case, we can make updating BlockColors after splitting
853 // predecessor fairly simple.
854 if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad())
855 return false;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000856 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
857 BasicBlock *BBPred = *PI;
858 if (isa<IndirectBrInst>(BBPred->getTerminator()))
859 return false;
860 }
861 return true;
862}
863
864static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000865 LoopInfo *LI, const Loop *CurLoop,
866 LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000867#ifndef NDEBUG
868 SmallVector<BasicBlock *, 32> ExitBlocks;
869 CurLoop->getUniqueExitBlocks(ExitBlocks);
870 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
871 ExitBlocks.end());
872#endif
873 BasicBlock *ExitBB = PN->getParent();
874 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
875
876 // Split predecessors of the loop exit to make instructions in the loop are
Alina Sbirlea0e155012018-07-02 18:53:40 +0000877 // exposed to exit blocks through trivially replaceable PHIs while keeping the
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000878 // loop in the canonical form where each predecessor of each exit block should
879 // be contained within the loop. For example, this will convert the loop below
880 // from
881 //
882 // LB1:
883 // %v1 =
884 // br %LE, %LB2
885 // LB2:
886 // %v2 =
887 // br %LE, %LB1
888 // LE:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000889 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000890 //
891 // to
892 //
893 // LB1:
894 // %v1 =
895 // br %LE.split, %LB2
896 // LB2:
897 // %v2 =
898 // br %LE.split2, %LB1
899 // LE.split:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000900 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000901 // br %LE
902 // LE.split2:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000903 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000904 // br %LE
905 // LE:
906 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
907 //
Jun Bum Lim144eb592018-02-12 17:56:55 +0000908 auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000909 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
910 while (!PredBBs.empty()) {
911 BasicBlock *PredBB = *PredBBs.begin();
912 assert(CurLoop->contains(PredBB) &&
913 "Expect all predecessors are in the loop");
Jun Bum Lim144eb592018-02-12 17:56:55 +0000914 if (PN->getBasicBlockIndex(PredBB) >= 0) {
915 BasicBlock *NewPred = SplitBlockPredecessors(
916 ExitBB, PredBB, ".split.loop.exit", DT, LI, true);
917 // Since we do not allow splitting EH-block with BlockColors in
918 // canSplitPredecessors(), we can simply assign predecessor's color to
919 // the new block.
Andrew Kaylora2378662018-03-23 17:36:18 +0000920 if (!BlockColors.empty()) {
921 // Grab a reference to the ColorVector to be inserted before getting the
922 // reference to the vector we are copying because inserting the new
923 // element in BlockColors might cause the map to be reallocated.
924 ColorVector &ColorsForNewBlock = BlockColors[NewPred];
925 ColorVector &ColorsForOldBlock = BlockColors[PredBB];
926 ColorsForNewBlock = ColorsForOldBlock;
927 }
Jun Bum Lim144eb592018-02-12 17:56:55 +0000928 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000929 PredBBs.remove(PredBB);
930 }
931}
932
Hal Finkel3d4269a2015-02-22 18:35:32 +0000933/// When an instruction is found to only be used outside of the loop, this
934/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000935/// This method is guaranteed to remove the original instruction from its
936/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000937///
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000938static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000939 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000940 OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000941 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000942 ORE->emit([&]() {
943 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
944 << "sinking " << ore::NV("Inst", &I);
945 });
Hal Finkel3d4269a2015-02-22 18:35:32 +0000946 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000947 if (isa<LoadInst>(I))
948 ++NumMovedLoads;
949 else if (isa<CallInst>(I))
950 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000951 ++NumSunk;
Chris Lattner55c21132003-12-10 20:43:29 +0000952
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000953 // Iterate over users to be ready for actual sinking. Replace users via
954 // unrechable blocks with undef and make all user PHIs trivially replcable.
955 SmallPtrSet<Instruction *, 8> VisitedUsers;
956 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
957 auto *User = cast<Instruction>(*UI);
958 Use &U = UI.getUse();
959 ++UI;
960
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000961 if (VisitedUsers.count(User) || CurLoop->contains(User))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000962 continue;
963
964 if (!DT->isReachableFromEntry(User->getParent())) {
Jun Bum Lim0f906722017-11-17 20:38:25 +0000965 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000966 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000967 continue;
968 }
969
970 // The user must be a PHI node.
971 PHINode *PN = cast<PHINode>(User);
972
973 // Surprisingly, instructions can be used outside of loops without any
974 // exits. This can only happen in PHI nodes if the incoming block is
975 // unreachable.
976 BasicBlock *BB = PN->getIncomingBlock(U);
977 if (!DT->isReachableFromEntry(BB)) {
978 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000979 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000980 continue;
981 }
982
983 VisitedUsers.insert(PN);
Alina Sbirlea0e155012018-07-02 18:53:40 +0000984 if (isTriviallyReplaceablePHI(*PN, I))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000985 continue;
986
Jun Bum Lim144eb592018-02-12 17:56:55 +0000987 if (!canSplitPredecessors(PN, SafetyInfo))
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000988 return Changed;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000989
990 // Split predecessors of the PHI so that we can make users trivially
Alina Sbirlea0e155012018-07-02 18:53:40 +0000991 // replaceable.
Jun Bum Lim144eb592018-02-12 17:56:55 +0000992 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000993
994 // Should rebuild the iterators, as they may be invalidated by
995 // splitPredecessorsOfLoopExit().
996 UI = I.user_begin();
997 UE = I.user_end();
998 }
999
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001000 if (VisitedUsers.empty())
1001 return Changed;
1002
Chandler Carruthfc258542014-02-11 12:52:27 +00001003#ifndef NDEBUG
1004 SmallVector<BasicBlock *, 32> ExitBlocks;
1005 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001006 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +00001007 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +00001008#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +00001009
Evgeniy Stepanov10280da2014-06-25 07:54:58 +00001010 // Clones of this instruction. Don't create more than one per exit block!
1011 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1012
Chandler Carruthfc258542014-02-11 12:52:27 +00001013 // If this instruction is only used outside of the loop, then all users are
1014 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1015 // the instruction.
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001016 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1017 for (auto *UI : Users) {
1018 auto *User = cast<Instruction>(UI);
1019
1020 if (CurLoop->contains(User))
1021 continue;
1022
1023 PHINode *PN = cast<PHINode>(User);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001024 assert(ExitBlockSet.count(PN->getParent()) &&
Chandler Carruthfc258542014-02-11 12:52:27 +00001025 "The LCSSA PHI is not in an exit block!");
Alina Sbirlea0e155012018-07-02 18:53:40 +00001026 // The PHI must be trivially replaceable.
1027 Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies,
1028 SafetyInfo, CurLoop);
Chandler Carruthfc258542014-02-11 12:52:27 +00001029 PN->replaceAllUsesWith(New);
1030 PN->eraseFromParent();
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001031 Changed = true;
Chris Lattnercd96b4d2010-08-29 04:28:20 +00001032 }
Hal Finkel3d4269a2015-02-22 18:35:32 +00001033 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +00001034}
Chris Lattner64437692002-09-29 21:46:09 +00001035
Hal Finkel3d4269a2015-02-22 18:35:32 +00001036/// When an instruction is found to only use loop invariant operands that
1037/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +00001038///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001039static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +00001040 const LoopSafetyInfo *SafetyInfo,
1041 OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001042 auto *Preheader = CurLoop->getLoopPreheader();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001043 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1044 << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001045 ORE->emit([&]() {
1046 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1047 << ore::NV("Inst", &I);
1048 });
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001049
1050 // Metadata can be dependent on conditions we are hoisting above.
1051 // Conservatively strip all metadata on the instruction unless we were
1052 // guaranteed to execute I if we entered the loop, in which case the metadata
1053 // is valid in the loop preheader.
1054 if (I.hasMetadataOtherThanDebugLoc() &&
1055 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1056 // time in isGuaranteedToExecute if we don't actually have anything to
1057 // drop. It is a compile time optimization, not required for correctness.
1058 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1059 I.dropUnknownNonDebugMetadata();
1060
Chris Lattner6ac06592010-08-29 18:18:40 +00001061 // Move the new node to the Preheader, before its terminator.
1062 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001063
Wolfgang Piebc17a2792017-01-06 18:38:57 +00001064 // Do not retain debug locations when we are moving instructions to different
1065 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1066 // need to retain their debug locs because they may be inlined.
1067 // FIXME: How do we retain source locations without causing poor debugging
1068 // behavior?
1069 if (!isa<CallInst>(I))
1070 I.setDebugLoc(DebugLoc());
1071
Dehao Chend55bc4c2016-05-05 00:54:54 +00001072 if (isa<LoadInst>(I))
1073 ++NumMovedLoads;
1074 else if (isa<CallInst>(I))
1075 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +00001076 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +00001077 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +00001078}
1079
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00001080/// Only sink or hoist an instruction if it is not a trapping instruction,
1081/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001082/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001083static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +00001084 const DominatorTree *DT,
1085 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001086 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001087 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +00001088 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +00001089 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +00001090 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001091
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001092 bool GuaranteedToExecute =
1093 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1094
1095 if (!GuaranteedToExecute) {
1096 auto *LI = dyn_cast<LoadInst>(&Inst);
1097 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +00001098 ORE->emit([&]() {
1099 return OptimizationRemarkMissed(
1100 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1101 << "failed to hoist load with loop-invariant address "
1102 "because load is conditionally executed";
1103 });
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001104 }
1105
1106 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001107}
1108
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001109namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +00001110class LoopPromoter : public LoadAndStorePromoter {
1111 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001112 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001113 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1114 SmallVectorImpl<Instruction *> &LoopInsertPts;
1115 PredIteratorCache &PredCache;
1116 AliasSetTracker &AST;
1117 LoopInfo &LI;
1118 DebugLoc DL;
1119 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001120 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001121 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +00001122
Dehao Chend55bc4c2016-05-05 00:54:54 +00001123 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1124 if (Instruction *I = dyn_cast<Instruction>(V))
1125 if (Loop *L = LI.getLoopFor(I->getParent()))
1126 if (!L->contains(BB)) {
1127 // We need to create an LCSSA PHI node for the incoming value and
1128 // store that.
1129 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1130 I->getName() + ".lcssa", &BB->front());
1131 for (BasicBlock *Pred : PredCache.get(BB))
1132 PN->addIncoming(I, Pred);
1133 return PN;
1134 }
1135 return V;
1136 }
Chandler Carruthfc258542014-02-11 12:52:27 +00001137
Dehao Chend55bc4c2016-05-05 00:54:54 +00001138public:
1139 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001140 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001141 SmallVectorImpl<BasicBlock *> &LEB,
1142 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1143 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001144 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +00001145 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1146 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001147 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001148 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +00001149
Dehao Chend55bc4c2016-05-05 00:54:54 +00001150 bool isInstInList(Instruction *I,
1151 const SmallVectorImpl<Instruction *> &) const override {
1152 Value *Ptr;
1153 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1154 Ptr = LI->getOperand(0);
1155 else
1156 Ptr = cast<StoreInst>(I)->getPointerOperand();
1157 return PointerMustAliases.count(Ptr);
1158 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001159
Dehao Chend55bc4c2016-05-05 00:54:54 +00001160 void doExtraRewritesBeforeFinalDeletion() const override {
1161 // Insert stores after in the loop exit blocks. Each exit block gets a
1162 // store of the live-out values that feed them. Since we've already told
1163 // the SSA updater about the defs in the loop and the preheader
1164 // definition, it is all set and we can start using it.
1165 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1166 BasicBlock *ExitBlock = LoopExitBlocks[i];
1167 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1168 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1169 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1170 Instruction *InsertPos = LoopInsertPts[i];
1171 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001172 if (UnorderedAtomic)
1173 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001174 NewSI->setAlignment(Alignment);
1175 NewSI->setDebugLoc(DL);
1176 if (AATags)
1177 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001178 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001179 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001180
Dehao Chend55bc4c2016-05-05 00:54:54 +00001181 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1182 // Update alias analysis.
1183 AST.copyValue(LI, V);
1184 }
1185 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1186};
Philip Reames21cc2fa2017-10-26 21:00:15 +00001187
1188
1189/// Return true iff we can prove that a caller of this function can not inspect
1190/// the contents of the provided object in a well defined program.
1191bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1192 if (isa<AllocaInst>(Object))
1193 // Since the alloca goes out of scope, we know the caller can't retain a
1194 // reference to it and be well defined. Thus, we don't need to check for
Fangrui Songf78650a2018-07-30 19:41:25 +00001195 // capture.
Philip Reames21cc2fa2017-10-26 21:00:15 +00001196 return true;
Fangrui Songf78650a2018-07-30 19:41:25 +00001197
Philip Reames21cc2fa2017-10-26 21:00:15 +00001198 // For all other objects we need to know that the caller can't possibly
1199 // have gotten a reference to the object. There are two components of
1200 // that:
1201 // 1) Object can't be escaped by this function. This is what
1202 // PointerMayBeCaptured checks.
1203 // 2) Object can't have been captured at definition site. For this, we
1204 // need to know the return value is noalias. At the moment, we use a
1205 // weaker condition and handle only AllocLikeFunctions (which are
1206 // known to be noalias). TODO
1207 return isAllocLikeFn(Object, TLI) &&
1208 !PointerMayBeCaptured(Object, true, true);
1209}
1210
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001211} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001212
Hal Finkel3d4269a2015-02-22 18:35:32 +00001213/// Try to promote memory values to scalars by sinking stores out of the
1214/// loop and moving loads to before the loop. We do this by looping over
1215/// the stores in the loop, looking for stores to Must pointers which are
1216/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001217///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001218bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001219 const SmallSetVector<Value *, 8> &PointerMustAliases,
1220 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001221 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1222 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001223 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1224 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001225 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001226 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1227 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001228 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001229
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001230 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001231 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001232
Anna Thomas5ac72f92018-03-13 19:38:45 +00001233 // It is not safe to promote a load/store from the loop if the load/store is
Chris Lattner1dc98b42010-08-29 06:43:52 +00001234 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001235 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001236 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001237 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001238 // into:
1239 //
1240 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1241 //
1242 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001243 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001244 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001245 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001246 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001247 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001248 // path which did not originally have one.
1249 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001250 // If at least one store is guaranteed to execute, both properties are
1251 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001252 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001253 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001254 // guaranteed to execute, we can still establish these properties.
1255 // We can establish (p1) by proving that hoisting the load into the preheader
1256 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001257 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001258 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001259 //
1260 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001261 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001262 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001263 // b) Prove a store dominates every exit block. In this case, if an exit
1264 // blocks is reached, the original dynamic path would have taken us through
1265 // the store, so inserting a store into the exit block is safe. Note that this
1266 // is different from the store being guaranteed to execute. For instance,
1267 // if an exception is thrown on the first iteration of the loop, the original
1268 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001269
1270 bool DereferenceableInPH = false;
1271 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001272
Dehao Chend55bc4c2016-05-05 00:54:54 +00001273 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001274
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001275 // We start with an alignment of one and try to find instructions that allow
1276 // us to prove better alignment.
1277 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001278 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001279 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001280 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001281 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001282
Philip Reamesb54c8e62016-03-09 22:59:30 +00001283 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1284
Philip Reames21cc2fa2017-10-26 21:00:15 +00001285 bool IsKnownThreadLocalObject = false;
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001286 if (SafetyInfo->MayThrow) {
Eli Friedmanee895052016-06-05 22:13:52 +00001287 // If a loop can throw, we have to insert a store along each unwind edge.
1288 // That said, we can't actually make the unwind edge explicit. Therefore,
Philip Reames21cc2fa2017-10-26 21:00:15 +00001289 // we have to prove that the store is dead along the unwind edge. We do
1290 // this by proving that the caller can't have a reference to the object
Fangrui Songf78650a2018-07-30 19:41:25 +00001291 // after return and thus can't possibly load from the object.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001292 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Philip Reames21cc2fa2017-10-26 21:00:15 +00001293 if (!isKnownNonEscaping(Object, TLI))
1294 return false;
1295 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1296 // visible to other threads if captured and used during their lifetimes.
1297 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
Eli Friedmanee895052016-06-05 22:13:52 +00001298 }
1299
Chris Lattner1dc98b42010-08-29 06:43:52 +00001300 // Check that all of the pointers in the alias set have the same type. We
1301 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001302 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001303 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001304 // Check that all of the pointers in the alias set have the same type. We
1305 // cannot (yet) promote a memory location that is loaded and stored in
1306 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001307 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001308 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001309
Chandler Carruthcdf47882014-03-09 03:16:01 +00001310 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001311 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001312 Instruction *UI = dyn_cast<Instruction>(U);
1313 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001314 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001315
Chris Lattner1dc98b42010-08-29 06:43:52 +00001316 // If there is an non-load/store instruction in the loop, we can't promote
1317 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001318 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Sanjay Patel9f49b682016-01-08 22:05:03 +00001319 assert(!Load->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001320 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001321 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001322
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001323 SawUnorderedAtomic |= Load->isAtomic();
1324 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001325
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001326 if (!DereferenceableInPH)
1327 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001328 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001329 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001330 // Stores *of* the pointer are not interesting, only stores *to* the
1331 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001332 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001333 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +00001334 assert(!Store->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001335 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001336 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001337
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001338 SawUnorderedAtomic |= Store->isAtomic();
1339 SawNotAtomic |= !Store->isAtomic();
1340
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001341 // If the store is guaranteed to execute, both properties are satisfied.
1342 // We may want to check if a store is guaranteed to execute even if we
1343 // already know that promotion is safe, since it may have higher
1344 // alignment than any other guaranteed stores, in which case we can
1345 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001346 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001347 if (!InstAlignment)
1348 InstAlignment =
1349 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1350
1351 if (!DereferenceableInPH || !SafeToInsertStore ||
1352 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001353 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001354 DereferenceableInPH = true;
1355 SafeToInsertStore = true;
1356 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001357 }
Anna Thomas67151352016-06-24 12:38:45 +00001358 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001359
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001360 // If a store dominates all exit blocks, it is safe to sink.
1361 // As explained above, if an exit block was executed, a dominating
Fangrui Song956ee792018-03-30 22:22:31 +00001362 // store must have been executed at least once, so we are not
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001363 // introducing stores on paths that did not have them.
1364 // Note that this only looks at explicit exit blocks. If we ever
1365 // start sinking stores into unwind edges (see above), this will break.
1366 if (!SafeToInsertStore)
1367 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1368 return DT->dominates(Store->getParent(), Exit);
1369 });
1370
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001371 // If the store is not guaranteed to execute, we may still get
1372 // deref info through it.
1373 if (!DereferenceableInPH) {
1374 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001375 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001376 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001377 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001378 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001379 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001380
Hal Finkelcc39b672014-07-24 12:16:19 +00001381 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001382 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001383 // On the first load/store, just take its AA tags.
1384 UI->getAAMetadata(AATags);
1385 } else if (AATags) {
1386 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001387 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001388
1389 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001390 }
1391 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001392
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001393 // If we found both an unordered atomic instruction and a non-atomic memory
1394 // access, bail. We can't blindly promote non-atomic to atomic since we
1395 // might not be able to lower the result. We can't downgrade since that
1396 // would violate memory model. Also, align 0 is an error for atomics.
1397 if (SawUnorderedAtomic && SawNotAtomic)
1398 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001399
1400 // If we couldn't prove we can hoist the load, bail.
1401 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001402 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001403
1404 // We know we can hoist the load, but don't have a guaranteed store.
1405 // Check whether the location is thread-local. If it is, then we can insert
1406 // stores along paths which originally didn't have them without violating the
1407 // memory model.
1408 if (!SafeToInsertStore) {
Philip Reames21cc2fa2017-10-26 21:00:15 +00001409 if (IsKnownThreadLocalObject)
Xin Tong5ee40ba2017-01-19 19:31:40 +00001410 SafeToInsertStore = true;
1411 else {
1412 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1413 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001414 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1415 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001416 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001417 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001418
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001419 // If we've still failed to prove we can sink the store, give up.
1420 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001421 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001422
Chris Lattner1dc98b42010-08-29 06:43:52 +00001423 // Otherwise, this is safe to promote, lets do it!
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001424 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1425 << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +00001426 ORE->emit([&]() {
1427 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1428 LoopUses[0])
1429 << "Moving accesses to memory location out of the loop";
1430 });
Chris Lattner1dc98b42010-08-29 06:43:52 +00001431 ++NumPromoted;
1432
Eli Friedmanddf7f552011-05-27 20:31:51 +00001433 // Grab a debug location for the inserted loads/stores; given that the
1434 // inserted loads/stores have little relation to the original loads/stores,
1435 // this code just arbitrarily picks a location from one, since any debug
1436 // location is better than none.
1437 DebugLoc DL = LoopUses[0]->getDebugLoc();
1438
Chris Lattner1dc98b42010-08-29 06:43:52 +00001439 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001440 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001441 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001442 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001443 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1444 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001445
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001446 // Set up the preheader to have a definition of the value. It is the live-out
1447 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001448 LoadInst *PreheaderLoad = new LoadInst(
1449 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001450 if (SawUnorderedAtomic)
1451 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001452 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001453 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001454 if (AATags)
1455 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001456 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1457
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001458 // Rewrite all the loads in the loop and remember all the definitions from
1459 // stores in the loop.
1460 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001461
1462 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1463 if (PreheaderLoad->use_empty())
1464 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001465
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001466 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001467}
Devang Patelb98a0972007-07-31 08:01:41 +00001468
Roman Gareev036c0882016-02-15 14:48:50 +00001469/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001470/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001471/// FIXME: In new pass manager, there is no helper function to handle loop
1472/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001473/// from scratch for every loop. Hook up with the helper functions when
1474/// available in the new pass manager to avoid redundant computation.
1475AliasSetTracker *
1476LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1477 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001478 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001479 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001480 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001481 auto MapI = LoopToAliasSetMap.find(InnerL);
1482 // If the AST for this inner loop is missing it may have been merged into
1483 // some other loop's AST and then that loop unrolled, and so we need to
1484 // recompute it.
1485 if (MapI == LoopToAliasSetMap.end()) {
1486 RecomputeLoops.push_back(InnerL);
1487 continue;
1488 }
1489 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001490
1491 if (CurAST != nullptr) {
1492 // What if InnerLoop was modified by other passes ?
1493 CurAST->add(*InnerAST);
1494
1495 // Once we've incorporated the inner loop's AST into ours, we don't need
1496 // the subloop's anymore.
1497 delete InnerAST;
1498 } else {
1499 CurAST = InnerAST;
1500 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001501 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001502 }
1503 if (CurAST == nullptr)
1504 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001505
1506 auto mergeLoop = [&](Loop *L) {
1507 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chandler Carruthad8cb382016-02-27 04:34:07 +00001508 for (BasicBlock *BB : L->blocks())
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001509 CurAST->add(*BB); // Incorporate the specified basic block
Chandler Carruthad8cb382016-02-27 04:34:07 +00001510 };
1511
1512 // Add everything from the sub loops that are no longer directly available.
1513 for (Loop *InnerL : RecomputeLoops)
1514 mergeLoop(InnerL);
1515
1516 // And merge in this loop.
1517 mergeLoop(L);
1518
Roman Gareev036c0882016-02-15 14:48:50 +00001519 return CurAST;
1520}
1521
Ashutosh Nema47802622015-08-13 11:18:35 +00001522/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001523///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001524void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1525 Loop *L) {
1526 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001527 if (!AST)
1528 return;
1529
1530 AST->copyValue(From, To);
1531}
1532
Hal Finkel3d4269a2015-02-22 18:35:32 +00001533/// Simple Analysis hook. Delete value V from alias set
1534///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001535void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1536 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001537 if (!AST)
1538 return;
1539
1540 AST->deleteValue(V);
1541}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001542
1543/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001544///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001545void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1546 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001547 if (!AST)
1548 return;
1549
1550 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001551 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001552}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001553
Hal Finkel3d4269a2015-02-22 18:35:32 +00001554/// Return true if the body of this loop may store into the memory
1555/// location pointed to by V.
1556///
1557static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001558 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001559 AliasSetTracker *CurAST) {
1560 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1561 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1562}
1563
1564/// Little predicate that returns true if the specified basic block is in
1565/// a subloop of the current one, not the current one itself.
1566///
1567static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1568 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1569 return LI->getLoopFor(BB) != CurLoop;
1570}