1*9880d681SAndroid Build Coastguard Worker //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass performs loop invariant code motion, attempting to remove as much
11*9880d681SAndroid Build Coastguard Worker // code from the body of a loop as possible. It does this by either hoisting
12*9880d681SAndroid Build Coastguard Worker // code into the preheader block, or by sinking code to the exit blocks if it is
13*9880d681SAndroid Build Coastguard Worker // safe. This pass also promotes must-aliased memory locations in the loop to
14*9880d681SAndroid Build Coastguard Worker // live in registers, thus hoisting and sinking "invariant" loads and stores.
15*9880d681SAndroid Build Coastguard Worker //
16*9880d681SAndroid Build Coastguard Worker // This pass uses alias analysis for two purposes:
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker // 1. Moving loop invariant loads and calls out of loops. If we can determine
19*9880d681SAndroid Build Coastguard Worker // that a load or call inside of a loop never aliases anything stored to,
20*9880d681SAndroid Build Coastguard Worker // we can hoist it or sink it like any other instruction.
21*9880d681SAndroid Build Coastguard Worker // 2. Scalar Promotion of Memory - If there is a store instruction inside of
22*9880d681SAndroid Build Coastguard Worker // the loop, we try to move the store to happen AFTER the loop instead of
23*9880d681SAndroid Build Coastguard Worker // inside of the loop. This can only happen if a few conditions are true:
24*9880d681SAndroid Build Coastguard Worker // A. The pointer stored through is loop invariant
25*9880d681SAndroid Build Coastguard Worker // B. There are no stores or loads in the loop which _may_ alias the
26*9880d681SAndroid Build Coastguard Worker // pointer. There are no calls in the loop which mod/ref the pointer.
27*9880d681SAndroid Build Coastguard Worker // If these conditions are true, we can promote the loads and stores in the
28*9880d681SAndroid Build Coastguard Worker // loop of the pointer to use a temporary alloca'd variable. We then use
29*9880d681SAndroid Build Coastguard Worker // the SSAUpdater to construct the appropriate SSA form for the value.
30*9880d681SAndroid Build Coastguard Worker //
31*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
32*9880d681SAndroid Build Coastguard Worker
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/LICM.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasSetTracker.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CaptureTracking.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/Loads.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPass.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPassManager.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Metadata.h"
59*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PredIteratorCache.h"
60*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
61*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
62*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
63*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
64*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
65*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
66*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/SSAUpdater.h"
67*9880d681SAndroid Build Coastguard Worker #include <algorithm>
68*9880d681SAndroid Build Coastguard Worker #include <utility>
69*9880d681SAndroid Build Coastguard Worker using namespace llvm;
70*9880d681SAndroid Build Coastguard Worker
71*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "licm"
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSunk, "Number of instructions sunk out of loop");
74*9880d681SAndroid Build Coastguard Worker STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
75*9880d681SAndroid Build Coastguard Worker STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
76*9880d681SAndroid Build Coastguard Worker STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
77*9880d681SAndroid Build Coastguard Worker STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
78*9880d681SAndroid Build Coastguard Worker
79*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
80*9880d681SAndroid Build Coastguard Worker DisablePromotion("disable-licm-promotion", cl::Hidden,
81*9880d681SAndroid Build Coastguard Worker cl::desc("Disable memory promotion in LICM pass"));
82*9880d681SAndroid Build Coastguard Worker
83*9880d681SAndroid Build Coastguard Worker static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
84*9880d681SAndroid Build Coastguard Worker static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
85*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo);
86*9880d681SAndroid Build Coastguard Worker static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
87*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo);
88*9880d681SAndroid Build Coastguard Worker static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
89*9880d681SAndroid Build Coastguard Worker const Loop *CurLoop, AliasSetTracker *CurAST,
90*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo);
91*9880d681SAndroid Build Coastguard Worker static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
92*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT,
93*9880d681SAndroid Build Coastguard Worker const Loop *CurLoop,
94*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo,
95*9880d681SAndroid Build Coastguard Worker const Instruction *CtxI = nullptr);
96*9880d681SAndroid Build Coastguard Worker static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
97*9880d681SAndroid Build Coastguard Worker const AAMDNodes &AAInfo,
98*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST);
99*9880d681SAndroid Build Coastguard Worker static Instruction *
100*9880d681SAndroid Build Coastguard Worker CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
101*9880d681SAndroid Build Coastguard Worker const LoopInfo *LI,
102*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo);
103*9880d681SAndroid Build Coastguard Worker static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
104*9880d681SAndroid Build Coastguard Worker DominatorTree *DT, TargetLibraryInfo *TLI,
105*9880d681SAndroid Build Coastguard Worker Loop *CurLoop, AliasSetTracker *CurAST,
106*9880d681SAndroid Build Coastguard Worker LoopSafetyInfo *SafetyInfo);
107*9880d681SAndroid Build Coastguard Worker
108*9880d681SAndroid Build Coastguard Worker namespace {
109*9880d681SAndroid Build Coastguard Worker struct LoopInvariantCodeMotion {
110*9880d681SAndroid Build Coastguard Worker bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
111*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI, ScalarEvolution *SE, bool DeleteAST);
112*9880d681SAndroid Build Coastguard Worker
getLoopToAliasSetMap__anon7f8510b00111::LoopInvariantCodeMotion113*9880d681SAndroid Build Coastguard Worker DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
114*9880d681SAndroid Build Coastguard Worker return LoopToAliasSetMap;
115*9880d681SAndroid Build Coastguard Worker }
116*9880d681SAndroid Build Coastguard Worker
117*9880d681SAndroid Build Coastguard Worker private:
118*9880d681SAndroid Build Coastguard Worker DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
119*9880d681SAndroid Build Coastguard Worker
120*9880d681SAndroid Build Coastguard Worker AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
121*9880d681SAndroid Build Coastguard Worker AliasAnalysis *AA);
122*9880d681SAndroid Build Coastguard Worker };
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker struct LegacyLICMPass : public LoopPass {
125*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
LegacyLICMPass__anon7f8510b00111::LegacyLICMPass126*9880d681SAndroid Build Coastguard Worker LegacyLICMPass() : LoopPass(ID) {
127*9880d681SAndroid Build Coastguard Worker initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
128*9880d681SAndroid Build Coastguard Worker }
129*9880d681SAndroid Build Coastguard Worker
runOnLoop__anon7f8510b00111::LegacyLICMPass130*9880d681SAndroid Build Coastguard Worker bool runOnLoop(Loop *L, LPPassManager &LPM) override {
131*9880d681SAndroid Build Coastguard Worker if (skipLoop(L))
132*9880d681SAndroid Build Coastguard Worker return false;
133*9880d681SAndroid Build Coastguard Worker
134*9880d681SAndroid Build Coastguard Worker auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
135*9880d681SAndroid Build Coastguard Worker return LICM.runOnLoop(L,
136*9880d681SAndroid Build Coastguard Worker &getAnalysis<AAResultsWrapperPass>().getAAResults(),
137*9880d681SAndroid Build Coastguard Worker &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
138*9880d681SAndroid Build Coastguard Worker &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
139*9880d681SAndroid Build Coastguard Worker &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
140*9880d681SAndroid Build Coastguard Worker SE ? &SE->getSE() : nullptr, false);
141*9880d681SAndroid Build Coastguard Worker }
142*9880d681SAndroid Build Coastguard Worker
143*9880d681SAndroid Build Coastguard Worker /// This transformation requires natural loop information & requires that
144*9880d681SAndroid Build Coastguard Worker /// loop preheaders be inserted into the CFG...
145*9880d681SAndroid Build Coastguard Worker ///
getAnalysisUsage__anon7f8510b00111::LegacyLICMPass146*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
147*9880d681SAndroid Build Coastguard Worker AU.setPreservesCFG();
148*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
149*9880d681SAndroid Build Coastguard Worker getLoopAnalysisUsage(AU);
150*9880d681SAndroid Build Coastguard Worker }
151*9880d681SAndroid Build Coastguard Worker
152*9880d681SAndroid Build Coastguard Worker using llvm::Pass::doFinalization;
153*9880d681SAndroid Build Coastguard Worker
doFinalization__anon7f8510b00111::LegacyLICMPass154*9880d681SAndroid Build Coastguard Worker bool doFinalization() override {
155*9880d681SAndroid Build Coastguard Worker assert(LICM.getLoopToAliasSetMap().empty() &&
156*9880d681SAndroid Build Coastguard Worker "Didn't free loop alias sets");
157*9880d681SAndroid Build Coastguard Worker return false;
158*9880d681SAndroid Build Coastguard Worker }
159*9880d681SAndroid Build Coastguard Worker
160*9880d681SAndroid Build Coastguard Worker private:
161*9880d681SAndroid Build Coastguard Worker LoopInvariantCodeMotion LICM;
162*9880d681SAndroid Build Coastguard Worker
163*9880d681SAndroid Build Coastguard Worker /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
164*9880d681SAndroid Build Coastguard Worker void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
165*9880d681SAndroid Build Coastguard Worker Loop *L) override;
166*9880d681SAndroid Build Coastguard Worker
167*9880d681SAndroid Build Coastguard Worker /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
168*9880d681SAndroid Build Coastguard Worker /// set.
169*9880d681SAndroid Build Coastguard Worker void deleteAnalysisValue(Value *V, Loop *L) override;
170*9880d681SAndroid Build Coastguard Worker
171*9880d681SAndroid Build Coastguard Worker /// Simple Analysis hook. Delete loop L from alias set map.
172*9880d681SAndroid Build Coastguard Worker void deleteAnalysisLoop(Loop *L) override;
173*9880d681SAndroid Build Coastguard Worker };
174*9880d681SAndroid Build Coastguard Worker }
175*9880d681SAndroid Build Coastguard Worker
run(Loop & L,AnalysisManager<Loop> & AM)176*9880d681SAndroid Build Coastguard Worker PreservedAnalyses LICMPass::run(Loop &L, AnalysisManager<Loop> &AM) {
177*9880d681SAndroid Build Coastguard Worker const auto &FAM =
178*9880d681SAndroid Build Coastguard Worker AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
179*9880d681SAndroid Build Coastguard Worker Function *F = L.getHeader()->getParent();
180*9880d681SAndroid Build Coastguard Worker
181*9880d681SAndroid Build Coastguard Worker auto *AA = FAM.getCachedResult<AAManager>(*F);
182*9880d681SAndroid Build Coastguard Worker auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
183*9880d681SAndroid Build Coastguard Worker auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
184*9880d681SAndroid Build Coastguard Worker auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
185*9880d681SAndroid Build Coastguard Worker auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
186*9880d681SAndroid Build Coastguard Worker assert((AA && LI && DT && TLI && SE) && "Analyses for LICM not available");
187*9880d681SAndroid Build Coastguard Worker
188*9880d681SAndroid Build Coastguard Worker LoopInvariantCodeMotion LICM;
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker if (!LICM.runOnLoop(&L, AA, LI, DT, TLI, SE, true))
191*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
192*9880d681SAndroid Build Coastguard Worker
193*9880d681SAndroid Build Coastguard Worker // FIXME: There is no setPreservesCFG in the new PM. When that becomes
194*9880d681SAndroid Build Coastguard Worker // available, it should be used here.
195*9880d681SAndroid Build Coastguard Worker return getLoopPassPreservedAnalyses();
196*9880d681SAndroid Build Coastguard Worker }
197*9880d681SAndroid Build Coastguard Worker
198*9880d681SAndroid Build Coastguard Worker char LegacyLICMPass::ID = 0;
199*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
200*9880d681SAndroid Build Coastguard Worker false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)201*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopPass)
202*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
203*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
204*9880d681SAndroid Build Coastguard Worker false)
205*9880d681SAndroid Build Coastguard Worker
206*9880d681SAndroid Build Coastguard Worker Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
207*9880d681SAndroid Build Coastguard Worker
208*9880d681SAndroid Build Coastguard Worker /// Hoist expressions out of the specified loop. Note, alias info for inner
209*9880d681SAndroid Build Coastguard Worker /// loop is not preserved so it is not a good idea to run LICM multiple
210*9880d681SAndroid Build Coastguard Worker /// times on one loop.
211*9880d681SAndroid Build Coastguard Worker /// We should delete AST for inner loops in the new pass manager to avoid
212*9880d681SAndroid Build Coastguard Worker /// memory leak.
213*9880d681SAndroid Build Coastguard Worker ///
runOnLoop(Loop * L,AliasAnalysis * AA,LoopInfo * LI,DominatorTree * DT,TargetLibraryInfo * TLI,ScalarEvolution * SE,bool DeleteAST)214*9880d681SAndroid Build Coastguard Worker bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
215*9880d681SAndroid Build Coastguard Worker LoopInfo *LI, DominatorTree *DT,
216*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI,
217*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE, bool DeleteAST) {
218*9880d681SAndroid Build Coastguard Worker bool Changed = false;
219*9880d681SAndroid Build Coastguard Worker
220*9880d681SAndroid Build Coastguard Worker assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
221*9880d681SAndroid Build Coastguard Worker
222*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
223*9880d681SAndroid Build Coastguard Worker
224*9880d681SAndroid Build Coastguard Worker // Get the preheader block to move instructions into...
225*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
226*9880d681SAndroid Build Coastguard Worker
227*9880d681SAndroid Build Coastguard Worker // Compute loop safety information.
228*9880d681SAndroid Build Coastguard Worker LoopSafetyInfo SafetyInfo;
229*9880d681SAndroid Build Coastguard Worker computeLoopSafetyInfo(&SafetyInfo, L);
230*9880d681SAndroid Build Coastguard Worker
231*9880d681SAndroid Build Coastguard Worker // We want to visit all of the instructions in this loop... that are not parts
232*9880d681SAndroid Build Coastguard Worker // of our subloops (they have already had their invariants hoisted out of
233*9880d681SAndroid Build Coastguard Worker // their loop, into this loop, so there is no need to process the BODIES of
234*9880d681SAndroid Build Coastguard Worker // the subloops).
235*9880d681SAndroid Build Coastguard Worker //
236*9880d681SAndroid Build Coastguard Worker // Traverse the body of the loop in depth first order on the dominator tree so
237*9880d681SAndroid Build Coastguard Worker // that we are guaranteed to see definitions before we see uses. This allows
238*9880d681SAndroid Build Coastguard Worker // us to sink instructions in one pass, without iteration. After sinking
239*9880d681SAndroid Build Coastguard Worker // instructions, we perform another pass to hoist them out of the loop.
240*9880d681SAndroid Build Coastguard Worker //
241*9880d681SAndroid Build Coastguard Worker if (L->hasDedicatedExits())
242*9880d681SAndroid Build Coastguard Worker Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
243*9880d681SAndroid Build Coastguard Worker CurAST, &SafetyInfo);
244*9880d681SAndroid Build Coastguard Worker if (Preheader)
245*9880d681SAndroid Build Coastguard Worker Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
246*9880d681SAndroid Build Coastguard Worker CurAST, &SafetyInfo);
247*9880d681SAndroid Build Coastguard Worker
248*9880d681SAndroid Build Coastguard Worker // Now that all loop invariants have been removed from the loop, promote any
249*9880d681SAndroid Build Coastguard Worker // memory references to scalars that we can.
250*9880d681SAndroid Build Coastguard Worker if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
251*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 8> ExitBlocks;
252*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 8> InsertPts;
253*9880d681SAndroid Build Coastguard Worker PredIteratorCache PIC;
254*9880d681SAndroid Build Coastguard Worker
255*9880d681SAndroid Build Coastguard Worker // Loop over all of the alias sets in the tracker object.
256*9880d681SAndroid Build Coastguard Worker for (AliasSet &AS : *CurAST)
257*9880d681SAndroid Build Coastguard Worker Changed |= promoteLoopAccessesToScalars(
258*9880d681SAndroid Build Coastguard Worker AS, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L, CurAST, &SafetyInfo);
259*9880d681SAndroid Build Coastguard Worker
260*9880d681SAndroid Build Coastguard Worker // Once we have promoted values across the loop body we have to recursively
261*9880d681SAndroid Build Coastguard Worker // reform LCSSA as any nested loop may now have values defined within the
262*9880d681SAndroid Build Coastguard Worker // loop used in the outer loop.
263*9880d681SAndroid Build Coastguard Worker // FIXME: This is really heavy handed. It would be a bit better to use an
264*9880d681SAndroid Build Coastguard Worker // SSAUpdater strategy during promotion that was LCSSA aware and reformed
265*9880d681SAndroid Build Coastguard Worker // it as it went.
266*9880d681SAndroid Build Coastguard Worker if (Changed) {
267*9880d681SAndroid Build Coastguard Worker formLCSSARecursively(*L, *DT, LI, SE);
268*9880d681SAndroid Build Coastguard Worker }
269*9880d681SAndroid Build Coastguard Worker }
270*9880d681SAndroid Build Coastguard Worker
271*9880d681SAndroid Build Coastguard Worker // Check that neither this loop nor its parent have had LCSSA broken. LICM is
272*9880d681SAndroid Build Coastguard Worker // specifically moving instructions across the loop boundary and so it is
273*9880d681SAndroid Build Coastguard Worker // especially in need of sanity checking here.
274*9880d681SAndroid Build Coastguard Worker assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
275*9880d681SAndroid Build Coastguard Worker assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
276*9880d681SAndroid Build Coastguard Worker "Parent loop not left in LCSSA form after LICM!");
277*9880d681SAndroid Build Coastguard Worker
278*9880d681SAndroid Build Coastguard Worker // If this loop is nested inside of another one, save the alias information
279*9880d681SAndroid Build Coastguard Worker // for when we process the outer loop.
280*9880d681SAndroid Build Coastguard Worker if (L->getParentLoop() && !DeleteAST)
281*9880d681SAndroid Build Coastguard Worker LoopToAliasSetMap[L] = CurAST;
282*9880d681SAndroid Build Coastguard Worker else
283*9880d681SAndroid Build Coastguard Worker delete CurAST;
284*9880d681SAndroid Build Coastguard Worker
285*9880d681SAndroid Build Coastguard Worker if (Changed && SE)
286*9880d681SAndroid Build Coastguard Worker SE->forgetLoopDispositions(L);
287*9880d681SAndroid Build Coastguard Worker return Changed;
288*9880d681SAndroid Build Coastguard Worker }
289*9880d681SAndroid Build Coastguard Worker
290*9880d681SAndroid Build Coastguard Worker /// Walk the specified region of the CFG (defined by all blocks dominated by
291*9880d681SAndroid Build Coastguard Worker /// the specified block, and that are in the current loop) in reverse depth
292*9880d681SAndroid Build Coastguard Worker /// first order w.r.t the DominatorTree. This allows us to visit uses before
293*9880d681SAndroid Build Coastguard Worker /// definitions, allowing us to sink a loop body in one pass without iteration.
294*9880d681SAndroid Build Coastguard Worker ///
sinkRegion(DomTreeNode * N,AliasAnalysis * AA,LoopInfo * LI,DominatorTree * DT,TargetLibraryInfo * TLI,Loop * CurLoop,AliasSetTracker * CurAST,LoopSafetyInfo * SafetyInfo)295*9880d681SAndroid Build Coastguard Worker bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
296*9880d681SAndroid Build Coastguard Worker DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
297*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
298*9880d681SAndroid Build Coastguard Worker
299*9880d681SAndroid Build Coastguard Worker // Verify inputs.
300*9880d681SAndroid Build Coastguard Worker assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
301*9880d681SAndroid Build Coastguard Worker CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
302*9880d681SAndroid Build Coastguard Worker "Unexpected input to sinkRegion");
303*9880d681SAndroid Build Coastguard Worker
304*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = N->getBlock();
305*9880d681SAndroid Build Coastguard Worker // If this subregion is not in the top level loop at all, exit.
306*9880d681SAndroid Build Coastguard Worker if (!CurLoop->contains(BB))
307*9880d681SAndroid Build Coastguard Worker return false;
308*9880d681SAndroid Build Coastguard Worker
309*9880d681SAndroid Build Coastguard Worker // We are processing blocks in reverse dfo, so process children first.
310*9880d681SAndroid Build Coastguard Worker bool Changed = false;
311*9880d681SAndroid Build Coastguard Worker const std::vector<DomTreeNode *> &Children = N->getChildren();
312*9880d681SAndroid Build Coastguard Worker for (DomTreeNode *Child : Children)
313*9880d681SAndroid Build Coastguard Worker Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
314*9880d681SAndroid Build Coastguard Worker
315*9880d681SAndroid Build Coastguard Worker // Only need to process the contents of this block if it is not part of a
316*9880d681SAndroid Build Coastguard Worker // subloop (which would already have been processed).
317*9880d681SAndroid Build Coastguard Worker if (inSubLoop(BB, CurLoop, LI))
318*9880d681SAndroid Build Coastguard Worker return Changed;
319*9880d681SAndroid Build Coastguard Worker
320*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
321*9880d681SAndroid Build Coastguard Worker Instruction &I = *--II;
322*9880d681SAndroid Build Coastguard Worker
323*9880d681SAndroid Build Coastguard Worker // If the instruction is dead, we would try to sink it because it isn't used
324*9880d681SAndroid Build Coastguard Worker // in the loop, instead, just delete it.
325*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(&I, TLI)) {
326*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
327*9880d681SAndroid Build Coastguard Worker ++II;
328*9880d681SAndroid Build Coastguard Worker CurAST->deleteValue(&I);
329*9880d681SAndroid Build Coastguard Worker I.eraseFromParent();
330*9880d681SAndroid Build Coastguard Worker Changed = true;
331*9880d681SAndroid Build Coastguard Worker continue;
332*9880d681SAndroid Build Coastguard Worker }
333*9880d681SAndroid Build Coastguard Worker
334*9880d681SAndroid Build Coastguard Worker // Check to see if we can sink this instruction to the exit blocks
335*9880d681SAndroid Build Coastguard Worker // of the loop. We can do this if the all users of the instruction are
336*9880d681SAndroid Build Coastguard Worker // outside of the loop. In this case, it doesn't even matter if the
337*9880d681SAndroid Build Coastguard Worker // operands of the instruction are loop invariant.
338*9880d681SAndroid Build Coastguard Worker //
339*9880d681SAndroid Build Coastguard Worker if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
340*9880d681SAndroid Build Coastguard Worker canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
341*9880d681SAndroid Build Coastguard Worker ++II;
342*9880d681SAndroid Build Coastguard Worker Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
343*9880d681SAndroid Build Coastguard Worker }
344*9880d681SAndroid Build Coastguard Worker }
345*9880d681SAndroid Build Coastguard Worker return Changed;
346*9880d681SAndroid Build Coastguard Worker }
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard Worker /// Walk the specified region of the CFG (defined by all blocks dominated by
349*9880d681SAndroid Build Coastguard Worker /// the specified block, and that are in the current loop) in depth first
350*9880d681SAndroid Build Coastguard Worker /// order w.r.t the DominatorTree. This allows us to visit definitions before
351*9880d681SAndroid Build Coastguard Worker /// uses, allowing us to hoist a loop body in one pass without iteration.
352*9880d681SAndroid Build Coastguard Worker ///
hoistRegion(DomTreeNode * N,AliasAnalysis * AA,LoopInfo * LI,DominatorTree * DT,TargetLibraryInfo * TLI,Loop * CurLoop,AliasSetTracker * CurAST,LoopSafetyInfo * SafetyInfo)353*9880d681SAndroid Build Coastguard Worker bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354*9880d681SAndroid Build Coastguard Worker DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
355*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
356*9880d681SAndroid Build Coastguard Worker // Verify inputs.
357*9880d681SAndroid Build Coastguard Worker assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
358*9880d681SAndroid Build Coastguard Worker CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
359*9880d681SAndroid Build Coastguard Worker "Unexpected input to hoistRegion");
360*9880d681SAndroid Build Coastguard Worker
361*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = N->getBlock();
362*9880d681SAndroid Build Coastguard Worker
363*9880d681SAndroid Build Coastguard Worker // If this subregion is not in the top level loop at all, exit.
364*9880d681SAndroid Build Coastguard Worker if (!CurLoop->contains(BB))
365*9880d681SAndroid Build Coastguard Worker return false;
366*9880d681SAndroid Build Coastguard Worker
367*9880d681SAndroid Build Coastguard Worker // Only need to process the contents of this block if it is not part of a
368*9880d681SAndroid Build Coastguard Worker // subloop (which would already have been processed).
369*9880d681SAndroid Build Coastguard Worker bool Changed = false;
370*9880d681SAndroid Build Coastguard Worker if (!inSubLoop(BB, CurLoop, LI))
371*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
372*9880d681SAndroid Build Coastguard Worker Instruction &I = *II++;
373*9880d681SAndroid Build Coastguard Worker // Try constant folding this instruction. If all the operands are
374*9880d681SAndroid Build Coastguard Worker // constants, it is technically hoistable, but it would be better to just
375*9880d681SAndroid Build Coastguard Worker // fold it.
376*9880d681SAndroid Build Coastguard Worker if (Constant *C = ConstantFoldInstruction(
377*9880d681SAndroid Build Coastguard Worker &I, I.getModule()->getDataLayout(), TLI)) {
378*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
379*9880d681SAndroid Build Coastguard Worker CurAST->copyValue(&I, C);
380*9880d681SAndroid Build Coastguard Worker CurAST->deleteValue(&I);
381*9880d681SAndroid Build Coastguard Worker I.replaceAllUsesWith(C);
382*9880d681SAndroid Build Coastguard Worker I.eraseFromParent();
383*9880d681SAndroid Build Coastguard Worker continue;
384*9880d681SAndroid Build Coastguard Worker }
385*9880d681SAndroid Build Coastguard Worker
386*9880d681SAndroid Build Coastguard Worker // Try hoisting the instruction out to the preheader. We can only do this
387*9880d681SAndroid Build Coastguard Worker // if all of the operands of the instruction are loop invariant and if it
388*9880d681SAndroid Build Coastguard Worker // is safe to hoist the instruction.
389*9880d681SAndroid Build Coastguard Worker //
390*9880d681SAndroid Build Coastguard Worker if (CurLoop->hasLoopInvariantOperands(&I) &&
391*9880d681SAndroid Build Coastguard Worker canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
392*9880d681SAndroid Build Coastguard Worker isSafeToExecuteUnconditionally(
393*9880d681SAndroid Build Coastguard Worker I, DT, CurLoop, SafetyInfo,
394*9880d681SAndroid Build Coastguard Worker CurLoop->getLoopPreheader()->getTerminator()))
395*9880d681SAndroid Build Coastguard Worker Changed |= hoist(I, DT, CurLoop, SafetyInfo);
396*9880d681SAndroid Build Coastguard Worker }
397*9880d681SAndroid Build Coastguard Worker
398*9880d681SAndroid Build Coastguard Worker const std::vector<DomTreeNode *> &Children = N->getChildren();
399*9880d681SAndroid Build Coastguard Worker for (DomTreeNode *Child : Children)
400*9880d681SAndroid Build Coastguard Worker Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
401*9880d681SAndroid Build Coastguard Worker return Changed;
402*9880d681SAndroid Build Coastguard Worker }
403*9880d681SAndroid Build Coastguard Worker
404*9880d681SAndroid Build Coastguard Worker /// Computes loop safety information, checks loop body & header
405*9880d681SAndroid Build Coastguard Worker /// for the possibility of may throw exception.
406*9880d681SAndroid Build Coastguard Worker ///
computeLoopSafetyInfo(LoopSafetyInfo * SafetyInfo,Loop * CurLoop)407*9880d681SAndroid Build Coastguard Worker void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
408*9880d681SAndroid Build Coastguard Worker assert(CurLoop != nullptr && "CurLoop cant be null");
409*9880d681SAndroid Build Coastguard Worker BasicBlock *Header = CurLoop->getHeader();
410*9880d681SAndroid Build Coastguard Worker // Setting default safety values.
411*9880d681SAndroid Build Coastguard Worker SafetyInfo->MayThrow = false;
412*9880d681SAndroid Build Coastguard Worker SafetyInfo->HeaderMayThrow = false;
413*9880d681SAndroid Build Coastguard Worker // Iterate over header and compute safety info.
414*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = Header->begin(), E = Header->end();
415*9880d681SAndroid Build Coastguard Worker (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
416*9880d681SAndroid Build Coastguard Worker SafetyInfo->HeaderMayThrow |=
417*9880d681SAndroid Build Coastguard Worker !isGuaranteedToTransferExecutionToSuccessor(&*I);
418*9880d681SAndroid Build Coastguard Worker
419*9880d681SAndroid Build Coastguard Worker SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
420*9880d681SAndroid Build Coastguard Worker // Iterate over loop instructions and compute safety info.
421*9880d681SAndroid Build Coastguard Worker for (Loop::block_iterator BB = CurLoop->block_begin(),
422*9880d681SAndroid Build Coastguard Worker BBE = CurLoop->block_end();
423*9880d681SAndroid Build Coastguard Worker (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
424*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
425*9880d681SAndroid Build Coastguard Worker (I != E) && !SafetyInfo->MayThrow; ++I)
426*9880d681SAndroid Build Coastguard Worker SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
427*9880d681SAndroid Build Coastguard Worker
428*9880d681SAndroid Build Coastguard Worker // Compute funclet colors if we might sink/hoist in a function with a funclet
429*9880d681SAndroid Build Coastguard Worker // personality routine.
430*9880d681SAndroid Build Coastguard Worker Function *Fn = CurLoop->getHeader()->getParent();
431*9880d681SAndroid Build Coastguard Worker if (Fn->hasPersonalityFn())
432*9880d681SAndroid Build Coastguard Worker if (Constant *PersonalityFn = Fn->getPersonalityFn())
433*9880d681SAndroid Build Coastguard Worker if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
434*9880d681SAndroid Build Coastguard Worker SafetyInfo->BlockColors = colorEHFunclets(*Fn);
435*9880d681SAndroid Build Coastguard Worker }
436*9880d681SAndroid Build Coastguard Worker
437*9880d681SAndroid Build Coastguard Worker /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
438*9880d681SAndroid Build Coastguard Worker /// instruction.
439*9880d681SAndroid Build Coastguard Worker ///
canSinkOrHoistInst(Instruction & I,AliasAnalysis * AA,DominatorTree * DT,TargetLibraryInfo * TLI,Loop * CurLoop,AliasSetTracker * CurAST,LoopSafetyInfo * SafetyInfo)440*9880d681SAndroid Build Coastguard Worker bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
441*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI, Loop *CurLoop,
442*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
443*9880d681SAndroid Build Coastguard Worker // Loads have extra constraints we have to verify before we can hoist them.
444*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
445*9880d681SAndroid Build Coastguard Worker if (!LI->isUnordered())
446*9880d681SAndroid Build Coastguard Worker return false; // Don't hoist volatile/atomic loads!
447*9880d681SAndroid Build Coastguard Worker
448*9880d681SAndroid Build Coastguard Worker // Loads from constant memory are always safe to move, even if they end up
449*9880d681SAndroid Build Coastguard Worker // in the same alias set as something that ends up being modified.
450*9880d681SAndroid Build Coastguard Worker if (AA->pointsToConstantMemory(LI->getOperand(0)))
451*9880d681SAndroid Build Coastguard Worker return true;
452*9880d681SAndroid Build Coastguard Worker if (LI->getMetadata(LLVMContext::MD_invariant_load))
453*9880d681SAndroid Build Coastguard Worker return true;
454*9880d681SAndroid Build Coastguard Worker
455*9880d681SAndroid Build Coastguard Worker // Don't hoist loads which have may-aliased stores in loop.
456*9880d681SAndroid Build Coastguard Worker uint64_t Size = 0;
457*9880d681SAndroid Build Coastguard Worker if (LI->getType()->isSized())
458*9880d681SAndroid Build Coastguard Worker Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
459*9880d681SAndroid Build Coastguard Worker
460*9880d681SAndroid Build Coastguard Worker AAMDNodes AAInfo;
461*9880d681SAndroid Build Coastguard Worker LI->getAAMetadata(AAInfo);
462*9880d681SAndroid Build Coastguard Worker
463*9880d681SAndroid Build Coastguard Worker return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
464*9880d681SAndroid Build Coastguard Worker } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
465*9880d681SAndroid Build Coastguard Worker // Don't sink or hoist dbg info; it's legal, but not useful.
466*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(I))
467*9880d681SAndroid Build Coastguard Worker return false;
468*9880d681SAndroid Build Coastguard Worker
469*9880d681SAndroid Build Coastguard Worker // Don't sink calls which can throw.
470*9880d681SAndroid Build Coastguard Worker if (CI->mayThrow())
471*9880d681SAndroid Build Coastguard Worker return false;
472*9880d681SAndroid Build Coastguard Worker
473*9880d681SAndroid Build Coastguard Worker // Handle simple cases by querying alias analysis.
474*9880d681SAndroid Build Coastguard Worker FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
475*9880d681SAndroid Build Coastguard Worker if (Behavior == FMRB_DoesNotAccessMemory)
476*9880d681SAndroid Build Coastguard Worker return true;
477*9880d681SAndroid Build Coastguard Worker if (AliasAnalysis::onlyReadsMemory(Behavior)) {
478*9880d681SAndroid Build Coastguard Worker // A readonly argmemonly function only reads from memory pointed to by
479*9880d681SAndroid Build Coastguard Worker // it's arguments with arbitrary offsets. If we can prove there are no
480*9880d681SAndroid Build Coastguard Worker // writes to this memory in the loop, we can hoist or sink.
481*9880d681SAndroid Build Coastguard Worker if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
482*9880d681SAndroid Build Coastguard Worker for (Value *Op : CI->arg_operands())
483*9880d681SAndroid Build Coastguard Worker if (Op->getType()->isPointerTy() &&
484*9880d681SAndroid Build Coastguard Worker pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
485*9880d681SAndroid Build Coastguard Worker AAMDNodes(), CurAST))
486*9880d681SAndroid Build Coastguard Worker return false;
487*9880d681SAndroid Build Coastguard Worker return true;
488*9880d681SAndroid Build Coastguard Worker }
489*9880d681SAndroid Build Coastguard Worker // If this call only reads from memory and there are no writes to memory
490*9880d681SAndroid Build Coastguard Worker // in the loop, we can hoist or sink the call as appropriate.
491*9880d681SAndroid Build Coastguard Worker bool FoundMod = false;
492*9880d681SAndroid Build Coastguard Worker for (AliasSet &AS : *CurAST) {
493*9880d681SAndroid Build Coastguard Worker if (!AS.isForwardingAliasSet() && AS.isMod()) {
494*9880d681SAndroid Build Coastguard Worker FoundMod = true;
495*9880d681SAndroid Build Coastguard Worker break;
496*9880d681SAndroid Build Coastguard Worker }
497*9880d681SAndroid Build Coastguard Worker }
498*9880d681SAndroid Build Coastguard Worker if (!FoundMod)
499*9880d681SAndroid Build Coastguard Worker return true;
500*9880d681SAndroid Build Coastguard Worker }
501*9880d681SAndroid Build Coastguard Worker
502*9880d681SAndroid Build Coastguard Worker // FIXME: This should use mod/ref information to see if we can hoist or
503*9880d681SAndroid Build Coastguard Worker // sink the call.
504*9880d681SAndroid Build Coastguard Worker
505*9880d681SAndroid Build Coastguard Worker return false;
506*9880d681SAndroid Build Coastguard Worker }
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard Worker // Only these instructions are hoistable/sinkable.
509*9880d681SAndroid Build Coastguard Worker if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
510*9880d681SAndroid Build Coastguard Worker !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
511*9880d681SAndroid Build Coastguard Worker !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
512*9880d681SAndroid Build Coastguard Worker !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
513*9880d681SAndroid Build Coastguard Worker !isa<InsertValueInst>(I))
514*9880d681SAndroid Build Coastguard Worker return false;
515*9880d681SAndroid Build Coastguard Worker
516*9880d681SAndroid Build Coastguard Worker // TODO: Plumb the context instruction through to make hoisting and sinking
517*9880d681SAndroid Build Coastguard Worker // more powerful. Hoisting of loads already works due to the special casing
518*9880d681SAndroid Build Coastguard Worker // above.
519*9880d681SAndroid Build Coastguard Worker return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
520*9880d681SAndroid Build Coastguard Worker }
521*9880d681SAndroid Build Coastguard Worker
522*9880d681SAndroid Build Coastguard Worker /// Returns true if a PHINode is a trivially replaceable with an
523*9880d681SAndroid Build Coastguard Worker /// Instruction.
524*9880d681SAndroid Build Coastguard Worker /// This is true when all incoming values are that instruction.
525*9880d681SAndroid Build Coastguard Worker /// This pattern occurs most often with LCSSA PHI nodes.
526*9880d681SAndroid Build Coastguard Worker ///
isTriviallyReplacablePHI(const PHINode & PN,const Instruction & I)527*9880d681SAndroid Build Coastguard Worker static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
528*9880d681SAndroid Build Coastguard Worker for (const Value *IncValue : PN.incoming_values())
529*9880d681SAndroid Build Coastguard Worker if (IncValue != &I)
530*9880d681SAndroid Build Coastguard Worker return false;
531*9880d681SAndroid Build Coastguard Worker
532*9880d681SAndroid Build Coastguard Worker return true;
533*9880d681SAndroid Build Coastguard Worker }
534*9880d681SAndroid Build Coastguard Worker
535*9880d681SAndroid Build Coastguard Worker /// Return true if the only users of this instruction are outside of
536*9880d681SAndroid Build Coastguard Worker /// the loop. If this is true, we can sink the instruction to the exit
537*9880d681SAndroid Build Coastguard Worker /// blocks of the loop.
538*9880d681SAndroid Build Coastguard Worker ///
isNotUsedInLoop(const Instruction & I,const Loop * CurLoop,const LoopSafetyInfo * SafetyInfo)539*9880d681SAndroid Build Coastguard Worker static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
540*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo) {
541*9880d681SAndroid Build Coastguard Worker const auto &BlockColors = SafetyInfo->BlockColors;
542*9880d681SAndroid Build Coastguard Worker for (const User *U : I.users()) {
543*9880d681SAndroid Build Coastguard Worker const Instruction *UI = cast<Instruction>(U);
544*9880d681SAndroid Build Coastguard Worker if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
545*9880d681SAndroid Build Coastguard Worker const BasicBlock *BB = PN->getParent();
546*9880d681SAndroid Build Coastguard Worker // We cannot sink uses in catchswitches.
547*9880d681SAndroid Build Coastguard Worker if (isa<CatchSwitchInst>(BB->getTerminator()))
548*9880d681SAndroid Build Coastguard Worker return false;
549*9880d681SAndroid Build Coastguard Worker
550*9880d681SAndroid Build Coastguard Worker // We need to sink a callsite to a unique funclet. Avoid sinking if the
551*9880d681SAndroid Build Coastguard Worker // phi use is too muddled.
552*9880d681SAndroid Build Coastguard Worker if (isa<CallInst>(I))
553*9880d681SAndroid Build Coastguard Worker if (!BlockColors.empty() &&
554*9880d681SAndroid Build Coastguard Worker BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
555*9880d681SAndroid Build Coastguard Worker return false;
556*9880d681SAndroid Build Coastguard Worker
557*9880d681SAndroid Build Coastguard Worker // A PHI node where all of the incoming values are this instruction are
558*9880d681SAndroid Build Coastguard Worker // special -- they can just be RAUW'ed with the instruction and thus
559*9880d681SAndroid Build Coastguard Worker // don't require a use in the predecessor. This is a particular important
560*9880d681SAndroid Build Coastguard Worker // special case because it is the pattern found in LCSSA form.
561*9880d681SAndroid Build Coastguard Worker if (isTriviallyReplacablePHI(*PN, I)) {
562*9880d681SAndroid Build Coastguard Worker if (CurLoop->contains(PN))
563*9880d681SAndroid Build Coastguard Worker return false;
564*9880d681SAndroid Build Coastguard Worker else
565*9880d681SAndroid Build Coastguard Worker continue;
566*9880d681SAndroid Build Coastguard Worker }
567*9880d681SAndroid Build Coastguard Worker
568*9880d681SAndroid Build Coastguard Worker // Otherwise, PHI node uses occur in predecessor blocks if the incoming
569*9880d681SAndroid Build Coastguard Worker // values. Check for such a use being inside the loop.
570*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
571*9880d681SAndroid Build Coastguard Worker if (PN->getIncomingValue(i) == &I)
572*9880d681SAndroid Build Coastguard Worker if (CurLoop->contains(PN->getIncomingBlock(i)))
573*9880d681SAndroid Build Coastguard Worker return false;
574*9880d681SAndroid Build Coastguard Worker
575*9880d681SAndroid Build Coastguard Worker continue;
576*9880d681SAndroid Build Coastguard Worker }
577*9880d681SAndroid Build Coastguard Worker
578*9880d681SAndroid Build Coastguard Worker if (CurLoop->contains(UI))
579*9880d681SAndroid Build Coastguard Worker return false;
580*9880d681SAndroid Build Coastguard Worker }
581*9880d681SAndroid Build Coastguard Worker return true;
582*9880d681SAndroid Build Coastguard Worker }
583*9880d681SAndroid Build Coastguard Worker
584*9880d681SAndroid Build Coastguard Worker static Instruction *
CloneInstructionInExitBlock(Instruction & I,BasicBlock & ExitBlock,PHINode & PN,const LoopInfo * LI,const LoopSafetyInfo * SafetyInfo)585*9880d681SAndroid Build Coastguard Worker CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
586*9880d681SAndroid Build Coastguard Worker const LoopInfo *LI,
587*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo) {
588*9880d681SAndroid Build Coastguard Worker Instruction *New;
589*9880d681SAndroid Build Coastguard Worker if (auto *CI = dyn_cast<CallInst>(&I)) {
590*9880d681SAndroid Build Coastguard Worker const auto &BlockColors = SafetyInfo->BlockColors;
591*9880d681SAndroid Build Coastguard Worker
592*9880d681SAndroid Build Coastguard Worker // Sinking call-sites need to be handled differently from other
593*9880d681SAndroid Build Coastguard Worker // instructions. The cloned call-site needs a funclet bundle operand
594*9880d681SAndroid Build Coastguard Worker // appropriate for it's location in the CFG.
595*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
596*9880d681SAndroid Build Coastguard Worker for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
597*9880d681SAndroid Build Coastguard Worker BundleIdx != BundleEnd; ++BundleIdx) {
598*9880d681SAndroid Build Coastguard Worker OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
599*9880d681SAndroid Build Coastguard Worker if (Bundle.getTagID() == LLVMContext::OB_funclet)
600*9880d681SAndroid Build Coastguard Worker continue;
601*9880d681SAndroid Build Coastguard Worker
602*9880d681SAndroid Build Coastguard Worker OpBundles.emplace_back(Bundle);
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker
605*9880d681SAndroid Build Coastguard Worker if (!BlockColors.empty()) {
606*9880d681SAndroid Build Coastguard Worker const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
607*9880d681SAndroid Build Coastguard Worker assert(CV.size() == 1 && "non-unique color for exit block!");
608*9880d681SAndroid Build Coastguard Worker BasicBlock *BBColor = CV.front();
609*9880d681SAndroid Build Coastguard Worker Instruction *EHPad = BBColor->getFirstNonPHI();
610*9880d681SAndroid Build Coastguard Worker if (EHPad->isEHPad())
611*9880d681SAndroid Build Coastguard Worker OpBundles.emplace_back("funclet", EHPad);
612*9880d681SAndroid Build Coastguard Worker }
613*9880d681SAndroid Build Coastguard Worker
614*9880d681SAndroid Build Coastguard Worker New = CallInst::Create(CI, OpBundles);
615*9880d681SAndroid Build Coastguard Worker } else {
616*9880d681SAndroid Build Coastguard Worker New = I.clone();
617*9880d681SAndroid Build Coastguard Worker }
618*9880d681SAndroid Build Coastguard Worker
619*9880d681SAndroid Build Coastguard Worker ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
620*9880d681SAndroid Build Coastguard Worker if (!I.getName().empty())
621*9880d681SAndroid Build Coastguard Worker New->setName(I.getName() + ".le");
622*9880d681SAndroid Build Coastguard Worker
623*9880d681SAndroid Build Coastguard Worker // Build LCSSA PHI nodes for any in-loop operands. Note that this is
624*9880d681SAndroid Build Coastguard Worker // particularly cheap because we can rip off the PHI node that we're
625*9880d681SAndroid Build Coastguard Worker // replacing for the number and blocks of the predecessors.
626*9880d681SAndroid Build Coastguard Worker // OPT: If this shows up in a profile, we can instead finish sinking all
627*9880d681SAndroid Build Coastguard Worker // invariant instructions, and then walk their operands to re-establish
628*9880d681SAndroid Build Coastguard Worker // LCSSA. That will eliminate creating PHI nodes just to nuke them when
629*9880d681SAndroid Build Coastguard Worker // sinking bottom-up.
630*9880d681SAndroid Build Coastguard Worker for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
631*9880d681SAndroid Build Coastguard Worker ++OI)
632*9880d681SAndroid Build Coastguard Worker if (Instruction *OInst = dyn_cast<Instruction>(*OI))
633*9880d681SAndroid Build Coastguard Worker if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
634*9880d681SAndroid Build Coastguard Worker if (!OLoop->contains(&PN)) {
635*9880d681SAndroid Build Coastguard Worker PHINode *OpPN =
636*9880d681SAndroid Build Coastguard Worker PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
637*9880d681SAndroid Build Coastguard Worker OInst->getName() + ".lcssa", &ExitBlock.front());
638*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
639*9880d681SAndroid Build Coastguard Worker OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
640*9880d681SAndroid Build Coastguard Worker *OI = OpPN;
641*9880d681SAndroid Build Coastguard Worker }
642*9880d681SAndroid Build Coastguard Worker return New;
643*9880d681SAndroid Build Coastguard Worker }
644*9880d681SAndroid Build Coastguard Worker
645*9880d681SAndroid Build Coastguard Worker /// When an instruction is found to only be used outside of the loop, this
646*9880d681SAndroid Build Coastguard Worker /// function moves it to the exit blocks and patches up SSA form as needed.
647*9880d681SAndroid Build Coastguard Worker /// This method is guaranteed to remove the original instruction from its
648*9880d681SAndroid Build Coastguard Worker /// position, and may either delete it or move it to outside of the loop.
649*9880d681SAndroid Build Coastguard Worker ///
sink(Instruction & I,const LoopInfo * LI,const DominatorTree * DT,const Loop * CurLoop,AliasSetTracker * CurAST,const LoopSafetyInfo * SafetyInfo)650*9880d681SAndroid Build Coastguard Worker static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
651*9880d681SAndroid Build Coastguard Worker const Loop *CurLoop, AliasSetTracker *CurAST,
652*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo) {
653*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
654*9880d681SAndroid Build Coastguard Worker bool Changed = false;
655*9880d681SAndroid Build Coastguard Worker if (isa<LoadInst>(I))
656*9880d681SAndroid Build Coastguard Worker ++NumMovedLoads;
657*9880d681SAndroid Build Coastguard Worker else if (isa<CallInst>(I))
658*9880d681SAndroid Build Coastguard Worker ++NumMovedCalls;
659*9880d681SAndroid Build Coastguard Worker ++NumSunk;
660*9880d681SAndroid Build Coastguard Worker Changed = true;
661*9880d681SAndroid Build Coastguard Worker
662*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
663*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 32> ExitBlocks;
664*9880d681SAndroid Build Coastguard Worker CurLoop->getUniqueExitBlocks(ExitBlocks);
665*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
666*9880d681SAndroid Build Coastguard Worker ExitBlocks.end());
667*9880d681SAndroid Build Coastguard Worker #endif
668*9880d681SAndroid Build Coastguard Worker
669*9880d681SAndroid Build Coastguard Worker // Clones of this instruction. Don't create more than one per exit block!
670*9880d681SAndroid Build Coastguard Worker SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
671*9880d681SAndroid Build Coastguard Worker
672*9880d681SAndroid Build Coastguard Worker // If this instruction is only used outside of the loop, then all users are
673*9880d681SAndroid Build Coastguard Worker // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
674*9880d681SAndroid Build Coastguard Worker // the instruction.
675*9880d681SAndroid Build Coastguard Worker while (!I.use_empty()) {
676*9880d681SAndroid Build Coastguard Worker Value::user_iterator UI = I.user_begin();
677*9880d681SAndroid Build Coastguard Worker auto *User = cast<Instruction>(*UI);
678*9880d681SAndroid Build Coastguard Worker if (!DT->isReachableFromEntry(User->getParent())) {
679*9880d681SAndroid Build Coastguard Worker User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
680*9880d681SAndroid Build Coastguard Worker continue;
681*9880d681SAndroid Build Coastguard Worker }
682*9880d681SAndroid Build Coastguard Worker // The user must be a PHI node.
683*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(User);
684*9880d681SAndroid Build Coastguard Worker
685*9880d681SAndroid Build Coastguard Worker // Surprisingly, instructions can be used outside of loops without any
686*9880d681SAndroid Build Coastguard Worker // exits. This can only happen in PHI nodes if the incoming block is
687*9880d681SAndroid Build Coastguard Worker // unreachable.
688*9880d681SAndroid Build Coastguard Worker Use &U = UI.getUse();
689*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = PN->getIncomingBlock(U);
690*9880d681SAndroid Build Coastguard Worker if (!DT->isReachableFromEntry(BB)) {
691*9880d681SAndroid Build Coastguard Worker U = UndefValue::get(I.getType());
692*9880d681SAndroid Build Coastguard Worker continue;
693*9880d681SAndroid Build Coastguard Worker }
694*9880d681SAndroid Build Coastguard Worker
695*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitBlock = PN->getParent();
696*9880d681SAndroid Build Coastguard Worker assert(ExitBlockSet.count(ExitBlock) &&
697*9880d681SAndroid Build Coastguard Worker "The LCSSA PHI is not in an exit block!");
698*9880d681SAndroid Build Coastguard Worker
699*9880d681SAndroid Build Coastguard Worker Instruction *New;
700*9880d681SAndroid Build Coastguard Worker auto It = SunkCopies.find(ExitBlock);
701*9880d681SAndroid Build Coastguard Worker if (It != SunkCopies.end())
702*9880d681SAndroid Build Coastguard Worker New = It->second;
703*9880d681SAndroid Build Coastguard Worker else
704*9880d681SAndroid Build Coastguard Worker New = SunkCopies[ExitBlock] =
705*9880d681SAndroid Build Coastguard Worker CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
706*9880d681SAndroid Build Coastguard Worker
707*9880d681SAndroid Build Coastguard Worker PN->replaceAllUsesWith(New);
708*9880d681SAndroid Build Coastguard Worker PN->eraseFromParent();
709*9880d681SAndroid Build Coastguard Worker }
710*9880d681SAndroid Build Coastguard Worker
711*9880d681SAndroid Build Coastguard Worker CurAST->deleteValue(&I);
712*9880d681SAndroid Build Coastguard Worker I.eraseFromParent();
713*9880d681SAndroid Build Coastguard Worker return Changed;
714*9880d681SAndroid Build Coastguard Worker }
715*9880d681SAndroid Build Coastguard Worker
716*9880d681SAndroid Build Coastguard Worker /// When an instruction is found to only use loop invariant operands that
717*9880d681SAndroid Build Coastguard Worker /// is safe to hoist, this instruction is called to do the dirty work.
718*9880d681SAndroid Build Coastguard Worker ///
hoist(Instruction & I,const DominatorTree * DT,const Loop * CurLoop,const LoopSafetyInfo * SafetyInfo)719*9880d681SAndroid Build Coastguard Worker static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
720*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo) {
721*9880d681SAndroid Build Coastguard Worker auto *Preheader = CurLoop->getLoopPreheader();
722*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
723*9880d681SAndroid Build Coastguard Worker << "\n");
724*9880d681SAndroid Build Coastguard Worker
725*9880d681SAndroid Build Coastguard Worker // Metadata can be dependent on conditions we are hoisting above.
726*9880d681SAndroid Build Coastguard Worker // Conservatively strip all metadata on the instruction unless we were
727*9880d681SAndroid Build Coastguard Worker // guaranteed to execute I if we entered the loop, in which case the metadata
728*9880d681SAndroid Build Coastguard Worker // is valid in the loop preheader.
729*9880d681SAndroid Build Coastguard Worker if (I.hasMetadataOtherThanDebugLoc() &&
730*9880d681SAndroid Build Coastguard Worker // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
731*9880d681SAndroid Build Coastguard Worker // time in isGuaranteedToExecute if we don't actually have anything to
732*9880d681SAndroid Build Coastguard Worker // drop. It is a compile time optimization, not required for correctness.
733*9880d681SAndroid Build Coastguard Worker !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
734*9880d681SAndroid Build Coastguard Worker I.dropUnknownNonDebugMetadata();
735*9880d681SAndroid Build Coastguard Worker
736*9880d681SAndroid Build Coastguard Worker // Move the new node to the Preheader, before its terminator.
737*9880d681SAndroid Build Coastguard Worker I.moveBefore(Preheader->getTerminator());
738*9880d681SAndroid Build Coastguard Worker
739*9880d681SAndroid Build Coastguard Worker if (isa<LoadInst>(I))
740*9880d681SAndroid Build Coastguard Worker ++NumMovedLoads;
741*9880d681SAndroid Build Coastguard Worker else if (isa<CallInst>(I))
742*9880d681SAndroid Build Coastguard Worker ++NumMovedCalls;
743*9880d681SAndroid Build Coastguard Worker ++NumHoisted;
744*9880d681SAndroid Build Coastguard Worker return true;
745*9880d681SAndroid Build Coastguard Worker }
746*9880d681SAndroid Build Coastguard Worker
747*9880d681SAndroid Build Coastguard Worker /// Only sink or hoist an instruction if it is not a trapping instruction,
748*9880d681SAndroid Build Coastguard Worker /// or if the instruction is known not to trap when moved to the preheader.
749*9880d681SAndroid Build Coastguard Worker /// or if it is a trapping instruction and is guaranteed to execute.
isSafeToExecuteUnconditionally(const Instruction & Inst,const DominatorTree * DT,const Loop * CurLoop,const LoopSafetyInfo * SafetyInfo,const Instruction * CtxI)750*9880d681SAndroid Build Coastguard Worker static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
751*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT,
752*9880d681SAndroid Build Coastguard Worker const Loop *CurLoop,
753*9880d681SAndroid Build Coastguard Worker const LoopSafetyInfo *SafetyInfo,
754*9880d681SAndroid Build Coastguard Worker const Instruction *CtxI) {
755*9880d681SAndroid Build Coastguard Worker if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
756*9880d681SAndroid Build Coastguard Worker return true;
757*9880d681SAndroid Build Coastguard Worker
758*9880d681SAndroid Build Coastguard Worker return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
759*9880d681SAndroid Build Coastguard Worker }
760*9880d681SAndroid Build Coastguard Worker
761*9880d681SAndroid Build Coastguard Worker namespace {
762*9880d681SAndroid Build Coastguard Worker class LoopPromoter : public LoadAndStorePromoter {
763*9880d681SAndroid Build Coastguard Worker Value *SomePtr; // Designated pointer to store to.
764*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<Value *> &PointerMustAliases;
765*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
766*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Instruction *> &LoopInsertPts;
767*9880d681SAndroid Build Coastguard Worker PredIteratorCache &PredCache;
768*9880d681SAndroid Build Coastguard Worker AliasSetTracker &AST;
769*9880d681SAndroid Build Coastguard Worker LoopInfo &LI;
770*9880d681SAndroid Build Coastguard Worker DebugLoc DL;
771*9880d681SAndroid Build Coastguard Worker int Alignment;
772*9880d681SAndroid Build Coastguard Worker AAMDNodes AATags;
773*9880d681SAndroid Build Coastguard Worker
maybeInsertLCSSAPHI(Value * V,BasicBlock * BB) const774*9880d681SAndroid Build Coastguard Worker Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
775*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(V))
776*9880d681SAndroid Build Coastguard Worker if (Loop *L = LI.getLoopFor(I->getParent()))
777*9880d681SAndroid Build Coastguard Worker if (!L->contains(BB)) {
778*9880d681SAndroid Build Coastguard Worker // We need to create an LCSSA PHI node for the incoming value and
779*9880d681SAndroid Build Coastguard Worker // store that.
780*9880d681SAndroid Build Coastguard Worker PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
781*9880d681SAndroid Build Coastguard Worker I->getName() + ".lcssa", &BB->front());
782*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Pred : PredCache.get(BB))
783*9880d681SAndroid Build Coastguard Worker PN->addIncoming(I, Pred);
784*9880d681SAndroid Build Coastguard Worker return PN;
785*9880d681SAndroid Build Coastguard Worker }
786*9880d681SAndroid Build Coastguard Worker return V;
787*9880d681SAndroid Build Coastguard Worker }
788*9880d681SAndroid Build Coastguard Worker
789*9880d681SAndroid Build Coastguard Worker public:
LoopPromoter(Value * SP,ArrayRef<const Instruction * > Insts,SSAUpdater & S,SmallPtrSetImpl<Value * > & PMA,SmallVectorImpl<BasicBlock * > & LEB,SmallVectorImpl<Instruction * > & LIP,PredIteratorCache & PIC,AliasSetTracker & ast,LoopInfo & li,DebugLoc dl,int alignment,const AAMDNodes & AATags)790*9880d681SAndroid Build Coastguard Worker LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
791*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<Value *> &PMA,
792*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<BasicBlock *> &LEB,
793*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
794*9880d681SAndroid Build Coastguard Worker AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
795*9880d681SAndroid Build Coastguard Worker const AAMDNodes &AATags)
796*9880d681SAndroid Build Coastguard Worker : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
797*9880d681SAndroid Build Coastguard Worker LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
798*9880d681SAndroid Build Coastguard Worker LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
799*9880d681SAndroid Build Coastguard Worker
isInstInList(Instruction * I,const SmallVectorImpl<Instruction * > &) const800*9880d681SAndroid Build Coastguard Worker bool isInstInList(Instruction *I,
801*9880d681SAndroid Build Coastguard Worker const SmallVectorImpl<Instruction *> &) const override {
802*9880d681SAndroid Build Coastguard Worker Value *Ptr;
803*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(I))
804*9880d681SAndroid Build Coastguard Worker Ptr = LI->getOperand(0);
805*9880d681SAndroid Build Coastguard Worker else
806*9880d681SAndroid Build Coastguard Worker Ptr = cast<StoreInst>(I)->getPointerOperand();
807*9880d681SAndroid Build Coastguard Worker return PointerMustAliases.count(Ptr);
808*9880d681SAndroid Build Coastguard Worker }
809*9880d681SAndroid Build Coastguard Worker
doExtraRewritesBeforeFinalDeletion() const810*9880d681SAndroid Build Coastguard Worker void doExtraRewritesBeforeFinalDeletion() const override {
811*9880d681SAndroid Build Coastguard Worker // Insert stores after in the loop exit blocks. Each exit block gets a
812*9880d681SAndroid Build Coastguard Worker // store of the live-out values that feed them. Since we've already told
813*9880d681SAndroid Build Coastguard Worker // the SSA updater about the defs in the loop and the preheader
814*9880d681SAndroid Build Coastguard Worker // definition, it is all set and we can start using it.
815*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
816*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitBlock = LoopExitBlocks[i];
817*9880d681SAndroid Build Coastguard Worker Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
818*9880d681SAndroid Build Coastguard Worker LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
819*9880d681SAndroid Build Coastguard Worker Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
820*9880d681SAndroid Build Coastguard Worker Instruction *InsertPos = LoopInsertPts[i];
821*9880d681SAndroid Build Coastguard Worker StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
822*9880d681SAndroid Build Coastguard Worker NewSI->setAlignment(Alignment);
823*9880d681SAndroid Build Coastguard Worker NewSI->setDebugLoc(DL);
824*9880d681SAndroid Build Coastguard Worker if (AATags)
825*9880d681SAndroid Build Coastguard Worker NewSI->setAAMetadata(AATags);
826*9880d681SAndroid Build Coastguard Worker }
827*9880d681SAndroid Build Coastguard Worker }
828*9880d681SAndroid Build Coastguard Worker
replaceLoadWithValue(LoadInst * LI,Value * V) const829*9880d681SAndroid Build Coastguard Worker void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
830*9880d681SAndroid Build Coastguard Worker // Update alias analysis.
831*9880d681SAndroid Build Coastguard Worker AST.copyValue(LI, V);
832*9880d681SAndroid Build Coastguard Worker }
instructionDeleted(Instruction * I) const833*9880d681SAndroid Build Coastguard Worker void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
834*9880d681SAndroid Build Coastguard Worker };
835*9880d681SAndroid Build Coastguard Worker } // end anon namespace
836*9880d681SAndroid Build Coastguard Worker
837*9880d681SAndroid Build Coastguard Worker /// Try to promote memory values to scalars by sinking stores out of the
838*9880d681SAndroid Build Coastguard Worker /// loop and moving loads to before the loop. We do this by looping over
839*9880d681SAndroid Build Coastguard Worker /// the stores in the loop, looking for stores to Must pointers which are
840*9880d681SAndroid Build Coastguard Worker /// loop invariant.
841*9880d681SAndroid Build Coastguard Worker ///
promoteLoopAccessesToScalars(AliasSet & AS,SmallVectorImpl<BasicBlock * > & ExitBlocks,SmallVectorImpl<Instruction * > & InsertPts,PredIteratorCache & PIC,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,Loop * CurLoop,AliasSetTracker * CurAST,LoopSafetyInfo * SafetyInfo)842*9880d681SAndroid Build Coastguard Worker bool llvm::promoteLoopAccessesToScalars(
843*9880d681SAndroid Build Coastguard Worker AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
844*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
845*9880d681SAndroid Build Coastguard Worker LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
846*9880d681SAndroid Build Coastguard Worker Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
847*9880d681SAndroid Build Coastguard Worker // Verify inputs.
848*9880d681SAndroid Build Coastguard Worker assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
849*9880d681SAndroid Build Coastguard Worker CurAST != nullptr && SafetyInfo != nullptr &&
850*9880d681SAndroid Build Coastguard Worker "Unexpected Input to promoteLoopAccessesToScalars");
851*9880d681SAndroid Build Coastguard Worker
852*9880d681SAndroid Build Coastguard Worker // We can promote this alias set if it has a store, if it is a "Must" alias
853*9880d681SAndroid Build Coastguard Worker // set, if the pointer is loop invariant, and if we are not eliminating any
854*9880d681SAndroid Build Coastguard Worker // volatile loads or stores.
855*9880d681SAndroid Build Coastguard Worker if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
856*9880d681SAndroid Build Coastguard Worker AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
857*9880d681SAndroid Build Coastguard Worker return false;
858*9880d681SAndroid Build Coastguard Worker
859*9880d681SAndroid Build Coastguard Worker assert(!AS.empty() &&
860*9880d681SAndroid Build Coastguard Worker "Must alias set should have at least one pointer element in it!");
861*9880d681SAndroid Build Coastguard Worker
862*9880d681SAndroid Build Coastguard Worker Value *SomePtr = AS.begin()->getValue();
863*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = CurLoop->getLoopPreheader();
864*9880d681SAndroid Build Coastguard Worker
865*9880d681SAndroid Build Coastguard Worker // It isn't safe to promote a load/store from the loop if the load/store is
866*9880d681SAndroid Build Coastguard Worker // conditional. For example, turning:
867*9880d681SAndroid Build Coastguard Worker //
868*9880d681SAndroid Build Coastguard Worker // for () { if (c) *P += 1; }
869*9880d681SAndroid Build Coastguard Worker //
870*9880d681SAndroid Build Coastguard Worker // into:
871*9880d681SAndroid Build Coastguard Worker //
872*9880d681SAndroid Build Coastguard Worker // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
873*9880d681SAndroid Build Coastguard Worker //
874*9880d681SAndroid Build Coastguard Worker // is not safe, because *P may only be valid to access if 'c' is true.
875*9880d681SAndroid Build Coastguard Worker //
876*9880d681SAndroid Build Coastguard Worker // The safety property divides into two parts:
877*9880d681SAndroid Build Coastguard Worker // 1) The memory may not be dereferenceable on entry to the loop. In this
878*9880d681SAndroid Build Coastguard Worker // case, we can't insert the required load in the preheader.
879*9880d681SAndroid Build Coastguard Worker // 2) The memory model does not allow us to insert a store along any dynamic
880*9880d681SAndroid Build Coastguard Worker // path which did not originally have one.
881*9880d681SAndroid Build Coastguard Worker //
882*9880d681SAndroid Build Coastguard Worker // It is safe to promote P if all uses are direct load/stores and if at
883*9880d681SAndroid Build Coastguard Worker // least one is guaranteed to be executed.
884*9880d681SAndroid Build Coastguard Worker bool GuaranteedToExecute = false;
885*9880d681SAndroid Build Coastguard Worker
886*9880d681SAndroid Build Coastguard Worker // It is also safe to promote P if we can prove that speculating a load into
887*9880d681SAndroid Build Coastguard Worker // the preheader is safe (i.e. proving dereferenceability on all
888*9880d681SAndroid Build Coastguard Worker // paths through the loop), and that the memory can be proven thread local
889*9880d681SAndroid Build Coastguard Worker // (so that the memory model requirement doesn't apply.) We first establish
890*9880d681SAndroid Build Coastguard Worker // the former, and then run a capture analysis below to establish the later.
891*9880d681SAndroid Build Coastguard Worker // We can use any access within the alias set to prove dereferenceability
892*9880d681SAndroid Build Coastguard Worker // since they're all must alias.
893*9880d681SAndroid Build Coastguard Worker bool CanSpeculateLoad = false;
894*9880d681SAndroid Build Coastguard Worker
895*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 64> LoopUses;
896*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value *, 4> PointerMustAliases;
897*9880d681SAndroid Build Coastguard Worker
898*9880d681SAndroid Build Coastguard Worker // We start with an alignment of one and try to find instructions that allow
899*9880d681SAndroid Build Coastguard Worker // us to prove better alignment.
900*9880d681SAndroid Build Coastguard Worker unsigned Alignment = 1;
901*9880d681SAndroid Build Coastguard Worker AAMDNodes AATags;
902*9880d681SAndroid Build Coastguard Worker bool HasDedicatedExits = CurLoop->hasDedicatedExits();
903*9880d681SAndroid Build Coastguard Worker
904*9880d681SAndroid Build Coastguard Worker // Don't sink stores from loops without dedicated block exits. Exits
905*9880d681SAndroid Build Coastguard Worker // containing indirect branches are not transformed by loop simplify,
906*9880d681SAndroid Build Coastguard Worker // make sure we catch that. An additional load may be generated in the
907*9880d681SAndroid Build Coastguard Worker // preheader for SSA updater, so also avoid sinking when no preheader
908*9880d681SAndroid Build Coastguard Worker // is available.
909*9880d681SAndroid Build Coastguard Worker if (!HasDedicatedExits || !Preheader)
910*9880d681SAndroid Build Coastguard Worker return false;
911*9880d681SAndroid Build Coastguard Worker
912*9880d681SAndroid Build Coastguard Worker const DataLayout &MDL = Preheader->getModule()->getDataLayout();
913*9880d681SAndroid Build Coastguard Worker
914*9880d681SAndroid Build Coastguard Worker if (SafetyInfo->MayThrow) {
915*9880d681SAndroid Build Coastguard Worker // If a loop can throw, we have to insert a store along each unwind edge.
916*9880d681SAndroid Build Coastguard Worker // That said, we can't actually make the unwind edge explicit. Therefore,
917*9880d681SAndroid Build Coastguard Worker // we have to prove that the store is dead along the unwind edge.
918*9880d681SAndroid Build Coastguard Worker //
919*9880d681SAndroid Build Coastguard Worker // Currently, this code just special-cases alloca instructions.
920*9880d681SAndroid Build Coastguard Worker if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
921*9880d681SAndroid Build Coastguard Worker return false;
922*9880d681SAndroid Build Coastguard Worker }
923*9880d681SAndroid Build Coastguard Worker
924*9880d681SAndroid Build Coastguard Worker // Check that all of the pointers in the alias set have the same type. We
925*9880d681SAndroid Build Coastguard Worker // cannot (yet) promote a memory location that is loaded and stored in
926*9880d681SAndroid Build Coastguard Worker // different sizes. While we are at it, collect alignment and AA info.
927*9880d681SAndroid Build Coastguard Worker bool Changed = false;
928*9880d681SAndroid Build Coastguard Worker for (const auto &ASI : AS) {
929*9880d681SAndroid Build Coastguard Worker Value *ASIV = ASI.getValue();
930*9880d681SAndroid Build Coastguard Worker PointerMustAliases.insert(ASIV);
931*9880d681SAndroid Build Coastguard Worker
932*9880d681SAndroid Build Coastguard Worker // Check that all of the pointers in the alias set have the same type. We
933*9880d681SAndroid Build Coastguard Worker // cannot (yet) promote a memory location that is loaded and stored in
934*9880d681SAndroid Build Coastguard Worker // different sizes.
935*9880d681SAndroid Build Coastguard Worker if (SomePtr->getType() != ASIV->getType())
936*9880d681SAndroid Build Coastguard Worker return Changed;
937*9880d681SAndroid Build Coastguard Worker
938*9880d681SAndroid Build Coastguard Worker for (User *U : ASIV->users()) {
939*9880d681SAndroid Build Coastguard Worker // Ignore instructions that are outside the loop.
940*9880d681SAndroid Build Coastguard Worker Instruction *UI = dyn_cast<Instruction>(U);
941*9880d681SAndroid Build Coastguard Worker if (!UI || !CurLoop->contains(UI))
942*9880d681SAndroid Build Coastguard Worker continue;
943*9880d681SAndroid Build Coastguard Worker
944*9880d681SAndroid Build Coastguard Worker // If there is an non-load/store instruction in the loop, we can't promote
945*9880d681SAndroid Build Coastguard Worker // it.
946*9880d681SAndroid Build Coastguard Worker if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
947*9880d681SAndroid Build Coastguard Worker assert(!Load->isVolatile() && "AST broken");
948*9880d681SAndroid Build Coastguard Worker if (!Load->isSimple())
949*9880d681SAndroid Build Coastguard Worker return Changed;
950*9880d681SAndroid Build Coastguard Worker
951*9880d681SAndroid Build Coastguard Worker if (!GuaranteedToExecute && !CanSpeculateLoad)
952*9880d681SAndroid Build Coastguard Worker CanSpeculateLoad = isSafeToExecuteUnconditionally(
953*9880d681SAndroid Build Coastguard Worker *Load, DT, CurLoop, SafetyInfo, Preheader->getTerminator());
954*9880d681SAndroid Build Coastguard Worker } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
955*9880d681SAndroid Build Coastguard Worker // Stores *of* the pointer are not interesting, only stores *to* the
956*9880d681SAndroid Build Coastguard Worker // pointer.
957*9880d681SAndroid Build Coastguard Worker if (UI->getOperand(1) != ASIV)
958*9880d681SAndroid Build Coastguard Worker continue;
959*9880d681SAndroid Build Coastguard Worker assert(!Store->isVolatile() && "AST broken");
960*9880d681SAndroid Build Coastguard Worker if (!Store->isSimple())
961*9880d681SAndroid Build Coastguard Worker return Changed;
962*9880d681SAndroid Build Coastguard Worker
963*9880d681SAndroid Build Coastguard Worker // Note that we only check GuaranteedToExecute inside the store case
964*9880d681SAndroid Build Coastguard Worker // so that we do not introduce stores where they did not exist before
965*9880d681SAndroid Build Coastguard Worker // (which would break the LLVM concurrency model).
966*9880d681SAndroid Build Coastguard Worker
967*9880d681SAndroid Build Coastguard Worker // If the alignment of this instruction allows us to specify a more
968*9880d681SAndroid Build Coastguard Worker // restrictive (and performant) alignment and if we are sure this
969*9880d681SAndroid Build Coastguard Worker // instruction will be executed, update the alignment.
970*9880d681SAndroid Build Coastguard Worker // Larger is better, with the exception of 0 being the best alignment.
971*9880d681SAndroid Build Coastguard Worker unsigned InstAlignment = Store->getAlignment();
972*9880d681SAndroid Build Coastguard Worker if ((InstAlignment > Alignment || InstAlignment == 0) &&
973*9880d681SAndroid Build Coastguard Worker Alignment != 0) {
974*9880d681SAndroid Build Coastguard Worker if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
975*9880d681SAndroid Build Coastguard Worker GuaranteedToExecute = true;
976*9880d681SAndroid Build Coastguard Worker Alignment = InstAlignment;
977*9880d681SAndroid Build Coastguard Worker }
978*9880d681SAndroid Build Coastguard Worker } else if (!GuaranteedToExecute) {
979*9880d681SAndroid Build Coastguard Worker GuaranteedToExecute =
980*9880d681SAndroid Build Coastguard Worker isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
981*9880d681SAndroid Build Coastguard Worker }
982*9880d681SAndroid Build Coastguard Worker
983*9880d681SAndroid Build Coastguard Worker if (!GuaranteedToExecute && !CanSpeculateLoad) {
984*9880d681SAndroid Build Coastguard Worker CanSpeculateLoad = isDereferenceableAndAlignedPointer(
985*9880d681SAndroid Build Coastguard Worker Store->getPointerOperand(), Store->getAlignment(), MDL,
986*9880d681SAndroid Build Coastguard Worker Preheader->getTerminator(), DT);
987*9880d681SAndroid Build Coastguard Worker }
988*9880d681SAndroid Build Coastguard Worker } else
989*9880d681SAndroid Build Coastguard Worker return Changed; // Not a load or store.
990*9880d681SAndroid Build Coastguard Worker
991*9880d681SAndroid Build Coastguard Worker // Merge the AA tags.
992*9880d681SAndroid Build Coastguard Worker if (LoopUses.empty()) {
993*9880d681SAndroid Build Coastguard Worker // On the first load/store, just take its AA tags.
994*9880d681SAndroid Build Coastguard Worker UI->getAAMetadata(AATags);
995*9880d681SAndroid Build Coastguard Worker } else if (AATags) {
996*9880d681SAndroid Build Coastguard Worker UI->getAAMetadata(AATags, /* Merge = */ true);
997*9880d681SAndroid Build Coastguard Worker }
998*9880d681SAndroid Build Coastguard Worker
999*9880d681SAndroid Build Coastguard Worker LoopUses.push_back(UI);
1000*9880d681SAndroid Build Coastguard Worker }
1001*9880d681SAndroid Build Coastguard Worker }
1002*9880d681SAndroid Build Coastguard Worker
1003*9880d681SAndroid Build Coastguard Worker // Check legality per comment above. Otherwise, we can't promote.
1004*9880d681SAndroid Build Coastguard Worker bool PromotionIsLegal = GuaranteedToExecute;
1005*9880d681SAndroid Build Coastguard Worker if (!PromotionIsLegal && CanSpeculateLoad) {
1006*9880d681SAndroid Build Coastguard Worker // If this is a thread local location, then we can insert stores along
1007*9880d681SAndroid Build Coastguard Worker // paths which originally didn't have them without violating the memory
1008*9880d681SAndroid Build Coastguard Worker // model.
1009*9880d681SAndroid Build Coastguard Worker Value *Object = GetUnderlyingObject(SomePtr, MDL);
1010*9880d681SAndroid Build Coastguard Worker PromotionIsLegal =
1011*9880d681SAndroid Build Coastguard Worker isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
1012*9880d681SAndroid Build Coastguard Worker }
1013*9880d681SAndroid Build Coastguard Worker if (!PromotionIsLegal)
1014*9880d681SAndroid Build Coastguard Worker return Changed;
1015*9880d681SAndroid Build Coastguard Worker
1016*9880d681SAndroid Build Coastguard Worker // Figure out the loop exits and their insertion points, if this is the
1017*9880d681SAndroid Build Coastguard Worker // first promotion.
1018*9880d681SAndroid Build Coastguard Worker if (ExitBlocks.empty()) {
1019*9880d681SAndroid Build Coastguard Worker CurLoop->getUniqueExitBlocks(ExitBlocks);
1020*9880d681SAndroid Build Coastguard Worker InsertPts.clear();
1021*9880d681SAndroid Build Coastguard Worker InsertPts.reserve(ExitBlocks.size());
1022*9880d681SAndroid Build Coastguard Worker for (BasicBlock *ExitBlock : ExitBlocks)
1023*9880d681SAndroid Build Coastguard Worker InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
1024*9880d681SAndroid Build Coastguard Worker }
1025*9880d681SAndroid Build Coastguard Worker
1026*9880d681SAndroid Build Coastguard Worker // Can't insert into a catchswitch.
1027*9880d681SAndroid Build Coastguard Worker for (BasicBlock *ExitBlock : ExitBlocks)
1028*9880d681SAndroid Build Coastguard Worker if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1029*9880d681SAndroid Build Coastguard Worker return Changed;
1030*9880d681SAndroid Build Coastguard Worker
1031*9880d681SAndroid Build Coastguard Worker // Otherwise, this is safe to promote, lets do it!
1032*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1033*9880d681SAndroid Build Coastguard Worker << '\n');
1034*9880d681SAndroid Build Coastguard Worker Changed = true;
1035*9880d681SAndroid Build Coastguard Worker ++NumPromoted;
1036*9880d681SAndroid Build Coastguard Worker
1037*9880d681SAndroid Build Coastguard Worker // Grab a debug location for the inserted loads/stores; given that the
1038*9880d681SAndroid Build Coastguard Worker // inserted loads/stores have little relation to the original loads/stores,
1039*9880d681SAndroid Build Coastguard Worker // this code just arbitrarily picks a location from one, since any debug
1040*9880d681SAndroid Build Coastguard Worker // location is better than none.
1041*9880d681SAndroid Build Coastguard Worker DebugLoc DL = LoopUses[0]->getDebugLoc();
1042*9880d681SAndroid Build Coastguard Worker
1043*9880d681SAndroid Build Coastguard Worker // We use the SSAUpdater interface to insert phi nodes as required.
1044*9880d681SAndroid Build Coastguard Worker SmallVector<PHINode *, 16> NewPHIs;
1045*9880d681SAndroid Build Coastguard Worker SSAUpdater SSA(&NewPHIs);
1046*9880d681SAndroid Build Coastguard Worker LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1047*9880d681SAndroid Build Coastguard Worker InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
1048*9880d681SAndroid Build Coastguard Worker
1049*9880d681SAndroid Build Coastguard Worker // Set up the preheader to have a definition of the value. It is the live-out
1050*9880d681SAndroid Build Coastguard Worker // value from the preheader that uses in the loop will use.
1051*9880d681SAndroid Build Coastguard Worker LoadInst *PreheaderLoad = new LoadInst(
1052*9880d681SAndroid Build Coastguard Worker SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1053*9880d681SAndroid Build Coastguard Worker PreheaderLoad->setAlignment(Alignment);
1054*9880d681SAndroid Build Coastguard Worker PreheaderLoad->setDebugLoc(DL);
1055*9880d681SAndroid Build Coastguard Worker if (AATags)
1056*9880d681SAndroid Build Coastguard Worker PreheaderLoad->setAAMetadata(AATags);
1057*9880d681SAndroid Build Coastguard Worker SSA.AddAvailableValue(Preheader, PreheaderLoad);
1058*9880d681SAndroid Build Coastguard Worker
1059*9880d681SAndroid Build Coastguard Worker // Rewrite all the loads in the loop and remember all the definitions from
1060*9880d681SAndroid Build Coastguard Worker // stores in the loop.
1061*9880d681SAndroid Build Coastguard Worker Promoter.run(LoopUses);
1062*9880d681SAndroid Build Coastguard Worker
1063*9880d681SAndroid Build Coastguard Worker // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1064*9880d681SAndroid Build Coastguard Worker if (PreheaderLoad->use_empty())
1065*9880d681SAndroid Build Coastguard Worker PreheaderLoad->eraseFromParent();
1066*9880d681SAndroid Build Coastguard Worker
1067*9880d681SAndroid Build Coastguard Worker return Changed;
1068*9880d681SAndroid Build Coastguard Worker }
1069*9880d681SAndroid Build Coastguard Worker
1070*9880d681SAndroid Build Coastguard Worker /// Returns an owning pointer to an alias set which incorporates aliasing info
1071*9880d681SAndroid Build Coastguard Worker /// from L and all subloops of L.
1072*9880d681SAndroid Build Coastguard Worker /// FIXME: In new pass manager, there is no helper functions to handle loop
1073*9880d681SAndroid Build Coastguard Worker /// analysis such as cloneBasicBlockAnalysis. So the AST needs to be recompute
1074*9880d681SAndroid Build Coastguard Worker /// from scratch for every loop. Hook up with the helper functions when
1075*9880d681SAndroid Build Coastguard Worker /// available in the new pass manager to avoid redundant computation.
1076*9880d681SAndroid Build Coastguard Worker AliasSetTracker *
collectAliasInfoForLoop(Loop * L,LoopInfo * LI,AliasAnalysis * AA)1077*9880d681SAndroid Build Coastguard Worker LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1078*9880d681SAndroid Build Coastguard Worker AliasAnalysis *AA) {
1079*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST = nullptr;
1080*9880d681SAndroid Build Coastguard Worker SmallVector<Loop *, 4> RecomputeLoops;
1081*9880d681SAndroid Build Coastguard Worker for (Loop *InnerL : L->getSubLoops()) {
1082*9880d681SAndroid Build Coastguard Worker auto MapI = LoopToAliasSetMap.find(InnerL);
1083*9880d681SAndroid Build Coastguard Worker // If the AST for this inner loop is missing it may have been merged into
1084*9880d681SAndroid Build Coastguard Worker // some other loop's AST and then that loop unrolled, and so we need to
1085*9880d681SAndroid Build Coastguard Worker // recompute it.
1086*9880d681SAndroid Build Coastguard Worker if (MapI == LoopToAliasSetMap.end()) {
1087*9880d681SAndroid Build Coastguard Worker RecomputeLoops.push_back(InnerL);
1088*9880d681SAndroid Build Coastguard Worker continue;
1089*9880d681SAndroid Build Coastguard Worker }
1090*9880d681SAndroid Build Coastguard Worker AliasSetTracker *InnerAST = MapI->second;
1091*9880d681SAndroid Build Coastguard Worker
1092*9880d681SAndroid Build Coastguard Worker if (CurAST != nullptr) {
1093*9880d681SAndroid Build Coastguard Worker // What if InnerLoop was modified by other passes ?
1094*9880d681SAndroid Build Coastguard Worker CurAST->add(*InnerAST);
1095*9880d681SAndroid Build Coastguard Worker
1096*9880d681SAndroid Build Coastguard Worker // Once we've incorporated the inner loop's AST into ours, we don't need
1097*9880d681SAndroid Build Coastguard Worker // the subloop's anymore.
1098*9880d681SAndroid Build Coastguard Worker delete InnerAST;
1099*9880d681SAndroid Build Coastguard Worker } else {
1100*9880d681SAndroid Build Coastguard Worker CurAST = InnerAST;
1101*9880d681SAndroid Build Coastguard Worker }
1102*9880d681SAndroid Build Coastguard Worker LoopToAliasSetMap.erase(MapI);
1103*9880d681SAndroid Build Coastguard Worker }
1104*9880d681SAndroid Build Coastguard Worker if (CurAST == nullptr)
1105*9880d681SAndroid Build Coastguard Worker CurAST = new AliasSetTracker(*AA);
1106*9880d681SAndroid Build Coastguard Worker
1107*9880d681SAndroid Build Coastguard Worker auto mergeLoop = [&](Loop *L) {
1108*9880d681SAndroid Build Coastguard Worker // Loop over the body of this loop, looking for calls, invokes, and stores.
1109*9880d681SAndroid Build Coastguard Worker // Because subloops have already been incorporated into AST, we skip blocks
1110*9880d681SAndroid Build Coastguard Worker // in subloops.
1111*9880d681SAndroid Build Coastguard Worker for (BasicBlock *BB : L->blocks())
1112*9880d681SAndroid Build Coastguard Worker if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1113*9880d681SAndroid Build Coastguard Worker CurAST->add(*BB); // Incorporate the specified basic block
1114*9880d681SAndroid Build Coastguard Worker };
1115*9880d681SAndroid Build Coastguard Worker
1116*9880d681SAndroid Build Coastguard Worker // Add everything from the sub loops that are no longer directly available.
1117*9880d681SAndroid Build Coastguard Worker for (Loop *InnerL : RecomputeLoops)
1118*9880d681SAndroid Build Coastguard Worker mergeLoop(InnerL);
1119*9880d681SAndroid Build Coastguard Worker
1120*9880d681SAndroid Build Coastguard Worker // And merge in this loop.
1121*9880d681SAndroid Build Coastguard Worker mergeLoop(L);
1122*9880d681SAndroid Build Coastguard Worker
1123*9880d681SAndroid Build Coastguard Worker return CurAST;
1124*9880d681SAndroid Build Coastguard Worker }
1125*9880d681SAndroid Build Coastguard Worker
1126*9880d681SAndroid Build Coastguard Worker /// Simple analysis hook. Clone alias set info.
1127*9880d681SAndroid Build Coastguard Worker ///
cloneBasicBlockAnalysis(BasicBlock * From,BasicBlock * To,Loop * L)1128*9880d681SAndroid Build Coastguard Worker void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1129*9880d681SAndroid Build Coastguard Worker Loop *L) {
1130*9880d681SAndroid Build Coastguard Worker AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1131*9880d681SAndroid Build Coastguard Worker if (!AST)
1132*9880d681SAndroid Build Coastguard Worker return;
1133*9880d681SAndroid Build Coastguard Worker
1134*9880d681SAndroid Build Coastguard Worker AST->copyValue(From, To);
1135*9880d681SAndroid Build Coastguard Worker }
1136*9880d681SAndroid Build Coastguard Worker
1137*9880d681SAndroid Build Coastguard Worker /// Simple Analysis hook. Delete value V from alias set
1138*9880d681SAndroid Build Coastguard Worker ///
deleteAnalysisValue(Value * V,Loop * L)1139*9880d681SAndroid Build Coastguard Worker void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1140*9880d681SAndroid Build Coastguard Worker AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1141*9880d681SAndroid Build Coastguard Worker if (!AST)
1142*9880d681SAndroid Build Coastguard Worker return;
1143*9880d681SAndroid Build Coastguard Worker
1144*9880d681SAndroid Build Coastguard Worker AST->deleteValue(V);
1145*9880d681SAndroid Build Coastguard Worker }
1146*9880d681SAndroid Build Coastguard Worker
1147*9880d681SAndroid Build Coastguard Worker /// Simple Analysis hook. Delete value L from alias set map.
1148*9880d681SAndroid Build Coastguard Worker ///
deleteAnalysisLoop(Loop * L)1149*9880d681SAndroid Build Coastguard Worker void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1150*9880d681SAndroid Build Coastguard Worker AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1151*9880d681SAndroid Build Coastguard Worker if (!AST)
1152*9880d681SAndroid Build Coastguard Worker return;
1153*9880d681SAndroid Build Coastguard Worker
1154*9880d681SAndroid Build Coastguard Worker delete AST;
1155*9880d681SAndroid Build Coastguard Worker LICM.getLoopToAliasSetMap().erase(L);
1156*9880d681SAndroid Build Coastguard Worker }
1157*9880d681SAndroid Build Coastguard Worker
1158*9880d681SAndroid Build Coastguard Worker /// Return true if the body of this loop may store into the memory
1159*9880d681SAndroid Build Coastguard Worker /// location pointed to by V.
1160*9880d681SAndroid Build Coastguard Worker ///
pointerInvalidatedByLoop(Value * V,uint64_t Size,const AAMDNodes & AAInfo,AliasSetTracker * CurAST)1161*9880d681SAndroid Build Coastguard Worker static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1162*9880d681SAndroid Build Coastguard Worker const AAMDNodes &AAInfo,
1163*9880d681SAndroid Build Coastguard Worker AliasSetTracker *CurAST) {
1164*9880d681SAndroid Build Coastguard Worker // Check to see if any of the basic blocks in CurLoop invalidate *V.
1165*9880d681SAndroid Build Coastguard Worker return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1166*9880d681SAndroid Build Coastguard Worker }
1167*9880d681SAndroid Build Coastguard Worker
1168*9880d681SAndroid Build Coastguard Worker /// Little predicate that returns true if the specified basic block is in
1169*9880d681SAndroid Build Coastguard Worker /// a subloop of the current one, not the current one itself.
1170*9880d681SAndroid Build Coastguard Worker ///
inSubLoop(BasicBlock * BB,Loop * CurLoop,LoopInfo * LI)1171*9880d681SAndroid Build Coastguard Worker static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1172*9880d681SAndroid Build Coastguard Worker assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1173*9880d681SAndroid Build Coastguard Worker return LI->getLoopFor(BB) != CurLoop;
1174*9880d681SAndroid Build Coastguard Worker }
1175