xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
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 transforms loops that contain branches on loop-invariant conditions
11*9880d681SAndroid Build Coastguard Worker // to have multiple loops.  For example, it turns the left into the right code:
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //  for (...)                  if (lic)
14*9880d681SAndroid Build Coastguard Worker //    A                          for (...)
15*9880d681SAndroid Build Coastguard Worker //    if (lic)                     A; B; C
16*9880d681SAndroid Build Coastguard Worker //      B                      else
17*9880d681SAndroid Build Coastguard Worker //    C                          for (...)
18*9880d681SAndroid Build Coastguard Worker //                                 A; C
19*9880d681SAndroid Build Coastguard Worker //
20*9880d681SAndroid Build Coastguard Worker // This can increase the size of the code exponentially (doubling it every time
21*9880d681SAndroid Build Coastguard Worker // a loop is unswitched) so we only unswitch if the resultant code will be
22*9880d681SAndroid Build Coastguard Worker // smaller than a threshold.
23*9880d681SAndroid Build Coastguard Worker //
24*9880d681SAndroid Build Coastguard Worker // This pass expects LICM to be run before it to hoist invariant conditions out
25*9880d681SAndroid Build Coastguard Worker // of the loop, to make the unswitching opportunity obvious.
26*9880d681SAndroid Build Coastguard Worker //
27*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
28*9880d681SAndroid Build Coastguard Worker 
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CodeMetrics.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPass.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BlockFrequencyInfo.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BranchProbabilityInfo.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/BranchProbability.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/MDBuilder.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Cloning.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
59*9880d681SAndroid Build Coastguard Worker #include <algorithm>
60*9880d681SAndroid Build Coastguard Worker #include <map>
61*9880d681SAndroid Build Coastguard Worker #include <set>
62*9880d681SAndroid Build Coastguard Worker using namespace llvm;
63*9880d681SAndroid Build Coastguard Worker 
64*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "loop-unswitch"
65*9880d681SAndroid Build Coastguard Worker 
66*9880d681SAndroid Build Coastguard Worker STATISTIC(NumBranches, "Number of branches unswitched");
67*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSwitches, "Number of switches unswitched");
68*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGuards,   "Number of guards unswitched");
69*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSelects , "Number of selects unswitched");
70*9880d681SAndroid Build Coastguard Worker STATISTIC(NumTrivial , "Number of unswitches that are trivial");
71*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
72*9880d681SAndroid Build Coastguard Worker STATISTIC(TotalInsts,  "Total number of instructions analyzed");
73*9880d681SAndroid Build Coastguard Worker 
74*9880d681SAndroid Build Coastguard Worker // The specific value of 100 here was chosen based only on intuition and a
75*9880d681SAndroid Build Coastguard Worker // few specific examples.
76*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned>
77*9880d681SAndroid Build Coastguard Worker Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
78*9880d681SAndroid Build Coastguard Worker           cl::init(100), cl::Hidden);
79*9880d681SAndroid Build Coastguard Worker 
80*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
81*9880d681SAndroid Build Coastguard Worker LoopUnswitchWithBlockFrequency("loop-unswitch-with-block-frequency",
82*9880d681SAndroid Build Coastguard Worker     cl::init(false), cl::Hidden,
83*9880d681SAndroid Build Coastguard Worker     cl::desc("Enable the use of the block frequency analysis to access PGO "
84*9880d681SAndroid Build Coastguard Worker              "heuristics to minimize code growth in cold regions."));
85*9880d681SAndroid Build Coastguard Worker 
86*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned>
87*9880d681SAndroid Build Coastguard Worker ColdnessThreshold("loop-unswitch-coldness-threshold", cl::init(1), cl::Hidden,
88*9880d681SAndroid Build Coastguard Worker     cl::desc("Coldness threshold in percentage. The loop header frequency "
89*9880d681SAndroid Build Coastguard Worker              "(relative to the entry frequency) is compared with this "
90*9880d681SAndroid Build Coastguard Worker              "threshold to determine if non-trivial unswitching should be "
91*9880d681SAndroid Build Coastguard Worker              "enabled."));
92*9880d681SAndroid Build Coastguard Worker 
93*9880d681SAndroid Build Coastguard Worker namespace {
94*9880d681SAndroid Build Coastguard Worker 
95*9880d681SAndroid Build Coastguard Worker   class LUAnalysisCache {
96*9880d681SAndroid Build Coastguard Worker 
97*9880d681SAndroid Build Coastguard Worker     typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
98*9880d681SAndroid Build Coastguard Worker       UnswitchedValsMap;
99*9880d681SAndroid Build Coastguard Worker 
100*9880d681SAndroid Build Coastguard Worker     typedef UnswitchedValsMap::iterator UnswitchedValsIt;
101*9880d681SAndroid Build Coastguard Worker 
102*9880d681SAndroid Build Coastguard Worker     struct LoopProperties {
103*9880d681SAndroid Build Coastguard Worker       unsigned CanBeUnswitchedCount;
104*9880d681SAndroid Build Coastguard Worker       unsigned WasUnswitchedCount;
105*9880d681SAndroid Build Coastguard Worker       unsigned SizeEstimation;
106*9880d681SAndroid Build Coastguard Worker       UnswitchedValsMap UnswitchedVals;
107*9880d681SAndroid Build Coastguard Worker     };
108*9880d681SAndroid Build Coastguard Worker 
109*9880d681SAndroid Build Coastguard Worker     // Here we use std::map instead of DenseMap, since we need to keep valid
110*9880d681SAndroid Build Coastguard Worker     // LoopProperties pointer for current loop for better performance.
111*9880d681SAndroid Build Coastguard Worker     typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
112*9880d681SAndroid Build Coastguard Worker     typedef LoopPropsMap::iterator LoopPropsMapIt;
113*9880d681SAndroid Build Coastguard Worker 
114*9880d681SAndroid Build Coastguard Worker     LoopPropsMap LoopsProperties;
115*9880d681SAndroid Build Coastguard Worker     UnswitchedValsMap *CurLoopInstructions;
116*9880d681SAndroid Build Coastguard Worker     LoopProperties *CurrentLoopProperties;
117*9880d681SAndroid Build Coastguard Worker 
118*9880d681SAndroid Build Coastguard Worker     // A loop unswitching with an estimated cost above this threshold
119*9880d681SAndroid Build Coastguard Worker     // is not performed. MaxSize is turned into unswitching quota for
120*9880d681SAndroid Build Coastguard Worker     // the current loop, and reduced correspondingly, though note that
121*9880d681SAndroid Build Coastguard Worker     // the quota is returned by releaseMemory() when the loop has been
122*9880d681SAndroid Build Coastguard Worker     // processed, so that MaxSize will return to its previous
123*9880d681SAndroid Build Coastguard Worker     // value. So in most cases MaxSize will equal the Threshold flag
124*9880d681SAndroid Build Coastguard Worker     // when a new loop is processed. An exception to that is that
125*9880d681SAndroid Build Coastguard Worker     // MaxSize will have a smaller value while processing nested loops
126*9880d681SAndroid Build Coastguard Worker     // that were introduced due to loop unswitching of an outer loop.
127*9880d681SAndroid Build Coastguard Worker     //
128*9880d681SAndroid Build Coastguard Worker     // FIXME: The way that MaxSize works is subtle and depends on the
129*9880d681SAndroid Build Coastguard Worker     // pass manager processing loops and calling releaseMemory() in a
130*9880d681SAndroid Build Coastguard Worker     // specific order. It would be good to find a more straightforward
131*9880d681SAndroid Build Coastguard Worker     // way of doing what MaxSize does.
132*9880d681SAndroid Build Coastguard Worker     unsigned MaxSize;
133*9880d681SAndroid Build Coastguard Worker 
134*9880d681SAndroid Build Coastguard Worker   public:
LUAnalysisCache()135*9880d681SAndroid Build Coastguard Worker     LUAnalysisCache()
136*9880d681SAndroid Build Coastguard Worker         : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
137*9880d681SAndroid Build Coastguard Worker           MaxSize(Threshold) {}
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker     // Analyze loop. Check its size, calculate is it possible to unswitch
140*9880d681SAndroid Build Coastguard Worker     // it. Returns true if we can unswitch this loop.
141*9880d681SAndroid Build Coastguard Worker     bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
142*9880d681SAndroid Build Coastguard Worker                    AssumptionCache *AC);
143*9880d681SAndroid Build Coastguard Worker 
144*9880d681SAndroid Build Coastguard Worker     // Clean all data related to given loop.
145*9880d681SAndroid Build Coastguard Worker     void forgetLoop(const Loop *L);
146*9880d681SAndroid Build Coastguard Worker 
147*9880d681SAndroid Build Coastguard Worker     // Mark case value as unswitched.
148*9880d681SAndroid Build Coastguard Worker     // Since SI instruction can be partly unswitched, in order to avoid
149*9880d681SAndroid Build Coastguard Worker     // extra unswitching in cloned loops keep track all unswitched values.
150*9880d681SAndroid Build Coastguard Worker     void setUnswitched(const SwitchInst *SI, const Value *V);
151*9880d681SAndroid Build Coastguard Worker 
152*9880d681SAndroid Build Coastguard Worker     // Check was this case value unswitched before or not.
153*9880d681SAndroid Build Coastguard Worker     bool isUnswitched(const SwitchInst *SI, const Value *V);
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker     // Returns true if another unswitching could be done within the cost
156*9880d681SAndroid Build Coastguard Worker     // threshold.
157*9880d681SAndroid Build Coastguard Worker     bool CostAllowsUnswitching();
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker     // Clone all loop-unswitch related loop properties.
160*9880d681SAndroid Build Coastguard Worker     // Redistribute unswitching quotas.
161*9880d681SAndroid Build Coastguard Worker     // Note, that new loop data is stored inside the VMap.
162*9880d681SAndroid Build Coastguard Worker     void cloneData(const Loop *NewLoop, const Loop *OldLoop,
163*9880d681SAndroid Build Coastguard Worker                    const ValueToValueMapTy &VMap);
164*9880d681SAndroid Build Coastguard Worker   };
165*9880d681SAndroid Build Coastguard Worker 
166*9880d681SAndroid Build Coastguard Worker   class LoopUnswitch : public LoopPass {
167*9880d681SAndroid Build Coastguard Worker     LoopInfo *LI;  // Loop information
168*9880d681SAndroid Build Coastguard Worker     LPPassManager *LPM;
169*9880d681SAndroid Build Coastguard Worker     AssumptionCache *AC;
170*9880d681SAndroid Build Coastguard Worker 
171*9880d681SAndroid Build Coastguard Worker     // Used to check if second loop needs processing after
172*9880d681SAndroid Build Coastguard Worker     // RewriteLoopBodyWithConditionConstant rewrites first loop.
173*9880d681SAndroid Build Coastguard Worker     std::vector<Loop*> LoopProcessWorklist;
174*9880d681SAndroid Build Coastguard Worker 
175*9880d681SAndroid Build Coastguard Worker     LUAnalysisCache BranchesInfo;
176*9880d681SAndroid Build Coastguard Worker 
177*9880d681SAndroid Build Coastguard Worker     bool EnabledPGO;
178*9880d681SAndroid Build Coastguard Worker 
179*9880d681SAndroid Build Coastguard Worker     // BFI and ColdEntryFreq are only used when PGO and
180*9880d681SAndroid Build Coastguard Worker     // LoopUnswitchWithBlockFrequency are enabled.
181*9880d681SAndroid Build Coastguard Worker     BlockFrequencyInfo BFI;
182*9880d681SAndroid Build Coastguard Worker     BlockFrequency ColdEntryFreq;
183*9880d681SAndroid Build Coastguard Worker 
184*9880d681SAndroid Build Coastguard Worker     bool OptimizeForSize;
185*9880d681SAndroid Build Coastguard Worker     bool redoLoop;
186*9880d681SAndroid Build Coastguard Worker 
187*9880d681SAndroid Build Coastguard Worker     Loop *currentLoop;
188*9880d681SAndroid Build Coastguard Worker     DominatorTree *DT;
189*9880d681SAndroid Build Coastguard Worker     BasicBlock *loopHeader;
190*9880d681SAndroid Build Coastguard Worker     BasicBlock *loopPreheader;
191*9880d681SAndroid Build Coastguard Worker 
192*9880d681SAndroid Build Coastguard Worker     bool SanitizeMemory;
193*9880d681SAndroid Build Coastguard Worker     LoopSafetyInfo SafetyInfo;
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker     // LoopBlocks contains all of the basic blocks of the loop, including the
196*9880d681SAndroid Build Coastguard Worker     // preheader of the loop, the body of the loop, and the exit blocks of the
197*9880d681SAndroid Build Coastguard Worker     // loop, in that order.
198*9880d681SAndroid Build Coastguard Worker     std::vector<BasicBlock*> LoopBlocks;
199*9880d681SAndroid Build Coastguard Worker     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
200*9880d681SAndroid Build Coastguard Worker     std::vector<BasicBlock*> NewBlocks;
201*9880d681SAndroid Build Coastguard Worker 
202*9880d681SAndroid Build Coastguard Worker   public:
203*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass ID, replacement for typeid
LoopUnswitch(bool Os=false)204*9880d681SAndroid Build Coastguard Worker     explicit LoopUnswitch(bool Os = false) :
205*9880d681SAndroid Build Coastguard Worker       LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
206*9880d681SAndroid Build Coastguard Worker       currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
207*9880d681SAndroid Build Coastguard Worker       loopPreheader(nullptr) {
208*9880d681SAndroid Build Coastguard Worker         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
209*9880d681SAndroid Build Coastguard Worker       }
210*9880d681SAndroid Build Coastguard Worker 
211*9880d681SAndroid Build Coastguard Worker     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
212*9880d681SAndroid Build Coastguard Worker     bool processCurrentLoop();
213*9880d681SAndroid Build Coastguard Worker 
214*9880d681SAndroid Build Coastguard Worker     /// This transformation requires natural loop information & requires that
215*9880d681SAndroid Build Coastguard Worker     /// loop preheaders be inserted into the CFG.
216*9880d681SAndroid Build Coastguard Worker     ///
getAnalysisUsage(AnalysisUsage & AU) const217*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
218*9880d681SAndroid Build Coastguard Worker       AU.addRequired<AssumptionCacheTracker>();
219*9880d681SAndroid Build Coastguard Worker       AU.addRequired<TargetTransformInfoWrapperPass>();
220*9880d681SAndroid Build Coastguard Worker       getLoopAnalysisUsage(AU);
221*9880d681SAndroid Build Coastguard Worker     }
222*9880d681SAndroid Build Coastguard Worker 
223*9880d681SAndroid Build Coastguard Worker   private:
224*9880d681SAndroid Build Coastguard Worker 
releaseMemory()225*9880d681SAndroid Build Coastguard Worker     void releaseMemory() override {
226*9880d681SAndroid Build Coastguard Worker       BranchesInfo.forgetLoop(currentLoop);
227*9880d681SAndroid Build Coastguard Worker     }
228*9880d681SAndroid Build Coastguard Worker 
initLoopData()229*9880d681SAndroid Build Coastguard Worker     void initLoopData() {
230*9880d681SAndroid Build Coastguard Worker       loopHeader = currentLoop->getHeader();
231*9880d681SAndroid Build Coastguard Worker       loopPreheader = currentLoop->getLoopPreheader();
232*9880d681SAndroid Build Coastguard Worker     }
233*9880d681SAndroid Build Coastguard Worker 
234*9880d681SAndroid Build Coastguard Worker     /// Split all of the edges from inside the loop to their exit blocks.
235*9880d681SAndroid Build Coastguard Worker     /// Update the appropriate Phi nodes as we do so.
236*9880d681SAndroid Build Coastguard Worker     void SplitExitEdges(Loop *L,
237*9880d681SAndroid Build Coastguard Worker                         const SmallVectorImpl<BasicBlock *> &ExitBlocks);
238*9880d681SAndroid Build Coastguard Worker 
239*9880d681SAndroid Build Coastguard Worker     bool TryTrivialLoopUnswitch(bool &Changed);
240*9880d681SAndroid Build Coastguard Worker 
241*9880d681SAndroid Build Coastguard Worker     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
242*9880d681SAndroid Build Coastguard Worker                               TerminatorInst *TI = nullptr);
243*9880d681SAndroid Build Coastguard Worker     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
244*9880d681SAndroid Build Coastguard Worker                                   BasicBlock *ExitBlock, TerminatorInst *TI);
245*9880d681SAndroid Build Coastguard Worker     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
246*9880d681SAndroid Build Coastguard Worker                                      TerminatorInst *TI);
247*9880d681SAndroid Build Coastguard Worker 
248*9880d681SAndroid Build Coastguard Worker     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
249*9880d681SAndroid Build Coastguard Worker                                               Constant *Val, bool isEqual);
250*9880d681SAndroid Build Coastguard Worker 
251*9880d681SAndroid Build Coastguard Worker     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
252*9880d681SAndroid Build Coastguard Worker                                         BasicBlock *TrueDest,
253*9880d681SAndroid Build Coastguard Worker                                         BasicBlock *FalseDest,
254*9880d681SAndroid Build Coastguard Worker                                         Instruction *InsertPt,
255*9880d681SAndroid Build Coastguard Worker                                         TerminatorInst *TI);
256*9880d681SAndroid Build Coastguard Worker 
257*9880d681SAndroid Build Coastguard Worker     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
258*9880d681SAndroid Build Coastguard Worker   };
259*9880d681SAndroid Build Coastguard Worker }
260*9880d681SAndroid Build Coastguard Worker 
261*9880d681SAndroid Build Coastguard Worker // Analyze loop. Check its size, calculate is it possible to unswitch
262*9880d681SAndroid Build Coastguard Worker // it. Returns true if we can unswitch this loop.
countLoop(const Loop * L,const TargetTransformInfo & TTI,AssumptionCache * AC)263*9880d681SAndroid Build Coastguard Worker bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
264*9880d681SAndroid Build Coastguard Worker                                 AssumptionCache *AC) {
265*9880d681SAndroid Build Coastguard Worker 
266*9880d681SAndroid Build Coastguard Worker   LoopPropsMapIt PropsIt;
267*9880d681SAndroid Build Coastguard Worker   bool Inserted;
268*9880d681SAndroid Build Coastguard Worker   std::tie(PropsIt, Inserted) =
269*9880d681SAndroid Build Coastguard Worker       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
270*9880d681SAndroid Build Coastguard Worker 
271*9880d681SAndroid Build Coastguard Worker   LoopProperties &Props = PropsIt->second;
272*9880d681SAndroid Build Coastguard Worker 
273*9880d681SAndroid Build Coastguard Worker   if (Inserted) {
274*9880d681SAndroid Build Coastguard Worker     // New loop.
275*9880d681SAndroid Build Coastguard Worker 
276*9880d681SAndroid Build Coastguard Worker     // Limit the number of instructions to avoid causing significant code
277*9880d681SAndroid Build Coastguard Worker     // expansion, and the number of basic blocks, to avoid loops with
278*9880d681SAndroid Build Coastguard Worker     // large numbers of branches which cause loop unswitching to go crazy.
279*9880d681SAndroid Build Coastguard Worker     // This is a very ad-hoc heuristic.
280*9880d681SAndroid Build Coastguard Worker 
281*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<const Value *, 32> EphValues;
282*9880d681SAndroid Build Coastguard Worker     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
283*9880d681SAndroid Build Coastguard Worker 
284*9880d681SAndroid Build Coastguard Worker     // FIXME: This is overly conservative because it does not take into
285*9880d681SAndroid Build Coastguard Worker     // consideration code simplification opportunities and code that can
286*9880d681SAndroid Build Coastguard Worker     // be shared by the resultant unswitched loops.
287*9880d681SAndroid Build Coastguard Worker     CodeMetrics Metrics;
288*9880d681SAndroid Build Coastguard Worker     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
289*9880d681SAndroid Build Coastguard Worker          ++I)
290*9880d681SAndroid Build Coastguard Worker       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker     Props.SizeEstimation = Metrics.NumInsts;
293*9880d681SAndroid Build Coastguard Worker     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
294*9880d681SAndroid Build Coastguard Worker     Props.WasUnswitchedCount = 0;
295*9880d681SAndroid Build Coastguard Worker     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
296*9880d681SAndroid Build Coastguard Worker 
297*9880d681SAndroid Build Coastguard Worker     if (Metrics.notDuplicatable) {
298*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "NOT unswitching loop %"
299*9880d681SAndroid Build Coastguard Worker                    << L->getHeader()->getName() << ", contents cannot be "
300*9880d681SAndroid Build Coastguard Worker                    << "duplicated!\n");
301*9880d681SAndroid Build Coastguard Worker       return false;
302*9880d681SAndroid Build Coastguard Worker     }
303*9880d681SAndroid Build Coastguard Worker   }
304*9880d681SAndroid Build Coastguard Worker 
305*9880d681SAndroid Build Coastguard Worker   // Be careful. This links are good only before new loop addition.
306*9880d681SAndroid Build Coastguard Worker   CurrentLoopProperties = &Props;
307*9880d681SAndroid Build Coastguard Worker   CurLoopInstructions = &Props.UnswitchedVals;
308*9880d681SAndroid Build Coastguard Worker 
309*9880d681SAndroid Build Coastguard Worker   return true;
310*9880d681SAndroid Build Coastguard Worker }
311*9880d681SAndroid Build Coastguard Worker 
312*9880d681SAndroid Build Coastguard Worker // Clean all data related to given loop.
forgetLoop(const Loop * L)313*9880d681SAndroid Build Coastguard Worker void LUAnalysisCache::forgetLoop(const Loop *L) {
314*9880d681SAndroid Build Coastguard Worker 
315*9880d681SAndroid Build Coastguard Worker   LoopPropsMapIt LIt = LoopsProperties.find(L);
316*9880d681SAndroid Build Coastguard Worker 
317*9880d681SAndroid Build Coastguard Worker   if (LIt != LoopsProperties.end()) {
318*9880d681SAndroid Build Coastguard Worker     LoopProperties &Props = LIt->second;
319*9880d681SAndroid Build Coastguard Worker     MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
320*9880d681SAndroid Build Coastguard Worker                Props.SizeEstimation;
321*9880d681SAndroid Build Coastguard Worker     LoopsProperties.erase(LIt);
322*9880d681SAndroid Build Coastguard Worker   }
323*9880d681SAndroid Build Coastguard Worker 
324*9880d681SAndroid Build Coastguard Worker   CurrentLoopProperties = nullptr;
325*9880d681SAndroid Build Coastguard Worker   CurLoopInstructions = nullptr;
326*9880d681SAndroid Build Coastguard Worker }
327*9880d681SAndroid Build Coastguard Worker 
328*9880d681SAndroid Build Coastguard Worker // Mark case value as unswitched.
329*9880d681SAndroid Build Coastguard Worker // Since SI instruction can be partly unswitched, in order to avoid
330*9880d681SAndroid Build Coastguard Worker // extra unswitching in cloned loops keep track all unswitched values.
setUnswitched(const SwitchInst * SI,const Value * V)331*9880d681SAndroid Build Coastguard Worker void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
332*9880d681SAndroid Build Coastguard Worker   (*CurLoopInstructions)[SI].insert(V);
333*9880d681SAndroid Build Coastguard Worker }
334*9880d681SAndroid Build Coastguard Worker 
335*9880d681SAndroid Build Coastguard Worker // Check was this case value unswitched before or not.
isUnswitched(const SwitchInst * SI,const Value * V)336*9880d681SAndroid Build Coastguard Worker bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
337*9880d681SAndroid Build Coastguard Worker   return (*CurLoopInstructions)[SI].count(V);
338*9880d681SAndroid Build Coastguard Worker }
339*9880d681SAndroid Build Coastguard Worker 
CostAllowsUnswitching()340*9880d681SAndroid Build Coastguard Worker bool LUAnalysisCache::CostAllowsUnswitching() {
341*9880d681SAndroid Build Coastguard Worker   return CurrentLoopProperties->CanBeUnswitchedCount > 0;
342*9880d681SAndroid Build Coastguard Worker }
343*9880d681SAndroid Build Coastguard Worker 
344*9880d681SAndroid Build Coastguard Worker // Clone all loop-unswitch related loop properties.
345*9880d681SAndroid Build Coastguard Worker // Redistribute unswitching quotas.
346*9880d681SAndroid Build Coastguard Worker // Note, that new loop data is stored inside the VMap.
cloneData(const Loop * NewLoop,const Loop * OldLoop,const ValueToValueMapTy & VMap)347*9880d681SAndroid Build Coastguard Worker void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
348*9880d681SAndroid Build Coastguard Worker                                 const ValueToValueMapTy &VMap) {
349*9880d681SAndroid Build Coastguard Worker 
350*9880d681SAndroid Build Coastguard Worker   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
351*9880d681SAndroid Build Coastguard Worker   LoopProperties &OldLoopProps = *CurrentLoopProperties;
352*9880d681SAndroid Build Coastguard Worker   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
353*9880d681SAndroid Build Coastguard Worker 
354*9880d681SAndroid Build Coastguard Worker   // Reallocate "can-be-unswitched quota"
355*9880d681SAndroid Build Coastguard Worker 
356*9880d681SAndroid Build Coastguard Worker   --OldLoopProps.CanBeUnswitchedCount;
357*9880d681SAndroid Build Coastguard Worker   ++OldLoopProps.WasUnswitchedCount;
358*9880d681SAndroid Build Coastguard Worker   NewLoopProps.WasUnswitchedCount = 0;
359*9880d681SAndroid Build Coastguard Worker   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
360*9880d681SAndroid Build Coastguard Worker   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
361*9880d681SAndroid Build Coastguard Worker   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
364*9880d681SAndroid Build Coastguard Worker 
365*9880d681SAndroid Build Coastguard Worker   // Clone unswitched values info:
366*9880d681SAndroid Build Coastguard Worker   // for new loop switches we clone info about values that was
367*9880d681SAndroid Build Coastguard Worker   // already unswitched and has redundant successors.
368*9880d681SAndroid Build Coastguard Worker   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
369*9880d681SAndroid Build Coastguard Worker     const SwitchInst *OldInst = I->first;
370*9880d681SAndroid Build Coastguard Worker     Value *NewI = VMap.lookup(OldInst);
371*9880d681SAndroid Build Coastguard Worker     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
372*9880d681SAndroid Build Coastguard Worker     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
375*9880d681SAndroid Build Coastguard Worker   }
376*9880d681SAndroid Build Coastguard Worker }
377*9880d681SAndroid Build Coastguard Worker 
378*9880d681SAndroid Build Coastguard Worker char LoopUnswitch::ID = 0;
379*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
380*9880d681SAndroid Build Coastguard Worker                       false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)381*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
382*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopPass)
383*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
384*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
385*9880d681SAndroid Build Coastguard Worker                       false, false)
386*9880d681SAndroid Build Coastguard Worker 
387*9880d681SAndroid Build Coastguard Worker Pass *llvm::createLoopUnswitchPass(bool Os) {
388*9880d681SAndroid Build Coastguard Worker   return new LoopUnswitch(Os);
389*9880d681SAndroid Build Coastguard Worker }
390*9880d681SAndroid Build Coastguard Worker 
391*9880d681SAndroid Build Coastguard Worker /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
392*9880d681SAndroid Build Coastguard Worker /// an invariant piece, return the invariant. Otherwise, return null.
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed,DenseMap<Value *,Value * > & Cache)393*9880d681SAndroid Build Coastguard Worker static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
394*9880d681SAndroid Build Coastguard Worker                                    DenseMap<Value *, Value *> &Cache) {
395*9880d681SAndroid Build Coastguard Worker   auto CacheIt = Cache.find(Cond);
396*9880d681SAndroid Build Coastguard Worker   if (CacheIt != Cache.end())
397*9880d681SAndroid Build Coastguard Worker     return CacheIt->second;
398*9880d681SAndroid Build Coastguard Worker 
399*9880d681SAndroid Build Coastguard Worker   // We started analyze new instruction, increment scanned instructions counter.
400*9880d681SAndroid Build Coastguard Worker   ++TotalInsts;
401*9880d681SAndroid Build Coastguard Worker 
402*9880d681SAndroid Build Coastguard Worker   // We can never unswitch on vector conditions.
403*9880d681SAndroid Build Coastguard Worker   if (Cond->getType()->isVectorTy())
404*9880d681SAndroid Build Coastguard Worker     return nullptr;
405*9880d681SAndroid Build Coastguard Worker 
406*9880d681SAndroid Build Coastguard Worker   // Constants should be folded, not unswitched on!
407*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(Cond)) return nullptr;
408*9880d681SAndroid Build Coastguard Worker 
409*9880d681SAndroid Build Coastguard Worker   // TODO: Handle: br (VARIANT|INVARIANT).
410*9880d681SAndroid Build Coastguard Worker 
411*9880d681SAndroid Build Coastguard Worker   // Hoist simple values out.
412*9880d681SAndroid Build Coastguard Worker   if (L->makeLoopInvariant(Cond, Changed)) {
413*9880d681SAndroid Build Coastguard Worker     Cache[Cond] = Cond;
414*9880d681SAndroid Build Coastguard Worker     return Cond;
415*9880d681SAndroid Build Coastguard Worker   }
416*9880d681SAndroid Build Coastguard Worker 
417*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
418*9880d681SAndroid Build Coastguard Worker     if (BO->getOpcode() == Instruction::And ||
419*9880d681SAndroid Build Coastguard Worker         BO->getOpcode() == Instruction::Or) {
420*9880d681SAndroid Build Coastguard Worker       // If either the left or right side is invariant, we can unswitch on this,
421*9880d681SAndroid Build Coastguard Worker       // which will cause the branch to go away in one loop and the condition to
422*9880d681SAndroid Build Coastguard Worker       // simplify in the other one.
423*9880d681SAndroid Build Coastguard Worker       if (Value *LHS =
424*9880d681SAndroid Build Coastguard Worker               FindLIVLoopCondition(BO->getOperand(0), L, Changed, Cache)) {
425*9880d681SAndroid Build Coastguard Worker         Cache[Cond] = LHS;
426*9880d681SAndroid Build Coastguard Worker         return LHS;
427*9880d681SAndroid Build Coastguard Worker       }
428*9880d681SAndroid Build Coastguard Worker       if (Value *RHS =
429*9880d681SAndroid Build Coastguard Worker               FindLIVLoopCondition(BO->getOperand(1), L, Changed, Cache)) {
430*9880d681SAndroid Build Coastguard Worker         Cache[Cond] = RHS;
431*9880d681SAndroid Build Coastguard Worker         return RHS;
432*9880d681SAndroid Build Coastguard Worker       }
433*9880d681SAndroid Build Coastguard Worker     }
434*9880d681SAndroid Build Coastguard Worker 
435*9880d681SAndroid Build Coastguard Worker   Cache[Cond] = nullptr;
436*9880d681SAndroid Build Coastguard Worker   return nullptr;
437*9880d681SAndroid Build Coastguard Worker }
438*9880d681SAndroid Build Coastguard Worker 
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed)439*9880d681SAndroid Build Coastguard Worker static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
440*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, Value *> Cache;
441*9880d681SAndroid Build Coastguard Worker   return FindLIVLoopCondition(Cond, L, Changed, Cache);
442*9880d681SAndroid Build Coastguard Worker }
443*9880d681SAndroid Build Coastguard Worker 
runOnLoop(Loop * L,LPPassManager & LPM_Ref)444*9880d681SAndroid Build Coastguard Worker bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
445*9880d681SAndroid Build Coastguard Worker   if (skipLoop(L))
446*9880d681SAndroid Build Coastguard Worker     return false;
447*9880d681SAndroid Build Coastguard Worker 
448*9880d681SAndroid Build Coastguard Worker   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
449*9880d681SAndroid Build Coastguard Worker       *L->getHeader()->getParent());
450*9880d681SAndroid Build Coastguard Worker   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
451*9880d681SAndroid Build Coastguard Worker   LPM = &LPM_Ref;
452*9880d681SAndroid Build Coastguard Worker   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
453*9880d681SAndroid Build Coastguard Worker   currentLoop = L;
454*9880d681SAndroid Build Coastguard Worker   Function *F = currentLoop->getHeader()->getParent();
455*9880d681SAndroid Build Coastguard Worker 
456*9880d681SAndroid Build Coastguard Worker   SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
457*9880d681SAndroid Build Coastguard Worker   if (SanitizeMemory)
458*9880d681SAndroid Build Coastguard Worker     computeLoopSafetyInfo(&SafetyInfo, L);
459*9880d681SAndroid Build Coastguard Worker 
460*9880d681SAndroid Build Coastguard Worker   EnabledPGO = F->getEntryCount().hasValue();
461*9880d681SAndroid Build Coastguard Worker 
462*9880d681SAndroid Build Coastguard Worker   if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
463*9880d681SAndroid Build Coastguard Worker     BranchProbabilityInfo BPI(*F, *LI);
464*9880d681SAndroid Build Coastguard Worker     BFI.calculate(*L->getHeader()->getParent(), BPI, *LI);
465*9880d681SAndroid Build Coastguard Worker 
466*9880d681SAndroid Build Coastguard Worker     // Use BranchProbability to compute a minimum frequency based on
467*9880d681SAndroid Build Coastguard Worker     // function entry baseline frequency. Loops with headers below this
468*9880d681SAndroid Build Coastguard Worker     // frequency are considered as cold.
469*9880d681SAndroid Build Coastguard Worker     const BranchProbability ColdProb(ColdnessThreshold, 100);
470*9880d681SAndroid Build Coastguard Worker     ColdEntryFreq = BlockFrequency(BFI.getEntryFreq()) * ColdProb;
471*9880d681SAndroid Build Coastguard Worker   }
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
474*9880d681SAndroid Build Coastguard Worker   do {
475*9880d681SAndroid Build Coastguard Worker     assert(currentLoop->isLCSSAForm(*DT));
476*9880d681SAndroid Build Coastguard Worker     redoLoop = false;
477*9880d681SAndroid Build Coastguard Worker     Changed |= processCurrentLoop();
478*9880d681SAndroid Build Coastguard Worker   } while(redoLoop);
479*9880d681SAndroid Build Coastguard Worker 
480*9880d681SAndroid Build Coastguard Worker   // FIXME: Reconstruct dom info, because it is not preserved properly.
481*9880d681SAndroid Build Coastguard Worker   if (Changed)
482*9880d681SAndroid Build Coastguard Worker     DT->recalculate(*F);
483*9880d681SAndroid Build Coastguard Worker   return Changed;
484*9880d681SAndroid Build Coastguard Worker }
485*9880d681SAndroid Build Coastguard Worker 
486*9880d681SAndroid Build Coastguard Worker /// Do actual work and unswitch loop if possible and profitable.
processCurrentLoop()487*9880d681SAndroid Build Coastguard Worker bool LoopUnswitch::processCurrentLoop() {
488*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
489*9880d681SAndroid Build Coastguard Worker 
490*9880d681SAndroid Build Coastguard Worker   initLoopData();
491*9880d681SAndroid Build Coastguard Worker 
492*9880d681SAndroid Build Coastguard Worker   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
493*9880d681SAndroid Build Coastguard Worker   if (!loopPreheader)
494*9880d681SAndroid Build Coastguard Worker     return false;
495*9880d681SAndroid Build Coastguard Worker 
496*9880d681SAndroid Build Coastguard Worker   // Loops with indirectbr cannot be cloned.
497*9880d681SAndroid Build Coastguard Worker   if (!currentLoop->isSafeToClone())
498*9880d681SAndroid Build Coastguard Worker     return false;
499*9880d681SAndroid Build Coastguard Worker 
500*9880d681SAndroid Build Coastguard Worker   // Without dedicated exits, splitting the exit edge may fail.
501*9880d681SAndroid Build Coastguard Worker   if (!currentLoop->hasDedicatedExits())
502*9880d681SAndroid Build Coastguard Worker     return false;
503*9880d681SAndroid Build Coastguard Worker 
504*9880d681SAndroid Build Coastguard Worker   LLVMContext &Context = loopHeader->getContext();
505*9880d681SAndroid Build Coastguard Worker 
506*9880d681SAndroid Build Coastguard Worker   // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
507*9880d681SAndroid Build Coastguard Worker   if (!BranchesInfo.countLoop(
508*9880d681SAndroid Build Coastguard Worker           currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
509*9880d681SAndroid Build Coastguard Worker                            *currentLoop->getHeader()->getParent()),
510*9880d681SAndroid Build Coastguard Worker           AC))
511*9880d681SAndroid Build Coastguard Worker     return false;
512*9880d681SAndroid Build Coastguard Worker 
513*9880d681SAndroid Build Coastguard Worker   // Try trivial unswitch first before loop over other basic blocks in the loop.
514*9880d681SAndroid Build Coastguard Worker   if (TryTrivialLoopUnswitch(Changed)) {
515*9880d681SAndroid Build Coastguard Worker     return true;
516*9880d681SAndroid Build Coastguard Worker   }
517*9880d681SAndroid Build Coastguard Worker 
518*9880d681SAndroid Build Coastguard Worker   // Run through the instructions in the loop, keeping track of three things:
519*9880d681SAndroid Build Coastguard Worker   //
520*9880d681SAndroid Build Coastguard Worker   //  - That we do not unswitch loops containing convergent operations, as we
521*9880d681SAndroid Build Coastguard Worker   //    might be making them control dependent on the unswitch value when they
522*9880d681SAndroid Build Coastguard Worker   //    were not before.
523*9880d681SAndroid Build Coastguard Worker   //    FIXME: This could be refined to only bail if the convergent operation is
524*9880d681SAndroid Build Coastguard Worker   //    not already control-dependent on the unswitch value.
525*9880d681SAndroid Build Coastguard Worker   //
526*9880d681SAndroid Build Coastguard Worker   //  - That basic blocks in the loop contain invokes whose predecessor edges we
527*9880d681SAndroid Build Coastguard Worker   //    cannot split.
528*9880d681SAndroid Build Coastguard Worker   //
529*9880d681SAndroid Build Coastguard Worker   //  - The set of guard intrinsics encountered (these are non terminator
530*9880d681SAndroid Build Coastguard Worker   //    instructions that are also profitable to be unswitched).
531*9880d681SAndroid Build Coastguard Worker 
532*9880d681SAndroid Build Coastguard Worker   SmallVector<IntrinsicInst *, 4> Guards;
533*9880d681SAndroid Build Coastguard Worker 
534*9880d681SAndroid Build Coastguard Worker   for (const auto BB : currentLoop->blocks()) {
535*9880d681SAndroid Build Coastguard Worker     for (auto &I : *BB) {
536*9880d681SAndroid Build Coastguard Worker       auto CS = CallSite(&I);
537*9880d681SAndroid Build Coastguard Worker       if (!CS) continue;
538*9880d681SAndroid Build Coastguard Worker       if (CS.hasFnAttr(Attribute::Convergent))
539*9880d681SAndroid Build Coastguard Worker         return false;
540*9880d681SAndroid Build Coastguard Worker       if (auto *II = dyn_cast<InvokeInst>(&I))
541*9880d681SAndroid Build Coastguard Worker         if (!II->getUnwindDest()->canSplitPredecessors())
542*9880d681SAndroid Build Coastguard Worker           return false;
543*9880d681SAndroid Build Coastguard Worker       if (auto *II = dyn_cast<IntrinsicInst>(&I))
544*9880d681SAndroid Build Coastguard Worker         if (II->getIntrinsicID() == Intrinsic::experimental_guard)
545*9880d681SAndroid Build Coastguard Worker           Guards.push_back(II);
546*9880d681SAndroid Build Coastguard Worker     }
547*9880d681SAndroid Build Coastguard Worker   }
548*9880d681SAndroid Build Coastguard Worker 
549*9880d681SAndroid Build Coastguard Worker   // Do not do non-trivial unswitch while optimizing for size.
550*9880d681SAndroid Build Coastguard Worker   // FIXME: Use Function::optForSize().
551*9880d681SAndroid Build Coastguard Worker   if (OptimizeForSize ||
552*9880d681SAndroid Build Coastguard Worker       loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
553*9880d681SAndroid Build Coastguard Worker     return false;
554*9880d681SAndroid Build Coastguard Worker 
555*9880d681SAndroid Build Coastguard Worker   if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
556*9880d681SAndroid Build Coastguard Worker     // Compute the weighted frequency of the hottest block in the
557*9880d681SAndroid Build Coastguard Worker     // loop (loopHeader in this case since inner loops should be
558*9880d681SAndroid Build Coastguard Worker     // processed before outer loop). If it is less than ColdFrequency,
559*9880d681SAndroid Build Coastguard Worker     // we should not unswitch.
560*9880d681SAndroid Build Coastguard Worker     BlockFrequency LoopEntryFreq = BFI.getBlockFreq(loopHeader);
561*9880d681SAndroid Build Coastguard Worker     if (LoopEntryFreq < ColdEntryFreq)
562*9880d681SAndroid Build Coastguard Worker       return false;
563*9880d681SAndroid Build Coastguard Worker   }
564*9880d681SAndroid Build Coastguard Worker 
565*9880d681SAndroid Build Coastguard Worker   for (IntrinsicInst *Guard : Guards) {
566*9880d681SAndroid Build Coastguard Worker     Value *LoopCond =
567*9880d681SAndroid Build Coastguard Worker         FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed);
568*9880d681SAndroid Build Coastguard Worker     if (LoopCond &&
569*9880d681SAndroid Build Coastguard Worker         UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
570*9880d681SAndroid Build Coastguard Worker       // NB! Unswitching (if successful) could have erased some of the
571*9880d681SAndroid Build Coastguard Worker       // instructions in Guards leaving dangling pointers there.  This is fine
572*9880d681SAndroid Build Coastguard Worker       // because we're returning now, and won't look at Guards again.
573*9880d681SAndroid Build Coastguard Worker       ++NumGuards;
574*9880d681SAndroid Build Coastguard Worker       return true;
575*9880d681SAndroid Build Coastguard Worker     }
576*9880d681SAndroid Build Coastguard Worker   }
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker   // Loop over all of the basic blocks in the loop.  If we find an interior
579*9880d681SAndroid Build Coastguard Worker   // block that is branching on a loop-invariant condition, we can unswitch this
580*9880d681SAndroid Build Coastguard Worker   // loop.
581*9880d681SAndroid Build Coastguard Worker   for (Loop::block_iterator I = currentLoop->block_begin(),
582*9880d681SAndroid Build Coastguard Worker          E = currentLoop->block_end(); I != E; ++I) {
583*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = (*I)->getTerminator();
584*9880d681SAndroid Build Coastguard Worker 
585*9880d681SAndroid Build Coastguard Worker     // Unswitching on a potentially uninitialized predicate is not
586*9880d681SAndroid Build Coastguard Worker     // MSan-friendly. Limit this to the cases when the original predicate is
587*9880d681SAndroid Build Coastguard Worker     // guaranteed to execute, to avoid creating a use-of-uninitialized-value
588*9880d681SAndroid Build Coastguard Worker     // in the code that did not have one.
589*9880d681SAndroid Build Coastguard Worker     // This is a workaround for the discrepancy between LLVM IR and MSan
590*9880d681SAndroid Build Coastguard Worker     // semantics. See PR28054 for more details.
591*9880d681SAndroid Build Coastguard Worker     if (SanitizeMemory &&
592*9880d681SAndroid Build Coastguard Worker         !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
593*9880d681SAndroid Build Coastguard Worker       continue;
594*9880d681SAndroid Build Coastguard Worker 
595*9880d681SAndroid Build Coastguard Worker     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
596*9880d681SAndroid Build Coastguard Worker       // If this isn't branching on an invariant condition, we can't unswitch
597*9880d681SAndroid Build Coastguard Worker       // it.
598*9880d681SAndroid Build Coastguard Worker       if (BI->isConditional()) {
599*9880d681SAndroid Build Coastguard Worker         // See if this, or some part of it, is loop invariant.  If so, we can
600*9880d681SAndroid Build Coastguard Worker         // unswitch on it if we desire.
601*9880d681SAndroid Build Coastguard Worker         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
602*9880d681SAndroid Build Coastguard Worker                                                currentLoop, Changed);
603*9880d681SAndroid Build Coastguard Worker         if (LoopCond &&
604*9880d681SAndroid Build Coastguard Worker             UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
605*9880d681SAndroid Build Coastguard Worker           ++NumBranches;
606*9880d681SAndroid Build Coastguard Worker           return true;
607*9880d681SAndroid Build Coastguard Worker         }
608*9880d681SAndroid Build Coastguard Worker       }
609*9880d681SAndroid Build Coastguard Worker     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
610*9880d681SAndroid Build Coastguard Worker       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
611*9880d681SAndroid Build Coastguard Worker                                              currentLoop, Changed);
612*9880d681SAndroid Build Coastguard Worker       unsigned NumCases = SI->getNumCases();
613*9880d681SAndroid Build Coastguard Worker       if (LoopCond && NumCases) {
614*9880d681SAndroid Build Coastguard Worker         // Find a value to unswitch on:
615*9880d681SAndroid Build Coastguard Worker         // FIXME: this should chose the most expensive case!
616*9880d681SAndroid Build Coastguard Worker         // FIXME: scan for a case with a non-critical edge?
617*9880d681SAndroid Build Coastguard Worker         Constant *UnswitchVal = nullptr;
618*9880d681SAndroid Build Coastguard Worker 
619*9880d681SAndroid Build Coastguard Worker         // Do not process same value again and again.
620*9880d681SAndroid Build Coastguard Worker         // At this point we have some cases already unswitched and
621*9880d681SAndroid Build Coastguard Worker         // some not yet unswitched. Let's find the first not yet unswitched one.
622*9880d681SAndroid Build Coastguard Worker         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
623*9880d681SAndroid Build Coastguard Worker              i != e; ++i) {
624*9880d681SAndroid Build Coastguard Worker           Constant *UnswitchValCandidate = i.getCaseValue();
625*9880d681SAndroid Build Coastguard Worker           if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
626*9880d681SAndroid Build Coastguard Worker             UnswitchVal = UnswitchValCandidate;
627*9880d681SAndroid Build Coastguard Worker             break;
628*9880d681SAndroid Build Coastguard Worker           }
629*9880d681SAndroid Build Coastguard Worker         }
630*9880d681SAndroid Build Coastguard Worker 
631*9880d681SAndroid Build Coastguard Worker         if (!UnswitchVal)
632*9880d681SAndroid Build Coastguard Worker           continue;
633*9880d681SAndroid Build Coastguard Worker 
634*9880d681SAndroid Build Coastguard Worker         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
635*9880d681SAndroid Build Coastguard Worker           ++NumSwitches;
636*9880d681SAndroid Build Coastguard Worker           return true;
637*9880d681SAndroid Build Coastguard Worker         }
638*9880d681SAndroid Build Coastguard Worker       }
639*9880d681SAndroid Build Coastguard Worker     }
640*9880d681SAndroid Build Coastguard Worker 
641*9880d681SAndroid Build Coastguard Worker     // Scan the instructions to check for unswitchable values.
642*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
643*9880d681SAndroid Build Coastguard Worker          BBI != E; ++BBI)
644*9880d681SAndroid Build Coastguard Worker       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
645*9880d681SAndroid Build Coastguard Worker         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
646*9880d681SAndroid Build Coastguard Worker                                                currentLoop, Changed);
647*9880d681SAndroid Build Coastguard Worker         if (LoopCond && UnswitchIfProfitable(LoopCond,
648*9880d681SAndroid Build Coastguard Worker                                              ConstantInt::getTrue(Context))) {
649*9880d681SAndroid Build Coastguard Worker           ++NumSelects;
650*9880d681SAndroid Build Coastguard Worker           return true;
651*9880d681SAndroid Build Coastguard Worker         }
652*9880d681SAndroid Build Coastguard Worker       }
653*9880d681SAndroid Build Coastguard Worker   }
654*9880d681SAndroid Build Coastguard Worker   return Changed;
655*9880d681SAndroid Build Coastguard Worker }
656*9880d681SAndroid Build Coastguard Worker 
657*9880d681SAndroid Build Coastguard Worker /// Check to see if all paths from BB exit the loop with no side effects
658*9880d681SAndroid Build Coastguard Worker /// (including infinite loops).
659*9880d681SAndroid Build Coastguard Worker ///
660*9880d681SAndroid Build Coastguard Worker /// If true, we return true and set ExitBB to the block we
661*9880d681SAndroid Build Coastguard Worker /// exit through.
662*9880d681SAndroid Build Coastguard Worker ///
isTrivialLoopExitBlockHelper(Loop * L,BasicBlock * BB,BasicBlock * & ExitBB,std::set<BasicBlock * > & Visited)663*9880d681SAndroid Build Coastguard Worker static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
664*9880d681SAndroid Build Coastguard Worker                                          BasicBlock *&ExitBB,
665*9880d681SAndroid Build Coastguard Worker                                          std::set<BasicBlock*> &Visited) {
666*9880d681SAndroid Build Coastguard Worker   if (!Visited.insert(BB).second) {
667*9880d681SAndroid Build Coastguard Worker     // Already visited. Without more analysis, this could indicate an infinite
668*9880d681SAndroid Build Coastguard Worker     // loop.
669*9880d681SAndroid Build Coastguard Worker     return false;
670*9880d681SAndroid Build Coastguard Worker   }
671*9880d681SAndroid Build Coastguard Worker   if (!L->contains(BB)) {
672*9880d681SAndroid Build Coastguard Worker     // Otherwise, this is a loop exit, this is fine so long as this is the
673*9880d681SAndroid Build Coastguard Worker     // first exit.
674*9880d681SAndroid Build Coastguard Worker     if (ExitBB) return false;
675*9880d681SAndroid Build Coastguard Worker     ExitBB = BB;
676*9880d681SAndroid Build Coastguard Worker     return true;
677*9880d681SAndroid Build Coastguard Worker   }
678*9880d681SAndroid Build Coastguard Worker 
679*9880d681SAndroid Build Coastguard Worker   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
680*9880d681SAndroid Build Coastguard Worker   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
681*9880d681SAndroid Build Coastguard Worker     // Check to see if the successor is a trivial loop exit.
682*9880d681SAndroid Build Coastguard Worker     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
683*9880d681SAndroid Build Coastguard Worker       return false;
684*9880d681SAndroid Build Coastguard Worker   }
685*9880d681SAndroid Build Coastguard Worker 
686*9880d681SAndroid Build Coastguard Worker   // Okay, everything after this looks good, check to make sure that this block
687*9880d681SAndroid Build Coastguard Worker   // doesn't include any side effects.
688*9880d681SAndroid Build Coastguard Worker   for (Instruction &I : *BB)
689*9880d681SAndroid Build Coastguard Worker     if (I.mayHaveSideEffects())
690*9880d681SAndroid Build Coastguard Worker       return false;
691*9880d681SAndroid Build Coastguard Worker 
692*9880d681SAndroid Build Coastguard Worker   return true;
693*9880d681SAndroid Build Coastguard Worker }
694*9880d681SAndroid Build Coastguard Worker 
695*9880d681SAndroid Build Coastguard Worker /// Return true if the specified block unconditionally leads to an exit from
696*9880d681SAndroid Build Coastguard Worker /// the specified loop, and has no side-effects in the process. If so, return
697*9880d681SAndroid Build Coastguard Worker /// the block that is exited to, otherwise return null.
isTrivialLoopExitBlock(Loop * L,BasicBlock * BB)698*9880d681SAndroid Build Coastguard Worker static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
699*9880d681SAndroid Build Coastguard Worker   std::set<BasicBlock*> Visited;
700*9880d681SAndroid Build Coastguard Worker   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
701*9880d681SAndroid Build Coastguard Worker   BasicBlock *ExitBB = nullptr;
702*9880d681SAndroid Build Coastguard Worker   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
703*9880d681SAndroid Build Coastguard Worker     return ExitBB;
704*9880d681SAndroid Build Coastguard Worker   return nullptr;
705*9880d681SAndroid Build Coastguard Worker }
706*9880d681SAndroid Build Coastguard Worker 
707*9880d681SAndroid Build Coastguard Worker /// We have found that we can unswitch currentLoop when LoopCond == Val to
708*9880d681SAndroid Build Coastguard Worker /// simplify the loop.  If we decide that this is profitable,
709*9880d681SAndroid Build Coastguard Worker /// unswitch the loop, reprocess the pieces, then return true.
UnswitchIfProfitable(Value * LoopCond,Constant * Val,TerminatorInst * TI)710*9880d681SAndroid Build Coastguard Worker bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
711*9880d681SAndroid Build Coastguard Worker                                         TerminatorInst *TI) {
712*9880d681SAndroid Build Coastguard Worker   // Check to see if it would be profitable to unswitch current loop.
713*9880d681SAndroid Build Coastguard Worker   if (!BranchesInfo.CostAllowsUnswitching()) {
714*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "NOT unswitching loop %"
715*9880d681SAndroid Build Coastguard Worker                  << currentLoop->getHeader()->getName()
716*9880d681SAndroid Build Coastguard Worker                  << " at non-trivial condition '" << *Val
717*9880d681SAndroid Build Coastguard Worker                  << "' == " << *LoopCond << "\n"
718*9880d681SAndroid Build Coastguard Worker                  << ". Cost too high.\n");
719*9880d681SAndroid Build Coastguard Worker     return false;
720*9880d681SAndroid Build Coastguard Worker   }
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker   UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
723*9880d681SAndroid Build Coastguard Worker   return true;
724*9880d681SAndroid Build Coastguard Worker }
725*9880d681SAndroid Build Coastguard Worker 
726*9880d681SAndroid Build Coastguard Worker /// Recursively clone the specified loop and all of its children,
727*9880d681SAndroid Build Coastguard Worker /// mapping the blocks with the specified map.
CloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)728*9880d681SAndroid Build Coastguard Worker static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
729*9880d681SAndroid Build Coastguard Worker                        LoopInfo *LI, LPPassManager *LPM) {
730*9880d681SAndroid Build Coastguard Worker   Loop &New = LPM->addLoop(PL);
731*9880d681SAndroid Build Coastguard Worker 
732*9880d681SAndroid Build Coastguard Worker   // Add all of the blocks in L to the new loop.
733*9880d681SAndroid Build Coastguard Worker   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
734*9880d681SAndroid Build Coastguard Worker        I != E; ++I)
735*9880d681SAndroid Build Coastguard Worker     if (LI->getLoopFor(*I) == L)
736*9880d681SAndroid Build Coastguard Worker       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
737*9880d681SAndroid Build Coastguard Worker 
738*9880d681SAndroid Build Coastguard Worker   // Add all of the subloops to the new loop.
739*9880d681SAndroid Build Coastguard Worker   for (Loop *I : *L)
740*9880d681SAndroid Build Coastguard Worker     CloneLoop(I, &New, VM, LI, LPM);
741*9880d681SAndroid Build Coastguard Worker 
742*9880d681SAndroid Build Coastguard Worker   return &New;
743*9880d681SAndroid Build Coastguard Worker }
744*9880d681SAndroid Build Coastguard Worker 
copyMetadata(Instruction * DstInst,const Instruction * SrcInst,bool Swapped)745*9880d681SAndroid Build Coastguard Worker static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
746*9880d681SAndroid Build Coastguard Worker                          bool Swapped) {
747*9880d681SAndroid Build Coastguard Worker   if (!SrcInst || !SrcInst->hasMetadata())
748*9880d681SAndroid Build Coastguard Worker     return;
749*9880d681SAndroid Build Coastguard Worker 
750*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
751*9880d681SAndroid Build Coastguard Worker   SrcInst->getAllMetadata(MDs);
752*9880d681SAndroid Build Coastguard Worker   for (auto &MD : MDs) {
753*9880d681SAndroid Build Coastguard Worker     switch (MD.first) {
754*9880d681SAndroid Build Coastguard Worker     default:
755*9880d681SAndroid Build Coastguard Worker       break;
756*9880d681SAndroid Build Coastguard Worker     case LLVMContext::MD_prof:
757*9880d681SAndroid Build Coastguard Worker       if (Swapped && MD.second->getNumOperands() == 3 &&
758*9880d681SAndroid Build Coastguard Worker           isa<MDString>(MD.second->getOperand(0))) {
759*9880d681SAndroid Build Coastguard Worker         MDString *MDName = cast<MDString>(MD.second->getOperand(0));
760*9880d681SAndroid Build Coastguard Worker         if (MDName->getString() == "branch_weights") {
761*9880d681SAndroid Build Coastguard Worker           auto *ValT = cast_or_null<ConstantAsMetadata>(
762*9880d681SAndroid Build Coastguard Worker                            MD.second->getOperand(1))->getValue();
763*9880d681SAndroid Build Coastguard Worker           auto *ValF = cast_or_null<ConstantAsMetadata>(
764*9880d681SAndroid Build Coastguard Worker                            MD.second->getOperand(2))->getValue();
765*9880d681SAndroid Build Coastguard Worker           assert(ValT && ValF && "Invalid Operands of branch_weights");
766*9880d681SAndroid Build Coastguard Worker           auto NewMD =
767*9880d681SAndroid Build Coastguard Worker               MDBuilder(DstInst->getParent()->getContext())
768*9880d681SAndroid Build Coastguard Worker                   .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
769*9880d681SAndroid Build Coastguard Worker                                        cast<ConstantInt>(ValT)->getZExtValue());
770*9880d681SAndroid Build Coastguard Worker           MD.second = NewMD;
771*9880d681SAndroid Build Coastguard Worker         }
772*9880d681SAndroid Build Coastguard Worker       }
773*9880d681SAndroid Build Coastguard Worker       // fallthrough.
774*9880d681SAndroid Build Coastguard Worker     case LLVMContext::MD_make_implicit:
775*9880d681SAndroid Build Coastguard Worker     case LLVMContext::MD_dbg:
776*9880d681SAndroid Build Coastguard Worker       DstInst->setMetadata(MD.first, MD.second);
777*9880d681SAndroid Build Coastguard Worker     }
778*9880d681SAndroid Build Coastguard Worker   }
779*9880d681SAndroid Build Coastguard Worker }
780*9880d681SAndroid Build Coastguard Worker 
781*9880d681SAndroid Build Coastguard Worker /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
782*9880d681SAndroid Build Coastguard Worker /// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
EmitPreheaderBranchOnCondition(Value * LIC,Constant * Val,BasicBlock * TrueDest,BasicBlock * FalseDest,Instruction * InsertPt,TerminatorInst * TI)783*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
784*9880d681SAndroid Build Coastguard Worker                                                   BasicBlock *TrueDest,
785*9880d681SAndroid Build Coastguard Worker                                                   BasicBlock *FalseDest,
786*9880d681SAndroid Build Coastguard Worker                                                   Instruction *InsertPt,
787*9880d681SAndroid Build Coastguard Worker                                                   TerminatorInst *TI) {
788*9880d681SAndroid Build Coastguard Worker   // Insert a conditional branch on LIC to the two preheaders.  The original
789*9880d681SAndroid Build Coastguard Worker   // code is the true version and the new code is the false version.
790*9880d681SAndroid Build Coastguard Worker   Value *BranchVal = LIC;
791*9880d681SAndroid Build Coastguard Worker   bool Swapped = false;
792*9880d681SAndroid Build Coastguard Worker   if (!isa<ConstantInt>(Val) ||
793*9880d681SAndroid Build Coastguard Worker       Val->getType() != Type::getInt1Ty(LIC->getContext()))
794*9880d681SAndroid Build Coastguard Worker     BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
795*9880d681SAndroid Build Coastguard Worker   else if (Val != ConstantInt::getTrue(Val->getContext())) {
796*9880d681SAndroid Build Coastguard Worker     // We want to enter the new loop when the condition is true.
797*9880d681SAndroid Build Coastguard Worker     std::swap(TrueDest, FalseDest);
798*9880d681SAndroid Build Coastguard Worker     Swapped = true;
799*9880d681SAndroid Build Coastguard Worker   }
800*9880d681SAndroid Build Coastguard Worker 
801*9880d681SAndroid Build Coastguard Worker   // Insert the new branch.
802*9880d681SAndroid Build Coastguard Worker   BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
803*9880d681SAndroid Build Coastguard Worker   copyMetadata(BI, TI, Swapped);
804*9880d681SAndroid Build Coastguard Worker 
805*9880d681SAndroid Build Coastguard Worker   // If either edge is critical, split it. This helps preserve LoopSimplify
806*9880d681SAndroid Build Coastguard Worker   // form for enclosing loops.
807*9880d681SAndroid Build Coastguard Worker   auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
808*9880d681SAndroid Build Coastguard Worker   SplitCriticalEdge(BI, 0, Options);
809*9880d681SAndroid Build Coastguard Worker   SplitCriticalEdge(BI, 1, Options);
810*9880d681SAndroid Build Coastguard Worker }
811*9880d681SAndroid Build Coastguard Worker 
812*9880d681SAndroid Build Coastguard Worker /// Given a loop that has a trivial unswitchable condition in it (a cond branch
813*9880d681SAndroid Build Coastguard Worker /// from its header block to its latch block, where the path through the loop
814*9880d681SAndroid Build Coastguard Worker /// that doesn't execute its body has no side-effects), unswitch it. This
815*9880d681SAndroid Build Coastguard Worker /// doesn't involve any code duplication, just moving the conditional branch
816*9880d681SAndroid Build Coastguard Worker /// outside of the loop and updating loop info.
UnswitchTrivialCondition(Loop * L,Value * Cond,Constant * Val,BasicBlock * ExitBlock,TerminatorInst * TI)817*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
818*9880d681SAndroid Build Coastguard Worker                                             BasicBlock *ExitBlock,
819*9880d681SAndroid Build Coastguard Worker                                             TerminatorInst *TI) {
820*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
821*9880d681SAndroid Build Coastguard Worker                << loopHeader->getName() << " [" << L->getBlocks().size()
822*9880d681SAndroid Build Coastguard Worker                << " blocks] in Function "
823*9880d681SAndroid Build Coastguard Worker                << L->getHeader()->getParent()->getName() << " on cond: " << *Val
824*9880d681SAndroid Build Coastguard Worker                << " == " << *Cond << "\n");
825*9880d681SAndroid Build Coastguard Worker 
826*9880d681SAndroid Build Coastguard Worker   // First step, split the preheader, so that we know that there is a safe place
827*9880d681SAndroid Build Coastguard Worker   // to insert the conditional branch.  We will change loopPreheader to have a
828*9880d681SAndroid Build Coastguard Worker   // conditional branch on Cond.
829*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
830*9880d681SAndroid Build Coastguard Worker 
831*9880d681SAndroid Build Coastguard Worker   // Now that we have a place to insert the conditional branch, create a place
832*9880d681SAndroid Build Coastguard Worker   // to branch to: this is the exit block out of the loop that we should
833*9880d681SAndroid Build Coastguard Worker   // short-circuit to.
834*9880d681SAndroid Build Coastguard Worker 
835*9880d681SAndroid Build Coastguard Worker   // Split this block now, so that the loop maintains its exit block, and so
836*9880d681SAndroid Build Coastguard Worker   // that the jump from the preheader can execute the contents of the exit block
837*9880d681SAndroid Build Coastguard Worker   // without actually branching to it (the exit block should be dominated by the
838*9880d681SAndroid Build Coastguard Worker   // loop header, not the preheader).
839*9880d681SAndroid Build Coastguard Worker   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
840*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker   // Okay, now we have a position to branch from and a position to branch to,
843*9880d681SAndroid Build Coastguard Worker   // insert the new conditional branch.
844*9880d681SAndroid Build Coastguard Worker   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
845*9880d681SAndroid Build Coastguard Worker                                  loopPreheader->getTerminator(), TI);
846*9880d681SAndroid Build Coastguard Worker   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
847*9880d681SAndroid Build Coastguard Worker   loopPreheader->getTerminator()->eraseFromParent();
848*9880d681SAndroid Build Coastguard Worker 
849*9880d681SAndroid Build Coastguard Worker   // We need to reprocess this loop, it could be unswitched again.
850*9880d681SAndroid Build Coastguard Worker   redoLoop = true;
851*9880d681SAndroid Build Coastguard Worker 
852*9880d681SAndroid Build Coastguard Worker   // Now that we know that the loop is never entered when this condition is a
853*9880d681SAndroid Build Coastguard Worker   // particular value, rewrite the loop with this info.  We know that this will
854*9880d681SAndroid Build Coastguard Worker   // at least eliminate the old branch.
855*9880d681SAndroid Build Coastguard Worker   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
856*9880d681SAndroid Build Coastguard Worker   ++NumTrivial;
857*9880d681SAndroid Build Coastguard Worker }
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker /// Check if the first non-constant condition starting from the loop header is
860*9880d681SAndroid Build Coastguard Worker /// a trivial unswitch condition: that is, a condition controls whether or not
861*9880d681SAndroid Build Coastguard Worker /// the loop does anything at all. If it is a trivial condition, unswitching
862*9880d681SAndroid Build Coastguard Worker /// produces no code duplications (equivalently, it produces a simpler loop and
863*9880d681SAndroid Build Coastguard Worker /// a new empty loop, which gets deleted). Therefore always unswitch trivial
864*9880d681SAndroid Build Coastguard Worker /// condition.
TryTrivialLoopUnswitch(bool & Changed)865*9880d681SAndroid Build Coastguard Worker bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
866*9880d681SAndroid Build Coastguard Worker   BasicBlock *CurrentBB = currentLoop->getHeader();
867*9880d681SAndroid Build Coastguard Worker   TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
868*9880d681SAndroid Build Coastguard Worker   LLVMContext &Context = CurrentBB->getContext();
869*9880d681SAndroid Build Coastguard Worker 
870*9880d681SAndroid Build Coastguard Worker   // If loop header has only one reachable successor (currently via an
871*9880d681SAndroid Build Coastguard Worker   // unconditional branch or constant foldable conditional branch, but
872*9880d681SAndroid Build Coastguard Worker   // should also consider adding constant foldable switch instruction in
873*9880d681SAndroid Build Coastguard Worker   // future), we should keep looking for trivial condition candidates in
874*9880d681SAndroid Build Coastguard Worker   // the successor as well. An alternative is to constant fold conditions
875*9880d681SAndroid Build Coastguard Worker   // and merge successors into loop header (then we only need to check header's
876*9880d681SAndroid Build Coastguard Worker   // terminator). The reason for not doing this in LoopUnswitch pass is that
877*9880d681SAndroid Build Coastguard Worker   // it could potentially break LoopPassManager's invariants. Folding dead
878*9880d681SAndroid Build Coastguard Worker   // branches could either eliminate the current loop or make other loops
879*9880d681SAndroid Build Coastguard Worker   // unreachable. LCSSA form might also not be preserved after deleting
880*9880d681SAndroid Build Coastguard Worker   // branches. The following code keeps traversing loop header's successors
881*9880d681SAndroid Build Coastguard Worker   // until it finds the trivial condition candidate (condition that is not a
882*9880d681SAndroid Build Coastguard Worker   // constant). Since unswitching generates branches with constant conditions,
883*9880d681SAndroid Build Coastguard Worker   // this scenario could be very common in practice.
884*9880d681SAndroid Build Coastguard Worker   SmallSet<BasicBlock*, 8> Visited;
885*9880d681SAndroid Build Coastguard Worker 
886*9880d681SAndroid Build Coastguard Worker   while (true) {
887*9880d681SAndroid Build Coastguard Worker     // If we exit loop or reach a previous visited block, then
888*9880d681SAndroid Build Coastguard Worker     // we can not reach any trivial condition candidates (unfoldable
889*9880d681SAndroid Build Coastguard Worker     // branch instructions or switch instructions) and no unswitch
890*9880d681SAndroid Build Coastguard Worker     // can happen. Exit and return false.
891*9880d681SAndroid Build Coastguard Worker     if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
892*9880d681SAndroid Build Coastguard Worker       return false;
893*9880d681SAndroid Build Coastguard Worker 
894*9880d681SAndroid Build Coastguard Worker     // Check if this loop will execute any side-effecting instructions (e.g.
895*9880d681SAndroid Build Coastguard Worker     // stores, calls, volatile loads) in the part of the loop that the code
896*9880d681SAndroid Build Coastguard Worker     // *would* execute. Check the header first.
897*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *CurrentBB)
898*9880d681SAndroid Build Coastguard Worker       if (I.mayHaveSideEffects())
899*9880d681SAndroid Build Coastguard Worker         return false;
900*9880d681SAndroid Build Coastguard Worker 
901*9880d681SAndroid Build Coastguard Worker     // FIXME: add check for constant foldable switch instructions.
902*9880d681SAndroid Build Coastguard Worker     if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
903*9880d681SAndroid Build Coastguard Worker       if (BI->isUnconditional()) {
904*9880d681SAndroid Build Coastguard Worker         CurrentBB = BI->getSuccessor(0);
905*9880d681SAndroid Build Coastguard Worker       } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
906*9880d681SAndroid Build Coastguard Worker         CurrentBB = BI->getSuccessor(0);
907*9880d681SAndroid Build Coastguard Worker       } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
908*9880d681SAndroid Build Coastguard Worker         CurrentBB = BI->getSuccessor(1);
909*9880d681SAndroid Build Coastguard Worker       } else {
910*9880d681SAndroid Build Coastguard Worker         // Found a trivial condition candidate: non-foldable conditional branch.
911*9880d681SAndroid Build Coastguard Worker         break;
912*9880d681SAndroid Build Coastguard Worker       }
913*9880d681SAndroid Build Coastguard Worker     } else {
914*9880d681SAndroid Build Coastguard Worker       break;
915*9880d681SAndroid Build Coastguard Worker     }
916*9880d681SAndroid Build Coastguard Worker 
917*9880d681SAndroid Build Coastguard Worker     CurrentTerm = CurrentBB->getTerminator();
918*9880d681SAndroid Build Coastguard Worker   }
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker   // CondVal is the condition that controls the trivial condition.
921*9880d681SAndroid Build Coastguard Worker   // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
922*9880d681SAndroid Build Coastguard Worker   Constant *CondVal = nullptr;
923*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopExitBB = nullptr;
924*9880d681SAndroid Build Coastguard Worker 
925*9880d681SAndroid Build Coastguard Worker   if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
926*9880d681SAndroid Build Coastguard Worker     // If this isn't branching on an invariant condition, we can't unswitch it.
927*9880d681SAndroid Build Coastguard Worker     if (!BI->isConditional())
928*9880d681SAndroid Build Coastguard Worker       return false;
929*9880d681SAndroid Build Coastguard Worker 
930*9880d681SAndroid Build Coastguard Worker     Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
931*9880d681SAndroid Build Coastguard Worker                                            currentLoop, Changed);
932*9880d681SAndroid Build Coastguard Worker 
933*9880d681SAndroid Build Coastguard Worker     // Unswitch only if the trivial condition itself is an LIV (not
934*9880d681SAndroid Build Coastguard Worker     // partial LIV which could occur in and/or)
935*9880d681SAndroid Build Coastguard Worker     if (!LoopCond || LoopCond != BI->getCondition())
936*9880d681SAndroid Build Coastguard Worker       return false;
937*9880d681SAndroid Build Coastguard Worker 
938*9880d681SAndroid Build Coastguard Worker     // Check to see if a successor of the branch is guaranteed to
939*9880d681SAndroid Build Coastguard Worker     // exit through a unique exit block without having any
940*9880d681SAndroid Build Coastguard Worker     // side-effects.  If so, determine the value of Cond that causes
941*9880d681SAndroid Build Coastguard Worker     // it to do this.
942*9880d681SAndroid Build Coastguard Worker     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
943*9880d681SAndroid Build Coastguard Worker                                              BI->getSuccessor(0)))) {
944*9880d681SAndroid Build Coastguard Worker       CondVal = ConstantInt::getTrue(Context);
945*9880d681SAndroid Build Coastguard Worker     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
946*9880d681SAndroid Build Coastguard Worker                                                     BI->getSuccessor(1)))) {
947*9880d681SAndroid Build Coastguard Worker       CondVal = ConstantInt::getFalse(Context);
948*9880d681SAndroid Build Coastguard Worker     }
949*9880d681SAndroid Build Coastguard Worker 
950*9880d681SAndroid Build Coastguard Worker     // If we didn't find a single unique LoopExit block, or if the loop exit
951*9880d681SAndroid Build Coastguard Worker     // block contains phi nodes, this isn't trivial.
952*9880d681SAndroid Build Coastguard Worker     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
953*9880d681SAndroid Build Coastguard Worker       return false;   // Can't handle this.
954*9880d681SAndroid Build Coastguard Worker 
955*9880d681SAndroid Build Coastguard Worker     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
956*9880d681SAndroid Build Coastguard Worker                              CurrentTerm);
957*9880d681SAndroid Build Coastguard Worker     ++NumBranches;
958*9880d681SAndroid Build Coastguard Worker     return true;
959*9880d681SAndroid Build Coastguard Worker   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
960*9880d681SAndroid Build Coastguard Worker     // If this isn't switching on an invariant condition, we can't unswitch it.
961*9880d681SAndroid Build Coastguard Worker     Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
962*9880d681SAndroid Build Coastguard Worker                                            currentLoop, Changed);
963*9880d681SAndroid Build Coastguard Worker 
964*9880d681SAndroid Build Coastguard Worker     // Unswitch only if the trivial condition itself is an LIV (not
965*9880d681SAndroid Build Coastguard Worker     // partial LIV which could occur in and/or)
966*9880d681SAndroid Build Coastguard Worker     if (!LoopCond || LoopCond != SI->getCondition())
967*9880d681SAndroid Build Coastguard Worker       return false;
968*9880d681SAndroid Build Coastguard Worker 
969*9880d681SAndroid Build Coastguard Worker     // Check to see if a successor of the switch is guaranteed to go to the
970*9880d681SAndroid Build Coastguard Worker     // latch block or exit through a one exit block without having any
971*9880d681SAndroid Build Coastguard Worker     // side-effects.  If so, determine the value of Cond that causes it to do
972*9880d681SAndroid Build Coastguard Worker     // this.
973*9880d681SAndroid Build Coastguard Worker     // Note that we can't trivially unswitch on the default case or
974*9880d681SAndroid Build Coastguard Worker     // on already unswitched cases.
975*9880d681SAndroid Build Coastguard Worker     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
976*9880d681SAndroid Build Coastguard Worker          i != e; ++i) {
977*9880d681SAndroid Build Coastguard Worker       BasicBlock *LoopExitCandidate;
978*9880d681SAndroid Build Coastguard Worker       if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
979*9880d681SAndroid Build Coastguard Worker                                                i.getCaseSuccessor()))) {
980*9880d681SAndroid Build Coastguard Worker         // Okay, we found a trivial case, remember the value that is trivial.
981*9880d681SAndroid Build Coastguard Worker         ConstantInt *CaseVal = i.getCaseValue();
982*9880d681SAndroid Build Coastguard Worker 
983*9880d681SAndroid Build Coastguard Worker         // Check that it was not unswitched before, since already unswitched
984*9880d681SAndroid Build Coastguard Worker         // trivial vals are looks trivial too.
985*9880d681SAndroid Build Coastguard Worker         if (BranchesInfo.isUnswitched(SI, CaseVal))
986*9880d681SAndroid Build Coastguard Worker           continue;
987*9880d681SAndroid Build Coastguard Worker         LoopExitBB = LoopExitCandidate;
988*9880d681SAndroid Build Coastguard Worker         CondVal = CaseVal;
989*9880d681SAndroid Build Coastguard Worker         break;
990*9880d681SAndroid Build Coastguard Worker       }
991*9880d681SAndroid Build Coastguard Worker     }
992*9880d681SAndroid Build Coastguard Worker 
993*9880d681SAndroid Build Coastguard Worker     // If we didn't find a single unique LoopExit block, or if the loop exit
994*9880d681SAndroid Build Coastguard Worker     // block contains phi nodes, this isn't trivial.
995*9880d681SAndroid Build Coastguard Worker     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
996*9880d681SAndroid Build Coastguard Worker       return false;   // Can't handle this.
997*9880d681SAndroid Build Coastguard Worker 
998*9880d681SAndroid Build Coastguard Worker     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
999*9880d681SAndroid Build Coastguard Worker                              nullptr);
1000*9880d681SAndroid Build Coastguard Worker     ++NumSwitches;
1001*9880d681SAndroid Build Coastguard Worker     return true;
1002*9880d681SAndroid Build Coastguard Worker   }
1003*9880d681SAndroid Build Coastguard Worker   return false;
1004*9880d681SAndroid Build Coastguard Worker }
1005*9880d681SAndroid Build Coastguard Worker 
1006*9880d681SAndroid Build Coastguard Worker /// Split all of the edges from inside the loop to their exit blocks.
1007*9880d681SAndroid Build Coastguard Worker /// Update the appropriate Phi nodes as we do so.
SplitExitEdges(Loop * L,const SmallVectorImpl<BasicBlock * > & ExitBlocks)1008*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::SplitExitEdges(Loop *L,
1009*9880d681SAndroid Build Coastguard Worker                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
1010*9880d681SAndroid Build Coastguard Worker 
1011*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1012*9880d681SAndroid Build Coastguard Worker     BasicBlock *ExitBlock = ExitBlocks[i];
1013*9880d681SAndroid Build Coastguard Worker     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1014*9880d681SAndroid Build Coastguard Worker                                        pred_end(ExitBlock));
1015*9880d681SAndroid Build Coastguard Worker 
1016*9880d681SAndroid Build Coastguard Worker     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1017*9880d681SAndroid Build Coastguard Worker     // general, if we call it on all predecessors of all exits then it does.
1018*9880d681SAndroid Build Coastguard Worker     SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
1019*9880d681SAndroid Build Coastguard Worker                            /*PreserveLCSSA*/ true);
1020*9880d681SAndroid Build Coastguard Worker   }
1021*9880d681SAndroid Build Coastguard Worker }
1022*9880d681SAndroid Build Coastguard Worker 
1023*9880d681SAndroid Build Coastguard Worker /// We determined that the loop is profitable to unswitch when LIC equal Val.
1024*9880d681SAndroid Build Coastguard Worker /// Split it into loop versions and test the condition outside of either loop.
1025*9880d681SAndroid Build Coastguard Worker /// Return the loops created as Out1/Out2.
UnswitchNontrivialCondition(Value * LIC,Constant * Val,Loop * L,TerminatorInst * TI)1026*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
1027*9880d681SAndroid Build Coastguard Worker                                                Loop *L, TerminatorInst *TI) {
1028*9880d681SAndroid Build Coastguard Worker   Function *F = loopHeader->getParent();
1029*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1030*9880d681SAndroid Build Coastguard Worker         << loopHeader->getName() << " [" << L->getBlocks().size()
1031*9880d681SAndroid Build Coastguard Worker         << " blocks] in Function " << F->getName()
1032*9880d681SAndroid Build Coastguard Worker         << " when '" << *Val << "' == " << *LIC << "\n");
1033*9880d681SAndroid Build Coastguard Worker 
1034*9880d681SAndroid Build Coastguard Worker   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1035*9880d681SAndroid Build Coastguard Worker     SEWP->getSE().forgetLoop(L);
1036*9880d681SAndroid Build Coastguard Worker 
1037*9880d681SAndroid Build Coastguard Worker   LoopBlocks.clear();
1038*9880d681SAndroid Build Coastguard Worker   NewBlocks.clear();
1039*9880d681SAndroid Build Coastguard Worker 
1040*9880d681SAndroid Build Coastguard Worker   // First step, split the preheader and exit blocks, and add these blocks to
1041*9880d681SAndroid Build Coastguard Worker   // the LoopBlocks list.
1042*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
1043*9880d681SAndroid Build Coastguard Worker   LoopBlocks.push_back(NewPreheader);
1044*9880d681SAndroid Build Coastguard Worker 
1045*9880d681SAndroid Build Coastguard Worker   // We want the loop to come after the preheader, but before the exit blocks.
1046*9880d681SAndroid Build Coastguard Worker   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1047*9880d681SAndroid Build Coastguard Worker 
1048*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> ExitBlocks;
1049*9880d681SAndroid Build Coastguard Worker   L->getUniqueExitBlocks(ExitBlocks);
1050*9880d681SAndroid Build Coastguard Worker 
1051*9880d681SAndroid Build Coastguard Worker   // Split all of the edges from inside the loop to their exit blocks.  Update
1052*9880d681SAndroid Build Coastguard Worker   // the appropriate Phi nodes as we do so.
1053*9880d681SAndroid Build Coastguard Worker   SplitExitEdges(L, ExitBlocks);
1054*9880d681SAndroid Build Coastguard Worker 
1055*9880d681SAndroid Build Coastguard Worker   // The exit blocks may have been changed due to edge splitting, recompute.
1056*9880d681SAndroid Build Coastguard Worker   ExitBlocks.clear();
1057*9880d681SAndroid Build Coastguard Worker   L->getUniqueExitBlocks(ExitBlocks);
1058*9880d681SAndroid Build Coastguard Worker 
1059*9880d681SAndroid Build Coastguard Worker   // Add exit blocks to the loop blocks.
1060*9880d681SAndroid Build Coastguard Worker   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
1061*9880d681SAndroid Build Coastguard Worker 
1062*9880d681SAndroid Build Coastguard Worker   // Next step, clone all of the basic blocks that make up the loop (including
1063*9880d681SAndroid Build Coastguard Worker   // the loop preheader and exit blocks), keeping track of the mapping between
1064*9880d681SAndroid Build Coastguard Worker   // the instructions and blocks.
1065*9880d681SAndroid Build Coastguard Worker   NewBlocks.reserve(LoopBlocks.size());
1066*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
1067*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1068*9880d681SAndroid Build Coastguard Worker     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
1069*9880d681SAndroid Build Coastguard Worker 
1070*9880d681SAndroid Build Coastguard Worker     NewBlocks.push_back(NewBB);
1071*9880d681SAndroid Build Coastguard Worker     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
1072*9880d681SAndroid Build Coastguard Worker     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1073*9880d681SAndroid Build Coastguard Worker   }
1074*9880d681SAndroid Build Coastguard Worker 
1075*9880d681SAndroid Build Coastguard Worker   // Splice the newly inserted blocks into the function right before the
1076*9880d681SAndroid Build Coastguard Worker   // original preheader.
1077*9880d681SAndroid Build Coastguard Worker   F->getBasicBlockList().splice(NewPreheader->getIterator(),
1078*9880d681SAndroid Build Coastguard Worker                                 F->getBasicBlockList(),
1079*9880d681SAndroid Build Coastguard Worker                                 NewBlocks[0]->getIterator(), F->end());
1080*9880d681SAndroid Build Coastguard Worker 
1081*9880d681SAndroid Build Coastguard Worker   // FIXME: We could register any cloned assumptions instead of clearing the
1082*9880d681SAndroid Build Coastguard Worker   // whole function's cache.
1083*9880d681SAndroid Build Coastguard Worker   AC->clear();
1084*9880d681SAndroid Build Coastguard Worker 
1085*9880d681SAndroid Build Coastguard Worker   // Now we create the new Loop object for the versioned loop.
1086*9880d681SAndroid Build Coastguard Worker   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1087*9880d681SAndroid Build Coastguard Worker 
1088*9880d681SAndroid Build Coastguard Worker   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1089*9880d681SAndroid Build Coastguard Worker   // Probably clone more loop-unswitch related loop properties.
1090*9880d681SAndroid Build Coastguard Worker   BranchesInfo.cloneData(NewLoop, L, VMap);
1091*9880d681SAndroid Build Coastguard Worker 
1092*9880d681SAndroid Build Coastguard Worker   Loop *ParentLoop = L->getParentLoop();
1093*9880d681SAndroid Build Coastguard Worker   if (ParentLoop) {
1094*9880d681SAndroid Build Coastguard Worker     // Make sure to add the cloned preheader and exit blocks to the parent loop
1095*9880d681SAndroid Build Coastguard Worker     // as well.
1096*9880d681SAndroid Build Coastguard Worker     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1097*9880d681SAndroid Build Coastguard Worker   }
1098*9880d681SAndroid Build Coastguard Worker 
1099*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1100*9880d681SAndroid Build Coastguard Worker     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1101*9880d681SAndroid Build Coastguard Worker     // The new exit block should be in the same loop as the old one.
1102*9880d681SAndroid Build Coastguard Worker     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1103*9880d681SAndroid Build Coastguard Worker       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1104*9880d681SAndroid Build Coastguard Worker 
1105*9880d681SAndroid Build Coastguard Worker     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1106*9880d681SAndroid Build Coastguard Worker            "Exit block should have been split to have one successor!");
1107*9880d681SAndroid Build Coastguard Worker     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1108*9880d681SAndroid Build Coastguard Worker 
1109*9880d681SAndroid Build Coastguard Worker     // If the successor of the exit block had PHI nodes, add an entry for
1110*9880d681SAndroid Build Coastguard Worker     // NewExit.
1111*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator I = ExitSucc->begin();
1112*9880d681SAndroid Build Coastguard Worker          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1113*9880d681SAndroid Build Coastguard Worker       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
1114*9880d681SAndroid Build Coastguard Worker       ValueToValueMapTy::iterator It = VMap.find(V);
1115*9880d681SAndroid Build Coastguard Worker       if (It != VMap.end()) V = It->second;
1116*9880d681SAndroid Build Coastguard Worker       PN->addIncoming(V, NewExit);
1117*9880d681SAndroid Build Coastguard Worker     }
1118*9880d681SAndroid Build Coastguard Worker 
1119*9880d681SAndroid Build Coastguard Worker     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1120*9880d681SAndroid Build Coastguard Worker       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1121*9880d681SAndroid Build Coastguard Worker                                     &*ExitSucc->getFirstInsertionPt());
1122*9880d681SAndroid Build Coastguard Worker 
1123*9880d681SAndroid Build Coastguard Worker       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1124*9880d681SAndroid Build Coastguard Worker            I != E; ++I) {
1125*9880d681SAndroid Build Coastguard Worker         BasicBlock *BB = *I;
1126*9880d681SAndroid Build Coastguard Worker         LandingPadInst *LPI = BB->getLandingPadInst();
1127*9880d681SAndroid Build Coastguard Worker         LPI->replaceAllUsesWith(PN);
1128*9880d681SAndroid Build Coastguard Worker         PN->addIncoming(LPI, BB);
1129*9880d681SAndroid Build Coastguard Worker       }
1130*9880d681SAndroid Build Coastguard Worker     }
1131*9880d681SAndroid Build Coastguard Worker   }
1132*9880d681SAndroid Build Coastguard Worker 
1133*9880d681SAndroid Build Coastguard Worker   // Rewrite the code to refer to itself.
1134*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
1135*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *NewBlocks[i])
1136*9880d681SAndroid Build Coastguard Worker       RemapInstruction(&I, VMap,
1137*9880d681SAndroid Build Coastguard Worker                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1138*9880d681SAndroid Build Coastguard Worker 
1139*9880d681SAndroid Build Coastguard Worker   // Rewrite the original preheader to select between versions of the loop.
1140*9880d681SAndroid Build Coastguard Worker   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1141*9880d681SAndroid Build Coastguard Worker   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1142*9880d681SAndroid Build Coastguard Worker          "Preheader splitting did not work correctly!");
1143*9880d681SAndroid Build Coastguard Worker 
1144*9880d681SAndroid Build Coastguard Worker   // Emit the new branch that selects between the two versions of this loop.
1145*9880d681SAndroid Build Coastguard Worker   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1146*9880d681SAndroid Build Coastguard Worker                                  TI);
1147*9880d681SAndroid Build Coastguard Worker   LPM->deleteSimpleAnalysisValue(OldBR, L);
1148*9880d681SAndroid Build Coastguard Worker   OldBR->eraseFromParent();
1149*9880d681SAndroid Build Coastguard Worker 
1150*9880d681SAndroid Build Coastguard Worker   LoopProcessWorklist.push_back(NewLoop);
1151*9880d681SAndroid Build Coastguard Worker   redoLoop = true;
1152*9880d681SAndroid Build Coastguard Worker 
1153*9880d681SAndroid Build Coastguard Worker   // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
1154*9880d681SAndroid Build Coastguard Worker   // deletes the instruction (for example by simplifying a PHI that feeds into
1155*9880d681SAndroid Build Coastguard Worker   // the condition that we're unswitching on), we don't rewrite the second
1156*9880d681SAndroid Build Coastguard Worker   // iteration.
1157*9880d681SAndroid Build Coastguard Worker   WeakVH LICHandle(LIC);
1158*9880d681SAndroid Build Coastguard Worker 
1159*9880d681SAndroid Build Coastguard Worker   // Now we rewrite the original code to know that the condition is true and the
1160*9880d681SAndroid Build Coastguard Worker   // new code to know that the condition is false.
1161*9880d681SAndroid Build Coastguard Worker   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1162*9880d681SAndroid Build Coastguard Worker 
1163*9880d681SAndroid Build Coastguard Worker   // It's possible that simplifying one loop could cause the other to be
1164*9880d681SAndroid Build Coastguard Worker   // changed to another value or a constant.  If its a constant, don't simplify
1165*9880d681SAndroid Build Coastguard Worker   // it.
1166*9880d681SAndroid Build Coastguard Worker   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1167*9880d681SAndroid Build Coastguard Worker       LICHandle && !isa<Constant>(LICHandle))
1168*9880d681SAndroid Build Coastguard Worker     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1169*9880d681SAndroid Build Coastguard Worker }
1170*9880d681SAndroid Build Coastguard Worker 
1171*9880d681SAndroid Build Coastguard Worker /// Remove all instances of I from the worklist vector specified.
RemoveFromWorklist(Instruction * I,std::vector<Instruction * > & Worklist)1172*9880d681SAndroid Build Coastguard Worker static void RemoveFromWorklist(Instruction *I,
1173*9880d681SAndroid Build Coastguard Worker                                std::vector<Instruction*> &Worklist) {
1174*9880d681SAndroid Build Coastguard Worker 
1175*9880d681SAndroid Build Coastguard Worker   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1176*9880d681SAndroid Build Coastguard Worker                  Worklist.end());
1177*9880d681SAndroid Build Coastguard Worker }
1178*9880d681SAndroid Build Coastguard Worker 
1179*9880d681SAndroid Build Coastguard Worker /// When we find that I really equals V, remove I from the
1180*9880d681SAndroid Build Coastguard Worker /// program, replacing all uses with V and update the worklist.
ReplaceUsesOfWith(Instruction * I,Value * V,std::vector<Instruction * > & Worklist,Loop * L,LPPassManager * LPM)1181*9880d681SAndroid Build Coastguard Worker static void ReplaceUsesOfWith(Instruction *I, Value *V,
1182*9880d681SAndroid Build Coastguard Worker                               std::vector<Instruction*> &Worklist,
1183*9880d681SAndroid Build Coastguard Worker                               Loop *L, LPPassManager *LPM) {
1184*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
1185*9880d681SAndroid Build Coastguard Worker 
1186*9880d681SAndroid Build Coastguard Worker   // Add uses to the worklist, which may be dead now.
1187*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1188*9880d681SAndroid Build Coastguard Worker     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1189*9880d681SAndroid Build Coastguard Worker       Worklist.push_back(Use);
1190*9880d681SAndroid Build Coastguard Worker 
1191*9880d681SAndroid Build Coastguard Worker   // Add users to the worklist which may be simplified now.
1192*9880d681SAndroid Build Coastguard Worker   for (User *U : I->users())
1193*9880d681SAndroid Build Coastguard Worker     Worklist.push_back(cast<Instruction>(U));
1194*9880d681SAndroid Build Coastguard Worker   LPM->deleteSimpleAnalysisValue(I, L);
1195*9880d681SAndroid Build Coastguard Worker   RemoveFromWorklist(I, Worklist);
1196*9880d681SAndroid Build Coastguard Worker   I->replaceAllUsesWith(V);
1197*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
1198*9880d681SAndroid Build Coastguard Worker   ++NumSimplify;
1199*9880d681SAndroid Build Coastguard Worker }
1200*9880d681SAndroid Build Coastguard Worker 
1201*9880d681SAndroid Build Coastguard Worker /// We know either that the value LIC has the value specified by Val in the
1202*9880d681SAndroid Build Coastguard Worker /// specified loop, or we know it does NOT have that value.
1203*9880d681SAndroid Build Coastguard Worker /// Rewrite any uses of LIC or of properties correlated to it.
RewriteLoopBodyWithConditionConstant(Loop * L,Value * LIC,Constant * Val,bool IsEqual)1204*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1205*9880d681SAndroid Build Coastguard Worker                                                         Constant *Val,
1206*9880d681SAndroid Build Coastguard Worker                                                         bool IsEqual) {
1207*9880d681SAndroid Build Coastguard Worker   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1208*9880d681SAndroid Build Coastguard Worker 
1209*9880d681SAndroid Build Coastguard Worker   // FIXME: Support correlated properties, like:
1210*9880d681SAndroid Build Coastguard Worker   //  for (...)
1211*9880d681SAndroid Build Coastguard Worker   //    if (li1 < li2)
1212*9880d681SAndroid Build Coastguard Worker   //      ...
1213*9880d681SAndroid Build Coastguard Worker   //    if (li1 > li2)
1214*9880d681SAndroid Build Coastguard Worker   //      ...
1215*9880d681SAndroid Build Coastguard Worker 
1216*9880d681SAndroid Build Coastguard Worker   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
1217*9880d681SAndroid Build Coastguard Worker   // selects, switches.
1218*9880d681SAndroid Build Coastguard Worker   std::vector<Instruction*> Worklist;
1219*9880d681SAndroid Build Coastguard Worker   LLVMContext &Context = Val->getContext();
1220*9880d681SAndroid Build Coastguard Worker 
1221*9880d681SAndroid Build Coastguard Worker   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1222*9880d681SAndroid Build Coastguard Worker   // in the loop with the appropriate one directly.
1223*9880d681SAndroid Build Coastguard Worker   if (IsEqual || (isa<ConstantInt>(Val) &&
1224*9880d681SAndroid Build Coastguard Worker       Val->getType()->isIntegerTy(1))) {
1225*9880d681SAndroid Build Coastguard Worker     Value *Replacement;
1226*9880d681SAndroid Build Coastguard Worker     if (IsEqual)
1227*9880d681SAndroid Build Coastguard Worker       Replacement = Val;
1228*9880d681SAndroid Build Coastguard Worker     else
1229*9880d681SAndroid Build Coastguard Worker       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1230*9880d681SAndroid Build Coastguard Worker                                      !cast<ConstantInt>(Val)->getZExtValue());
1231*9880d681SAndroid Build Coastguard Worker 
1232*9880d681SAndroid Build Coastguard Worker     for (User *U : LIC->users()) {
1233*9880d681SAndroid Build Coastguard Worker       Instruction *UI = dyn_cast<Instruction>(U);
1234*9880d681SAndroid Build Coastguard Worker       if (!UI || !L->contains(UI))
1235*9880d681SAndroid Build Coastguard Worker         continue;
1236*9880d681SAndroid Build Coastguard Worker       Worklist.push_back(UI);
1237*9880d681SAndroid Build Coastguard Worker     }
1238*9880d681SAndroid Build Coastguard Worker 
1239*9880d681SAndroid Build Coastguard Worker     for (Instruction *UI : Worklist)
1240*9880d681SAndroid Build Coastguard Worker       UI->replaceUsesOfWith(LIC, Replacement);
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker     SimplifyCode(Worklist, L);
1243*9880d681SAndroid Build Coastguard Worker     return;
1244*9880d681SAndroid Build Coastguard Worker   }
1245*9880d681SAndroid Build Coastguard Worker 
1246*9880d681SAndroid Build Coastguard Worker   // Otherwise, we don't know the precise value of LIC, but we do know that it
1247*9880d681SAndroid Build Coastguard Worker   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
1248*9880d681SAndroid Build Coastguard Worker   // can.  This case occurs when we unswitch switch statements.
1249*9880d681SAndroid Build Coastguard Worker   for (User *U : LIC->users()) {
1250*9880d681SAndroid Build Coastguard Worker     Instruction *UI = dyn_cast<Instruction>(U);
1251*9880d681SAndroid Build Coastguard Worker     if (!UI || !L->contains(UI))
1252*9880d681SAndroid Build Coastguard Worker       continue;
1253*9880d681SAndroid Build Coastguard Worker 
1254*9880d681SAndroid Build Coastguard Worker     Worklist.push_back(UI);
1255*9880d681SAndroid Build Coastguard Worker 
1256*9880d681SAndroid Build Coastguard Worker     // TODO: We could do other simplifications, for example, turning
1257*9880d681SAndroid Build Coastguard Worker     // 'icmp eq LIC, Val' -> false.
1258*9880d681SAndroid Build Coastguard Worker 
1259*9880d681SAndroid Build Coastguard Worker     // If we know that LIC is not Val, use this info to simplify code.
1260*9880d681SAndroid Build Coastguard Worker     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1261*9880d681SAndroid Build Coastguard Worker     if (!SI || !isa<ConstantInt>(Val)) continue;
1262*9880d681SAndroid Build Coastguard Worker 
1263*9880d681SAndroid Build Coastguard Worker     SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1264*9880d681SAndroid Build Coastguard Worker     // Default case is live for multiple values.
1265*9880d681SAndroid Build Coastguard Worker     if (DeadCase == SI->case_default()) continue;
1266*9880d681SAndroid Build Coastguard Worker 
1267*9880d681SAndroid Build Coastguard Worker     // Found a dead case value.  Don't remove PHI nodes in the
1268*9880d681SAndroid Build Coastguard Worker     // successor if they become single-entry, those PHI nodes may
1269*9880d681SAndroid Build Coastguard Worker     // be in the Users list.
1270*9880d681SAndroid Build Coastguard Worker 
1271*9880d681SAndroid Build Coastguard Worker     BasicBlock *Switch = SI->getParent();
1272*9880d681SAndroid Build Coastguard Worker     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1273*9880d681SAndroid Build Coastguard Worker     BasicBlock *Latch = L->getLoopLatch();
1274*9880d681SAndroid Build Coastguard Worker 
1275*9880d681SAndroid Build Coastguard Worker     BranchesInfo.setUnswitched(SI, Val);
1276*9880d681SAndroid Build Coastguard Worker 
1277*9880d681SAndroid Build Coastguard Worker     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
1278*9880d681SAndroid Build Coastguard Worker     // If the DeadCase successor dominates the loop latch, then the
1279*9880d681SAndroid Build Coastguard Worker     // transformation isn't safe since it will delete the sole predecessor edge
1280*9880d681SAndroid Build Coastguard Worker     // to the latch.
1281*9880d681SAndroid Build Coastguard Worker     if (Latch && DT->dominates(SISucc, Latch))
1282*9880d681SAndroid Build Coastguard Worker       continue;
1283*9880d681SAndroid Build Coastguard Worker 
1284*9880d681SAndroid Build Coastguard Worker     // FIXME: This is a hack.  We need to keep the successor around
1285*9880d681SAndroid Build Coastguard Worker     // and hooked up so as to preserve the loop structure, because
1286*9880d681SAndroid Build Coastguard Worker     // trying to update it is complicated.  So instead we preserve the
1287*9880d681SAndroid Build Coastguard Worker     // loop structure and put the block on a dead code path.
1288*9880d681SAndroid Build Coastguard Worker     SplitEdge(Switch, SISucc, DT, LI);
1289*9880d681SAndroid Build Coastguard Worker     // Compute the successors instead of relying on the return value
1290*9880d681SAndroid Build Coastguard Worker     // of SplitEdge, since it may have split the switch successor
1291*9880d681SAndroid Build Coastguard Worker     // after PHI nodes.
1292*9880d681SAndroid Build Coastguard Worker     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1293*9880d681SAndroid Build Coastguard Worker     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1294*9880d681SAndroid Build Coastguard Worker     // Create an "unreachable" destination.
1295*9880d681SAndroid Build Coastguard Worker     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1296*9880d681SAndroid Build Coastguard Worker                                            Switch->getParent(),
1297*9880d681SAndroid Build Coastguard Worker                                            OldSISucc);
1298*9880d681SAndroid Build Coastguard Worker     new UnreachableInst(Context, Abort);
1299*9880d681SAndroid Build Coastguard Worker     // Force the new case destination to branch to the "unreachable"
1300*9880d681SAndroid Build Coastguard Worker     // block while maintaining a (dead) CFG edge to the old block.
1301*9880d681SAndroid Build Coastguard Worker     NewSISucc->getTerminator()->eraseFromParent();
1302*9880d681SAndroid Build Coastguard Worker     BranchInst::Create(Abort, OldSISucc,
1303*9880d681SAndroid Build Coastguard Worker                        ConstantInt::getTrue(Context), NewSISucc);
1304*9880d681SAndroid Build Coastguard Worker     // Release the PHI operands for this edge.
1305*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator II = NewSISucc->begin();
1306*9880d681SAndroid Build Coastguard Worker          PHINode *PN = dyn_cast<PHINode>(II); ++II)
1307*9880d681SAndroid Build Coastguard Worker       PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1308*9880d681SAndroid Build Coastguard Worker                            UndefValue::get(PN->getType()));
1309*9880d681SAndroid Build Coastguard Worker     // Tell the domtree about the new block. We don't fully update the
1310*9880d681SAndroid Build Coastguard Worker     // domtree here -- instead we force it to do a full recomputation
1311*9880d681SAndroid Build Coastguard Worker     // after the pass is complete -- but we do need to inform it of
1312*9880d681SAndroid Build Coastguard Worker     // new blocks.
1313*9880d681SAndroid Build Coastguard Worker     DT->addNewBlock(Abort, NewSISucc);
1314*9880d681SAndroid Build Coastguard Worker   }
1315*9880d681SAndroid Build Coastguard Worker 
1316*9880d681SAndroid Build Coastguard Worker   SimplifyCode(Worklist, L);
1317*9880d681SAndroid Build Coastguard Worker }
1318*9880d681SAndroid Build Coastguard Worker 
1319*9880d681SAndroid Build Coastguard Worker /// Now that we have simplified some instructions in the loop, walk over it and
1320*9880d681SAndroid Build Coastguard Worker /// constant prop, dce, and fold control flow where possible. Note that this is
1321*9880d681SAndroid Build Coastguard Worker /// effectively a very simple loop-structure-aware optimizer. During processing
1322*9880d681SAndroid Build Coastguard Worker /// of this loop, L could very well be deleted, so it must not be used.
1323*9880d681SAndroid Build Coastguard Worker ///
1324*9880d681SAndroid Build Coastguard Worker /// FIXME: When the loop optimizer is more mature, separate this out to a new
1325*9880d681SAndroid Build Coastguard Worker /// pass.
1326*9880d681SAndroid Build Coastguard Worker ///
SimplifyCode(std::vector<Instruction * > & Worklist,Loop * L)1327*9880d681SAndroid Build Coastguard Worker void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1328*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1329*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty()) {
1330*9880d681SAndroid Build Coastguard Worker     Instruction *I = Worklist.back();
1331*9880d681SAndroid Build Coastguard Worker     Worklist.pop_back();
1332*9880d681SAndroid Build Coastguard Worker 
1333*9880d681SAndroid Build Coastguard Worker     // Simple DCE.
1334*9880d681SAndroid Build Coastguard Worker     if (isInstructionTriviallyDead(I)) {
1335*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "Remove dead instruction '" << *I);
1336*9880d681SAndroid Build Coastguard Worker 
1337*9880d681SAndroid Build Coastguard Worker       // Add uses to the worklist, which may be dead now.
1338*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1339*9880d681SAndroid Build Coastguard Worker         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1340*9880d681SAndroid Build Coastguard Worker           Worklist.push_back(Use);
1341*9880d681SAndroid Build Coastguard Worker       LPM->deleteSimpleAnalysisValue(I, L);
1342*9880d681SAndroid Build Coastguard Worker       RemoveFromWorklist(I, Worklist);
1343*9880d681SAndroid Build Coastguard Worker       I->eraseFromParent();
1344*9880d681SAndroid Build Coastguard Worker       ++NumSimplify;
1345*9880d681SAndroid Build Coastguard Worker       continue;
1346*9880d681SAndroid Build Coastguard Worker     }
1347*9880d681SAndroid Build Coastguard Worker 
1348*9880d681SAndroid Build Coastguard Worker     // See if instruction simplification can hack this up.  This is common for
1349*9880d681SAndroid Build Coastguard Worker     // things like "select false, X, Y" after unswitching made the condition be
1350*9880d681SAndroid Build Coastguard Worker     // 'false'.  TODO: update the domtree properly so we can pass it here.
1351*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyInstruction(I, DL))
1352*9880d681SAndroid Build Coastguard Worker       if (LI->replacementPreservesLCSSAForm(I, V)) {
1353*9880d681SAndroid Build Coastguard Worker         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1354*9880d681SAndroid Build Coastguard Worker         continue;
1355*9880d681SAndroid Build Coastguard Worker       }
1356*9880d681SAndroid Build Coastguard Worker 
1357*9880d681SAndroid Build Coastguard Worker     // Special case hacks that appear commonly in unswitched code.
1358*9880d681SAndroid Build Coastguard Worker     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1359*9880d681SAndroid Build Coastguard Worker       if (BI->isUnconditional()) {
1360*9880d681SAndroid Build Coastguard Worker         // If BI's parent is the only pred of the successor, fold the two blocks
1361*9880d681SAndroid Build Coastguard Worker         // together.
1362*9880d681SAndroid Build Coastguard Worker         BasicBlock *Pred = BI->getParent();
1363*9880d681SAndroid Build Coastguard Worker         BasicBlock *Succ = BI->getSuccessor(0);
1364*9880d681SAndroid Build Coastguard Worker         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1365*9880d681SAndroid Build Coastguard Worker         if (!SinglePred) continue;  // Nothing to do.
1366*9880d681SAndroid Build Coastguard Worker         assert(SinglePred == Pred && "CFG broken");
1367*9880d681SAndroid Build Coastguard Worker 
1368*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1369*9880d681SAndroid Build Coastguard Worker               << Succ->getName() << "\n");
1370*9880d681SAndroid Build Coastguard Worker 
1371*9880d681SAndroid Build Coastguard Worker         // Resolve any single entry PHI nodes in Succ.
1372*9880d681SAndroid Build Coastguard Worker         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1373*9880d681SAndroid Build Coastguard Worker           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1374*9880d681SAndroid Build Coastguard Worker 
1375*9880d681SAndroid Build Coastguard Worker         // If Succ has any successors with PHI nodes, update them to have
1376*9880d681SAndroid Build Coastguard Worker         // entries coming from Pred instead of Succ.
1377*9880d681SAndroid Build Coastguard Worker         Succ->replaceAllUsesWith(Pred);
1378*9880d681SAndroid Build Coastguard Worker 
1379*9880d681SAndroid Build Coastguard Worker         // Move all of the successor contents from Succ to Pred.
1380*9880d681SAndroid Build Coastguard Worker         Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1381*9880d681SAndroid Build Coastguard Worker                                    Succ->begin(), Succ->end());
1382*9880d681SAndroid Build Coastguard Worker         LPM->deleteSimpleAnalysisValue(BI, L);
1383*9880d681SAndroid Build Coastguard Worker         BI->eraseFromParent();
1384*9880d681SAndroid Build Coastguard Worker         RemoveFromWorklist(BI, Worklist);
1385*9880d681SAndroid Build Coastguard Worker 
1386*9880d681SAndroid Build Coastguard Worker         // Remove Succ from the loop tree.
1387*9880d681SAndroid Build Coastguard Worker         LI->removeBlock(Succ);
1388*9880d681SAndroid Build Coastguard Worker         LPM->deleteSimpleAnalysisValue(Succ, L);
1389*9880d681SAndroid Build Coastguard Worker         Succ->eraseFromParent();
1390*9880d681SAndroid Build Coastguard Worker         ++NumSimplify;
1391*9880d681SAndroid Build Coastguard Worker         continue;
1392*9880d681SAndroid Build Coastguard Worker       }
1393*9880d681SAndroid Build Coastguard Worker 
1394*9880d681SAndroid Build Coastguard Worker       continue;
1395*9880d681SAndroid Build Coastguard Worker     }
1396*9880d681SAndroid Build Coastguard Worker   }
1397*9880d681SAndroid Build Coastguard Worker }
1398