blob: 6c8992895935ea9ad5aef3f2046be48aa01a906f [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"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000041#include "llvm/Analysis/GuardUtils.h"
Philip Reamese0a54542016-03-09 23:07:53 +000042#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000043#include "llvm/Analysis/LoopInfo.h"
44#include "llvm/Analysis/LoopPass.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000045#include "llvm/Analysis/MemoryBuiltins.h"
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +000046#include "llvm/Analysis/MemorySSA.h"
Adam Nemet0965da22017-10-09 23:19:02 +000047#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000051#include "llvm/Transforms/Utils/Local.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000052#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000053#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/Constants.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Instructions.h"
59#include "llvm/IR/IntrinsicInst.h"
60#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000061#include "llvm/IR/Metadata.h"
Max Kazantsev097ef692018-08-21 08:11:31 +000062#include "llvm/IR/PatternMatch.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000063#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000064#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000067#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000068#include "llvm/Transforms/Scalar/LoopPassManager.h"
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000069#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000070#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000071#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000072#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000073#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000074using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000075
Chandler Carruth964daaa2014-04-22 02:55:47 +000076#define DEBUG_TYPE "licm"
77
Dehao Chend55bc4c2016-05-05 00:54:54 +000078STATISTIC(NumSunk, "Number of instructions sunk out of loop");
79STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000080STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
81STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000082STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000083
Xin Tongccee0e02017-02-21 20:53:48 +000084/// Memory promotion is enabled by default.
Dan Gohmand78c4002008-05-13 00:00:25 +000085static cl::opt<bool>
Xin Tongccee0e02017-02-21 20:53:48 +000086 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
Dehao Chend55bc4c2016-05-05 00:54:54 +000087 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000088
Anna Thomas7f4b26e2017-02-02 13:22:03 +000089static cl::opt<uint32_t> MaxNumUsesTraversed(
90 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
91 cl::desc("Max num uses visited for identifying load "
92 "invariance in loop using invariant start (default = 8)"));
93
Anna Thomas19626212018-08-17 13:44:00 +000094// Default value of zero implies we use the regular alias set tracker mechanism
95// instead of the cross product using AA to identify aliasing of the memory
96// location we are interested in.
97static cl::opt<int>
98LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
99 cl::desc("How many instruction to cross product using AA"));
100
Hal Finkel3d4269a2015-02-22 18:35:32 +0000101static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000102static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
103 const LoopSafetyInfo *SafetyInfo,
104 TargetTransformInfo *TTI, bool &FreeInLoop);
Max Kazantsev68290f82018-08-15 02:49:12 +0000105static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Max Kazantsev72d7d642018-08-16 08:30:15 +0000106 LoopSafetyInfo *SafetyInfo,
Adam Nemet358433c2017-01-11 04:39:35 +0000107 OptimizationRemarkEmitter *ORE);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000108static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000109 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000110 OptimizationRemarkEmitter *ORE, bool FreeInLoop);
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000111static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000112 const DominatorTree *DT,
113 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000114 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000115 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000116 const Instruction *CtxI = nullptr);
Anna Thomas19626212018-08-17 13:44:00 +0000117static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
118 AliasSetTracker *CurAST, Loop *CurLoop,
119 AliasAnalysis *AA);
120
David Majnemer42a07302016-01-04 03:37:39 +0000121static Instruction *
122CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
123 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000124 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000125
Dan Gohmand78c4002008-05-13 00:00:25 +0000126namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000127struct LoopInvariantCodeMotion {
Marcello Maggioni883fe452018-08-21 20:30:14 +0000128 using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000129 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000130 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
131 ScalarEvolution *SE, MemorySSA *MSSA,
Adam Nemet358433c2017-01-11 04:39:35 +0000132 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000133
Marcello Maggioni883fe452018-08-21 20:30:14 +0000134 ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
Dehao Chen7ef58202016-07-11 22:45:24 +0000135
Dehao Chen9cba1f42016-07-12 22:37:48 +0000136private:
Marcello Maggioni883fe452018-08-21 20:30:14 +0000137 ASTrackerMapTy LoopToAliasSetMap;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000138
Marcello Maggioni883fe452018-08-21 20:30:14 +0000139 std::unique_ptr<AliasSetTracker>
140 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000141};
142
143struct LegacyLICMPass : public LoopPass {
144 static char ID; // Pass identification, replacement for typeid
145 LegacyLICMPass() : LoopPass(ID) {
146 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
147 }
148
149 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000150 if (skipLoop(L)) {
151 // If we have run LICM on a previous loop but now we are skipping
152 // (because we've hit the opt-bisect limit), we need to clear the
153 // loop alias information.
154 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000155 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000156 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000157
158 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000159 MemorySSA *MSSA = EnableMSSALoopDependency
160 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
161 : nullptr;
Adam Nemet358433c2017-01-11 04:39:35 +0000162 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
163 // pass. Function analyses need to be preserved across loop transformations
164 // but ORE cannot be preserved (see comment before the pass definition).
165 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000166 return LICM.runOnLoop(L,
167 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
168 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
169 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
170 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000171 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
172 *L->getHeader()->getParent()),
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000173 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000174 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000175
Dehao Chend55bc4c2016-05-05 00:54:54 +0000176 /// This transformation requires natural loop information & requires that
177 /// loop preheaders be inserted into the CFG...
178 ///
179 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000180 AU.addPreserved<DominatorTreeWrapperPass>();
181 AU.addPreserved<LoopInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000182 AU.addRequired<TargetLibraryInfoWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000183 if (EnableMSSALoopDependency)
184 AU.addRequired<MemorySSAWrapperPass>();
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000185 AU.addRequired<TargetTransformInfoWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000186 getLoopAnalysisUsage(AU);
187 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000188
Dehao Chend55bc4c2016-05-05 00:54:54 +0000189 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000190
Dehao Chend55bc4c2016-05-05 00:54:54 +0000191 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000192 assert(LICM.getLoopToAliasSetMap().empty() &&
193 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000194 return false;
195 }
Devang Patel69730c92007-03-07 04:41:30 +0000196
Dehao Chend55bc4c2016-05-05 00:54:54 +0000197private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000198 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000199
Dehao Chend55bc4c2016-05-05 00:54:54 +0000200 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
201 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
202 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000203
Dehao Chend55bc4c2016-05-05 00:54:54 +0000204 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
205 /// set.
206 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000207
Dehao Chend55bc4c2016-05-05 00:54:54 +0000208 /// Simple Analysis hook. Delete loop L from alias set map.
209 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000210};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000211} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000212
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000213PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
214 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000215 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000216 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000217 Function *F = L.getHeader()->getParent();
218
Adam Nemet358433c2017-01-11 04:39:35 +0000219 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000220 // FIXME: This should probably be optional rather than required.
221 if (!ORE)
222 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
223 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000224
225 LoopInvariantCodeMotion LICM;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000226 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
227 AR.MSSA, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000228 return PreservedAnalyses::all();
229
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000230 auto PA = getLoopPassPreservedAnalyses();
Jun Bum Limdfbe6fa2018-05-24 15:58:34 +0000231
232 PA.preserve<DominatorTreeAnalysis>();
233 PA.preserve<LoopAnalysis>();
234
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000235 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000236}
237
238char LegacyLICMPass::ID = 0;
239INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
240 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000241INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000242INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000243INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000244INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000245INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
246 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000247
Dehao Chen9cba1f42016-07-12 22:37:48 +0000248Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000249
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000250/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000251/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000252/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000253/// We should delete AST for inner loops in the new pass manager to avoid
254/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000255///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000256bool LoopInvariantCodeMotion::runOnLoop(
257 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
258 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
259 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000260 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000261
Chandler Carruthfc258542014-02-11 12:52:27 +0000262 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
263
Marcello Maggioni883fe452018-08-21 20:30:14 +0000264 std::unique_ptr<AliasSetTracker> CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000265
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000266 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000267 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000268
Hal Finkel3d4269a2015-02-22 18:35:32 +0000269 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000270 LoopSafetyInfo SafetyInfo;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000271 SafetyInfo.computeLoopSafetyInfo(L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000272
Chris Lattner6ec05f52002-05-10 22:44:58 +0000273 // We want to visit all of the instructions in this loop... that are not parts
274 // of our subloops (they have already had their invariants hoisted out of
275 // their loop, into this loop, so there is no need to process the BODIES of
276 // the subloops).
277 //
Chris Lattner64437692002-09-29 21:46:09 +0000278 // Traverse the body of the loop in depth first order on the dominator tree so
279 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000280 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000281 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000282 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000283 if (L->hasDedicatedExits())
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000284 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
Marcello Maggioni883fe452018-08-21 20:30:14 +0000285 CurAST.get(), &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000286 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000287 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Marcello Maggioni883fe452018-08-21 20:30:14 +0000288 CurAST.get(), &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000289
Chris Lattner45d67d62003-02-24 03:52:32 +0000290 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000291 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000292 // Don't sink stores from loops without dedicated block exits. Exits
293 // containing indirect branches are not transformed by loop simplify,
294 // make sure we catch that. An additional load may be generated in the
295 // preheader for SSA updater, so also avoid sinking when no preheader
296 // is available.
297 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000298 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000299 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000300 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000301
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000302 // We can't insert into a catchswitch.
303 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
304 return isa<CatchSwitchInst>(Exit->getTerminator());
305 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000306
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000307 if (!HasCatchSwitch) {
308 SmallVector<Instruction *, 8> InsertPts;
309 InsertPts.reserve(ExitBlocks.size());
310 for (BasicBlock *ExitBlock : ExitBlocks)
311 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000312
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000313 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000314
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000315 bool Promoted = false;
316
317 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000318 for (AliasSet &AS : *CurAST) {
319 // We can promote this alias set if it has a store, if it is a "Must"
320 // alias set, if the pointer is loop invariant, and if we are not
321 // eliminating any volatile loads or stores.
322 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
Philip Reamesc3c23e82018-08-21 17:59:11 +0000323 !L->isLoopInvariant(AS.begin()->getValue()))
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000324 continue;
325
326 assert(
327 !AS.empty() &&
328 "Must alias set should have at least one pointer element in it!");
329
330 SmallSetVector<Value *, 8> PointerMustAliases;
331 for (const auto &ASI : AS)
332 PointerMustAliases.insert(ASI.getValue());
333
Marcello Maggioni883fe452018-08-21 20:30:14 +0000334 Promoted |= promoteLoopAccessesToScalars(
335 PointerMustAliases, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L,
336 CurAST.get(), &SafetyInfo, ORE);
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000337 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000338
339 // Once we have promoted values across the loop body we have to
340 // recursively reform LCSSA as any nested loop may now have values defined
341 // within the loop used in the outer loop.
342 // FIXME: This is really heavy handed. It would be a bit better to use an
343 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
344 // it as it went.
345 if (Promoted)
346 formLCSSARecursively(*L, *DT, LI, SE);
347
348 Changed |= Promoted;
349 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000350 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000351
Chandler Carruthfc258542014-02-11 12:52:27 +0000352 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
353 // specifically moving instructions across the loop boundary and so it is
354 // especially in need of sanity checking here.
355 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
356 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
357 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000358
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000359 // If this loop is nested inside of another one, save the alias information
360 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000361 if (L->getParentLoop() && !DeleteAST)
Marcello Maggioni883fe452018-08-21 20:30:14 +0000362 LoopToAliasSetMap[L] = std::move(CurAST);
Sanjoy Das4ae39202016-05-03 17:50:11 +0000363
Dehao Chen9cba1f42016-07-12 22:37:48 +0000364 if (Changed && SE)
365 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000366 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000367}
368
Hal Finkel3d4269a2015-02-22 18:35:32 +0000369/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000370/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000371/// first order w.r.t the DominatorTree. This allows us to visit uses before
372/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000373///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000374bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000375 DominatorTree *DT, TargetLibraryInfo *TLI,
376 TargetTransformInfo *TTI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000377 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
378 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000379
Hal Finkel3d4269a2015-02-22 18:35:32 +0000380 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000381 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
Marcello Maggioni883fe452018-08-21 20:30:14 +0000382 CurLoop != nullptr && CurAST && SafetyInfo != nullptr &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000383 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000384
David Majnemere6bb8952017-07-20 03:27:02 +0000385 // We want to visit children before parents. We will enque all the parents
386 // before their children in the worklist and process the worklist in reverse
387 // order.
388 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000389
Sanjay Patel99133222016-01-13 23:01:57 +0000390 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000391 for (DomTreeNode *DTN : reverse(Worklist)) {
392 BasicBlock *BB = DTN->getBlock();
393 // Only need to process the contents of this block if it is not part of a
394 // subloop (which would already have been processed).
395 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000396 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000397
David Majnemere6bb8952017-07-20 03:27:02 +0000398 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
399 Instruction &I = *--II;
400
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000401 // If the instruction is dead, we would try to sink it because it isn't
402 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000403 if (isInstructionTriviallyDead(&I, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000404 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Anastasis Grammenos3a589102018-03-18 15:59:19 +0000405 salvageDebugInfo(I);
David Majnemere6bb8952017-07-20 03:27:02 +0000406 ++II;
407 CurAST->deleteValue(&I);
408 I.eraseFromParent();
409 Changed = true;
410 continue;
411 }
412
413 // Check to see if we can sink this instruction to the exit blocks
414 // of the loop. We can do this if the all users of the instruction are
415 // outside of the loop. In this case, it doesn't even matter if the
416 // operands of the instruction are loop invariant.
417 //
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000418 bool FreeInLoop = false;
419 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
Philip Reamesf562fc82018-08-29 21:49:30 +0000420 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
421 !I.mayHaveSideEffects()) {
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000422 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
423 if (!FreeInLoop) {
424 ++II;
425 CurAST->deleteValue(&I);
426 I.eraseFromParent();
427 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000428 Changed = true;
429 }
David Majnemere6bb8952017-07-20 03:27:02 +0000430 }
Chris Lattner91846012003-12-19 08:18:16 +0000431 }
Chris Lattner547192d62003-12-19 07:22:45 +0000432 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000433 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000434}
435
Hal Finkel3d4269a2015-02-22 18:35:32 +0000436/// Walk the specified region of the CFG (defined by all blocks dominated by
437/// the specified block, and that are in the current loop) in depth first
438/// order w.r.t the DominatorTree. This allows us to visit definitions before
439/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000440///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
442 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000443 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
444 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000445 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000446 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
447 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
448 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000449
David Majnemere6bb8952017-07-20 03:27:02 +0000450 // We want to visit parents before children. We will enque all the parents
451 // before their children in the worklist and process the worklist in order.
452 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000453
Sanjay Patel99133222016-01-13 23:01:57 +0000454 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000455 for (DomTreeNode *DTN : Worklist) {
456 BasicBlock *BB = DTN->getBlock();
457 // Only need to process the contents of this block if it is not part of a
458 // subloop (which would already have been processed).
Philip Reames5a648242018-04-27 20:58:30 +0000459 if (inSubLoop(BB, CurLoop, LI))
460 continue;
David Majnemere6bb8952017-07-20 03:27:02 +0000461
Philip Reames5b39acd2018-05-04 21:35:00 +0000462 // Keep track of whether the prefix of instructions visited so far are such
463 // that the next instruction visited is guaranteed to execute if the loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000464 // is entered.
Philip Reames5b39acd2018-05-04 21:35:00 +0000465 bool IsMustExecute = CurLoop->getHeader() == BB;
Max Kazantsev097ef692018-08-21 08:11:31 +0000466 // Keep track of whether the prefix instructions could have written memory.
467 // TODO: This and IsMustExecute may be done smarter if we keep track of all
468 // throwing and mem-writing operations in every block, e.g. using something
469 // similar to isGuaranteedToExecute.
470 bool IsMemoryNotModified = CurLoop->getHeader() == BB;
Philip Reames5b39acd2018-05-04 21:35:00 +0000471
Philip Reames5a648242018-04-27 20:58:30 +0000472 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
473 Instruction &I = *II++;
474 // Try constant folding this instruction. If all the operands are
475 // constants, it is technically hoistable, but it would be better to
476 // just fold it.
477 if (Constant *C = ConstantFoldInstruction(
478 &I, I.getModule()->getDataLayout(), TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000479 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C
480 << '\n');
Philip Reames5a648242018-04-27 20:58:30 +0000481 CurAST->copyValue(&I, C);
482 I.replaceAllUsesWith(C);
483 if (isInstructionTriviallyDead(&I, TLI)) {
484 CurAST->deleteValue(&I);
David Majnemere6bb8952017-07-20 03:27:02 +0000485 I.eraseFromParent();
David Majnemere6bb8952017-07-20 03:27:02 +0000486 }
Philip Reames5a648242018-04-27 20:58:30 +0000487 Changed = true;
488 continue;
Chris Lattner030f0202010-08-31 23:00:16 +0000489 }
Philip Reames5a648242018-04-27 20:58:30 +0000490
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000491 // Try hoisting the instruction out to the preheader. We can only do
492 // this if all of the operands of the instruction are loop invariant and
493 // if it is safe to hoist the instruction.
494 //
495 if (CurLoop->hasLoopInvariantOperands(&I) &&
Philip Reames32cb80b2018-08-02 04:08:04 +0000496 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000497 (IsMustExecute ||
498 isSafeToExecuteUnconditionally(
499 I, DT, CurLoop, SafetyInfo, ORE,
500 CurLoop->getLoopPreheader()->getTerminator()))) {
Max Kazantsev68290f82018-08-15 02:49:12 +0000501 hoist(I, DT, CurLoop, SafetyInfo, ORE);
502 Changed = true;
Stanislav Mekhanoshind8c93742018-06-23 04:01:28 +0000503 continue;
504 }
505
Philip Reames5a648242018-04-27 20:58:30 +0000506 // Attempt to remove floating point division out of the loop by
507 // converting it to a reciprocal multiplication.
508 if (I.getOpcode() == Instruction::FDiv &&
509 CurLoop->isLoopInvariant(I.getOperand(1)) &&
510 I.hasAllowReciprocal()) {
511 auto Divisor = I.getOperand(1);
512 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
513 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
514 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
515 ReciprocalDivisor->insertBefore(&I);
516
517 auto Product =
518 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
519 Product->setFastMathFlags(I.getFastMathFlags());
520 Product->insertAfter(&I);
521 I.replaceAllUsesWith(Product);
522 I.eraseFromParent();
523
524 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
525 Changed = true;
526 continue;
527 }
528
Max Kazantsev097ef692018-08-21 08:11:31 +0000529 using namespace PatternMatch;
Philip Reames9ec15fa2018-08-24 16:24:48 +0000530 if (((I.use_empty() &&
531 match(&I, m_Intrinsic<Intrinsic::invariant_start>())) ||
Max Kazantsev3c284bd2018-08-30 03:39:16 +0000532 isGuard(&I)) &&
Max Kazantsev097ef692018-08-21 08:11:31 +0000533 IsMustExecute && IsMemoryNotModified &&
534 CurLoop->hasLoopInvariantOperands(&I)) {
535 hoist(I, DT, CurLoop, SafetyInfo, ORE);
536 Changed = true;
537 continue;
538 }
539
Philip Reames5b39acd2018-05-04 21:35:00 +0000540 if (IsMustExecute)
541 IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I);
Max Kazantsev097ef692018-08-21 08:11:31 +0000542 if (IsMemoryNotModified)
543 IsMemoryNotModified = !I.mayWriteToMemory();
Philip Reames5a648242018-04-27 20:58:30 +0000544 }
David Majnemere6bb8952017-07-20 03:27:02 +0000545 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000546
Hal Finkel3d4269a2015-02-22 18:35:32 +0000547 return Changed;
548}
549
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000550// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000551// CurLoop is dominated by an invariant.start representing the same memory
552// location and size as the memory location LI loads from, and also the
553// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000554static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
555 Loop *CurLoop) {
556 Value *Addr = LI->getOperand(0);
557 const DataLayout &DL = LI->getModule()->getDataLayout();
558 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
559 cast<PointerType>(Addr->getType())->getElementType());
560
561 // if the type is i8 addrspace(x)*, we know this is the type of
562 // llvm.invariant.start operand
563 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
564 LI->getPointerAddressSpace());
565 unsigned BitcastsVisited = 0;
566 // Look through bitcasts until we reach the i8* type (this is invariant.start
567 // operand type).
568 while (Addr->getType() != PtrInt8Ty) {
569 auto *BC = dyn_cast<BitCastInst>(Addr);
570 // Avoid traversing high number of bitcast uses.
571 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
572 return false;
573 Addr = BC->getOperand(0);
574 }
575
576 unsigned UsesVisited = 0;
577 // Traverse all uses of the load operand value, to see if invariant.start is
578 // one of the uses, and whether it dominates the load instruction.
579 for (auto *U : Addr->users()) {
580 // Avoid traversing for Load operand with high number of users.
581 if (++UsesVisited > MaxNumUsesTraversed)
582 return false;
583 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
584 // If there are escaping uses of invariant.start instruction, the load maybe
585 // non-invariant.
586 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000587 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000588 continue;
589 unsigned InvariantSizeInBits =
590 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
591 // Confirm the invariant.start location size contains the load operand size
592 // in bits. Also, the invariant.start should dominate the load, and we
593 // should not hoist the load out of a loop that contains this dominating
594 // invariant.start.
595 if (LocSizeInBits <= InvariantSizeInBits &&
596 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
597 return true;
598 }
599
600 return false;
601}
602
Philip Reames09de4702018-08-02 00:54:14 +0000603namespace {
604/// Return true if-and-only-if we know how to (mechanically) both hoist and
605/// sink a given instruction out of a loop. Does not address legality
606/// concerns such as aliasing or speculation safety.
607bool isHoistableAndSinkableInst(Instruction &I) {
608 // Only these instructions are hoistable/sinkable.
Philip Reamesf562fc82018-08-29 21:49:30 +0000609 return (isa<LoadInst>(I) || isa<StoreInst>(I) ||
610 isa<CallInst>(I) || isa<FenceInst>(I) ||
Philip Reames09de4702018-08-02 00:54:14 +0000611 isa<BinaryOperator>(I) || isa<CastInst>(I) ||
612 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) ||
613 isa<CmpInst>(I) || isa<InsertElementInst>(I) ||
614 isa<ExtractElementInst>(I) || isa<ShuffleVectorInst>(I) ||
615 isa<ExtractValueInst>(I) || isa<InsertValueInst>(I));
616}
Philip Reames3b35aaa2018-08-06 22:07:37 +0000617/// Return true if all of the alias sets within this AST are known not to
618/// contain a Mod.
619bool isReadOnly(AliasSetTracker *CurAST) {
620 for (AliasSet &AS : *CurAST) {
621 if (!AS.isForwardingAliasSet() && AS.isMod()) {
622 return false;
623 }
624 }
625 return true;
626}
Philip Reames09de4702018-08-02 00:54:14 +0000627}
628
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000629bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
630 Loop *CurLoop, AliasSetTracker *CurAST,
Philip Reames32cb80b2018-08-02 04:08:04 +0000631 bool TargetExecutesOncePerLoop,
Adam Nemet81941b32017-01-11 04:39:45 +0000632 OptimizationRemarkEmitter *ORE) {
Philip Reames09de4702018-08-02 00:54:14 +0000633 // If we don't understand the instruction, bail early.
634 if (!isHoistableAndSinkableInst(I))
635 return false;
636
Chris Lattner65c11932003-12-09 19:32:44 +0000637 // Loads have extra constraints we have to verify before we can hoist them.
638 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000639 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000640 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000641
Chris Lattner8a8fb902008-07-23 05:06:28 +0000642 // Loads from constant memory are always safe to move, even if they end up
643 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000644 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000645 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000646 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000647 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000648
Philip Reames32cb80b2018-08-02 04:08:04 +0000649 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
650 return false; // Don't risk duplicating unordered loads
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000651
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000652 // This checks for an invariant.start dominating the load.
653 if (isLoadInvariantInLoop(LI, DT, CurLoop))
654 return true;
655
Philip Reames1f52e382018-09-11 03:28:28 +0000656 bool Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI),
657 CurAST, CurLoop, AA);
Adam Nemet81941b32017-01-11 04:39:45 +0000658 // Check loop-invariant address because this may also be a sinkable load
659 // whose address is not necessarily loop-invariant.
660 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +0000661 ORE->emit([&]() {
662 return OptimizationRemarkMissed(
663 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
664 << "failed to move load with loop-invariant address "
665 "because the loop may invalidate its value";
666 });
Adam Nemet81941b32017-01-11 04:39:45 +0000667
668 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000669 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000670 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000671 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000672 return false;
673
David Majnemer42a07302016-01-04 03:37:39 +0000674 // Don't sink calls which can throw.
675 if (CI->mayThrow())
676 return false;
677
Philip Reames1c0fde62018-08-24 19:13:39 +0000678 using namespace PatternMatch;
679 if (match(CI, m_Intrinsic<Intrinsic::assume>()))
680 // Assumes don't actually alias anything or throw
681 return true;
Philip Reames85afd1a2018-08-10 22:21:56 +0000682
Eli Friedman942e1c12011-05-27 18:37:52 +0000683 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000684 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
685 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000686 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000687 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000688 // A readonly argmemonly function only reads from memory pointed to by
689 // it's arguments with arbitrary offsets. If we can prove there are no
690 // writes to this memory in the loop, we can hoist or sink.
691 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
Philip Reamesf562fc82018-08-29 21:49:30 +0000692 // TODO: expand to writeable arguments
Philip Reames5f994232015-09-21 22:27:59 +0000693 for (Value *Op : CI->arg_operands())
694 if (Op->getType()->isPointerTy() &&
Anna Thomas19626212018-08-17 13:44:00 +0000695 pointerInvalidatedByLoop(
George Burgess IV6ef80022018-10-10 21:28:44 +0000696 MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()),
Anna Thomas19626212018-08-17 13:44:00 +0000697 CurAST, CurLoop, AA))
Philip Reames5f994232015-09-21 22:27:59 +0000698 return false;
699 return true;
700 }
Philip Reames3b35aaa2018-08-06 22:07:37 +0000701
Duncan Sands68b6f502007-12-01 07:51:45 +0000702 // If this call only reads from memory and there are no writes to memory
703 // in the loop, we can hoist or sink the call as appropriate.
Philip Reames3b35aaa2018-08-06 22:07:37 +0000704 if (isReadOnly(CurAST))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000705 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000706 }
707
Nadav Rotem03dcd852012-09-04 10:25:04 +0000708 // FIXME: This should use mod/ref information to see if we can hoist or
709 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000710
Chris Lattner20cda262004-03-15 04:11:30 +0000711 return false;
Philip Reamesca256d92018-08-09 20:18:42 +0000712 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
713 // Fences alias (most) everything to provide ordering. For the moment,
714 // just give up if there are any other memory operations in the loop.
715 auto Begin = CurAST->begin();
716 assert(Begin != CurAST->end() && "must contain FI");
717 if (std::next(Begin) != CurAST->end())
718 // constant memory for instance, TODO: handle better
719 return false;
720 auto *UniqueI = Begin->getUniqueInstruction();
721 if (!UniqueI)
722 // other memory op, give up
723 return false;
Philip Reames7d794332018-08-09 21:15:33 +0000724 (void)FI; //suppress unused variable warning
Philip Reamesca256d92018-08-09 20:18:42 +0000725 assert(UniqueI == FI && "AS must contain FI");
726 return true;
Philip Reamesf562fc82018-08-29 21:49:30 +0000727 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
728 if (!SI->isUnordered())
729 return false; // Don't sink/hoist volatile or ordered atomic store!
730
731 // We can only hoist a store that we can prove writes a value which is not
732 // read or overwritten within the loop. For those cases, we fallback to
Philip Reames1887c402018-08-29 22:09:21 +0000733 // load store promotion instead. TODO: We can extend this to cases where
734 // there is exactly one write to the location and that write dominates an
735 // arbitrary number of reads in the loop.
Philip Reamesf562fc82018-08-29 21:49:30 +0000736 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
737
738 if (AS.isRef() || !AS.isMustAlias())
739 // Quick exit test, handled by the full path below as well.
740 return false;
741 auto *UniqueI = AS.getUniqueInstruction();
742 if (!UniqueI)
743 // other memory op, give up
744 return false;
745 assert(UniqueI == SI && "AS must contain SI");
746 return true;
Chris Lattner65c11932003-12-09 19:32:44 +0000747 }
748
Philip Reames22b20a02018-08-09 03:44:28 +0000749 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
750
Philip Reames32cb80b2018-08-02 04:08:04 +0000751 // We've established mechanical ability and aliasing, it's up to the caller
752 // to check fault safety
753 return true;
Chris Lattneraaaea512003-12-10 06:41:05 +0000754}
755
Hal Finkel3d4269a2015-02-22 18:35:32 +0000756/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000757/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000758/// This is true when all incoming values are that instruction.
759/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000760///
Alina Sbirlea0e155012018-07-02 18:53:40 +0000761static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000762 for (const Value *IncValue : PN.incoming_values())
763 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000764 return false;
765
766 return true;
767}
768
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000769/// Return true if the instruction is free in the loop.
770static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
771 const TargetTransformInfo *TTI) {
772
773 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
774 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
775 return false;
776 // For a GEP, we cannot simply use getUserCost because currently it
777 // optimistically assume that a GEP will fold into addressing mode
778 // regardless of its users.
779 const BasicBlock *BB = GEP->getParent();
780 for (const User *U : GEP->users()) {
781 const Instruction *UI = cast<Instruction>(U);
782 if (CurLoop->contains(UI) &&
783 (BB != UI->getParent() ||
784 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
785 return false;
786 }
787 return true;
788 } else
789 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
790}
791
Hal Finkel3d4269a2015-02-22 18:35:32 +0000792/// Return true if the only users of this instruction are outside of
793/// the loop. If this is true, we can sink the instruction to the exit
794/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000795///
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000796/// We also return true if the instruction could be folded away in lowering.
797/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
798static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
799 const LoopSafetyInfo *SafetyInfo,
800 TargetTransformInfo *TTI, bool &FreeInLoop) {
Max Kazantsev8d56be72018-10-16 08:07:14 +0000801 const auto &BlockColors = SafetyInfo->getBlockColors();
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000802 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
Pete Cooper0cabcf22015-05-13 01:12:18 +0000803 for (const User *U : I.users()) {
804 const Instruction *UI = cast<Instruction>(U);
805 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000806 const BasicBlock *BB = PN->getParent();
807 // We cannot sink uses in catchswitches.
808 if (isa<CatchSwitchInst>(BB->getTerminator()))
809 return false;
810
811 // We need to sink a callsite to a unique funclet. Avoid sinking if the
812 // phi use is too muddled.
813 if (isa<CallInst>(I))
814 if (!BlockColors.empty() &&
815 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
816 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000817 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000818
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000819 if (CurLoop->contains(UI)) {
820 if (IsFree) {
821 FreeInLoop = true;
822 continue;
823 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000824 return false;
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000825 }
Chris Lattner34399dd2003-12-11 22:23:32 +0000826 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000827 return true;
828}
829
David Majnemer42a07302016-01-04 03:37:39 +0000830static Instruction *
831CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
832 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000833 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000834 Instruction *New;
835 if (auto *CI = dyn_cast<CallInst>(&I)) {
Max Kazantsev8d56be72018-10-16 08:07:14 +0000836 const auto &BlockColors = SafetyInfo->getBlockColors();
David Majnemer42a07302016-01-04 03:37:39 +0000837
838 // Sinking call-sites need to be handled differently from other
839 // instructions. The cloned call-site needs a funclet bundle operand
840 // appropriate for it's location in the CFG.
841 SmallVector<OperandBundleDef, 1> OpBundles;
842 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
843 BundleIdx != BundleEnd; ++BundleIdx) {
844 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
845 if (Bundle.getTagID() == LLVMContext::OB_funclet)
846 continue;
847
848 OpBundles.emplace_back(Bundle);
849 }
850
851 if (!BlockColors.empty()) {
852 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
853 assert(CV.size() == 1 && "non-unique color for exit block!");
854 BasicBlock *BBColor = CV.front();
855 Instruction *EHPad = BBColor->getFirstNonPHI();
856 if (EHPad->isEHPad())
857 OpBundles.emplace_back("funclet", EHPad);
858 }
859
860 New = CallInst::Create(CI, OpBundles);
861 } else {
862 New = I.clone();
863 }
864
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000865 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000866 if (!I.getName().empty())
867 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000868
869 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
870 // particularly cheap because we can rip off the PHI node that we're
871 // replacing for the number and blocks of the predecessors.
872 // OPT: If this shows up in a profile, we can instead finish sinking all
873 // invariant instructions, and then walk their operands to re-establish
874 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
875 // sinking bottom-up.
876 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
877 ++OI)
878 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
879 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
880 if (!OLoop->contains(&PN)) {
881 PHINode *OpPN =
882 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000883 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000884 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
885 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
886 *OI = OpPN;
887 }
888 return New;
889}
890
Alina Sbirlea0e155012018-07-02 18:53:40 +0000891static Instruction *sinkThroughTriviallyReplaceablePHI(
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000892 PHINode *TPN, Instruction *I, LoopInfo *LI,
893 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
894 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
Alina Sbirlea0e155012018-07-02 18:53:40 +0000895 assert(isTriviallyReplaceablePHI(*TPN, *I) &&
896 "Expect only trivially replaceable PHI");
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000897 BasicBlock *ExitBlock = TPN->getParent();
898 Instruction *New;
899 auto It = SunkCopies.find(ExitBlock);
900 if (It != SunkCopies.end())
901 New = It->second;
902 else
903 New = SunkCopies[ExitBlock] =
904 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
905 return New;
906}
907
Jun Bum Lim144eb592018-02-12 17:56:55 +0000908static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000909 BasicBlock *BB = PN->getParent();
910 if (!BB->canSplitPredecessors())
911 return false;
Jun Bum Lim144eb592018-02-12 17:56:55 +0000912 // It's not impossible to split EHPad blocks, but if BlockColors already exist
913 // it require updating BlockColors for all offspring blocks accordingly. By
914 // skipping such corner case, we can make updating BlockColors after splitting
915 // predecessor fairly simple.
Max Kazantsev8d56be72018-10-16 08:07:14 +0000916 if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())
Jun Bum Lim144eb592018-02-12 17:56:55 +0000917 return false;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000918 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
919 BasicBlock *BBPred = *PI;
920 if (isa<IndirectBrInst>(BBPred->getTerminator()))
921 return false;
922 }
923 return true;
924}
925
926static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000927 LoopInfo *LI, const Loop *CurLoop,
928 LoopSafetyInfo *SafetyInfo) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000929#ifndef NDEBUG
930 SmallVector<BasicBlock *, 32> ExitBlocks;
931 CurLoop->getUniqueExitBlocks(ExitBlocks);
932 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
933 ExitBlocks.end());
934#endif
935 BasicBlock *ExitBB = PN->getParent();
936 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
937
938 // Split predecessors of the loop exit to make instructions in the loop are
Alina Sbirlea0e155012018-07-02 18:53:40 +0000939 // exposed to exit blocks through trivially replaceable PHIs while keeping the
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000940 // loop in the canonical form where each predecessor of each exit block should
941 // be contained within the loop. For example, this will convert the loop below
942 // from
943 //
944 // LB1:
945 // %v1 =
946 // br %LE, %LB2
947 // LB2:
948 // %v2 =
949 // br %LE, %LB1
950 // LE:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000951 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000952 //
953 // to
954 //
955 // LB1:
956 // %v1 =
957 // br %LE.split, %LB2
958 // LB2:
959 // %v2 =
960 // br %LE.split2, %LB1
961 // LE.split:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000962 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000963 // br %LE
964 // LE.split2:
Alina Sbirlea0e155012018-07-02 18:53:40 +0000965 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000966 // br %LE
967 // LE:
968 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
969 //
Max Kazantsev8d56be72018-10-16 08:07:14 +0000970 const auto &BlockColors = SafetyInfo->getBlockColors();
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000971 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
972 while (!PredBBs.empty()) {
973 BasicBlock *PredBB = *PredBBs.begin();
974 assert(CurLoop->contains(PredBB) &&
975 "Expect all predecessors are in the loop");
Jun Bum Lim144eb592018-02-12 17:56:55 +0000976 if (PN->getBasicBlockIndex(PredBB) >= 0) {
977 BasicBlock *NewPred = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000978 ExitBB, PredBB, ".split.loop.exit", DT, LI, nullptr, true);
Jun Bum Lim144eb592018-02-12 17:56:55 +0000979 // Since we do not allow splitting EH-block with BlockColors in
980 // canSplitPredecessors(), we can simply assign predecessor's color to
981 // the new block.
Max Kazantsev8d56be72018-10-16 08:07:14 +0000982 if (!BlockColors.empty())
Andrew Kaylora2378662018-03-23 17:36:18 +0000983 // Grab a reference to the ColorVector to be inserted before getting the
984 // reference to the vector we are copying because inserting the new
985 // element in BlockColors might cause the map to be reallocated.
Max Kazantsev8d56be72018-10-16 08:07:14 +0000986 SafetyInfo->copyColors(NewPred, PredBB);
Jun Bum Lim144eb592018-02-12 17:56:55 +0000987 }
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000988 PredBBs.remove(PredBB);
989 }
990}
991
Hal Finkel3d4269a2015-02-22 18:35:32 +0000992/// When an instruction is found to only be used outside of the loop, this
993/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000994/// This method is guaranteed to remove the original instruction from its
995/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000996///
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000997static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
Jun Bum Lim144eb592018-02-12 17:56:55 +0000998 const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
Jun Bum Lim44c58d32017-12-15 20:33:24 +0000999 OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001000 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001001 ORE->emit([&]() {
1002 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1003 << "sinking " << ore::NV("Inst", &I);
1004 });
Hal Finkel3d4269a2015-02-22 18:35:32 +00001005 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001006 if (isa<LoadInst>(I))
1007 ++NumMovedLoads;
1008 else if (isa<CallInst>(I))
1009 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +00001010 ++NumSunk;
Chris Lattner55c21132003-12-10 20:43:29 +00001011
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001012 // Iterate over users to be ready for actual sinking. Replace users via
1013 // unrechable blocks with undef and make all user PHIs trivially replcable.
1014 SmallPtrSet<Instruction *, 8> VisitedUsers;
1015 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1016 auto *User = cast<Instruction>(*UI);
1017 Use &U = UI.getUse();
1018 ++UI;
1019
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001020 if (VisitedUsers.count(User) || CurLoop->contains(User))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001021 continue;
1022
1023 if (!DT->isReachableFromEntry(User->getParent())) {
Jun Bum Lim0f906722017-11-17 20:38:25 +00001024 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001025 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001026 continue;
1027 }
1028
1029 // The user must be a PHI node.
1030 PHINode *PN = cast<PHINode>(User);
1031
1032 // Surprisingly, instructions can be used outside of loops without any
1033 // exits. This can only happen in PHI nodes if the incoming block is
1034 // unreachable.
1035 BasicBlock *BB = PN->getIncomingBlock(U);
1036 if (!DT->isReachableFromEntry(BB)) {
1037 U = UndefValue::get(I.getType());
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001038 Changed = true;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001039 continue;
1040 }
1041
1042 VisitedUsers.insert(PN);
Alina Sbirlea0e155012018-07-02 18:53:40 +00001043 if (isTriviallyReplaceablePHI(*PN, I))
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001044 continue;
1045
Jun Bum Lim144eb592018-02-12 17:56:55 +00001046 if (!canSplitPredecessors(PN, SafetyInfo))
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001047 return Changed;
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001048
1049 // Split predecessors of the PHI so that we can make users trivially
Alina Sbirlea0e155012018-07-02 18:53:40 +00001050 // replaceable.
Jun Bum Lim144eb592018-02-12 17:56:55 +00001051 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001052
1053 // Should rebuild the iterators, as they may be invalidated by
1054 // splitPredecessorsOfLoopExit().
1055 UI = I.user_begin();
1056 UE = I.user_end();
1057 }
1058
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001059 if (VisitedUsers.empty())
1060 return Changed;
1061
Chandler Carruthfc258542014-02-11 12:52:27 +00001062#ifndef NDEBUG
1063 SmallVector<BasicBlock *, 32> ExitBlocks;
1064 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001065 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +00001066 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +00001067#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +00001068
Evgeniy Stepanov10280da2014-06-25 07:54:58 +00001069 // Clones of this instruction. Don't create more than one per exit block!
1070 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1071
Chandler Carruthfc258542014-02-11 12:52:27 +00001072 // If this instruction is only used outside of the loop, then all users are
1073 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1074 // the instruction.
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001075 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1076 for (auto *UI : Users) {
1077 auto *User = cast<Instruction>(UI);
1078
1079 if (CurLoop->contains(User))
1080 continue;
1081
1082 PHINode *PN = cast<PHINode>(User);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +00001083 assert(ExitBlockSet.count(PN->getParent()) &&
Chandler Carruthfc258542014-02-11 12:52:27 +00001084 "The LCSSA PHI is not in an exit block!");
Alina Sbirlea0e155012018-07-02 18:53:40 +00001085 // The PHI must be trivially replaceable.
1086 Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies,
1087 SafetyInfo, CurLoop);
Chandler Carruthfc258542014-02-11 12:52:27 +00001088 PN->replaceAllUsesWith(New);
1089 PN->eraseFromParent();
Jun Bum Lim44c58d32017-12-15 20:33:24 +00001090 Changed = true;
Chris Lattnercd96b4d2010-08-29 04:28:20 +00001091 }
Hal Finkel3d4269a2015-02-22 18:35:32 +00001092 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +00001093}
Chris Lattner64437692002-09-29 21:46:09 +00001094
Hal Finkel3d4269a2015-02-22 18:35:32 +00001095/// When an instruction is found to only use loop invariant operands that
1096/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +00001097///
Max Kazantsev68290f82018-08-15 02:49:12 +00001098static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Max Kazantsev72d7d642018-08-16 08:30:15 +00001099 LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001100 auto *Preheader = CurLoop->getLoopPreheader();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001101 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1102 << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001103 ORE->emit([&]() {
1104 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1105 << ore::NV("Inst", &I);
1106 });
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001107
1108 // Metadata can be dependent on conditions we are hoisting above.
1109 // Conservatively strip all metadata on the instruction unless we were
1110 // guaranteed to execute I if we entered the loop, in which case the metadata
1111 // is valid in the loop preheader.
1112 if (I.hasMetadataOtherThanDebugLoc() &&
1113 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1114 // time in isGuaranteedToExecute if we don't actually have anything to
1115 // drop. It is a compile time optimization, not required for correctness.
Max Kazantsevc8466f92018-10-16 06:34:53 +00001116 !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))
Sanjoy Das7a2e2be2016-01-28 15:51:58 +00001117 I.dropUnknownNonDebugMetadata();
1118
Chris Lattner6ac06592010-08-29 18:18:40 +00001119 // Move the new node to the Preheader, before its terminator.
1120 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001121
Wolfgang Piebc17a2792017-01-06 18:38:57 +00001122 // Do not retain debug locations when we are moving instructions to different
1123 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1124 // need to retain their debug locs because they may be inlined.
1125 // FIXME: How do we retain source locations without causing poor debugging
1126 // behavior?
1127 if (!isa<CallInst>(I))
1128 I.setDebugLoc(DebugLoc());
1129
Dehao Chend55bc4c2016-05-05 00:54:54 +00001130 if (isa<LoadInst>(I))
1131 ++NumMovedLoads;
1132 else if (isa<CallInst>(I))
1133 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +00001134 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +00001135}
1136
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00001137/// Only sink or hoist an instruction if it is not a trapping instruction,
1138/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001139/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001140static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +00001141 const DominatorTree *DT,
1142 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001143 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001144 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +00001145 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +00001146 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +00001147 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001148
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001149 bool GuaranteedToExecute =
Max Kazantsevc8466f92018-10-16 06:34:53 +00001150 SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001151
1152 if (!GuaranteedToExecute) {
1153 auto *LI = dyn_cast<LoadInst>(&Inst);
1154 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +00001155 ORE->emit([&]() {
1156 return OptimizationRemarkMissed(
1157 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1158 << "failed to hoist load with loop-invariant address "
1159 "because load is conditionally executed";
1160 });
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001161 }
1162
1163 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001164}
1165
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001166namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +00001167class LoopPromoter : public LoadAndStorePromoter {
1168 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001169 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001170 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1171 SmallVectorImpl<Instruction *> &LoopInsertPts;
1172 PredIteratorCache &PredCache;
1173 AliasSetTracker &AST;
1174 LoopInfo &LI;
1175 DebugLoc DL;
1176 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001177 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001178 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +00001179
Dehao Chend55bc4c2016-05-05 00:54:54 +00001180 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1181 if (Instruction *I = dyn_cast<Instruction>(V))
1182 if (Loop *L = LI.getLoopFor(I->getParent()))
1183 if (!L->contains(BB)) {
1184 // We need to create an LCSSA PHI node for the incoming value and
1185 // store that.
1186 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1187 I->getName() + ".lcssa", &BB->front());
1188 for (BasicBlock *Pred : PredCache.get(BB))
1189 PN->addIncoming(I, Pred);
1190 return PN;
1191 }
1192 return V;
1193 }
Chandler Carruthfc258542014-02-11 12:52:27 +00001194
Dehao Chend55bc4c2016-05-05 00:54:54 +00001195public:
1196 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001197 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001198 SmallVectorImpl<BasicBlock *> &LEB,
1199 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1200 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001201 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +00001202 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1203 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001204 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001205 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +00001206
Dehao Chend55bc4c2016-05-05 00:54:54 +00001207 bool isInstInList(Instruction *I,
1208 const SmallVectorImpl<Instruction *> &) const override {
1209 Value *Ptr;
1210 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1211 Ptr = LI->getOperand(0);
1212 else
1213 Ptr = cast<StoreInst>(I)->getPointerOperand();
1214 return PointerMustAliases.count(Ptr);
1215 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001216
Dehao Chend55bc4c2016-05-05 00:54:54 +00001217 void doExtraRewritesBeforeFinalDeletion() const override {
1218 // Insert stores after in the loop exit blocks. Each exit block gets a
1219 // store of the live-out values that feed them. Since we've already told
1220 // the SSA updater about the defs in the loop and the preheader
1221 // definition, it is all set and we can start using it.
1222 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1223 BasicBlock *ExitBlock = LoopExitBlocks[i];
1224 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1225 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1226 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1227 Instruction *InsertPos = LoopInsertPts[i];
1228 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001229 if (UnorderedAtomic)
1230 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001231 NewSI->setAlignment(Alignment);
1232 NewSI->setDebugLoc(DL);
1233 if (AATags)
1234 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001235 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001236 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001237
Dehao Chend55bc4c2016-05-05 00:54:54 +00001238 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1239 // Update alias analysis.
1240 AST.copyValue(LI, V);
1241 }
1242 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1243};
Philip Reames21cc2fa2017-10-26 21:00:15 +00001244
1245
1246/// Return true iff we can prove that a caller of this function can not inspect
1247/// the contents of the provided object in a well defined program.
1248bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1249 if (isa<AllocaInst>(Object))
1250 // Since the alloca goes out of scope, we know the caller can't retain a
1251 // reference to it and be well defined. Thus, we don't need to check for
Fangrui Songf78650a2018-07-30 19:41:25 +00001252 // capture.
Philip Reames21cc2fa2017-10-26 21:00:15 +00001253 return true;
Fangrui Songf78650a2018-07-30 19:41:25 +00001254
Philip Reames21cc2fa2017-10-26 21:00:15 +00001255 // For all other objects we need to know that the caller can't possibly
1256 // have gotten a reference to the object. There are two components of
1257 // that:
1258 // 1) Object can't be escaped by this function. This is what
1259 // PointerMayBeCaptured checks.
1260 // 2) Object can't have been captured at definition site. For this, we
1261 // need to know the return value is noalias. At the moment, we use a
1262 // weaker condition and handle only AllocLikeFunctions (which are
1263 // known to be noalias). TODO
1264 return isAllocLikeFn(Object, TLI) &&
1265 !PointerMayBeCaptured(Object, true, true);
1266}
1267
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001268} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001269
Hal Finkel3d4269a2015-02-22 18:35:32 +00001270/// Try to promote memory values to scalars by sinking stores out of the
1271/// loop and moving loads to before the loop. We do this by looping over
1272/// the stores in the loop, looking for stores to Must pointers which are
1273/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001274///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001275bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001276 const SmallSetVector<Value *, 8> &PointerMustAliases,
1277 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001278 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1279 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001280 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1281 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001282 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001283 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1284 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001285 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001286
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001287 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001288 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001289
Anna Thomas5ac72f92018-03-13 19:38:45 +00001290 // It is not safe to promote a load/store from the loop if the load/store is
Chris Lattner1dc98b42010-08-29 06:43:52 +00001291 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001292 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001293 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001294 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001295 // into:
1296 //
1297 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1298 //
1299 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001300 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001301 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001302 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001303 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001304 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001305 // path which did not originally have one.
1306 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001307 // If at least one store is guaranteed to execute, both properties are
1308 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001309 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001310 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001311 // guaranteed to execute, we can still establish these properties.
1312 // We can establish (p1) by proving that hoisting the load into the preheader
1313 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001314 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001315 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001316 //
1317 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001318 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001319 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001320 // b) Prove a store dominates every exit block. In this case, if an exit
1321 // blocks is reached, the original dynamic path would have taken us through
1322 // the store, so inserting a store into the exit block is safe. Note that this
1323 // is different from the store being guaranteed to execute. For instance,
1324 // if an exception is thrown on the first iteration of the loop, the original
1325 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001326
1327 bool DereferenceableInPH = false;
1328 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001329
Dehao Chend55bc4c2016-05-05 00:54:54 +00001330 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001331
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001332 // We start with an alignment of one and try to find instructions that allow
1333 // us to prove better alignment.
1334 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001335 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001336 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001337 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001338 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001339
Philip Reamesb54c8e62016-03-09 22:59:30 +00001340 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1341
Philip Reames21cc2fa2017-10-26 21:00:15 +00001342 bool IsKnownThreadLocalObject = false;
Max Kazantsev530b8d12018-08-15 05:55:43 +00001343 if (SafetyInfo->anyBlockMayThrow()) {
Eli Friedmanee895052016-06-05 22:13:52 +00001344 // If a loop can throw, we have to insert a store along each unwind edge.
1345 // That said, we can't actually make the unwind edge explicit. Therefore,
Philip Reames21cc2fa2017-10-26 21:00:15 +00001346 // we have to prove that the store is dead along the unwind edge. We do
1347 // this by proving that the caller can't have a reference to the object
Fangrui Songf78650a2018-07-30 19:41:25 +00001348 // after return and thus can't possibly load from the object.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001349 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Philip Reames21cc2fa2017-10-26 21:00:15 +00001350 if (!isKnownNonEscaping(Object, TLI))
1351 return false;
1352 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1353 // visible to other threads if captured and used during their lifetimes.
1354 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
Eli Friedmanee895052016-06-05 22:13:52 +00001355 }
1356
Chris Lattner1dc98b42010-08-29 06:43:52 +00001357 // Check that all of the pointers in the alias set have the same type. We
1358 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001359 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001360 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001361 // Check that all of the pointers in the alias set have the same type. We
1362 // cannot (yet) promote a memory location that is loaded and stored in
1363 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001364 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001365 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001366
Chandler Carruthcdf47882014-03-09 03:16:01 +00001367 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001368 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001369 Instruction *UI = dyn_cast<Instruction>(U);
1370 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001371 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001372
Chris Lattner1dc98b42010-08-29 06:43:52 +00001373 // If there is an non-load/store instruction in the loop, we can't promote
1374 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001375 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001376 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001377 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001378
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001379 SawUnorderedAtomic |= Load->isAtomic();
1380 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001381
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001382 if (!DereferenceableInPH)
1383 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001384 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001385 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001386 // Stores *of* the pointer are not interesting, only stores *to* the
1387 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001388 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001389 continue;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001390 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001391 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001392
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001393 SawUnorderedAtomic |= Store->isAtomic();
1394 SawNotAtomic |= !Store->isAtomic();
1395
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001396 // If the store is guaranteed to execute, both properties are satisfied.
1397 // We may want to check if a store is guaranteed to execute even if we
1398 // already know that promotion is safe, since it may have higher
1399 // alignment than any other guaranteed stores, in which case we can
1400 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001401 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001402 if (!InstAlignment)
1403 InstAlignment =
1404 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1405
1406 if (!DereferenceableInPH || !SafeToInsertStore ||
1407 (InstAlignment > Alignment)) {
Max Kazantsevc8466f92018-10-16 06:34:53 +00001408 if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001409 DereferenceableInPH = true;
1410 SafeToInsertStore = true;
1411 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001412 }
Anna Thomas67151352016-06-24 12:38:45 +00001413 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001414
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001415 // If a store dominates all exit blocks, it is safe to sink.
1416 // As explained above, if an exit block was executed, a dominating
Fangrui Song956ee792018-03-30 22:22:31 +00001417 // store must have been executed at least once, so we are not
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001418 // introducing stores on paths that did not have them.
1419 // Note that this only looks at explicit exit blocks. If we ever
1420 // start sinking stores into unwind edges (see above), this will break.
1421 if (!SafeToInsertStore)
1422 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1423 return DT->dominates(Store->getParent(), Exit);
1424 });
1425
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001426 // If the store is not guaranteed to execute, we may still get
1427 // deref info through it.
1428 if (!DereferenceableInPH) {
1429 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001430 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001431 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001432 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001433 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001434 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001435
Hal Finkelcc39b672014-07-24 12:16:19 +00001436 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001437 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001438 // On the first load/store, just take its AA tags.
1439 UI->getAAMetadata(AATags);
1440 } else if (AATags) {
1441 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001442 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001443
1444 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001445 }
1446 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001447
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001448 // If we found both an unordered atomic instruction and a non-atomic memory
1449 // access, bail. We can't blindly promote non-atomic to atomic since we
1450 // might not be able to lower the result. We can't downgrade since that
1451 // would violate memory model. Also, align 0 is an error for atomics.
1452 if (SawUnorderedAtomic && SawNotAtomic)
1453 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001454
1455 // If we couldn't prove we can hoist the load, bail.
1456 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001457 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001458
1459 // We know we can hoist the load, but don't have a guaranteed store.
1460 // Check whether the location is thread-local. If it is, then we can insert
1461 // stores along paths which originally didn't have them without violating the
1462 // memory model.
1463 if (!SafeToInsertStore) {
Philip Reames21cc2fa2017-10-26 21:00:15 +00001464 if (IsKnownThreadLocalObject)
Xin Tong5ee40ba2017-01-19 19:31:40 +00001465 SafeToInsertStore = true;
1466 else {
1467 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1468 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001469 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1470 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001471 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001472 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001473
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001474 // If we've still failed to prove we can sink the store, give up.
1475 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001476 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001477
Chris Lattner1dc98b42010-08-29 06:43:52 +00001478 // Otherwise, this is safe to promote, lets do it!
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001479 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1480 << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +00001481 ORE->emit([&]() {
1482 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1483 LoopUses[0])
1484 << "Moving accesses to memory location out of the loop";
1485 });
Chris Lattner1dc98b42010-08-29 06:43:52 +00001486 ++NumPromoted;
1487
Eli Friedmanddf7f552011-05-27 20:31:51 +00001488 // Grab a debug location for the inserted loads/stores; given that the
1489 // inserted loads/stores have little relation to the original loads/stores,
1490 // this code just arbitrarily picks a location from one, since any debug
1491 // location is better than none.
1492 DebugLoc DL = LoopUses[0]->getDebugLoc();
1493
Chris Lattner1dc98b42010-08-29 06:43:52 +00001494 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001495 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001496 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001497 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001498 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1499 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001500
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001501 // Set up the preheader to have a definition of the value. It is the live-out
1502 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001503 LoadInst *PreheaderLoad = new LoadInst(
1504 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001505 if (SawUnorderedAtomic)
1506 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001507 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001508 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001509 if (AATags)
1510 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001511 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1512
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001513 // Rewrite all the loads in the loop and remember all the definitions from
1514 // stores in the loop.
1515 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001516
1517 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1518 if (PreheaderLoad->use_empty())
1519 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001520
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001521 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001522}
Devang Patelb98a0972007-07-31 08:01:41 +00001523
Roman Gareev036c0882016-02-15 14:48:50 +00001524/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001525/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001526/// FIXME: In new pass manager, there is no helper function to handle loop
1527/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001528/// from scratch for every loop. Hook up with the helper functions when
1529/// available in the new pass manager to avoid redundant computation.
Marcello Maggioni883fe452018-08-21 20:30:14 +00001530std::unique_ptr<AliasSetTracker>
Dehao Chen9cba1f42016-07-12 22:37:48 +00001531LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1532 AliasAnalysis *AA) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001533 std::unique_ptr<AliasSetTracker> CurAST;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001534 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001535 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001536 auto MapI = LoopToAliasSetMap.find(InnerL);
1537 // If the AST for this inner loop is missing it may have been merged into
1538 // some other loop's AST and then that loop unrolled, and so we need to
1539 // recompute it.
1540 if (MapI == LoopToAliasSetMap.end()) {
1541 RecomputeLoops.push_back(InnerL);
1542 continue;
1543 }
Marcello Maggioni883fe452018-08-21 20:30:14 +00001544 std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
Roman Gareev036c0882016-02-15 14:48:50 +00001545
Marcello Maggioni883fe452018-08-21 20:30:14 +00001546 if (CurAST) {
Roman Gareev036c0882016-02-15 14:48:50 +00001547 // What if InnerLoop was modified by other passes ?
Roman Gareev036c0882016-02-15 14:48:50 +00001548 // Once we've incorporated the inner loop's AST into ours, we don't need
1549 // the subloop's anymore.
Marcello Maggioni883fe452018-08-21 20:30:14 +00001550 CurAST->add(*InnerAST);
Roman Gareev036c0882016-02-15 14:48:50 +00001551 } else {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001552 CurAST = std::move(InnerAST);
Roman Gareev036c0882016-02-15 14:48:50 +00001553 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001554 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001555 }
Marcello Maggioni883fe452018-08-21 20:30:14 +00001556 if (!CurAST)
1557 CurAST = make_unique<AliasSetTracker>(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001558
1559 // Add everything from the sub loops that are no longer directly available.
1560 for (Loop *InnerL : RecomputeLoops)
Serguei Katkov5f4a9e92018-09-11 04:07:36 +00001561 for (BasicBlock *BB : InnerL->blocks())
1562 CurAST->add(*BB);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001563
Serguei Katkov5f4a9e92018-09-11 04:07:36 +00001564 // And merge in this loop (without anything from inner loops).
1565 for (BasicBlock *BB : L->blocks())
1566 if (LI->getLoopFor(BB) == L)
1567 CurAST->add(*BB);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001568
Roman Gareev036c0882016-02-15 14:48:50 +00001569 return CurAST;
1570}
1571
Ashutosh Nema47802622015-08-13 11:18:35 +00001572/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001573///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001574void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1575 Loop *L) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001576 auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
1577 if (ASTIt == LICM.getLoopToAliasSetMap().end())
Devang Patelb98a0972007-07-31 08:01:41 +00001578 return;
1579
Marcello Maggioni883fe452018-08-21 20:30:14 +00001580 ASTIt->second->copyValue(From, To);
Devang Patelb98a0972007-07-31 08:01:41 +00001581}
1582
Hal Finkel3d4269a2015-02-22 18:35:32 +00001583/// Simple Analysis hook. Delete value V from alias set
1584///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001585void LegacyLICMPass::deleteAnalysisValue(Value *V, 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->deleteValue(V);
Devang Patelb98a0972007-07-31 08:01:41 +00001591}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001592
1593/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001594///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001595void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
Marcello Maggioni883fe452018-08-21 20:30:14 +00001596 if (!LICM.getLoopToAliasSetMap().count(L))
David Peixotto0d4d5e62014-09-24 16:48:31 +00001597 return;
1598
Dehao Chen9cba1f42016-07-12 22:37:48 +00001599 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001600}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001601
Anna Thomas19626212018-08-17 13:44:00 +00001602static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
1603 AliasSetTracker *CurAST, Loop *CurLoop,
1604 AliasAnalysis *AA) {
1605 // First check to see if any of the basic blocks in CurLoop invalidate *V.
1606 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
1607
1608 if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
1609 return isInvalidatedAccordingToAST;
1610
1611 // Check with a diagnostic analysis if we can refine the information above.
1612 // This is to identify the limitations of using the AST.
1613 // The alias set mechanism used by LICM has a major weakness in that it
1614 // combines all things which may alias into a single set *before* asking
1615 // modref questions. As a result, a single readonly call within a loop will
1616 // collapse all loads and stores into a single alias set and report
1617 // invalidation if the loop contains any store. For example, readonly calls
1618 // with deopt states have this form and create a general alias set with all
1619 // loads and stores. In order to get any LICM in loops containing possible
1620 // deopt states we need a more precise invalidation of checking the mod ref
1621 // info of each instruction within the loop and LI. This has a complexity of
1622 // O(N^2), so currently, it is used only as a diagnostic tool since the
1623 // default value of LICMN2Threshold is zero.
1624
1625 // Don't look at nested loops.
1626 if (CurLoop->begin() != CurLoop->end())
1627 return true;
1628
1629 int N = 0;
1630 for (BasicBlock *BB : CurLoop->getBlocks())
1631 for (Instruction &I : *BB) {
1632 if (N >= LICMN2Theshold) {
1633 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "
1634 << *(MemLoc.Ptr) << "\n");
1635 return true;
1636 }
1637 N++;
1638 auto Res = AA->getModRefInfo(&I, MemLoc);
1639 if (isModSet(Res)) {
1640 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "
1641 << *(MemLoc.Ptr) << "\n");
1642 return true;
1643 }
1644 }
1645 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n");
1646 return false;
Hal Finkel3d4269a2015-02-22 18:35:32 +00001647}
1648
1649/// Little predicate that returns true if the specified basic block is in
1650/// a subloop of the current one, not the current one itself.
1651///
1652static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1653 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1654 return LI->getLoopFor(BB) != CurLoop;
1655}