blob: c83ba24018f87331b85848ee573ea09d068dbfc0 [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6ec05f52002-05-10 22:44:58 +00009//
Chris Lattnerc0517682003-12-09 17:18:00 +000010// This pass performs loop invariant code motion, attempting to remove as much
11// code from the body of a loop as possible. It does this by either hoisting
12// code into the preheader block, or by sinking code to the exit blocks if it is
13// safe. This pass also promotes must-aliased memory locations in the loop to
Chris Lattner547192d62003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattnerc0517682003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner45d67d62003-02-24 03:52:32 +000017//
Chris Lattner289ba2a2004-05-23 21:20:19 +000018// 1. Moving loop invariant loads and calls out of loops. If we can determine
19// that a load or call inside of a loop never aliases anything stored to,
20// we can hoist it or sink it like any other instruction.
Chris Lattner45d67d62003-02-24 03:52:32 +000021// 2. Scalar Promotion of Memory - If there is a store instruction inside of
22// the loop, we try to move the store to happen AFTER the loop instead of
23// inside of the loop. This can only happen if a few conditions are true:
24// A. The pointer stored through is loop invariant
25// B. There are no stores or loads in the loop which _may_ alias the
26// pointer. There are no calls in the loop which mod/ref the pointer.
27// If these conditions are true, we can promote the loads and stores in the
28// loop of the pointer to use a temporary alloca'd variable. We then use
Chris Lattner1dc98b42010-08-29 06:43:52 +000029// the SSAUpdater to construct the appropriate SSA form for the value.
Chris Lattner6ec05f52002-05-10 22:44:58 +000030//
Chris Lattner6ec05f52002-05-10 22:44:58 +000031//===----------------------------------------------------------------------===//
32
Dehao Chen9cba1f42016-07-12 22:37:48 +000033#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000035#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000036#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000037#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000038#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner030f0202010-08-31 23:00:16 +000039#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000040#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamese0a54542016-03-09 23:07:53 +000041#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000042#include "llvm/Analysis/LoopInfo.h"
43#include "llvm/Analysis/LoopPass.h"
Dehao Chen9cba1f42016-07-12 22:37:48 +000044#include "llvm/Analysis/LoopPassManager.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000045#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000046#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000047#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000049#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000050#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Constants.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Instructions.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000058#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000059#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000060#include "llvm/Support/CommandLine.h"
61#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000063#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000064#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000065#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000067#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000068#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000069using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "licm"
72
Dehao Chend55bc4c2016-05-05 00:54:54 +000073STATISTIC(NumSunk, "Number of instructions sunk out of loop");
74STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000075STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
76STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000077STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000078
Dan Gohmand78c4002008-05-13 00:00:25 +000079static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000080 DisablePromotion("disable-licm-promotion", cl::Hidden,
81 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000082
Hal Finkel3d4269a2015-02-22 18:35:32 +000083static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000084static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000085 const LoopSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000086static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000087 const LoopSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000088static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000089 const Loop *CurLoop, AliasSetTracker *CurAST,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000090 const LoopSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000091static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
92 const DominatorTree *DT,
93 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000094 const LoopSafetyInfo *SafetyInfo,
Philip Reamesb47b9c22015-05-22 02:14:05 +000095 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000096static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +000097 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +000098 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +000099static Instruction *
100CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
101 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000102 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000103
Dan Gohmand78c4002008-05-13 00:00:25 +0000104namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000105struct LoopInvariantCodeMotion {
106 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
107 TargetLibraryInfo *TLI, ScalarEvolution *SE, bool DeleteAST);
108
109 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
110 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000111 }
112
Dehao Chen9cba1f42016-07-12 22:37:48 +0000113private:
114 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
115
116 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
117 AliasAnalysis *AA);
118};
119
120struct LegacyLICMPass : public LoopPass {
121 static char ID; // Pass identification, replacement for typeid
122 LegacyLICMPass() : LoopPass(ID) {
123 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
124 }
125
126 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000127 if (skipLoop(L)) {
128 // If we have run LICM on a previous loop but now we are skipping
129 // (because we've hit the opt-bisect limit), we need to clear the
130 // loop alias information.
Davide Italianob9ff23a2016-12-23 15:02:35 +0000131 for (auto &LTAS : LICM.getLoopToAliasSetMap())
132 delete LTAS.second;
Davide Italiano34f94382016-12-23 13:12:50 +0000133 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000134 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000135 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000136
137 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
138 return LICM.runOnLoop(L,
139 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
140 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
141 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
142 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
143 SE ? &SE->getSE() : nullptr, false);
144 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000145
Dehao Chend55bc4c2016-05-05 00:54:54 +0000146 /// This transformation requires natural loop information & requires that
147 /// loop preheaders be inserted into the CFG...
148 ///
149 void getAnalysisUsage(AnalysisUsage &AU) const override {
150 AU.setPreservesCFG();
151 AU.addRequired<TargetLibraryInfoWrapperPass>();
152 getLoopAnalysisUsage(AU);
153 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000154
Dehao Chend55bc4c2016-05-05 00:54:54 +0000155 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000156
Dehao Chend55bc4c2016-05-05 00:54:54 +0000157 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000158 assert(LICM.getLoopToAliasSetMap().empty() &&
159 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000160 return false;
161 }
Devang Patel69730c92007-03-07 04:41:30 +0000162
Dehao Chend55bc4c2016-05-05 00:54:54 +0000163private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000164 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000165
Dehao Chend55bc4c2016-05-05 00:54:54 +0000166 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
167 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
168 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000169
Dehao Chend55bc4c2016-05-05 00:54:54 +0000170 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
171 /// set.
172 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000173
Dehao Chend55bc4c2016-05-05 00:54:54 +0000174 /// Simple Analysis hook. Delete loop L from alias set map.
175 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000176};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000177}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000178
Sean Silva0746f3b2016-08-09 00:28:52 +0000179PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000180 const auto &FAM =
181 AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
182 Function *F = L.getHeader()->getParent();
183
184 auto *AA = FAM.getCachedResult<AAManager>(*F);
185 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
186 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
187 auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
188 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
189 assert((AA && LI && DT && TLI && SE) && "Analyses for LICM not available");
190
191 LoopInvariantCodeMotion LICM;
192
193 if (!LICM.runOnLoop(&L, AA, LI, DT, TLI, SE, true))
194 return PreservedAnalyses::all();
195
196 // FIXME: There is no setPreservesCFG in the new PM. When that becomes
197 // available, it should be used here.
198 return getLoopPassPreservedAnalyses();
199}
200
201char LegacyLICMPass::ID = 0;
202INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
203 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000204INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000205INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000206INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
207 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000208
Dehao Chen9cba1f42016-07-12 22:37:48 +0000209Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000210
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000211/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000212/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000213/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000214/// We should delete AST for inner loops in the new pass manager to avoid
215/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000216///
Dehao Chen9cba1f42016-07-12 22:37:48 +0000217bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
218 LoopInfo *LI, DominatorTree *DT,
219 TargetLibraryInfo *TLI,
220 ScalarEvolution *SE, bool DeleteAST) {
221 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000222
Chandler Carruthfc258542014-02-11 12:52:27 +0000223 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
224
Dehao Chen9cba1f42016-07-12 22:37:48 +0000225 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000226
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000227 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000228 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000229
Hal Finkel3d4269a2015-02-22 18:35:32 +0000230 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000231 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000232 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000233
Chris Lattner6ec05f52002-05-10 22:44:58 +0000234 // We want to visit all of the instructions in this loop... that are not parts
235 // of our subloops (they have already had their invariants hoisted out of
236 // their loop, into this loop, so there is no need to process the BODIES of
237 // the subloops).
238 //
Chris Lattner64437692002-09-29 21:46:09 +0000239 // Traverse the body of the loop in depth first order on the dominator tree so
240 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000241 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000242 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000243 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000244 if (L->hasDedicatedExits())
Dehao Chen9cba1f42016-07-12 22:37:48 +0000245 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000247 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000248 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
249 CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000250
Chris Lattner45d67d62003-02-24 03:52:32 +0000251 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000252 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000253 // Don't sink stores from loops without dedicated block exits. Exits
254 // containing indirect branches are not transformed by loop simplify,
255 // make sure we catch that. An additional load may be generated in the
256 // preheader for SSA updater, so also avoid sinking when no preheader
257 // is available.
258 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000259 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000260 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000261 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000262
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000263 // We can't insert into a catchswitch.
264 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
265 return isa<CatchSwitchInst>(Exit->getTerminator());
266 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000267
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000268 if (!HasCatchSwitch) {
269 SmallVector<Instruction *, 8> InsertPts;
270 InsertPts.reserve(ExitBlocks.size());
271 for (BasicBlock *ExitBlock : ExitBlocks)
272 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000273
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000274 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000275
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000276 bool Promoted = false;
277
278 // Loop over all of the alias sets in the tracker object.
279 for (AliasSet &AS : *CurAST)
280 Promoted |=
281 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT,
282 TLI, L, CurAST, &SafetyInfo);
283
284 // Once we have promoted values across the loop body we have to
285 // recursively reform LCSSA as any nested loop may now have values defined
286 // within the loop used in the outer loop.
287 // FIXME: This is really heavy handed. It would be a bit better to use an
288 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
289 // it as it went.
290 if (Promoted)
291 formLCSSARecursively(*L, *DT, LI, SE);
292
293 Changed |= Promoted;
294 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000295 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000296
Chandler Carruthfc258542014-02-11 12:52:27 +0000297 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
298 // specifically moving instructions across the loop boundary and so it is
299 // especially in need of sanity checking here.
300 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
301 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
302 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000303
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000304 // If this loop is nested inside of another one, save the alias information
305 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000306 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000307 LoopToAliasSetMap[L] = CurAST;
308 else
309 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000310
Dehao Chen9cba1f42016-07-12 22:37:48 +0000311 if (Changed && SE)
312 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000313 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000314}
315
Hal Finkel3d4269a2015-02-22 18:35:32 +0000316/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000317/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000318/// first order w.r.t the DominatorTree. This allows us to visit uses before
319/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000320///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000321bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
322 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000323 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000324
Hal Finkel3d4269a2015-02-22 18:35:32 +0000325 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000326 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
327 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
328 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000329
Hal Finkel3d4269a2015-02-22 18:35:32 +0000330 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000331 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000332 if (!CurLoop->contains(BB))
333 return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000334
Chris Lattner263f8042010-08-29 18:22:25 +0000335 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000336 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000337 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000338 for (DomTreeNode *Child : Children)
339 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
340
Chris Lattner547192d62003-12-19 07:22:45 +0000341 // Only need to process the contents of this block if it is not part of a
342 // subloop (which would already have been processed).
Dehao Chend55bc4c2016-05-05 00:54:54 +0000343 if (inSubLoop(BB, CurLoop, LI))
344 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000345
Dehao Chend55bc4c2016-05-05 00:54:54 +0000346 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
Chris Lattner91846012003-12-19 08:18:16 +0000347 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000348
Chris Lattner263f8042010-08-29 18:22:25 +0000349 // If the instruction is dead, we would try to sink it because it isn't used
350 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000351 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000352 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000353 ++II;
354 CurAST->deleteValue(&I);
355 I.eraseFromParent();
356 Changed = true;
357 continue;
358 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000359
Chris Lattner547192d62003-12-19 07:22:45 +0000360 // Check to see if we can sink this instruction to the exit blocks
361 // of the loop. We can do this if the all users of the instruction are
362 // outside of the loop. In this case, it doesn't even matter if the
363 // operands of the instruction are loop invariant.
364 //
David Majnemer42a07302016-01-04 03:37:39 +0000365 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Dehao Chen92abc7e2016-10-03 18:52:08 +0000366 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000367 ++II;
David Majnemer42a07302016-01-04 03:37:39 +0000368 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
Chris Lattner91846012003-12-19 08:18:16 +0000369 }
Chris Lattner547192d62003-12-19 07:22:45 +0000370 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000371 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000372}
373
Hal Finkel3d4269a2015-02-22 18:35:32 +0000374/// Walk the specified region of the CFG (defined by all blocks dominated by
375/// the specified block, and that are in the current loop) in depth first
376/// order w.r.t the DominatorTree. This allows us to visit definitions before
377/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000378///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000379bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
380 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000381 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000382 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000383 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
384 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
385 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000386
Owen Andersonc24701e2007-04-24 06:40:39 +0000387 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000388
Chris Lattner05e86302002-09-29 22:26:07 +0000389 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000390 if (!CurLoop->contains(BB))
391 return false;
Sanjay Patel99133222016-01-13 23:01:57 +0000392
Chris Lattneraaaea512003-12-10 06:41:05 +0000393 // Only need to process the contents of this block if it is not part of a
394 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000395 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000396 if (!inSubLoop(BB, CurLoop, LI))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000397 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000398 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000399 // Try constant folding this instruction. If all the operands are
400 // constants, it is technically hoistable, but it would be better to just
401 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000402 if (Constant *C = ConstantFoldInstruction(
403 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000404 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
405 CurAST->copyValue(&I, C);
Chris Lattner030f0202010-08-31 23:00:16 +0000406 I.replaceAllUsesWith(C);
David Majnemer522a9112016-07-22 04:54:44 +0000407 if (isInstructionTriviallyDead(&I, TLI)) {
408 CurAST->deleteValue(&I);
409 I.eraseFromParent();
410 }
Chris Lattner030f0202010-08-31 23:00:16 +0000411 continue;
412 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000413
Chris Lattner547192d62003-12-19 07:22:45 +0000414 // Try hoisting the instruction out to the preheader. We can only do this
415 // if all of the operands of the instruction are loop invariant and if it
416 // is safe to hoist the instruction.
417 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000418 if (CurLoop->hasLoopInvariantOperands(&I) &&
Dehao Chen92abc7e2016-10-03 18:52:08 +0000419 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo) &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000420 isSafeToExecuteUnconditionally(
Sean Silva45835e72016-07-02 23:47:27 +0000421 I, DT, CurLoop, SafetyInfo,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000422 CurLoop->getLoopPreheader()->getTerminator()))
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000423 Changed |= hoist(I, DT, CurLoop, SafetyInfo);
Chris Lattner030f0202010-08-31 23:00:16 +0000424 }
Chris Lattner64437692002-09-29 21:46:09 +0000425
Dehao Chend55bc4c2016-05-05 00:54:54 +0000426 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000427 for (DomTreeNode *Child : Children)
428 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000429 return Changed;
430}
431
432/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000433/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000434///
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000435void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000436 assert(CurLoop != nullptr && "CurLoop cant be null");
437 BasicBlock *Header = CurLoop->getHeader();
438 // Setting default safety values.
439 SafetyInfo->MayThrow = false;
440 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000441 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000442 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
443 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000444 SafetyInfo->HeaderMayThrow |=
445 !isGuaranteedToTransferExecutionToSuccessor(&*I);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000446
Hal Finkel3d4269a2015-02-22 18:35:32 +0000447 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000448 // Iterate over loop instructions and compute safety info.
449 for (Loop::block_iterator BB = CurLoop->block_begin(),
450 BBE = CurLoop->block_end();
451 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000452 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
453 (I != E) && !SafetyInfo->MayThrow; ++I)
Eli Friedmanf1da33e2016-06-11 21:48:25 +0000454 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
David Majnemer42a07302016-01-04 03:37:39 +0000455
456 // Compute funclet colors if we might sink/hoist in a function with a funclet
457 // personality routine.
458 Function *Fn = CurLoop->getHeader()->getParent();
459 if (Fn->hasPersonalityFn())
460 if (Constant *PersonalityFn = Fn->getPersonalityFn())
461 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
462 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000463}
464
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000465bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
466 Loop *CurLoop, AliasSetTracker *CurAST,
467 LoopSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000468 // Loads have extra constraints we have to verify before we can hoist them.
469 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000470 if (!LI->isUnordered())
Dehao Chend55bc4c2016-05-05 00:54:54 +0000471 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000472
Chris Lattner8a8fb902008-07-23 05:06:28 +0000473 // Loads from constant memory are always safe to move, even if they end up
474 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000475 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000476 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000477 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000478 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000479
Chris Lattner65c11932003-12-09 19:32:44 +0000480 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000481 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000482 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000483 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000484
485 AAMDNodes AAInfo;
486 LI->getAAMetadata(AAInfo);
487
Hal Finkel3d4269a2015-02-22 18:35:32 +0000488 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000489 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000490 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000491 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000492 return false;
493
David Majnemer42a07302016-01-04 03:37:39 +0000494 // Don't sink calls which can throw.
495 if (CI->mayThrow())
496 return false;
497
Eli Friedman942e1c12011-05-27 18:37:52 +0000498 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000499 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
500 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000501 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000502 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000503 // A readonly argmemonly function only reads from memory pointed to by
504 // it's arguments with arbitrary offsets. If we can prove there are no
505 // writes to this memory in the loop, we can hoist or sink.
506 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
507 for (Value *Op : CI->arg_operands())
508 if (Op->getType()->isPointerTy() &&
509 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
510 AAMDNodes(), CurAST))
511 return false;
512 return true;
513 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000514 // If this call only reads from memory and there are no writes to memory
515 // in the loop, we can hoist or sink the call as appropriate.
516 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000517 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000518 if (!AS.isForwardingAliasSet() && AS.isMod()) {
519 FoundMod = true;
520 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000521 }
Chris Lattner20cda262004-03-15 04:11:30 +0000522 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000523 if (!FoundMod)
524 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000525 }
526
Nadav Rotem03dcd852012-09-04 10:25:04 +0000527 // FIXME: This should use mod/ref information to see if we can hoist or
528 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000529
Chris Lattner20cda262004-03-15 04:11:30 +0000530 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000531 }
532
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000533 // Only these instructions are hoistable/sinkable.
534 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
535 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
536 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
537 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
538 !isa<InsertValueInst>(I))
539 return false;
540
Dehao Chen92abc7e2016-10-03 18:52:08 +0000541 // SafetyInfo is nullptr if we are checking for sinking from preheader to
542 // loop body. It will be always safe as there is no speculative execution.
543 if (!SafetyInfo)
544 return true;
545
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000546 // TODO: Plumb the context instruction through to make hoisting and sinking
547 // more powerful. Hoisting of loads already works due to the special casing
548 // above.
549 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000550}
551
Hal Finkel3d4269a2015-02-22 18:35:32 +0000552/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000553/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000554/// This is true when all incoming values are that instruction.
555/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000556///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000557static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000558 for (const Value *IncValue : PN.incoming_values())
559 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000560 return false;
561
562 return true;
563}
564
Hal Finkel3d4269a2015-02-22 18:35:32 +0000565/// Return true if the only users of this instruction are outside of
566/// the loop. If this is true, we can sink the instruction to the exit
567/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000568///
David Majnemer42a07302016-01-04 03:37:39 +0000569static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000570 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000571 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000572 for (const User *U : I.users()) {
573 const Instruction *UI = cast<Instruction>(U);
574 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000575 const BasicBlock *BB = PN->getParent();
576 // We cannot sink uses in catchswitches.
577 if (isa<CatchSwitchInst>(BB->getTerminator()))
578 return false;
579
580 // We need to sink a callsite to a unique funclet. Avoid sinking if the
581 // phi use is too muddled.
582 if (isa<CallInst>(I))
583 if (!BlockColors.empty() &&
584 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
585 return false;
586
Chandler Carruth8765cf72014-01-25 04:07:24 +0000587 // A PHI node where all of the incoming values are this instruction are
588 // special -- they can just be RAUW'ed with the instruction and thus
589 // don't require a use in the predecessor. This is a particular important
590 // special case because it is the pattern found in LCSSA form.
591 if (isTriviallyReplacablePHI(*PN, I)) {
592 if (CurLoop->contains(PN))
593 return false;
594 else
595 continue;
596 }
597
598 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
599 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000600 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
601 if (PN->getIncomingValue(i) == &I)
602 if (CurLoop->contains(PN->getIncomingBlock(i)))
603 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000604
605 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000606 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000607
Chandler Carruthcdf47882014-03-09 03:16:01 +0000608 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000609 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000610 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000611 return true;
612}
613
David Majnemer42a07302016-01-04 03:37:39 +0000614static Instruction *
615CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
616 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000617 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000618 Instruction *New;
619 if (auto *CI = dyn_cast<CallInst>(&I)) {
620 const auto &BlockColors = SafetyInfo->BlockColors;
621
622 // Sinking call-sites need to be handled differently from other
623 // instructions. The cloned call-site needs a funclet bundle operand
624 // appropriate for it's location in the CFG.
625 SmallVector<OperandBundleDef, 1> OpBundles;
626 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
627 BundleIdx != BundleEnd; ++BundleIdx) {
628 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
629 if (Bundle.getTagID() == LLVMContext::OB_funclet)
630 continue;
631
632 OpBundles.emplace_back(Bundle);
633 }
634
635 if (!BlockColors.empty()) {
636 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
637 assert(CV.size() == 1 && "non-unique color for exit block!");
638 BasicBlock *BBColor = CV.front();
639 Instruction *EHPad = BBColor->getFirstNonPHI();
640 if (EHPad->isEHPad())
641 OpBundles.emplace_back("funclet", EHPad);
642 }
643
644 New = CallInst::Create(CI, OpBundles);
645 } else {
646 New = I.clone();
647 }
648
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000649 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000650 if (!I.getName().empty())
651 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000652
653 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
654 // particularly cheap because we can rip off the PHI node that we're
655 // replacing for the number and blocks of the predecessors.
656 // OPT: If this shows up in a profile, we can instead finish sinking all
657 // invariant instructions, and then walk their operands to re-establish
658 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
659 // sinking bottom-up.
660 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
661 ++OI)
662 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
663 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
664 if (!OLoop->contains(&PN)) {
665 PHINode *OpPN =
666 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000667 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000668 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
669 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
670 *OI = OpPN;
671 }
672 return New;
673}
674
Hal Finkel3d4269a2015-02-22 18:35:32 +0000675/// When an instruction is found to only be used outside of the loop, this
676/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000677/// This method is guaranteed to remove the original instruction from its
678/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000679///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000680static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000681 const Loop *CurLoop, AliasSetTracker *CurAST,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000682 const LoopSafetyInfo *SafetyInfo) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000683 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000684 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000685 if (isa<LoadInst>(I))
686 ++NumMovedLoads;
687 else if (isa<CallInst>(I))
688 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000689 ++NumSunk;
690 Changed = true;
691
Chandler Carruthfc258542014-02-11 12:52:27 +0000692#ifndef NDEBUG
693 SmallVector<BasicBlock *, 32> ExitBlocks;
694 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000695 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000696 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000697#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000698
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000699 // Clones of this instruction. Don't create more than one per exit block!
700 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
701
Chandler Carruthfc258542014-02-11 12:52:27 +0000702 // If this instruction is only used outside of the loop, then all users are
703 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
704 // the instruction.
705 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000706 Value::user_iterator UI = I.user_begin();
707 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000708 if (!DT->isReachableFromEntry(User->getParent())) {
709 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
710 continue;
711 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000712 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000713 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000714
David Majnemer6bc83e02015-07-12 03:53:05 +0000715 // Surprisingly, instructions can be used outside of loops without any
716 // exits. This can only happen in PHI nodes if the incoming block is
717 // unreachable.
718 Use &U = UI.getUse();
719 BasicBlock *BB = PN->getIncomingBlock(U);
720 if (!DT->isReachableFromEntry(BB)) {
721 U = UndefValue::get(I.getType());
722 continue;
723 }
724
Chandler Carruthfc258542014-02-11 12:52:27 +0000725 BasicBlock *ExitBlock = PN->getParent();
726 assert(ExitBlockSet.count(ExitBlock) &&
727 "The LCSSA PHI is not in an exit block!");
728
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000729 Instruction *New;
730 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000731 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000732 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000733 else
734 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000735 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000736
737 PN->replaceAllUsesWith(New);
738 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000739 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000740
Chris Lattner1a1ed692010-08-29 18:00:00 +0000741 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000742 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000743 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000744}
Chris Lattner64437692002-09-29 21:46:09 +0000745
Hal Finkel3d4269a2015-02-22 18:35:32 +0000746/// When an instruction is found to only use loop invariant operands that
747/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000748///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000749static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000750 const LoopSafetyInfo *SafetyInfo) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000751 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000752 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
753 << "\n");
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000754
755 // Metadata can be dependent on conditions we are hoisting above.
756 // Conservatively strip all metadata on the instruction unless we were
757 // guaranteed to execute I if we entered the loop, in which case the metadata
758 // is valid in the loop preheader.
759 if (I.hasMetadataOtherThanDebugLoc() &&
760 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
761 // time in isGuaranteedToExecute if we don't actually have anything to
762 // drop. It is a compile time optimization, not required for correctness.
763 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
764 I.dropUnknownNonDebugMetadata();
765
Chris Lattner6ac06592010-08-29 18:18:40 +0000766 // Move the new node to the Preheader, before its terminator.
767 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000768
Dehao Chend55bc4c2016-05-05 00:54:54 +0000769 if (isa<LoadInst>(I))
770 ++NumMovedLoads;
771 else if (isa<CallInst>(I))
772 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000773 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000774 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000775}
776
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000777/// Only sink or hoist an instruction if it is not a trapping instruction,
778/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000779/// or if it is a trapping instruction and is guaranteed to execute.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000780static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000781 const DominatorTree *DT,
782 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000783 const LoopSafetyInfo *SafetyInfo,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000784 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +0000785 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000786 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000787
Hal Finkel3d4269a2015-02-22 18:35:32 +0000788 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000789}
790
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000791namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000792class LoopPromoter : public LoadAndStorePromoter {
793 Value *SomePtr; // Designated pointer to store to.
794 SmallPtrSetImpl<Value *> &PointerMustAliases;
795 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
796 SmallVectorImpl<Instruction *> &LoopInsertPts;
797 PredIteratorCache &PredCache;
798 AliasSetTracker &AST;
799 LoopInfo &LI;
800 DebugLoc DL;
801 int Alignment;
802 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000803
Dehao Chend55bc4c2016-05-05 00:54:54 +0000804 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
805 if (Instruction *I = dyn_cast<Instruction>(V))
806 if (Loop *L = LI.getLoopFor(I->getParent()))
807 if (!L->contains(BB)) {
808 // We need to create an LCSSA PHI node for the incoming value and
809 // store that.
810 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
811 I->getName() + ".lcssa", &BB->front());
812 for (BasicBlock *Pred : PredCache.get(BB))
813 PN->addIncoming(I, Pred);
814 return PN;
815 }
816 return V;
817 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000818
Dehao Chend55bc4c2016-05-05 00:54:54 +0000819public:
820 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
821 SmallPtrSetImpl<Value *> &PMA,
822 SmallVectorImpl<BasicBlock *> &LEB,
823 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
824 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
825 const AAMDNodes &AATags)
826 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
827 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000828 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000829
Dehao Chend55bc4c2016-05-05 00:54:54 +0000830 bool isInstInList(Instruction *I,
831 const SmallVectorImpl<Instruction *> &) const override {
832 Value *Ptr;
833 if (LoadInst *LI = dyn_cast<LoadInst>(I))
834 Ptr = LI->getOperand(0);
835 else
836 Ptr = cast<StoreInst>(I)->getPointerOperand();
837 return PointerMustAliases.count(Ptr);
838 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000839
Dehao Chend55bc4c2016-05-05 00:54:54 +0000840 void doExtraRewritesBeforeFinalDeletion() const override {
841 // Insert stores after in the loop exit blocks. Each exit block gets a
842 // store of the live-out values that feed them. Since we've already told
843 // the SSA updater about the defs in the loop and the preheader
844 // definition, it is all set and we can start using it.
845 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
846 BasicBlock *ExitBlock = LoopExitBlocks[i];
847 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
848 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
849 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
850 Instruction *InsertPos = LoopInsertPts[i];
851 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
852 NewSI->setAlignment(Alignment);
853 NewSI->setDebugLoc(DL);
854 if (AATags)
855 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000856 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000857 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000858
Dehao Chend55bc4c2016-05-05 00:54:54 +0000859 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
860 // Update alias analysis.
861 AST.copyValue(LI, V);
862 }
863 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
864};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000865} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000866
Hal Finkel3d4269a2015-02-22 18:35:32 +0000867/// Try to promote memory values to scalars by sinking stores out of the
868/// loop and moving loads to before the loop. We do this by looping over
869/// the stores in the loop, looking for stores to Must pointers which are
870/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000871///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000872bool llvm::promoteLoopAccessesToScalars(
873 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
874 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
875 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000876 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000877 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000878 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
879 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +0000880 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000881
Chris Lattner1dc98b42010-08-29 06:43:52 +0000882 // We can promote this alias set if it has a store, if it is a "Must" alias
883 // set, if the pointer is loop invariant, and if we are not eliminating any
884 // volatile loads or stores.
885 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
886 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000887 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000888
Chris Lattner1dc98b42010-08-29 06:43:52 +0000889 assert(!AS.empty() &&
890 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000891
Chris Lattner1dc98b42010-08-29 06:43:52 +0000892 Value *SomePtr = AS.begin()->getValue();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000893 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000894
Chris Lattner1dc98b42010-08-29 06:43:52 +0000895 // It isn't safe to promote a load/store from the loop if the load/store is
896 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000897 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000898 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000899 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000900 // into:
901 //
902 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
903 //
904 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000905 //
Philip Reamesb54c8e62016-03-09 22:59:30 +0000906 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000907 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +0000908 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000909 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +0000910 // path which did not originally have one.
911 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000912 // If at least one store is guaranteed to execute, both properties are
913 // satisfied, and promotion is legal.
914 // This, however, is not a necessary condition. Even if no store/load is
915 // guaranteed to execute, we can still establish these properties:
916 // (p1) by proving that hoisting the load into the preheader is
917 // safe (i.e. proving dereferenceability on all paths through the loop). We
918 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +0000919 // since they're all must alias.
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000920 // (p2) by proving the memory is thread-local, so the memory model
921 // requirement does not apply, and stores are safe to insert.
922
923 bool DereferenceableInPH = false;
924 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000925
Dehao Chend55bc4c2016-05-05 00:54:54 +0000926 SmallVector<Instruction *, 64> LoopUses;
927 SmallPtrSet<Value *, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000928
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000929 // We start with an alignment of one and try to find instructions that allow
930 // us to prove better alignment.
931 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000932 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000933
Philip Reamesb54c8e62016-03-09 22:59:30 +0000934 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
935
Eli Friedmanee895052016-06-05 22:13:52 +0000936 if (SafetyInfo->MayThrow) {
937 // If a loop can throw, we have to insert a store along each unwind edge.
938 // That said, we can't actually make the unwind edge explicit. Therefore,
939 // we have to prove that the store is dead along the unwind edge.
940 //
941 // Currently, this code just special-cases alloca instructions.
942 if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
943 return false;
944 }
945
Chris Lattner1dc98b42010-08-29 06:43:52 +0000946 // Check that all of the pointers in the alias set have the same type. We
947 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000948 // different sizes. While we are at it, collect alignment and AA info.
Sanjay Patel99133222016-01-13 23:01:57 +0000949 bool Changed = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000950 for (const auto &ASI : AS) {
951 Value *ASIV = ASI.getValue();
Chris Lattner1dc98b42010-08-29 06:43:52 +0000952 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000953
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000954 // Check that all of the pointers in the alias set have the same type. We
955 // cannot (yet) promote a memory location that is loaded and stored in
956 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000957 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000958 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000959
Chandler Carruthcdf47882014-03-09 03:16:01 +0000960 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000961 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000962 Instruction *UI = dyn_cast<Instruction>(U);
963 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000964 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000965
Chris Lattner1dc98b42010-08-29 06:43:52 +0000966 // If there is an non-load/store instruction in the loop, we can't promote
967 // it.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000968 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
969 assert(!Load->isVolatile() && "AST broken");
970 if (!Load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000971 return Changed;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000972
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000973 if (!DereferenceableInPH)
974 DereferenceableInPH = isSafeToExecuteUnconditionally(
Sean Silva45835e72016-07-02 23:47:27 +0000975 *Load, DT, CurLoop, SafetyInfo, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +0000976 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000977 // Stores *of* the pointer are not interesting, only stores *to* the
978 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000979 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000980 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000981 assert(!Store->isVolatile() && "AST broken");
982 if (!Store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000983 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000984
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000985 // If the store is guaranteed to execute, both properties are satisfied.
986 // We may want to check if a store is guaranteed to execute even if we
987 // already know that promotion is safe, since it may have higher
988 // alignment than any other guaranteed stores, in which case we can
989 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000990 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000991 if (!InstAlignment)
992 InstAlignment =
993 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
994
995 if (!DereferenceableInPH || !SafeToInsertStore ||
996 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000997 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +0000998 DereferenceableInPH = true;
999 SafeToInsertStore = true;
1000 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001001 }
Anna Thomas67151352016-06-24 12:38:45 +00001002 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001003
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001004 // If the store is not guaranteed to execute, we may still get
1005 // deref info through it.
1006 if (!DereferenceableInPH) {
1007 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001008 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001009 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001010 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001011 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +00001012 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001013
Hal Finkelcc39b672014-07-24 12:16:19 +00001014 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001015 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001016 // On the first load/store, just take its AA tags.
1017 UI->getAAMetadata(AATags);
1018 } else if (AATags) {
1019 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001020 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001021
1022 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001023 }
1024 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001025
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001026
1027 // If we couldn't prove we can hoist the load, bail.
1028 if (!DereferenceableInPH)
1029 return Changed;
1030
1031 // We know we can hoist the load, but don't have a guaranteed store.
1032 // Check whether the location is thread-local. If it is, then we can insert
1033 // stores along paths which originally didn't have them without violating the
1034 // memory model.
1035 if (!SafeToInsertStore) {
Philip Reamesb54c8e62016-03-09 22:59:30 +00001036 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001037 SafeToInsertStore =
Dehao Chend55bc4c2016-05-05 00:54:54 +00001038 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001039 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001040
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001041 // If we've still failed to prove we can sink the store, give up.
1042 if (!SafeToInsertStore)
Hal Finkel3d4269a2015-02-22 18:35:32 +00001043 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +00001044
Chris Lattner1dc98b42010-08-29 06:43:52 +00001045 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001046 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1047 << '\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +00001048 Changed = true;
1049 ++NumPromoted;
1050
Eli Friedmanddf7f552011-05-27 20:31:51 +00001051 // Grab a debug location for the inserted loads/stores; given that the
1052 // inserted loads/stores have little relation to the original loads/stores,
1053 // this code just arbitrarily picks a location from one, since any debug
1054 // location is better than none.
1055 DebugLoc DL = LoopUses[0]->getDebugLoc();
1056
Chris Lattner1dc98b42010-08-29 06:43:52 +00001057 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001058 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001059 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001060 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001061 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001062
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001063 // Set up the preheader to have a definition of the value. It is the live-out
1064 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001065 LoadInst *PreheaderLoad = new LoadInst(
1066 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001067 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001068 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001069 if (AATags)
1070 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001071 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1072
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001073 // Rewrite all the loads in the loop and remember all the definitions from
1074 // stores in the loop.
1075 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001076
1077 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1078 if (PreheaderLoad->use_empty())
1079 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001080
1081 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +00001082}
Devang Patelb98a0972007-07-31 08:01:41 +00001083
Roman Gareev036c0882016-02-15 14:48:50 +00001084/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001085/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001086/// FIXME: In new pass manager, there is no helper function to handle loop
1087/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001088/// from scratch for every loop. Hook up with the helper functions when
1089/// available in the new pass manager to avoid redundant computation.
1090AliasSetTracker *
1091LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1092 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001093 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001094 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001095 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001096 auto MapI = LoopToAliasSetMap.find(InnerL);
1097 // If the AST for this inner loop is missing it may have been merged into
1098 // some other loop's AST and then that loop unrolled, and so we need to
1099 // recompute it.
1100 if (MapI == LoopToAliasSetMap.end()) {
1101 RecomputeLoops.push_back(InnerL);
1102 continue;
1103 }
1104 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001105
1106 if (CurAST != nullptr) {
1107 // What if InnerLoop was modified by other passes ?
1108 CurAST->add(*InnerAST);
1109
1110 // Once we've incorporated the inner loop's AST into ours, we don't need
1111 // the subloop's anymore.
1112 delete InnerAST;
1113 } else {
1114 CurAST = InnerAST;
1115 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001116 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001117 }
1118 if (CurAST == nullptr)
1119 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001120
1121 auto mergeLoop = [&](Loop *L) {
1122 // Loop over the body of this loop, looking for calls, invokes, and stores.
1123 // Because subloops have already been incorporated into AST, we skip blocks
1124 // in subloops.
1125 for (BasicBlock *BB : L->blocks())
1126 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1127 CurAST->add(*BB); // Incorporate the specified basic block
1128 };
1129
1130 // Add everything from the sub loops that are no longer directly available.
1131 for (Loop *InnerL : RecomputeLoops)
1132 mergeLoop(InnerL);
1133
1134 // And merge in this loop.
1135 mergeLoop(L);
1136
Roman Gareev036c0882016-02-15 14:48:50 +00001137 return CurAST;
1138}
1139
Ashutosh Nema47802622015-08-13 11:18:35 +00001140/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001141///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001142void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1143 Loop *L) {
1144 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001145 if (!AST)
1146 return;
1147
1148 AST->copyValue(From, To);
1149}
1150
Hal Finkel3d4269a2015-02-22 18:35:32 +00001151/// Simple Analysis hook. Delete value V from alias set
1152///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001153void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1154 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001155 if (!AST)
1156 return;
1157
1158 AST->deleteValue(V);
1159}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001160
1161/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001162///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001163void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1164 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001165 if (!AST)
1166 return;
1167
1168 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001169 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001170}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001171
Hal Finkel3d4269a2015-02-22 18:35:32 +00001172/// Return true if the body of this loop may store into the memory
1173/// location pointed to by V.
1174///
1175static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001176 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001177 AliasSetTracker *CurAST) {
1178 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1179 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1180}
1181
1182/// Little predicate that returns true if the specified basic block is in
1183/// a subloop of the current one, not the current one itself.
1184///
1185static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1186 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1187 return LI->getLoopFor(BB) != CurLoop;
1188}