blob: ff7cb3c26c9f953d3ea13f408b1b254733376189 [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"
Max Kazantsev097ef692018-08-21 08:11:31 +000061#include "llvm/IR/PatternMatch.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000062#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000063#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000066#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000067#include "llvm/Transforms/Scalar/LoopPassManager.h"
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000068#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000069#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000071#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000072#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000073using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000074
Chandler Carruth964daaa2014-04-22 02:55:47 +000075#define DEBUG_TYPE "licm"
76
Dehao Chend55bc4c2016-05-05 00:54:54 +000077STATISTIC(NumSunk, "Number of instructions sunk out of loop");
78STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000079STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
80STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000081STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000082
Xin Tongccee0e02017-02-21 20:53:48 +000083/// Memory promotion is enabled by default.
Dan Gohmand78c4002008-05-13 00:00:25 +000084static cl::opt<bool>
Xin Tongccee0e02017-02-21 20:53:48 +000085 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
Dehao Chend55bc4c2016-05-05 00:54:54 +000086 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000087
Anna Thomas7f4b26e2017-02-02 13:22:03 +000088static cl::opt<uint32_t> MaxNumUsesTraversed(
89 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
90 cl::desc("Max num uses visited for identifying load "
91 "invariance in loop using invariant start (default = 8)"));
92
Anna Thomas19626212018-08-17 13:44:00 +000093// Default value of zero implies we use the regular alias set tracker mechanism
94// instead of the cross product using AA to identify aliasing of the memory
95// location we are interested in.
96static cl::opt<int>
97LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
98 cl::desc("How many instruction to cross product using AA"));
99
Hal Finkel3d4269a2015-02-22 18:35:32 +0000100static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000101static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
102 const LoopSafetyInfo *SafetyInfo,
103 TargetTransformInfo *TTI, bool &FreeInLoop);
Max Kazantsev68290f82018-08-15 02:49:12 +0000104static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Max Kazantsev72d7d642018-08-16 08:30:15 +0000105 LoopSafetyInfo *SafetyInfo,
Adam Nemet358433c2017-01-11 04:39:35 +0000106 OptimizationRemarkEmitter *ORE);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000107static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000108 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000109 OptimizationRemarkEmitter *ORE, bool FreeInLoop);
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000110static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000111 const DominatorTree *DT,
112 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000113 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000114 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000115 const Instruction *CtxI = nullptr);
Anna Thomas19626212018-08-17 13:44:00 +0000116static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
117 AliasSetTracker *CurAST, Loop *CurLoop,
118 AliasAnalysis *AA);
119
David Majnemer42a07302016-01-04 03:37:39 +0000120static Instruction *
121CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
122 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000123 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000124
Dan Gohmand78c4002008-05-13 00:00:25 +0000125namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000126struct LoopInvariantCodeMotion {
Marcello Maggioni883fe452018-08-21 20:30:14 +0000127 using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000128 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000129 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
130 ScalarEvolution *SE, MemorySSA *MSSA,
Adam Nemet358433c2017-01-11 04:39:35 +0000131 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000132
Marcello Maggioni883fe452018-08-21 20:30:14 +0000133 ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
Dehao Chen7ef58202016-07-11 22:45:24 +0000134
Dehao Chen9cba1f42016-07-12 22:37:48 +0000135private:
Marcello Maggioni883fe452018-08-21 20:30:14 +0000136 ASTrackerMapTy LoopToAliasSetMap;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000137
Marcello Maggioni883fe452018-08-21 20:30:14 +0000138 std::unique_ptr<AliasSetTracker>
139 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000140};
141
142struct LegacyLICMPass : public LoopPass {
143 static char ID; // Pass identification, replacement for typeid
144 LegacyLICMPass() : LoopPass(ID) {
145 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
146 }
147
148 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000149 if (skipLoop(L)) {
150 // If we have run LICM on a previous loop but now we are skipping
151 // (because we've hit the opt-bisect limit), we need to clear the
152 // loop alias information.
153 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000154 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000155 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000156
157 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000158 MemorySSA *MSSA = EnableMSSALoopDependency
159 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
160 : nullptr;
Adam Nemet358433c2017-01-11 04:39:35 +0000161 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
162 // pass. Function analyses need to be preserved across loop transformations
163 // but ORE cannot be preserved (see comment before the pass definition).
164 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000165 return LICM.runOnLoop(L,
166 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
167 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
168 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
169 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000170 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
171 *L->getHeader()->getParent()),
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000172 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000173 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000174
Dehao Chend55bc4c2016-05-05 00:54:54 +0000175 /// This transformation requires natural loop information & requires that
176 /// loop preheaders be inserted into the CFG...
177 ///
178 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000179 AU.addPreserved<DominatorTreeWrapperPass>();
180 AU.addPreserved<LoopInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000181 AU.addRequired<TargetLibraryInfoWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000182 if (EnableMSSALoopDependency)
183 AU.addRequired<MemorySSAWrapperPass>();
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000184 AU.addRequired<TargetTransformInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000185 getLoopAnalysisUsage(AU);
186 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000187
Dehao Chend55bc4c2016-05-05 00:54:54 +0000188 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000189
Dehao Chend55bc4c2016-05-05 00:54:54 +0000190 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000191 assert(LICM.getLoopToAliasSetMap().empty() &&
192 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000193 return false;
194 }
Devang Patel69730c92007-03-07 04:41:30 +0000195
Dehao Chend55bc4c2016-05-05 00:54:54 +0000196private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000197 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000198
Dehao Chend55bc4c2016-05-05 00:54:54 +0000199 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
200 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
201 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000202
Dehao Chend55bc4c2016-05-05 00:54:54 +0000203 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
204 /// set.
205 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000206
Dehao Chend55bc4c2016-05-05 00:54:54 +0000207 /// Simple Analysis hook. Delete loop L from alias set map.
208 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000209};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000210} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000211
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000212PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
213 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000214 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000215 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000216 Function *F = L.getHeader()->getParent();
217
Adam Nemet358433c2017-01-11 04:39:35 +0000218 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000219 // FIXME: This should probably be optional rather than required.
220 if (!ORE)
221 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
222 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000223
224 LoopInvariantCodeMotion LICM;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000225 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
226 AR.MSSA, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000227 return PreservedAnalyses::all();
228
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000229 auto PA = getLoopPassPreservedAnalyses();
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000230
231 PA.preserve<DominatorTreeAnalysis>();
232 PA.preserve<LoopAnalysis>();
233
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000234 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000235}
236
237char LegacyLICMPass::ID = 0;
238INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
239 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000240INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000241INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000242INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000243INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000244INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
245 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000246
Dehao Chen9cba1f42016-07-12 22:37:48 +0000247Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000248
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000249/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000250/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000251/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000252/// We should delete AST for inner loops in the new pass manager to avoid
253/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000254///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000255bool LoopInvariantCodeMotion::runOnLoop(
256 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
257 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
258 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000259 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000260
Chandler Carruthfc258542014-02-11 12:52:27 +0000261 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
262
Marcello Maggioni883fe452018-08-21 20:30:14 +0000263 std::unique_ptr<AliasSetTracker> CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000264
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000265 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000266 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000267
Hal Finkel3d4269a2015-02-22 18:35:32 +0000268 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000269 LoopSafetyInfo SafetyInfo;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000270 SafetyInfo.computeLoopSafetyInfo(L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000271
Chris Lattner6ec05f52002-05-10 22:44:58 +0000272 // We want to visit all of the instructions in this loop... that are not parts
273 // of our subloops (they have already had their invariants hoisted out of
274 // their loop, into this loop, so there is no need to process the BODIES of
275 // the subloops).
276 //
Chris Lattner64437692002-09-29 21:46:09 +0000277 // Traverse the body of the loop in depth first order on the dominator tree so
278 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000279 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000280 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000281 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000282 if (L->hasDedicatedExits())
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000283 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
Marcello Maggioni883fe452018-08-21 20:30:14 +0000284 CurAST.get(), &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000285 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000286 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Marcello Maggioni883fe452018-08-21 20:30:14 +0000287 CurAST.get(), &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000288
Chris Lattner45d67d62003-02-24 03:52:32 +0000289 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000290 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000291 // Don't sink stores from loops without dedicated block exits. Exits
292 // containing indirect branches are not transformed by loop simplify,
293 // make sure we catch that. An additional load may be generated in the
294 // preheader for SSA updater, so also avoid sinking when no preheader
295 // is available.
296 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000297 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000298 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000299 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000300
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000301 // We can't insert into a catchswitch.
302 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
303 return isa<CatchSwitchInst>(Exit->getTerminator());
304 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000305
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000306 if (!HasCatchSwitch) {
307 SmallVector<Instruction *, 8> InsertPts;
308 InsertPts.reserve(ExitBlocks.size());
309 for (BasicBlock *ExitBlock : ExitBlocks)
310 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000311
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000312 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000313
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000314 bool Promoted = false;
315
316 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000317 for (AliasSet &AS : *CurAST) {
318 // We can promote this alias set if it has a store, if it is a "Must"
319 // alias set, if the pointer is loop invariant, and if we are not
320 // eliminating any volatile loads or stores.
321 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
Philip Reamesc3c23e82018-08-21 17:59:11 +0000322 !L->isLoopInvariant(AS.begin()->getValue()))
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000323 continue;
324
325 assert(
326 !AS.empty() &&
327 "Must alias set should have at least one pointer element in it!");
328
329 SmallSetVector<Value *, 8> PointerMustAliases;
330 for (const auto &ASI : AS)
331 PointerMustAliases.insert(ASI.getValue());
332
Marcello Maggioni883fe452018-08-21 20:30:14 +0000333 Promoted |= promoteLoopAccessesToScalars(
334 PointerMustAliases, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L,
335 CurAST.get(), &SafetyInfo, ORE);
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000336 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000337
338 // Once we have promoted values across the loop body we have to
339 // recursively reform LCSSA as any nested loop may now have values defined
340 // within the loop used in the outer loop.
341 // FIXME: This is really heavy handed. It would be a bit better to use an
342 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
343 // it as it went.
344 if (Promoted)
345 formLCSSARecursively(*L, *DT, LI, SE);
346
347 Changed |= Promoted;
348 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000349 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000350
Chandler Carruthfc258542014-02-11 12:52:27 +0000351 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
352 // specifically moving instructions across the loop boundary and so it is
353 // especially in need of sanity checking here.
354 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
355 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
356 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000357
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000358 // If this loop is nested inside of another one, save the alias information
359 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000360 if (L->getParentLoop() && !DeleteAST)
Marcello Maggioni883fe452018-08-21 20:30:14 +0000361 LoopToAliasSetMap[L] = std::move(CurAST);
Sanjoy Das4ae39202016-05-03 17:50:11 +0000362
Dehao Chen9cba1f42016-07-12 22:37:48 +0000363 if (Changed && SE)
364 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000365 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000366}
367
Hal Finkel3d4269a2015-02-22 18:35:32 +0000368/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000369/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000370/// first order w.r.t the DominatorTree. This allows us to visit uses before
371/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000372///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000373bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000374 DominatorTree *DT, TargetLibraryInfo *TLI,
375 TargetTransformInfo *TTI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000376 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
377 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000378
Hal Finkel3d4269a2015-02-22 18:35:32 +0000379 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000380 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
Marcello Maggioni883fe452018-08-21 20:30:14 +0000381 CurLoop != nullptr && CurAST && SafetyInfo != nullptr &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000382 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000383
David Majnemere6bb8952017-07-20 03:27:02 +0000384 // We want to visit children before parents. We will enque all the parents
385 // before their children in the worklist and process the worklist in reverse
386 // order.
387 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000388
Sanjay Patel99133222016-01-13 23:01:57 +0000389 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000390 for (DomTreeNode *DTN : reverse(Worklist)) {
391 BasicBlock *BB = DTN->getBlock();
392 // Only need to process the contents of this block if it is not part of a
393 // subloop (which would already have been processed).
394 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000395 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000396
David Majnemere6bb8952017-07-20 03:27:02 +0000397 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
398 Instruction &I = *--II;
399
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000400 // If the instruction is dead, we would try to sink it because it isn't
401 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000402 if (isInstructionTriviallyDead(&I, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000403 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Anastasis Grammenos3a589102018-03-18 15:59:19 +0000404 salvageDebugInfo(I);
David Majnemere6bb8952017-07-20 03:27:02 +0000405 ++II;
406 CurAST->deleteValue(&I);
407 I.eraseFromParent();
408 Changed = true;
409 continue;
410 }
411
412 // Check to see if we can sink this instruction to the exit blocks
413 // of the loop. We can do this if the all users of the instruction are
414 // outside of the loop. In this case, it doesn't even matter if the
415 // operands of the instruction are loop invariant.
416 //
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000417 bool FreeInLoop = false;
418 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
Philip Reamesf562fc82018-08-29 21:49:30 +0000419 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
420 !I.mayHaveSideEffects()) {
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000421 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
422 if (!FreeInLoop) {
423 ++II;
424 CurAST->deleteValue(&I);
425 I.eraseFromParent();
426 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000427 Changed = true;
428 }
David Majnemere6bb8952017-07-20 03:27:02 +0000429 }
Chris Lattner91846012003-12-19 08:18:16 +0000430 }
Chris Lattner547192d62003-12-19 07:22:45 +0000431 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000432 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000433}
434
Hal Finkel3d4269a2015-02-22 18:35:32 +0000435/// Walk the specified region of the CFG (defined by all blocks dominated by
436/// the specified block, and that are in the current loop) in depth first
437/// order w.r.t the DominatorTree. This allows us to visit definitions before
438/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000439///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
441 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000442 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
443 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000444 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000445 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
446 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
447 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000448
David Majnemere6bb8952017-07-20 03:27:02 +0000449 // We want to visit parents before children. We will enque all the parents
450 // before their children in the worklist and process the worklist in order.
451 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000452
Sanjay Patel99133222016-01-13 23:01:57 +0000453 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000454 for (DomTreeNode *DTN : Worklist) {
455 BasicBlock *BB = DTN->getBlock();
456 // Only need to process the contents of this block if it is not part of a
457 // subloop (which would already have been processed).
Philip Reames5a648242018-04-27 20:58:30 +0000458 if (inSubLoop(BB, CurLoop, LI))
459 continue;
David Majnemere6bb8952017-07-20 03:27:02 +0000460
Philip Reames5b39acd2018-05-04 21:35:00 +0000461 // Keep track of whether the prefix of instructions visited so far are such
462 // that the next instruction visited is guaranteed to execute if the loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000463 // is entered.
Philip Reames5b39acd2018-05-04 21:35:00 +0000464 bool IsMustExecute = CurLoop->getHeader() == BB;
Max Kazantsev097ef692018-08-21 08:11:31 +0000465 // Keep track of whether the prefix instructions could have written memory.
466 // TODO: This and IsMustExecute may be done smarter if we keep track of all
467 // throwing and mem-writing operations in every block, e.g. using something
468 // similar to isGuaranteedToExecute.
469 bool IsMemoryNotModified = CurLoop->getHeader() == BB;
Philip Reames5b39acd2018-05-04 21:35:00 +0000470
Philip Reames5a648242018-04-27 20:58:30 +0000471 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
472 Instruction &I = *II++;
473 // Try constant folding this instruction. If all the operands are
474 // constants, it is technically hoistable, but it would be better to
475 // just fold it.
476 if (Constant *C = ConstantFoldInstruction(
477 &I, I.getModule()->getDataLayout(), TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000478 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C
479 << '\n');
Philip Reames5a648242018-04-27 20:58:30 +0000480 CurAST->copyValue(&I, C);
481 I.replaceAllUsesWith(C);
482 if (isInstructionTriviallyDead(&I, TLI)) {
483 CurAST->deleteValue(&I);
David Majnemere6bb8952017-07-20 03:27:02 +0000484 I.eraseFromParent();
David Majnemere6bb8952017-07-20 03:27:02 +0000485 }
Philip Reames5a648242018-04-27 20:58:30 +0000486 Changed = true;
487 continue;
Chris Lattner030f0202010-08-31 23:00:16 +0000488 }
Philip Reames5a648242018-04-27 20:58:30 +0000489
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000490 // 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) &&
Philip Reames32cb80b2018-08-02 04:08:04 +0000495 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000496 (IsMustExecute ||
497 isSafeToExecuteUnconditionally(
498 I, DT, CurLoop, SafetyInfo, ORE,
499 CurLoop->getLoopPreheader()->getTerminator()))) {
Max Kazantsev68290f82018-08-15 02:49:12 +0000500 hoist(I, DT, CurLoop, SafetyInfo, ORE);
501 Changed = true;
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000502 continue;
503 }
504
Philip Reames5a648242018-04-27 20:58:30 +0000505 // Attempt to remove floating point division out of the loop by
506 // converting it to a reciprocal multiplication.
507 if (I.getOpcode() == Instruction::FDiv &&
508 CurLoop->isLoopInvariant(I.getOperand(1)) &&
509 I.hasAllowReciprocal()) {
510 auto Divisor = I.getOperand(1);
511 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
512 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
513 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
514 ReciprocalDivisor->insertBefore(&I);
515
516 auto Product =
517 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
518 Product->setFastMathFlags(I.getFastMathFlags());
519 Product->insertAfter(&I);
520 I.replaceAllUsesWith(Product);
521 I.eraseFromParent();
522
523 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
524 Changed = true;
525 continue;
526 }
527
Max Kazantsev097ef692018-08-21 08:11:31 +0000528 using namespace PatternMatch;
Philip Reames9ec15fa2018-08-24 16:24:48 +0000529 if (((I.use_empty() &&
530 match(&I, m_Intrinsic<Intrinsic::invariant_start>())) ||
Hans Wennborg2c390c52018-08-29 12:21:32 +0000531 match(&I, m_Intrinsic<Intrinsic::experimental_guard>())) &&
Max Kazantsev097ef692018-08-21 08:11:31 +0000532 IsMustExecute && IsMemoryNotModified &&
533 CurLoop->hasLoopInvariantOperands(&I)) {
534 hoist(I, DT, CurLoop, SafetyInfo, ORE);
535 Changed = true;
536 continue;
537 }
538
Philip Reames5b39acd2018-05-04 21:35:00 +0000539 if (IsMustExecute)
540 IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I);
Max Kazantsev097ef692018-08-21 08:11:31 +0000541 if (IsMemoryNotModified)
542 IsMemoryNotModified = !I.mayWriteToMemory();
Philip Reames5a648242018-04-27 20:58:30 +0000543 }
David Majnemere6bb8952017-07-20 03:27:02 +0000544 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000545
Hal Finkel3d4269a2015-02-22 18:35:32 +0000546 return Changed;
547}
548
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000549// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000550// CurLoop is dominated by an invariant.start representing the same memory
551// location and size as the memory location LI loads from, and also the
552// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000553static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
554 Loop *CurLoop) {
555 Value *Addr = LI->getOperand(0);
556 const DataLayout &DL = LI->getModule()->getDataLayout();
557 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
558 cast<PointerType>(Addr->getType())->getElementType());
559
560 // if the type is i8 addrspace(x)*, we know this is the type of
561 // llvm.invariant.start operand
562 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
563 LI->getPointerAddressSpace());
564 unsigned BitcastsVisited = 0;
565 // Look through bitcasts until we reach the i8* type (this is invariant.start
566 // operand type).
567 while (Addr->getType() != PtrInt8Ty) {
568 auto *BC = dyn_cast<BitCastInst>(Addr);
569 // Avoid traversing high number of bitcast uses.
570 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
571 return false;
572 Addr = BC->getOperand(0);
573 }
574
575 unsigned UsesVisited = 0;
576 // Traverse all uses of the load operand value, to see if invariant.start is
577 // one of the uses, and whether it dominates the load instruction.
578 for (auto *U : Addr->users()) {
579 // Avoid traversing for Load operand with high number of users.
580 if (++UsesVisited > MaxNumUsesTraversed)
581 return false;
582 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
583 // If there are escaping uses of invariant.start instruction, the load maybe
584 // non-invariant.
585 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000586 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000587 continue;
588 unsigned InvariantSizeInBits =
589 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
590 // Confirm the invariant.start location size contains the load operand size
591 // in bits. Also, the invariant.start should dominate the load, and we
592 // should not hoist the load out of a loop that contains this dominating
593 // invariant.start.
594 if (LocSizeInBits <= InvariantSizeInBits &&
595 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
596 return true;
597 }
598
599 return false;
600}
601
Philip Reames09de4702018-08-02 00:54:14 +0000602namespace {
603/// Return true if-and-only-if we know how to (mechanically) both hoist and
604/// sink a given instruction out of a loop. Does not address legality
605/// concerns such as aliasing or speculation safety.
606bool isHoistableAndSinkableInst(Instruction &I) {
607 // Only these instructions are hoistable/sinkable.
Philip Reamesf562fc82018-08-29 21:49:30 +0000608 return (isa<LoadInst>(I) || isa<StoreInst>(I) ||
609 isa<CallInst>(I) || isa<FenceInst>(I) ||
Philip Reames09de4702018-08-02 00:54:14 +0000610 isa<BinaryOperator>(I) || isa<CastInst>(I) ||
611 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) ||
612 isa<CmpInst>(I) || isa<InsertElementInst>(I) ||
613 isa<ExtractElementInst>(I) || isa<ShuffleVectorInst>(I) ||
614 isa<ExtractValueInst>(I) || isa<InsertValueInst>(I));
615}
Philip Reames3b35aaa2018-08-06 22:07:37 +0000616/// Return true if all of the alias sets within this AST are known not to
617/// contain a Mod.
618bool isReadOnly(AliasSetTracker *CurAST) {
619 for (AliasSet &AS : *CurAST) {
620 if (!AS.isForwardingAliasSet() && AS.isMod()) {
621 return false;
622 }
623 }
624 return true;
625}
Philip Reames09de4702018-08-02 00:54:14 +0000626}
627
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000628bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
629 Loop *CurLoop, AliasSetTracker *CurAST,
Philip Reames32cb80b2018-08-02 04:08:04 +0000630 bool TargetExecutesOncePerLoop,
Adam Nemet81941b32017-01-11 04:39:45 +0000631 OptimizationRemarkEmitter *ORE) {
Philip Reames09de4702018-08-02 00:54:14 +0000632 // If we don't understand the instruction, bail early.
633 if (!isHoistableAndSinkableInst(I))
634 return false;
635
Chris Lattner65c11932003-12-09 19:32:44 +0000636 // Loads have extra constraints we have to verify before we can hoist them.
637 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000638 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000639 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000640
Chris Lattner8a8fb902008-07-23 05:06:28 +0000641 // Loads from constant memory are always safe to move, even if they end up
642 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000643 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000644 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000645 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000646 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000647
Philip Reames32cb80b2018-08-02 04:08:04 +0000648 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
649 return false; // Don't risk duplicating unordered loads
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000650
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000651 // This checks for an invariant.start dominating the load.
652 if (isLoadInvariantInLoop(LI, DT, CurLoop))
653 return true;
654
Anna Thomas19626212018-08-17 13:44:00 +0000655 // Don't hoist loads which have may-aliased stores in loop.
656 uint64_t Size = 0;
657 if (LI->getType()->isSized())
658 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
659
660 AAMDNodes AAInfo;
661 LI->getAAMetadata(AAInfo);
662
663 bool Invalidated = pointerInvalidatedByLoop(
664 MemoryLocation(LI->getOperand(0), Size, AAInfo), CurAST, CurLoop, AA);
Adam Nemet81941b32017-01-11 04:39:45 +0000665 // Check loop-invariant address because this may also be a sinkable load
666 // whose address is not necessarily loop-invariant.
667 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +0000668 ORE->emit([&]() {
669 return OptimizationRemarkMissed(
670 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
671 << "failed to move load with loop-invariant address "
672 "because the loop may invalidate its value";
673 });
Adam Nemet81941b32017-01-11 04:39:45 +0000674
675 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000676 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000677 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000678 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000679 return false;
680
David Majnemer42a07302016-01-04 03:37:39 +0000681 // Don't sink calls which can throw.
682 if (CI->mayThrow())
683 return false;
684
Philip Reames1c0fde62018-08-24 19:13:39 +0000685 using namespace PatternMatch;
686 if (match(CI, m_Intrinsic<Intrinsic::assume>()))
687 // Assumes don't actually alias anything or throw
688 return true;
Philip Reames85afd1a2018-08-10 22:21:56 +0000689
Eli Friedman942e1c12011-05-27 18:37:52 +0000690 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000691 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
692 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000693 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000694 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000695 // A readonly argmemonly function only reads from memory pointed to by
696 // it's arguments with arbitrary offsets. If we can prove there are no
697 // writes to this memory in the loop, we can hoist or sink.
698 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
Philip Reamesf562fc82018-08-29 21:49:30 +0000699 // TODO: expand to writeable arguments
Philip Reames5f994232015-09-21 22:27:59 +0000700 for (Value *Op : CI->arg_operands())
701 if (Op->getType()->isPointerTy() &&
Anna Thomas19626212018-08-17 13:44:00 +0000702 pointerInvalidatedByLoop(
703 MemoryLocation(Op, MemoryLocation::UnknownSize, AAMDNodes()),
704 CurAST, CurLoop, AA))
Philip Reames5f994232015-09-21 22:27:59 +0000705 return false;
706 return true;
707 }
Philip Reames3b35aaa2018-08-06 22:07:37 +0000708
Duncan Sands68b6f502007-12-01 07:51:45 +0000709 // If this call only reads from memory and there are no writes to memory
710 // in the loop, we can hoist or sink the call as appropriate.
Philip Reames3b35aaa2018-08-06 22:07:37 +0000711 if (isReadOnly(CurAST))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000712 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000713 }
714
Nadav Rotem03dcd852012-09-04 10:25:04 +0000715 // FIXME: This should use mod/ref information to see if we can hoist or
716 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000717
Chris Lattner20cda262004-03-15 04:11:30 +0000718 return false;
Philip Reamesca256d92018-08-09 20:18:42 +0000719 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
720 // Fences alias (most) everything to provide ordering. For the moment,
721 // just give up if there are any other memory operations in the loop.
722 auto Begin = CurAST->begin();
723 assert(Begin != CurAST->end() && "must contain FI");
724 if (std::next(Begin) != CurAST->end())
725 // constant memory for instance, TODO: handle better
726 return false;
727 auto *UniqueI = Begin->getUniqueInstruction();
728 if (!UniqueI)
729 // other memory op, give up
730 return false;
Philip Reames7d794332018-08-09 21:15:33 +0000731 (void)FI; //suppress unused variable warning
Philip Reamesca256d92018-08-09 20:18:42 +0000732 assert(UniqueI == FI && "AS must contain FI");
733 return true;
Philip Reamesf562fc82018-08-29 21:49:30 +0000734 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
735 if (!SI->isUnordered())
736 return false; // Don't sink/hoist volatile or ordered atomic store!
737
738 // We can only hoist a store that we can prove writes a value which is not
739 // read or overwritten within the loop. For those cases, we fallback to
740 // load store promotion instead.
741 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
742
743 if (AS.isRef() || !AS.isMustAlias())
744 // Quick exit test, handled by the full path below as well.
745 return false;
746 auto *UniqueI = AS.getUniqueInstruction();
747 if (!UniqueI)
748 // other memory op, give up
749 return false;
750 assert(UniqueI == SI && "AS must contain SI");
751 return true;
Chris Lattner65c11932003-12-09 19:32:44 +0000752 }
753
Philip Reames22b20a02018-08-09 03:44:28 +0000754 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
755
Philip Reames32cb80b2018-08-02 04:08:04 +0000756 // We've established mechanical ability and aliasing, it's up to the caller
757 // to check fault safety
758 return true;
Chris Lattneraaaea512003-12-10 06:41:05 +0000759}
760
Hal Finkel3d4269a2015-02-22 18:35:32 +0000761/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000762/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000763/// This is true when all incoming values are that instruction.
764/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000765///
Alina Sbirlea0e155012018-07-02 18:53:40 +0000766static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000767 for (const Value *IncValue : PN.incoming_values())
768 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000769 return false;
770
771 return true;
772}
773
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000774/// Return true if the instruction is free in the loop.
775static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
776 const TargetTransformInfo *TTI) {
777
778 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
779 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
780 return false;
781 // For a GEP, we cannot simply use getUserCost because currently it
782 // optimistically assume that a GEP will fold into addressing mode
783 // regardless of its users.
784 const BasicBlock *BB = GEP->getParent();
785 for (const User *U : GEP->users()) {
786 const Instruction *UI = cast<Instruction>(U);
787 if (CurLoop->contains(UI) &&
788 (BB != UI->getParent() ||
789 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
790 return false;
791 }
792 return true;
793 } else
794 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
795}
796
Hal Finkel3d4269a2015-02-22 18:35:32 +0000797/// Return true if the only users of this instruction are outside of
798/// the loop. If this is true, we can sink the instruction to the exit
799/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000800///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000801/// We also return true if the instruction could be folded away in lowering.
802/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
803static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
804 const LoopSafetyInfo *SafetyInfo,
805 TargetTransformInfo *TTI, bool &FreeInLoop) {
David Majnemer42a07302016-01-04 03:37:39 +0000806 const auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000807 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
Pete Cooper0cabcf22015-05-13 01:12:18 +0000808 for (const User *U : I.users()) {
809 const Instruction *UI = cast<Instruction>(U);
810 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000811 const BasicBlock *BB = PN->getParent();
812 // We cannot sink uses in catchswitches.
813 if (isa<CatchSwitchInst>(BB->getTerminator()))
814 return false;
815
816 // We need to sink a callsite to a unique funclet. Avoid sinking if the
817 // phi use is too muddled.
818 if (isa<CallInst>(I))
819 if (!BlockColors.empty() &&
820 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
821 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000822 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000823
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000824 if (CurLoop->contains(UI)) {
825 if (IsFree) {
826 FreeInLoop = true;
827 continue;
828 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000829 return false;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000830 }
Chris Lattner34399dd2003-12-11 22:23:32 +0000831 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000832 return true;
833}
834
David Majnemer42a07302016-01-04 03:37:39 +0000835static Instruction *
836CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
837 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000838 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000839 Instruction *New;
840 if (auto *CI = dyn_cast<CallInst>(&I)) {
841 const auto &BlockColors = SafetyInfo->BlockColors;
842
843 // Sinking call-sites need to be handled differently from other
844 // instructions. The cloned call-site needs a funclet bundle operand
845 // appropriate for it's location in the CFG.
846 SmallVector<OperandBundleDef, 1> OpBundles;
847 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
848 BundleIdx != BundleEnd; ++BundleIdx) {
849 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
850 if (Bundle.getTagID() == LLVMContext::OB_funclet)
851 continue;
852
853 OpBundles.emplace_back(Bundle);
854 }
855
856 if (!BlockColors.empty()) {
857 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
858 assert(CV.size() == 1 && "non-unique color for exit block!");
859 BasicBlock *BBColor = CV.front();
860 Instruction *EHPad = BBColor->getFirstNonPHI();
861 if (EHPad->isEHPad())
862 OpBundles.emplace_back("funclet", EHPad);
863 }
864
865 New = CallInst::Create(CI, OpBundles);
866 } else {
867 New = I.clone();
868 }
869
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000870 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000871 if (!I.getName().empty())
872 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000873
874 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
875 // particularly cheap because we can rip off the PHI node that we're
876 // replacing for the number and blocks of the predecessors.
877 // OPT: If this shows up in a profile, we can instead finish sinking all
878 // invariant instructions, and then walk their operands to re-establish
879 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
880 // sinking bottom-up.
881 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
882 ++OI)
883 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
884 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
885 if (!OLoop->contains(&PN)) {
886 PHINode *OpPN =
887 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000888 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000889 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
890 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
891 *OI = OpPN;
892 }
893 return New;
894}
895
Alina Sbirlea0e155012018-07-02 18:53:40 +0000896static Instruction *sinkThroughTriviallyReplaceablePHI(
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000897 PHINode *TPN, Instruction *I, LoopInfo *LI,
898 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
899 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
Alina Sbirlea0e155012018-07-02 18:53:40 +0000900 assert(isTriviallyReplaceablePHI(*TPN, *I) &&
901 "Expect only trivially replaceable PHI");
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000902 BasicBlock *ExitBlock = TPN->getParent();
903 Instruction *New;
904 auto It = SunkCopies.find(ExitBlock);
905 if (It != SunkCopies.end())
906 New = It->second;
907 else
908 New = SunkCopies[ExitBlock] =
909 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
910 return New;
911}
912
Jun Bum Lim144eb592018-02-12 17:56:55 +0000913static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000914 BasicBlock *BB = PN->getParent();
915 if (!BB->canSplitPredecessors())
916 return false;
Jun Bum Lim144eb592018-02-12 17:56:55 +0000917 // It's not impossible to split EHPad blocks, but if BlockColors already exist
918 // it require updating BlockColors for all offspring blocks accordingly. By
919 // skipping such corner case, we can make updating BlockColors after splitting
920 // predecessor fairly simple.
921 if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad())
922 return false;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000923 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
924 BasicBlock *BBPred = *PI;
925 if (isa<IndirectBrInst>(BBPred->getTerminator()))
926 return false;
927 }
928 return true;
929}
930
931static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000932 LoopInfo *LI, const Loop *CurLoop,
933 LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000934#ifndef NDEBUG
935 SmallVector<BasicBlock *, 32> ExitBlocks;
936 CurLoop->getUniqueExitBlocks(ExitBlocks);
937 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
938 ExitBlocks.end());
939#endif
940 BasicBlock *ExitBB = PN->getParent();
941 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
942
943 // Split predecessors of the loop exit to make instructions in the loop are
Alina Sbirlea0e155012018-07-02 18:53:40 +0000944 // exposed to exit blocks through trivially replaceable PHIs while keeping the
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000945 // loop in the canonical form where each predecessor of each exit block should
946 // be contained within the loop. For example, this will convert the loop below
947 // from
948 //
949 // LB1:
950 // %v1 =
951 // br %LE, %LB2
952 // LB2:
953 // %v2 =
954 // br %LE, %LB1
955 // LE:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000956 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000957 //
958 // to
959 //
960 // LB1:
961 // %v1 =
962 // br %LE.split, %LB2
963 // LB2:
964 // %v2 =
965 // br %LE.split2, %LB1
966 // LE.split:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000967 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000968 // br %LE
969 // LE.split2:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000970 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000971 // br %LE
972 // LE:
973 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
974 //
Jun Bum Lim144eb592018-02-12 17:56:55 +0000975 auto &BlockColors = SafetyInfo->BlockColors;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000976 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
977 while (!PredBBs.empty()) {
978 BasicBlock *PredBB = *PredBBs.begin();
979 assert(CurLoop->contains(PredBB) &&
980 "Expect all predecessors are in the loop");
Jun Bum Lim144eb592018-02-12 17:56:55 +0000981 if (PN->getBasicBlockIndex(PredBB) >= 0) {
982 BasicBlock *NewPred = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000983 ExitBB, PredBB, ".split.loop.exit", DT, LI, nullptr, true);
Jun Bum Lim144eb592018-02-12 17:56:55 +0000984 // Since we do not allow splitting EH-block with BlockColors in
985 // canSplitPredecessors(), we can simply assign predecessor's color to
986 // the new block.
Andrew Kaylora2378662018-03-23 17:36:18 +0000987 if (!BlockColors.empty()) {
988 // Grab a reference to the ColorVector to be inserted before getting the
989 // reference to the vector we are copying because inserting the new
990 // element in BlockColors might cause the map to be reallocated.
991 ColorVector &ColorsForNewBlock = BlockColors[NewPred];
992 ColorVector &ColorsForOldBlock = BlockColors[PredBB];
993 ColorsForNewBlock = ColorsForOldBlock;
994 }
Jun Bum Lim144eb592018-02-12 17:56:55 +0000995 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000996 PredBBs.remove(PredBB);
997 }
998}
999
Hal Finkel3d4269a2015-02-22 18:35:32 +00001000/// When an instruction is found to only be used outside of the loop, this
1001/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +00001002/// This method is guaranteed to remove the original instruction from its
1003/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +00001004///
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001005static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +00001006 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001007 OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001008 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001009 ORE->emit([&]() {
1010 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1011 << "sinking " << ore::NV("Inst", &I);
1012 });
Hal Finkel3d4269a2015-02-22 18:35:32 +00001013 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001014 if (isa<LoadInst>(I))
1015 ++NumMovedLoads;
1016 else if (isa<CallInst>(I))
1017 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +00001018 ++NumSunk;
Chris Lattner55c21132003-12-10 20:43:29 +00001019
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001020 // Iterate over users to be ready for actual sinking. Replace users via
1021 // unrechable blocks with undef and make all user PHIs trivially replcable.
1022 SmallPtrSet<Instruction *, 8> VisitedUsers;
1023 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1024 auto *User = cast<Instruction>(*UI);
1025 Use &U = UI.getUse();
1026 ++UI;
1027
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001028 if (VisitedUsers.count(User) || CurLoop->contains(User))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001029 continue;
1030
1031 if (!DT->isReachableFromEntry(User->getParent())) {
Jun Bum Lim0f906722017-11-17 20:38:25 +00001032 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001033 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001034 continue;
1035 }
1036
1037 // The user must be a PHI node.
1038 PHINode *PN = cast<PHINode>(User);
1039
1040 // Surprisingly, instructions can be used outside of loops without any
1041 // exits. This can only happen in PHI nodes if the incoming block is
1042 // unreachable.
1043 BasicBlock *BB = PN->getIncomingBlock(U);
1044 if (!DT->isReachableFromEntry(BB)) {
1045 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001046 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001047 continue;
1048 }
1049
1050 VisitedUsers.insert(PN);
Alina Sbirlea0e155012018-07-02 18:53:40 +00001051 if (isTriviallyReplaceablePHI(*PN, I))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001052 continue;
1053
Jun Bum Lim144eb592018-02-12 17:56:55 +00001054 if (!canSplitPredecessors(PN, SafetyInfo))
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001055 return Changed;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001056
1057 // Split predecessors of the PHI so that we can make users trivially
Alina Sbirlea0e155012018-07-02 18:53:40 +00001058 // replaceable.
Jun Bum Lim144eb592018-02-12 17:56:55 +00001059 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001060
1061 // Should rebuild the iterators, as they may be invalidated by
1062 // splitPredecessorsOfLoopExit().
1063 UI = I.user_begin();
1064 UE = I.user_end();
1065 }
1066
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001067 if (VisitedUsers.empty())
1068 return Changed;
1069
Chandler Carruthfc258542014-02-11 12:52:27 +00001070#ifndef NDEBUG
1071 SmallVector<BasicBlock *, 32> ExitBlocks;
1072 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001073 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +00001074 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +00001075#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +00001076
Evgeniy Stepanov10280da2014-06-25 07:54:58 +00001077 // Clones of this instruction. Don't create more than one per exit block!
1078 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1079
Chandler Carruthfc258542014-02-11 12:52:27 +00001080 // If this instruction is only used outside of the loop, then all users are
1081 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1082 // the instruction.
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001083 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1084 for (auto *UI : Users) {
1085 auto *User = cast<Instruction>(UI);
1086
1087 if (CurLoop->contains(User))
1088 continue;
1089
1090 PHINode *PN = cast<PHINode>(User);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001091 assert(ExitBlockSet.count(PN->getParent()) &&
Chandler Carruthfc258542014-02-11 12:52:27 +00001092 "The LCSSA PHI is not in an exit block!");
Alina Sbirlea0e155012018-07-02 18:53:40 +00001093 // The PHI must be trivially replaceable.
1094 Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies,
1095 SafetyInfo, CurLoop);
Chandler Carruthfc258542014-02-11 12:52:27 +00001096 PN->replaceAllUsesWith(New);
1097 PN->eraseFromParent();
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001098 Changed = true;
Chris Lattnercd96b4d2010-08-29 04:28:20 +00001099 }
Hal Finkel3d4269a2015-02-22 18:35:32 +00001100 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +00001101}
Chris Lattner64437692002-09-29 21:46:09 +00001102
Hal Finkel3d4269a2015-02-22 18:35:32 +00001103/// When an instruction is found to only use loop invariant operands that
1104/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +00001105///
Max Kazantsev68290f82018-08-15 02:49:12 +00001106static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Max Kazantsev72d7d642018-08-16 08:30:15 +00001107 LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001108 auto *Preheader = CurLoop->getLoopPreheader();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001109 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1110 << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001111 ORE->emit([&]() {
1112 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1113 << ore::NV("Inst", &I);
1114 });
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001115
1116 // Metadata can be dependent on conditions we are hoisting above.
1117 // Conservatively strip all metadata on the instruction unless we were
1118 // guaranteed to execute I if we entered the loop, in which case the metadata
1119 // is valid in the loop preheader.
1120 if (I.hasMetadataOtherThanDebugLoc() &&
1121 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1122 // time in isGuaranteedToExecute if we don't actually have anything to
1123 // drop. It is a compile time optimization, not required for correctness.
1124 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1125 I.dropUnknownNonDebugMetadata();
1126
Chris Lattner6ac06592010-08-29 18:18:40 +00001127 // Move the new node to the Preheader, before its terminator.
1128 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001129
Wolfgang Piebc17a2792017-01-06 18:38:57 +00001130 // Do not retain debug locations when we are moving instructions to different
1131 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1132 // need to retain their debug locs because they may be inlined.
1133 // FIXME: How do we retain source locations without causing poor debugging
1134 // behavior?
1135 if (!isa<CallInst>(I))
1136 I.setDebugLoc(DebugLoc());
1137
Dehao Chend55bc4c2016-05-05 00:54:54 +00001138 if (isa<LoadInst>(I))
1139 ++NumMovedLoads;
1140 else if (isa<CallInst>(I))
1141 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +00001142 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +00001143}
1144
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00001145/// Only sink or hoist an instruction if it is not a trapping instruction,
1146/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001147/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001148static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +00001149 const DominatorTree *DT,
1150 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001151 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001152 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +00001153 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +00001154 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +00001155 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001156
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001157 bool GuaranteedToExecute =
1158 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1159
1160 if (!GuaranteedToExecute) {
1161 auto *LI = dyn_cast<LoadInst>(&Inst);
1162 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +00001163 ORE->emit([&]() {
1164 return OptimizationRemarkMissed(
1165 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1166 << "failed to hoist load with loop-invariant address "
1167 "because load is conditionally executed";
1168 });
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001169 }
1170
1171 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001172}
1173
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001174namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +00001175class LoopPromoter : public LoadAndStorePromoter {
1176 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001177 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001178 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1179 SmallVectorImpl<Instruction *> &LoopInsertPts;
1180 PredIteratorCache &PredCache;
1181 AliasSetTracker &AST;
1182 LoopInfo &LI;
1183 DebugLoc DL;
1184 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001185 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001186 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +00001187
Dehao Chend55bc4c2016-05-05 00:54:54 +00001188 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1189 if (Instruction *I = dyn_cast<Instruction>(V))
1190 if (Loop *L = LI.getLoopFor(I->getParent()))
1191 if (!L->contains(BB)) {
1192 // We need to create an LCSSA PHI node for the incoming value and
1193 // store that.
1194 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1195 I->getName() + ".lcssa", &BB->front());
1196 for (BasicBlock *Pred : PredCache.get(BB))
1197 PN->addIncoming(I, Pred);
1198 return PN;
1199 }
1200 return V;
1201 }
Chandler Carruthfc258542014-02-11 12:52:27 +00001202
Dehao Chend55bc4c2016-05-05 00:54:54 +00001203public:
1204 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001205 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001206 SmallVectorImpl<BasicBlock *> &LEB,
1207 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1208 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001209 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +00001210 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1211 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001212 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001213 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +00001214
Dehao Chend55bc4c2016-05-05 00:54:54 +00001215 bool isInstInList(Instruction *I,
1216 const SmallVectorImpl<Instruction *> &) const override {
1217 Value *Ptr;
1218 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1219 Ptr = LI->getOperand(0);
1220 else
1221 Ptr = cast<StoreInst>(I)->getPointerOperand();
1222 return PointerMustAliases.count(Ptr);
1223 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001224
Dehao Chend55bc4c2016-05-05 00:54:54 +00001225 void doExtraRewritesBeforeFinalDeletion() const override {
1226 // Insert stores after in the loop exit blocks. Each exit block gets a
1227 // store of the live-out values that feed them. Since we've already told
1228 // the SSA updater about the defs in the loop and the preheader
1229 // definition, it is all set and we can start using it.
1230 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1231 BasicBlock *ExitBlock = LoopExitBlocks[i];
1232 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1233 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1234 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1235 Instruction *InsertPos = LoopInsertPts[i];
1236 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001237 if (UnorderedAtomic)
1238 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001239 NewSI->setAlignment(Alignment);
1240 NewSI->setDebugLoc(DL);
1241 if (AATags)
1242 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001243 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001244 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001245
Dehao Chend55bc4c2016-05-05 00:54:54 +00001246 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1247 // Update alias analysis.
1248 AST.copyValue(LI, V);
1249 }
1250 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1251};
Philip Reames21cc2fa2017-10-26 21:00:15 +00001252
1253
1254/// Return true iff we can prove that a caller of this function can not inspect
1255/// the contents of the provided object in a well defined program.
1256bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1257 if (isa<AllocaInst>(Object))
1258 // Since the alloca goes out of scope, we know the caller can't retain a
1259 // reference to it and be well defined. Thus, we don't need to check for
Fangrui Songf78650a2018-07-30 19:41:25 +00001260 // capture.
Philip Reames21cc2fa2017-10-26 21:00:15 +00001261 return true;
Fangrui Songf78650a2018-07-30 19:41:25 +00001262
Philip Reames21cc2fa2017-10-26 21:00:15 +00001263 // For all other objects we need to know that the caller can't possibly
1264 // have gotten a reference to the object. There are two components of
1265 // that:
1266 // 1) Object can't be escaped by this function. This is what
1267 // PointerMayBeCaptured checks.
1268 // 2) Object can't have been captured at definition site. For this, we
1269 // need to know the return value is noalias. At the moment, we use a
1270 // weaker condition and handle only AllocLikeFunctions (which are
1271 // known to be noalias). TODO
1272 return isAllocLikeFn(Object, TLI) &&
1273 !PointerMayBeCaptured(Object, true, true);
1274}
1275
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001276} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001277
Hal Finkel3d4269a2015-02-22 18:35:32 +00001278/// Try to promote memory values to scalars by sinking stores out of the
1279/// loop and moving loads to before the loop. We do this by looping over
1280/// the stores in the loop, looking for stores to Must pointers which are
1281/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001282///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001283bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001284 const SmallSetVector<Value *, 8> &PointerMustAliases,
1285 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001286 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1287 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001288 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1289 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001290 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001291 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1292 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001293 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001294
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001295 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001296 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001297
Anna Thomas5ac72f92018-03-13 19:38:45 +00001298 // It is not safe to promote a load/store from the loop if the load/store is
Chris Lattner1dc98b42010-08-29 06:43:52 +00001299 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001300 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001301 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001302 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001303 // into:
1304 //
1305 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1306 //
1307 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001308 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001309 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001310 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001311 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001312 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001313 // path which did not originally have one.
1314 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001315 // If at least one store is guaranteed to execute, both properties are
1316 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001317 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001318 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001319 // guaranteed to execute, we can still establish these properties.
1320 // We can establish (p1) by proving that hoisting the load into the preheader
1321 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001322 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001323 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001324 //
1325 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001326 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001327 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001328 // b) Prove a store dominates every exit block. In this case, if an exit
1329 // blocks is reached, the original dynamic path would have taken us through
1330 // the store, so inserting a store into the exit block is safe. Note that this
1331 // is different from the store being guaranteed to execute. For instance,
1332 // if an exception is thrown on the first iteration of the loop, the original
1333 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001334
1335 bool DereferenceableInPH = false;
1336 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001337
Dehao Chend55bc4c2016-05-05 00:54:54 +00001338 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001339
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001340 // We start with an alignment of one and try to find instructions that allow
1341 // us to prove better alignment.
1342 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001343 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001344 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001345 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001346 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001347
Philip Reamesb54c8e62016-03-09 22:59:30 +00001348 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1349
Philip Reames21cc2fa2017-10-26 21:00:15 +00001350 bool IsKnownThreadLocalObject = false;
Max Kazantsev530b8d12018-08-15 05:55:43 +00001351 if (SafetyInfo->anyBlockMayThrow()) {
Eli Friedmanee895052016-06-05 22:13:52 +00001352 // If a loop can throw, we have to insert a store along each unwind edge.
1353 // That said, we can't actually make the unwind edge explicit. Therefore,
Philip Reames21cc2fa2017-10-26 21:00:15 +00001354 // we have to prove that the store is dead along the unwind edge. We do
1355 // this by proving that the caller can't have a reference to the object
Fangrui Songf78650a2018-07-30 19:41:25 +00001356 // after return and thus can't possibly load from the object.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001357 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Philip Reames21cc2fa2017-10-26 21:00:15 +00001358 if (!isKnownNonEscaping(Object, TLI))
1359 return false;
1360 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1361 // visible to other threads if captured and used during their lifetimes.
1362 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
Eli Friedmanee895052016-06-05 22:13:52 +00001363 }
1364
Chris Lattner1dc98b42010-08-29 06:43:52 +00001365 // Check that all of the pointers in the alias set have the same type. We
1366 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001367 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001368 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001369 // Check that all of the pointers in the alias set have the same type. We
1370 // cannot (yet) promote a memory location that is loaded and stored in
1371 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001372 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001373 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001374
Chandler Carruthcdf47882014-03-09 03:16:01 +00001375 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001376 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001377 Instruction *UI = dyn_cast<Instruction>(U);
1378 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001379 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001380
Chris Lattner1dc98b42010-08-29 06:43:52 +00001381 // If there is an non-load/store instruction in the loop, we can't promote
1382 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001383 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001384 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001385 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001386
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001387 SawUnorderedAtomic |= Load->isAtomic();
1388 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001389
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001390 if (!DereferenceableInPH)
1391 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001392 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001393 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001394 // Stores *of* the pointer are not interesting, only stores *to* the
1395 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001396 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001397 continue;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001398 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001399 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001400
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001401 SawUnorderedAtomic |= Store->isAtomic();
1402 SawNotAtomic |= !Store->isAtomic();
1403
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001404 // If the store is guaranteed to execute, both properties are satisfied.
1405 // We may want to check if a store is guaranteed to execute even if we
1406 // already know that promotion is safe, since it may have higher
1407 // alignment than any other guaranteed stores, in which case we can
1408 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001409 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001410 if (!InstAlignment)
1411 InstAlignment =
1412 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1413
1414 if (!DereferenceableInPH || !SafeToInsertStore ||
1415 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001416 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001417 DereferenceableInPH = true;
1418 SafeToInsertStore = true;
1419 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001420 }
Anna Thomas67151352016-06-24 12:38:45 +00001421 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001422
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001423 // If a store dominates all exit blocks, it is safe to sink.
1424 // As explained above, if an exit block was executed, a dominating
Fangrui Song956ee792018-03-30 22:22:31 +00001425 // store must have been executed at least once, so we are not
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001426 // introducing stores on paths that did not have them.
1427 // Note that this only looks at explicit exit blocks. If we ever
1428 // start sinking stores into unwind edges (see above), this will break.
1429 if (!SafeToInsertStore)
1430 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1431 return DT->dominates(Store->getParent(), Exit);
1432 });
1433
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001434 // If the store is not guaranteed to execute, we may still get
1435 // deref info through it.
1436 if (!DereferenceableInPH) {
1437 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001438 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001439 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001440 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001441 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001442 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001443
Hal Finkelcc39b672014-07-24 12:16:19 +00001444 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001445 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001446 // On the first load/store, just take its AA tags.
1447 UI->getAAMetadata(AATags);
1448 } else if (AATags) {
1449 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001450 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001451
1452 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001453 }
1454 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001455
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001456 // If we found both an unordered atomic instruction and a non-atomic memory
1457 // access, bail. We can't blindly promote non-atomic to atomic since we
1458 // might not be able to lower the result. We can't downgrade since that
1459 // would violate memory model. Also, align 0 is an error for atomics.
1460 if (SawUnorderedAtomic && SawNotAtomic)
1461 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001462
1463 // If we couldn't prove we can hoist the load, bail.
1464 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001465 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001466
1467 // We know we can hoist the load, but don't have a guaranteed store.
1468 // Check whether the location is thread-local. If it is, then we can insert
1469 // stores along paths which originally didn't have them without violating the
1470 // memory model.
1471 if (!SafeToInsertStore) {
Philip Reames21cc2fa2017-10-26 21:00:15 +00001472 if (IsKnownThreadLocalObject)
Xin Tong5ee40ba2017-01-19 19:31:40 +00001473 SafeToInsertStore = true;
1474 else {
1475 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1476 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001477 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1478 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001479 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001480 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001481
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001482 // If we've still failed to prove we can sink the store, give up.
1483 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001484 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001485
Chris Lattner1dc98b42010-08-29 06:43:52 +00001486 // Otherwise, this is safe to promote, lets do it!
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001487 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1488 << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +00001489 ORE->emit([&]() {
1490 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1491 LoopUses[0])
1492 << "Moving accesses to memory location out of the loop";
1493 });
Chris Lattner1dc98b42010-08-29 06:43:52 +00001494 ++NumPromoted;
1495
Eli Friedmanddf7f552011-05-27 20:31:51 +00001496 // Grab a debug location for the inserted loads/stores; given that the
1497 // inserted loads/stores have little relation to the original loads/stores,
1498 // this code just arbitrarily picks a location from one, since any debug
1499 // location is better than none.
1500 DebugLoc DL = LoopUses[0]->getDebugLoc();
1501
Chris Lattner1dc98b42010-08-29 06:43:52 +00001502 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001503 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001504 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001505 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001506 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1507 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001508
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001509 // Set up the preheader to have a definition of the value. It is the live-out
1510 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001511 LoadInst *PreheaderLoad = new LoadInst(
1512 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001513 if (SawUnorderedAtomic)
1514 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001515 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001516 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001517 if (AATags)
1518 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001519 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1520
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001521 // Rewrite all the loads in the loop and remember all the definitions from
1522 // stores in the loop.
1523 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001524
1525 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1526 if (PreheaderLoad->use_empty())
1527 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001528
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001529 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001530}
Devang Patelb98a0972007-07-31 08:01:41 +00001531
Roman Gareev036c0882016-02-15 14:48:50 +00001532/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001533/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001534/// FIXME: In new pass manager, there is no helper function to handle loop
1535/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001536/// from scratch for every loop. Hook up with the helper functions when
1537/// available in the new pass manager to avoid redundant computation.
Marcello Maggioni883fe452018-08-21 20:30:14 +00001538std::unique_ptr<AliasSetTracker>
Dehao Chen9cba1f42016-07-12 22:37:48 +00001539LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1540 AliasAnalysis *AA) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001541 std::unique_ptr<AliasSetTracker> CurAST;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001542 SmallVector<Loop *, 4> RecomputeLoops;
Marcello Maggioni883fe452018-08-21 20:30:14 +00001543 auto mergeLoop = [&CurAST](Loop *L) {
1544 // Loop over the body of this loop, looking for calls, invokes, and stores.
1545 for (BasicBlock *BB : L->blocks())
1546 CurAST->add(*BB); // Incorporate the specified basic block
1547 };
Roman Gareev036c0882016-02-15 14:48:50 +00001548 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001549 auto MapI = LoopToAliasSetMap.find(InnerL);
1550 // If the AST for this inner loop is missing it may have been merged into
1551 // some other loop's AST and then that loop unrolled, and so we need to
1552 // recompute it.
1553 if (MapI == LoopToAliasSetMap.end()) {
1554 RecomputeLoops.push_back(InnerL);
1555 continue;
1556 }
Marcello Maggioni883fe452018-08-21 20:30:14 +00001557 std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
Roman Gareev036c0882016-02-15 14:48:50 +00001558
Marcello Maggioni883fe452018-08-21 20:30:14 +00001559 if (CurAST) {
Roman Gareev036c0882016-02-15 14:48:50 +00001560 // What if InnerLoop was modified by other passes ?
Roman Gareev036c0882016-02-15 14:48:50 +00001561 // Once we've incorporated the inner loop's AST into ours, we don't need
1562 // the subloop's anymore.
Marcello Maggioni883fe452018-08-21 20:30:14 +00001563 CurAST->add(*InnerAST);
Roman Gareev036c0882016-02-15 14:48:50 +00001564 } else {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001565 CurAST = std::move(InnerAST);
Roman Gareev036c0882016-02-15 14:48:50 +00001566 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001567 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001568 }
Marcello Maggioni883fe452018-08-21 20:30:14 +00001569 if (!CurAST)
1570 CurAST = make_unique<AliasSetTracker>(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001571
1572 // Add everything from the sub loops that are no longer directly available.
1573 for (Loop *InnerL : RecomputeLoops)
1574 mergeLoop(InnerL);
1575
1576 // And merge in this loop.
1577 mergeLoop(L);
1578
Roman Gareev036c0882016-02-15 14:48:50 +00001579 return CurAST;
1580}
1581
Ashutosh Nema47802622015-08-13 11:18:35 +00001582/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001583///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001584void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1585 Loop *L) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001586 auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
1587 if (ASTIt == LICM.getLoopToAliasSetMap().end())
Devang Patelb98a0972007-07-31 08:01:41 +00001588 return;
1589
Marcello Maggioni883fe452018-08-21 20:30:14 +00001590 ASTIt->second->copyValue(From, To);
Devang Patelb98a0972007-07-31 08:01:41 +00001591}
1592
Hal Finkel3d4269a2015-02-22 18:35:32 +00001593/// Simple Analysis hook. Delete value V from alias set
1594///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001595void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001596 auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
1597 if (ASTIt == LICM.getLoopToAliasSetMap().end())
Devang Patelb98a0972007-07-31 08:01:41 +00001598 return;
1599
Marcello Maggioni883fe452018-08-21 20:30:14 +00001600 ASTIt->second->deleteValue(V);
Devang Patelb98a0972007-07-31 08:01:41 +00001601}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001602
1603/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001604///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001605void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001606 if (!LICM.getLoopToAliasSetMap().count(L))
David Peixotto0d4d5e62014-09-24 16:48:31 +00001607 return;
1608
Dehao Chen9cba1f42016-07-12 22:37:48 +00001609 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001610}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001611
Anna Thomas19626212018-08-17 13:44:00 +00001612static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
1613 AliasSetTracker *CurAST, Loop *CurLoop,
1614 AliasAnalysis *AA) {
1615 // First check to see if any of the basic blocks in CurLoop invalidate *V.
1616 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
1617
1618 if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
1619 return isInvalidatedAccordingToAST;
1620
1621 // Check with a diagnostic analysis if we can refine the information above.
1622 // This is to identify the limitations of using the AST.
1623 // The alias set mechanism used by LICM has a major weakness in that it
1624 // combines all things which may alias into a single set *before* asking
1625 // modref questions. As a result, a single readonly call within a loop will
1626 // collapse all loads and stores into a single alias set and report
1627 // invalidation if the loop contains any store. For example, readonly calls
1628 // with deopt states have this form and create a general alias set with all
1629 // loads and stores. In order to get any LICM in loops containing possible
1630 // deopt states we need a more precise invalidation of checking the mod ref
1631 // info of each instruction within the loop and LI. This has a complexity of
1632 // O(N^2), so currently, it is used only as a diagnostic tool since the
1633 // default value of LICMN2Threshold is zero.
1634
1635 // Don't look at nested loops.
1636 if (CurLoop->begin() != CurLoop->end())
1637 return true;
1638
1639 int N = 0;
1640 for (BasicBlock *BB : CurLoop->getBlocks())
1641 for (Instruction &I : *BB) {
1642 if (N >= LICMN2Theshold) {
1643 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "
1644 << *(MemLoc.Ptr) << "\n");
1645 return true;
1646 }
1647 N++;
1648 auto Res = AA->getModRefInfo(&I, MemLoc);
1649 if (isModSet(Res)) {
1650 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "
1651 << *(MemLoc.Ptr) << "\n");
1652 return true;
1653 }
1654 }
1655 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n");
1656 return false;
Hal Finkel3d4269a2015-02-22 18:35:32 +00001657}
1658
1659/// Little predicate that returns true if the specified basic block is in
1660/// a subloop of the current one, not the current one itself.
1661///
1662static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1663 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1664 return LI->getLoopFor(BB) != CurLoop;
1665}