1 //===- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass transforms loops that contain branches on loop-invariant conditions
10 // to multiple loops.  For example, it turns the left into the right code:
11 //
12 //  for (...)                  if (lic)
13 //    A                          for (...)
14 //    if (lic)                     A; B; C
15 //      B                      else
16 //    C                          for (...)
17 //                                 A; C
18 //
19 // This can increase the size of the code exponentially (doubling it every time
20 // a loop is unswitched) so we only unswitch if the resultant code will be
21 // smaller than a threshold.
22 //
23 // This pass expects LICM to be run before it to hoist invariant conditions out
24 // of the loop, to make the unswitching opportunity obvious.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AssumptionCache.h"
33 #include "llvm/Analysis/CodeMetrics.h"
34 #include "llvm/Analysis/InstructionSimplify.h"
35 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopIterator.h"
38 #include "llvm/Analysis/LoopPass.h"
39 #include "llvm/Analysis/MemorySSA.h"
40 #include "llvm/Analysis/MemorySSAUpdater.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/TargetTransformInfo.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/BasicBlock.h"
45 #include "llvm/IR/CallSite.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DerivedTypes.h"
49 #include "llvm/IR/Dominators.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/IRBuilder.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/User.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/InitializePasses.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Transforms/Scalar.h"
69 #include "llvm/Transforms/Scalar/LoopPassManager.h"
70 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
71 #include "llvm/Transforms/Utils/Cloning.h"
72 #include "llvm/Transforms/Utils/Local.h"
73 #include "llvm/Transforms/Utils/LoopUtils.h"
74 #include "llvm/Transforms/Utils/ValueMapper.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <map>
78 #include <set>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "loop-unswitch"
86 
87 STATISTIC(NumBranches, "Number of branches unswitched");
88 STATISTIC(NumSwitches, "Number of switches unswitched");
89 STATISTIC(NumGuards,   "Number of guards unswitched");
90 STATISTIC(NumSelects , "Number of selects unswitched");
91 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
92 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
93 STATISTIC(TotalInsts,  "Total number of instructions analyzed");
94 
95 // The specific value of 100 here was chosen based only on intuition and a
96 // few specific examples.
97 static cl::opt<unsigned>
98 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
99           cl::init(100), cl::Hidden);
100 
101 namespace {
102 
103   class LUAnalysisCache {
104     using UnswitchedValsMap =
105         DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
106     using UnswitchedValsIt = UnswitchedValsMap::iterator;
107 
108     struct LoopProperties {
109       unsigned CanBeUnswitchedCount;
110       unsigned WasUnswitchedCount;
111       unsigned SizeEstimation;
112       UnswitchedValsMap UnswitchedVals;
113     };
114 
115     // Here we use std::map instead of DenseMap, since we need to keep valid
116     // LoopProperties pointer for current loop for better performance.
117     using LoopPropsMap = std::map<const Loop *, LoopProperties>;
118     using LoopPropsMapIt = LoopPropsMap::iterator;
119 
120     LoopPropsMap LoopsProperties;
121     UnswitchedValsMap *CurLoopInstructions = nullptr;
122     LoopProperties *CurrentLoopProperties = nullptr;
123 
124     // A loop unswitching with an estimated cost above this threshold
125     // is not performed. MaxSize is turned into unswitching quota for
126     // the current loop, and reduced correspondingly, though note that
127     // the quota is returned by releaseMemory() when the loop has been
128     // processed, so that MaxSize will return to its previous
129     // value. So in most cases MaxSize will equal the Threshold flag
130     // when a new loop is processed. An exception to that is that
131     // MaxSize will have a smaller value while processing nested loops
132     // that were introduced due to loop unswitching of an outer loop.
133     //
134     // FIXME: The way that MaxSize works is subtle and depends on the
135     // pass manager processing loops and calling releaseMemory() in a
136     // specific order. It would be good to find a more straightforward
137     // way of doing what MaxSize does.
138     unsigned MaxSize;
139 
140   public:
LUAnalysisCache()141     LUAnalysisCache() : MaxSize(Threshold) {}
142 
143     // Analyze loop. Check its size, calculate is it possible to unswitch
144     // it. Returns true if we can unswitch this loop.
145     bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
146                    AssumptionCache *AC);
147 
148     // Clean all data related to given loop.
149     void forgetLoop(const Loop *L);
150 
151     // Mark case value as unswitched.
152     // Since SI instruction can be partly unswitched, in order to avoid
153     // extra unswitching in cloned loops keep track all unswitched values.
154     void setUnswitched(const SwitchInst *SI, const Value *V);
155 
156     // Check was this case value unswitched before or not.
157     bool isUnswitched(const SwitchInst *SI, const Value *V);
158 
159     // Returns true if another unswitching could be done within the cost
160     // threshold.
161     bool CostAllowsUnswitching();
162 
163     // Clone all loop-unswitch related loop properties.
164     // Redistribute unswitching quotas.
165     // Note, that new loop data is stored inside the VMap.
166     void cloneData(const Loop *NewLoop, const Loop *OldLoop,
167                    const ValueToValueMapTy &VMap);
168   };
169 
170   class LoopUnswitch : public LoopPass {
171     LoopInfo *LI;  // Loop information
172     LPPassManager *LPM;
173     AssumptionCache *AC;
174 
175     // Used to check if second loop needs processing after
176     // RewriteLoopBodyWithConditionConstant rewrites first loop.
177     std::vector<Loop*> LoopProcessWorklist;
178 
179     LUAnalysisCache BranchesInfo;
180 
181     bool OptimizeForSize;
182     bool redoLoop = false;
183 
184     Loop *currentLoop = nullptr;
185     DominatorTree *DT = nullptr;
186     MemorySSA *MSSA = nullptr;
187     std::unique_ptr<MemorySSAUpdater> MSSAU;
188     BasicBlock *loopHeader = nullptr;
189     BasicBlock *loopPreheader = nullptr;
190 
191     bool SanitizeMemory;
192     SimpleLoopSafetyInfo SafetyInfo;
193 
194     // LoopBlocks contains all of the basic blocks of the loop, including the
195     // preheader of the loop, the body of the loop, and the exit blocks of the
196     // loop, in that order.
197     std::vector<BasicBlock*> LoopBlocks;
198     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
199     std::vector<BasicBlock*> NewBlocks;
200 
201     bool hasBranchDivergence;
202 
203   public:
204     static char ID; // Pass ID, replacement for typeid
205 
LoopUnswitch(bool Os=false,bool hasBranchDivergence=false)206     explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false)
207         : LoopPass(ID), OptimizeForSize(Os),
208           hasBranchDivergence(hasBranchDivergence) {
209         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
210     }
211 
212     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213     bool processCurrentLoop();
214     bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
215 
216     /// This transformation requires natural loop information & requires that
217     /// loop preheaders be inserted into the CFG.
218     ///
getAnalysisUsage(AnalysisUsage & AU) const219     void getAnalysisUsage(AnalysisUsage &AU) const override {
220       AU.addRequired<AssumptionCacheTracker>();
221       AU.addRequired<TargetTransformInfoWrapperPass>();
222       if (EnableMSSALoopDependency) {
223         AU.addRequired<MemorySSAWrapperPass>();
224         AU.addPreserved<MemorySSAWrapperPass>();
225       }
226       if (hasBranchDivergence)
227         AU.addRequired<LegacyDivergenceAnalysis>();
228       getLoopAnalysisUsage(AU);
229     }
230 
231   private:
releaseMemory()232     void releaseMemory() override {
233       BranchesInfo.forgetLoop(currentLoop);
234     }
235 
initLoopData()236     void initLoopData() {
237       loopHeader = currentLoop->getHeader();
238       loopPreheader = currentLoop->getLoopPreheader();
239     }
240 
241     /// Split all of the edges from inside the loop to their exit blocks.
242     /// Update the appropriate Phi nodes as we do so.
243     void SplitExitEdges(Loop *L,
244                         const SmallVectorImpl<BasicBlock *> &ExitBlocks);
245 
246     bool TryTrivialLoopUnswitch(bool &Changed);
247 
248     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
249                               Instruction *TI = nullptr);
250     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
251                                   BasicBlock *ExitBlock, Instruction *TI);
252     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
253                                      Instruction *TI);
254 
255     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
256                                               Constant *Val, bool isEqual);
257 
258     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
259                                         BasicBlock *TrueDest,
260                                         BasicBlock *FalseDest,
261                                         BranchInst *OldBranch, Instruction *TI);
262 
263     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
264 
265     /// Given that the Invariant is not equal to Val. Simplify instructions
266     /// in the loop.
267     Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
268                                            Constant *Val);
269   };
270 
271 } // end anonymous namespace
272 
273 // Analyze loop. Check its size, calculate is it possible to unswitch
274 // it. Returns true if we can unswitch this loop.
countLoop(const Loop * L,const TargetTransformInfo & TTI,AssumptionCache * AC)275 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
276                                 AssumptionCache *AC) {
277   LoopPropsMapIt PropsIt;
278   bool Inserted;
279   std::tie(PropsIt, Inserted) =
280       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
281 
282   LoopProperties &Props = PropsIt->second;
283 
284   if (Inserted) {
285     // New loop.
286 
287     // Limit the number of instructions to avoid causing significant code
288     // expansion, and the number of basic blocks, to avoid loops with
289     // large numbers of branches which cause loop unswitching to go crazy.
290     // This is a very ad-hoc heuristic.
291 
292     SmallPtrSet<const Value *, 32> EphValues;
293     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
294 
295     // FIXME: This is overly conservative because it does not take into
296     // consideration code simplification opportunities and code that can
297     // be shared by the resultant unswitched loops.
298     CodeMetrics Metrics;
299     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
300          ++I)
301       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
302 
303     Props.SizeEstimation = Metrics.NumInsts;
304     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
305     Props.WasUnswitchedCount = 0;
306     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
307 
308     if (Metrics.notDuplicatable) {
309       LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
310                         << ", contents cannot be "
311                         << "duplicated!\n");
312       return false;
313     }
314   }
315 
316   // Be careful. This links are good only before new loop addition.
317   CurrentLoopProperties = &Props;
318   CurLoopInstructions = &Props.UnswitchedVals;
319 
320   return true;
321 }
322 
323 // Clean all data related to given loop.
forgetLoop(const Loop * L)324 void LUAnalysisCache::forgetLoop(const Loop *L) {
325   LoopPropsMapIt LIt = LoopsProperties.find(L);
326 
327   if (LIt != LoopsProperties.end()) {
328     LoopProperties &Props = LIt->second;
329     MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
330                Props.SizeEstimation;
331     LoopsProperties.erase(LIt);
332   }
333 
334   CurrentLoopProperties = nullptr;
335   CurLoopInstructions = nullptr;
336 }
337 
338 // Mark case value as unswitched.
339 // Since SI instruction can be partly unswitched, in order to avoid
340 // extra unswitching in cloned loops keep track all unswitched values.
setUnswitched(const SwitchInst * SI,const Value * V)341 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
342   (*CurLoopInstructions)[SI].insert(V);
343 }
344 
345 // Check was this case value unswitched before or not.
isUnswitched(const SwitchInst * SI,const Value * V)346 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
347   return (*CurLoopInstructions)[SI].count(V);
348 }
349 
CostAllowsUnswitching()350 bool LUAnalysisCache::CostAllowsUnswitching() {
351   return CurrentLoopProperties->CanBeUnswitchedCount > 0;
352 }
353 
354 // Clone all loop-unswitch related loop properties.
355 // Redistribute unswitching quotas.
356 // Note, that new loop data is stored inside the VMap.
cloneData(const Loop * NewLoop,const Loop * OldLoop,const ValueToValueMapTy & VMap)357 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
358                                 const ValueToValueMapTy &VMap) {
359   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360   LoopProperties &OldLoopProps = *CurrentLoopProperties;
361   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
362 
363   // Reallocate "can-be-unswitched quota"
364 
365   --OldLoopProps.CanBeUnswitchedCount;
366   ++OldLoopProps.WasUnswitchedCount;
367   NewLoopProps.WasUnswitchedCount = 0;
368   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
371 
372   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
373 
374   // Clone unswitched values info:
375   // for new loop switches we clone info about values that was
376   // already unswitched and has redundant successors.
377   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
378     const SwitchInst *OldInst = I->first;
379     Value *NewI = VMap.lookup(OldInst);
380     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
381     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
382 
383     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
384   }
385 }
386 
387 char LoopUnswitch::ID = 0;
388 
389 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
390                       false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)391 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
392 INITIALIZE_PASS_DEPENDENCY(LoopPass)
393 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
394 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
395 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
396 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
397                       false, false)
398 
399 Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
400   return new LoopUnswitch(Os, hasBranchDivergence);
401 }
402 
403 /// Operator chain lattice.
404 enum OperatorChain {
405   OC_OpChainNone,    ///< There is no operator.
406   OC_OpChainOr,      ///< There are only ORs.
407   OC_OpChainAnd,     ///< There are only ANDs.
408   OC_OpChainMixed    ///< There are ANDs and ORs.
409 };
410 
411 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
412 /// an invariant piece, return the invariant. Otherwise, return null.
413 //
414 /// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
415 /// mixed operator chain, as we can not reliably find a value which will simplify
416 /// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
417 /// to simplify the chain.
418 ///
419 /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
420 /// simplify the condition itself to a loop variant condition, but at the
421 /// cost of creating an entirely new loop.
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed,OperatorChain & ParentChain,DenseMap<Value *,Value * > & Cache,MemorySSAUpdater * MSSAU)422 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
423                                    OperatorChain &ParentChain,
424                                    DenseMap<Value *, Value *> &Cache,
425                                    MemorySSAUpdater *MSSAU) {
426   auto CacheIt = Cache.find(Cond);
427   if (CacheIt != Cache.end())
428     return CacheIt->second;
429 
430   // We started analyze new instruction, increment scanned instructions counter.
431   ++TotalInsts;
432 
433   // We can never unswitch on vector conditions.
434   if (Cond->getType()->isVectorTy())
435     return nullptr;
436 
437   // Constants should be folded, not unswitched on!
438   if (isa<Constant>(Cond)) return nullptr;
439 
440   // TODO: Handle: br (VARIANT|INVARIANT).
441 
442   // Hoist simple values out.
443   if (L->makeLoopInvariant(Cond, Changed, nullptr, MSSAU)) {
444     Cache[Cond] = Cond;
445     return Cond;
446   }
447 
448   // Walk up the operator chain to find partial invariant conditions.
449   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
450     if (BO->getOpcode() == Instruction::And ||
451         BO->getOpcode() == Instruction::Or) {
452       // Given the previous operator, compute the current operator chain status.
453       OperatorChain NewChain;
454       switch (ParentChain) {
455       case OC_OpChainNone:
456         NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
457                                       OC_OpChainOr;
458         break;
459       case OC_OpChainOr:
460         NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
461                                       OC_OpChainMixed;
462         break;
463       case OC_OpChainAnd:
464         NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
465                                       OC_OpChainMixed;
466         break;
467       case OC_OpChainMixed:
468         NewChain = OC_OpChainMixed;
469         break;
470       }
471 
472       // If we reach a Mixed state, we do not want to keep walking up as we can not
473       // reliably find a value that will simplify the chain. With this check, we
474       // will return null on the first sight of mixed chain and the caller will
475       // either backtrack to find partial LIV in other operand or return null.
476       if (NewChain != OC_OpChainMixed) {
477         // Update the current operator chain type before we search up the chain.
478         ParentChain = NewChain;
479         // If either the left or right side is invariant, we can unswitch on this,
480         // which will cause the branch to go away in one loop and the condition to
481         // simplify in the other one.
482         if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
483                                               ParentChain, Cache, MSSAU)) {
484           Cache[Cond] = LHS;
485           return LHS;
486         }
487         // We did not manage to find a partial LIV in operand(0). Backtrack and try
488         // operand(1).
489         ParentChain = NewChain;
490         if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
491                                               ParentChain, Cache, MSSAU)) {
492           Cache[Cond] = RHS;
493           return RHS;
494         }
495       }
496     }
497 
498   Cache[Cond] = nullptr;
499   return nullptr;
500 }
501 
502 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
503 /// an invariant piece, return the invariant along with the operator chain type.
504 /// Otherwise, return null.
505 static std::pair<Value *, OperatorChain>
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed,MemorySSAUpdater * MSSAU)506 FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
507                      MemorySSAUpdater *MSSAU) {
508   DenseMap<Value *, Value *> Cache;
509   OperatorChain OpChain = OC_OpChainNone;
510   Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache, MSSAU);
511 
512   // In case we do find a LIV, it can not be obtained by walking up a mixed
513   // operator chain.
514   assert((!FCond || OpChain != OC_OpChainMixed) &&
515         "Do not expect a partial LIV with mixed operator chain");
516   return {FCond, OpChain};
517 }
518 
runOnLoop(Loop * L,LPPassManager & LPM_Ref)519 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
520   if (skipLoop(L))
521     return false;
522 
523   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
524       *L->getHeader()->getParent());
525   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
526   LPM = &LPM_Ref;
527   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
528   if (EnableMSSALoopDependency) {
529     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
530     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
531     assert(DT && "Cannot update MemorySSA without a valid DomTree.");
532   }
533   currentLoop = L;
534   Function *F = currentLoop->getHeader()->getParent();
535 
536   SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
537   if (SanitizeMemory)
538     SafetyInfo.computeLoopSafetyInfo(L);
539 
540   if (MSSA && VerifyMemorySSA)
541     MSSA->verifyMemorySSA();
542 
543   bool Changed = false;
544   do {
545     assert(currentLoop->isLCSSAForm(*DT));
546     if (MSSA && VerifyMemorySSA)
547       MSSA->verifyMemorySSA();
548     redoLoop = false;
549     Changed |= processCurrentLoop();
550   } while(redoLoop);
551 
552   if (MSSA && VerifyMemorySSA)
553     MSSA->verifyMemorySSA();
554 
555   return Changed;
556 }
557 
558 // Return true if the BasicBlock BB is unreachable from the loop header.
559 // Return false, otherwise.
isUnreachableDueToPreviousUnswitching(BasicBlock * BB)560 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
561   auto *Node = DT->getNode(BB)->getIDom();
562   BasicBlock *DomBB = Node->getBlock();
563   while (currentLoop->contains(DomBB)) {
564     BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
565 
566     Node = DT->getNode(DomBB)->getIDom();
567     DomBB = Node->getBlock();
568 
569     if (!BInst || !BInst->isConditional())
570       continue;
571 
572     Value *Cond = BInst->getCondition();
573     if (!isa<ConstantInt>(Cond))
574       continue;
575 
576     BasicBlock *UnreachableSucc =
577         Cond == ConstantInt::getTrue(Cond->getContext())
578             ? BInst->getSuccessor(1)
579             : BInst->getSuccessor(0);
580 
581     if (DT->dominates(UnreachableSucc, BB))
582       return true;
583   }
584   return false;
585 }
586 
587 /// FIXME: Remove this workaround when freeze related patches are done.
588 /// LoopUnswitch and Equality propagation in GVN have discrepancy about
589 /// whether branch on undef/poison has undefine behavior. Here it is to
590 /// rule out some common cases that we found such discrepancy already
591 /// causing problems. Detail could be found in PR31652. Note if the
592 /// func returns true, it is unsafe. But if it is false, it doesn't mean
593 /// it is necessarily safe.
EqualityPropUnSafe(Value & LoopCond)594 static bool EqualityPropUnSafe(Value &LoopCond) {
595   ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
596   if (!CI || !CI->isEquality())
597     return false;
598 
599   Value *LHS = CI->getOperand(0);
600   Value *RHS = CI->getOperand(1);
601   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
602     return true;
603 
604   auto hasUndefInPHI = [](PHINode &PN) {
605     for (Value *Opd : PN.incoming_values()) {
606       if (isa<UndefValue>(Opd))
607         return true;
608     }
609     return false;
610   };
611   PHINode *LPHI = dyn_cast<PHINode>(LHS);
612   PHINode *RPHI = dyn_cast<PHINode>(RHS);
613   if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
614     return true;
615 
616   auto hasUndefInSelect = [](SelectInst &SI) {
617     if (isa<UndefValue>(SI.getTrueValue()) ||
618         isa<UndefValue>(SI.getFalseValue()))
619       return true;
620     return false;
621   };
622   SelectInst *LSI = dyn_cast<SelectInst>(LHS);
623   SelectInst *RSI = dyn_cast<SelectInst>(RHS);
624   if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
625     return true;
626   return false;
627 }
628 
629 /// Do actual work and unswitch loop if possible and profitable.
processCurrentLoop()630 bool LoopUnswitch::processCurrentLoop() {
631   bool Changed = false;
632 
633   initLoopData();
634 
635   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
636   if (!loopPreheader)
637     return false;
638 
639   // Loops with indirectbr cannot be cloned.
640   if (!currentLoop->isSafeToClone())
641     return false;
642 
643   // Without dedicated exits, splitting the exit edge may fail.
644   if (!currentLoop->hasDedicatedExits())
645     return false;
646 
647   LLVMContext &Context = loopHeader->getContext();
648 
649   // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
650   if (!BranchesInfo.countLoop(
651           currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
652                            *currentLoop->getHeader()->getParent()),
653           AC))
654     return false;
655 
656   // Try trivial unswitch first before loop over other basic blocks in the loop.
657   if (TryTrivialLoopUnswitch(Changed)) {
658     return true;
659   }
660 
661   // Do not do non-trivial unswitch while optimizing for size.
662   // FIXME: Use Function::hasOptSize().
663   if (OptimizeForSize ||
664       loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
665     return false;
666 
667   // Run through the instructions in the loop, keeping track of three things:
668   //
669   //  - That we do not unswitch loops containing convergent operations, as we
670   //    might be making them control dependent on the unswitch value when they
671   //    were not before.
672   //    FIXME: This could be refined to only bail if the convergent operation is
673   //    not already control-dependent on the unswitch value.
674   //
675   //  - That basic blocks in the loop contain invokes whose predecessor edges we
676   //    cannot split.
677   //
678   //  - The set of guard intrinsics encountered (these are non terminator
679   //    instructions that are also profitable to be unswitched).
680 
681   SmallVector<IntrinsicInst *, 4> Guards;
682 
683   for (const auto BB : currentLoop->blocks()) {
684     for (auto &I : *BB) {
685       auto CS = CallSite(&I);
686       if (!CS) continue;
687       if (CS.isConvergent())
688         return false;
689       if (auto *II = dyn_cast<InvokeInst>(&I))
690         if (!II->getUnwindDest()->canSplitPredecessors())
691           return false;
692       if (auto *II = dyn_cast<IntrinsicInst>(&I))
693         if (II->getIntrinsicID() == Intrinsic::experimental_guard)
694           Guards.push_back(II);
695     }
696   }
697 
698   for (IntrinsicInst *Guard : Guards) {
699     Value *LoopCond = FindLIVLoopCondition(Guard->getOperand(0), currentLoop,
700                                            Changed, MSSAU.get())
701                           .first;
702     if (LoopCond &&
703         UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
704       // NB! Unswitching (if successful) could have erased some of the
705       // instructions in Guards leaving dangling pointers there.  This is fine
706       // because we're returning now, and won't look at Guards again.
707       ++NumGuards;
708       return true;
709     }
710   }
711 
712   // Loop over all of the basic blocks in the loop.  If we find an interior
713   // block that is branching on a loop-invariant condition, we can unswitch this
714   // loop.
715   for (Loop::block_iterator I = currentLoop->block_begin(),
716          E = currentLoop->block_end(); I != E; ++I) {
717     Instruction *TI = (*I)->getTerminator();
718 
719     // Unswitching on a potentially uninitialized predicate is not
720     // MSan-friendly. Limit this to the cases when the original predicate is
721     // guaranteed to execute, to avoid creating a use-of-uninitialized-value
722     // in the code that did not have one.
723     // This is a workaround for the discrepancy between LLVM IR and MSan
724     // semantics. See PR28054 for more details.
725     if (SanitizeMemory &&
726         !SafetyInfo.isGuaranteedToExecute(*TI, DT, currentLoop))
727       continue;
728 
729     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
730       // Some branches may be rendered unreachable because of previous
731       // unswitching.
732       // Unswitch only those branches that are reachable.
733       if (isUnreachableDueToPreviousUnswitching(*I))
734         continue;
735 
736       // If this isn't branching on an invariant condition, we can't unswitch
737       // it.
738       if (BI->isConditional()) {
739         // See if this, or some part of it, is loop invariant.  If so, we can
740         // unswitch on it if we desire.
741         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), currentLoop,
742                                                Changed, MSSAU.get())
743                               .first;
744         if (LoopCond && !EqualityPropUnSafe(*LoopCond) &&
745             UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
746           ++NumBranches;
747           return true;
748         }
749       }
750     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
751       Value *SC = SI->getCondition();
752       Value *LoopCond;
753       OperatorChain OpChain;
754       std::tie(LoopCond, OpChain) =
755           FindLIVLoopCondition(SC, currentLoop, Changed, MSSAU.get());
756 
757       unsigned NumCases = SI->getNumCases();
758       if (LoopCond && NumCases) {
759         // Find a value to unswitch on:
760         // FIXME: this should chose the most expensive case!
761         // FIXME: scan for a case with a non-critical edge?
762         Constant *UnswitchVal = nullptr;
763         // Find a case value such that at least one case value is unswitched
764         // out.
765         if (OpChain == OC_OpChainAnd) {
766           // If the chain only has ANDs and the switch has a case value of 0.
767           // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
768           auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
769           if (BranchesInfo.isUnswitched(SI, AllZero))
770             continue;
771           // We are unswitching 0 out.
772           UnswitchVal = AllZero;
773         } else if (OpChain == OC_OpChainOr) {
774           // If the chain only has ORs and the switch has a case value of ~0.
775           // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
776           auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
777           if (BranchesInfo.isUnswitched(SI, AllOne))
778             continue;
779           // We are unswitching ~0 out.
780           UnswitchVal = AllOne;
781         } else {
782           assert(OpChain == OC_OpChainNone &&
783                  "Expect to unswitch on trivial chain");
784           // Do not process same value again and again.
785           // At this point we have some cases already unswitched and
786           // some not yet unswitched. Let's find the first not yet unswitched one.
787           for (auto Case : SI->cases()) {
788             Constant *UnswitchValCandidate = Case.getCaseValue();
789             if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
790               UnswitchVal = UnswitchValCandidate;
791               break;
792             }
793           }
794         }
795 
796         if (!UnswitchVal)
797           continue;
798 
799         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
800           ++NumSwitches;
801           // In case of a full LIV, UnswitchVal is the value we unswitched out.
802           // In case of a partial LIV, we only unswitch when its an AND-chain
803           // or OR-chain. In both cases switch input value simplifies to
804           // UnswitchVal.
805           BranchesInfo.setUnswitched(SI, UnswitchVal);
806           return true;
807         }
808       }
809     }
810 
811     // Scan the instructions to check for unswitchable values.
812     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
813          BBI != E; ++BBI)
814       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
815         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), currentLoop,
816                                                Changed, MSSAU.get())
817                               .first;
818         if (LoopCond && UnswitchIfProfitable(LoopCond,
819                                              ConstantInt::getTrue(Context))) {
820           ++NumSelects;
821           return true;
822         }
823       }
824   }
825   return Changed;
826 }
827 
828 /// Check to see if all paths from BB exit the loop with no side effects
829 /// (including infinite loops).
830 ///
831 /// If true, we return true and set ExitBB to the block we
832 /// exit through.
833 ///
isTrivialLoopExitBlockHelper(Loop * L,BasicBlock * BB,BasicBlock * & ExitBB,std::set<BasicBlock * > & Visited)834 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
835                                          BasicBlock *&ExitBB,
836                                          std::set<BasicBlock*> &Visited) {
837   if (!Visited.insert(BB).second) {
838     // Already visited. Without more analysis, this could indicate an infinite
839     // loop.
840     return false;
841   }
842   if (!L->contains(BB)) {
843     // Otherwise, this is a loop exit, this is fine so long as this is the
844     // first exit.
845     if (ExitBB) return false;
846     ExitBB = BB;
847     return true;
848   }
849 
850   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
851   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
852     // Check to see if the successor is a trivial loop exit.
853     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
854       return false;
855   }
856 
857   // Okay, everything after this looks good, check to make sure that this block
858   // doesn't include any side effects.
859   for (Instruction &I : *BB)
860     if (I.mayHaveSideEffects())
861       return false;
862 
863   return true;
864 }
865 
866 /// Return true if the specified block unconditionally leads to an exit from
867 /// the specified loop, and has no side-effects in the process. If so, return
868 /// the block that is exited to, otherwise return null.
isTrivialLoopExitBlock(Loop * L,BasicBlock * BB)869 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
870   std::set<BasicBlock*> Visited;
871   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
872   BasicBlock *ExitBB = nullptr;
873   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
874     return ExitBB;
875   return nullptr;
876 }
877 
878 /// We have found that we can unswitch currentLoop when LoopCond == Val to
879 /// simplify the loop.  If we decide that this is profitable,
880 /// unswitch the loop, reprocess the pieces, then return true.
UnswitchIfProfitable(Value * LoopCond,Constant * Val,Instruction * TI)881 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
882                                         Instruction *TI) {
883   // Check to see if it would be profitable to unswitch current loop.
884   if (!BranchesInfo.CostAllowsUnswitching()) {
885     LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
886                       << currentLoop->getHeader()->getName()
887                       << " at non-trivial condition '" << *Val
888                       << "' == " << *LoopCond << "\n"
889                       << ". Cost too high.\n");
890     return false;
891   }
892   if (hasBranchDivergence &&
893       getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
894     LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
895                       << currentLoop->getHeader()->getName()
896                       << " at non-trivial condition '" << *Val
897                       << "' == " << *LoopCond << "\n"
898                       << ". Condition is divergent.\n");
899     return false;
900   }
901 
902   UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
903   return true;
904 }
905 
906 /// Recursively clone the specified loop and all of its children,
907 /// mapping the blocks with the specified map.
CloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)908 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
909                        LoopInfo *LI, LPPassManager *LPM) {
910   Loop &New = *LI->AllocateLoop();
911   if (PL)
912     PL->addChildLoop(&New);
913   else
914     LI->addTopLevelLoop(&New);
915   LPM->addLoop(New);
916 
917   // Add all of the blocks in L to the new loop.
918   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
919        I != E; ++I)
920     if (LI->getLoopFor(*I) == L)
921       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
922 
923   // Add all of the subloops to the new loop.
924   for (Loop *I : *L)
925     CloneLoop(I, &New, VM, LI, LPM);
926 
927   return &New;
928 }
929 
930 /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
931 /// otherwise branch to FalseDest. Insert the code immediately before OldBranch
932 /// and remove (but not erase!) it from the function.
EmitPreheaderBranchOnCondition(Value * LIC,Constant * Val,BasicBlock * TrueDest,BasicBlock * FalseDest,BranchInst * OldBranch,Instruction * TI)933 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
934                                                   BasicBlock *TrueDest,
935                                                   BasicBlock *FalseDest,
936                                                   BranchInst *OldBranch,
937                                                   Instruction *TI) {
938   assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
939   assert(TrueDest != FalseDest && "Branch targets should be different");
940   // Insert a conditional branch on LIC to the two preheaders.  The original
941   // code is the true version and the new code is the false version.
942   Value *BranchVal = LIC;
943   bool Swapped = false;
944   if (!isa<ConstantInt>(Val) ||
945       Val->getType() != Type::getInt1Ty(LIC->getContext()))
946     BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
947   else if (Val != ConstantInt::getTrue(Val->getContext())) {
948     // We want to enter the new loop when the condition is true.
949     std::swap(TrueDest, FalseDest);
950     Swapped = true;
951   }
952 
953   // Old branch will be removed, so save its parent and successor to update the
954   // DomTree.
955   auto *OldBranchSucc = OldBranch->getSuccessor(0);
956   auto *OldBranchParent = OldBranch->getParent();
957 
958   // Insert the new branch.
959   BranchInst *BI =
960       IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
961   if (Swapped)
962     BI->swapProfMetadata();
963 
964   // Remove the old branch so there is only one branch at the end. This is
965   // needed to perform DomTree's internal DFS walk on the function's CFG.
966   OldBranch->removeFromParent();
967 
968   // Inform the DT about the new branch.
969   if (DT) {
970     // First, add both successors.
971     SmallVector<DominatorTree::UpdateType, 3> Updates;
972     if (TrueDest != OldBranchSucc)
973       Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
974     if (FalseDest != OldBranchSucc)
975       Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
976     // If both of the new successors are different from the old one, inform the
977     // DT that the edge was deleted.
978     if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
979       Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
980     }
981     DT->applyUpdates(Updates);
982 
983     if (MSSAU)
984       MSSAU->applyUpdates(Updates, *DT);
985   }
986 
987   // If either edge is critical, split it. This helps preserve LoopSimplify
988   // form for enclosing loops.
989   auto Options =
990       CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
991   SplitCriticalEdge(BI, 0, Options);
992   SplitCriticalEdge(BI, 1, Options);
993 }
994 
995 /// Given a loop that has a trivial unswitchable condition in it (a cond branch
996 /// from its header block to its latch block, where the path through the loop
997 /// that doesn't execute its body has no side-effects), unswitch it. This
998 /// doesn't involve any code duplication, just moving the conditional branch
999 /// outside of the loop and updating loop info.
UnswitchTrivialCondition(Loop * L,Value * Cond,Constant * Val,BasicBlock * ExitBlock,Instruction * TI)1000 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
1001                                             BasicBlock *ExitBlock,
1002                                             Instruction *TI) {
1003   LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
1004                     << loopHeader->getName() << " [" << L->getBlocks().size()
1005                     << " blocks] in Function "
1006                     << L->getHeader()->getParent()->getName()
1007                     << " on cond: " << *Val << " == " << *Cond << "\n");
1008   // We are going to make essential changes to CFG. This may invalidate cached
1009   // information for L or one of its parent loops in SCEV.
1010   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1011     SEWP->getSE().forgetTopmostLoop(L);
1012 
1013   // First step, split the preheader, so that we know that there is a safe place
1014   // to insert the conditional branch.  We will change loopPreheader to have a
1015   // conditional branch on Cond.
1016   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1017 
1018   // Now that we have a place to insert the conditional branch, create a place
1019   // to branch to: this is the exit block out of the loop that we should
1020   // short-circuit to.
1021 
1022   // Split this block now, so that the loop maintains its exit block, and so
1023   // that the jump from the preheader can execute the contents of the exit block
1024   // without actually branching to it (the exit block should be dominated by the
1025   // loop header, not the preheader).
1026   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
1027   BasicBlock *NewExit =
1028       SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
1029 
1030   // Okay, now we have a position to branch from and a position to branch to,
1031   // insert the new conditional branch.
1032   auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
1033   assert(OldBranch && "Failed to split the preheader");
1034   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1035   LPM->deleteSimpleAnalysisValue(OldBranch, L);
1036 
1037   // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
1038   // Delete it, as it is no longer needed.
1039   delete OldBranch;
1040 
1041   // We need to reprocess this loop, it could be unswitched again.
1042   redoLoop = true;
1043 
1044   // Now that we know that the loop is never entered when this condition is a
1045   // particular value, rewrite the loop with this info.  We know that this will
1046   // at least eliminate the old branch.
1047   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
1048 
1049   ++NumTrivial;
1050 }
1051 
1052 /// Check if the first non-constant condition starting from the loop header is
1053 /// a trivial unswitch condition: that is, a condition controls whether or not
1054 /// the loop does anything at all. If it is a trivial condition, unswitching
1055 /// produces no code duplications (equivalently, it produces a simpler loop and
1056 /// a new empty loop, which gets deleted). Therefore always unswitch trivial
1057 /// condition.
TryTrivialLoopUnswitch(bool & Changed)1058 bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
1059   BasicBlock *CurrentBB = currentLoop->getHeader();
1060   Instruction *CurrentTerm = CurrentBB->getTerminator();
1061   LLVMContext &Context = CurrentBB->getContext();
1062 
1063   // If loop header has only one reachable successor (currently via an
1064   // unconditional branch or constant foldable conditional branch, but
1065   // should also consider adding constant foldable switch instruction in
1066   // future), we should keep looking for trivial condition candidates in
1067   // the successor as well. An alternative is to constant fold conditions
1068   // and merge successors into loop header (then we only need to check header's
1069   // terminator). The reason for not doing this in LoopUnswitch pass is that
1070   // it could potentially break LoopPassManager's invariants. Folding dead
1071   // branches could either eliminate the current loop or make other loops
1072   // unreachable. LCSSA form might also not be preserved after deleting
1073   // branches. The following code keeps traversing loop header's successors
1074   // until it finds the trivial condition candidate (condition that is not a
1075   // constant). Since unswitching generates branches with constant conditions,
1076   // this scenario could be very common in practice.
1077   SmallPtrSet<BasicBlock*, 8> Visited;
1078 
1079   while (true) {
1080     // If we exit loop or reach a previous visited block, then
1081     // we can not reach any trivial condition candidates (unfoldable
1082     // branch instructions or switch instructions) and no unswitch
1083     // can happen. Exit and return false.
1084     if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
1085       return false;
1086 
1087     // Check if this loop will execute any side-effecting instructions (e.g.
1088     // stores, calls, volatile loads) in the part of the loop that the code
1089     // *would* execute. Check the header first.
1090     for (Instruction &I : *CurrentBB)
1091       if (I.mayHaveSideEffects())
1092         return false;
1093 
1094     if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1095       if (BI->isUnconditional()) {
1096         CurrentBB = BI->getSuccessor(0);
1097       } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1098         CurrentBB = BI->getSuccessor(0);
1099       } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1100         CurrentBB = BI->getSuccessor(1);
1101       } else {
1102         // Found a trivial condition candidate: non-foldable conditional branch.
1103         break;
1104       }
1105     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1106       // At this point, any constant-foldable instructions should have probably
1107       // been folded.
1108       ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1109       if (!Cond)
1110         break;
1111       // Find the target block we are definitely going to.
1112       CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
1113     } else {
1114       // We do not understand these terminator instructions.
1115       break;
1116     }
1117 
1118     CurrentTerm = CurrentBB->getTerminator();
1119   }
1120 
1121   // CondVal is the condition that controls the trivial condition.
1122   // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1123   Constant *CondVal = nullptr;
1124   BasicBlock *LoopExitBB = nullptr;
1125 
1126   if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1127     // If this isn't branching on an invariant condition, we can't unswitch it.
1128     if (!BI->isConditional())
1129       return false;
1130 
1131     Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), currentLoop,
1132                                            Changed, MSSAU.get())
1133                           .first;
1134 
1135     // Unswitch only if the trivial condition itself is an LIV (not
1136     // partial LIV which could occur in and/or)
1137     if (!LoopCond || LoopCond != BI->getCondition())
1138       return false;
1139 
1140     // Check to see if a successor of the branch is guaranteed to
1141     // exit through a unique exit block without having any
1142     // side-effects.  If so, determine the value of Cond that causes
1143     // it to do this.
1144     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1145                                              BI->getSuccessor(0)))) {
1146       CondVal = ConstantInt::getTrue(Context);
1147     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1148                                                     BI->getSuccessor(1)))) {
1149       CondVal = ConstantInt::getFalse(Context);
1150     }
1151 
1152     // If we didn't find a single unique LoopExit block, or if the loop exit
1153     // block contains phi nodes, this isn't trivial.
1154     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1155       return false;   // Can't handle this.
1156 
1157     if (EqualityPropUnSafe(*LoopCond))
1158       return false;
1159 
1160     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1161                              CurrentTerm);
1162     ++NumBranches;
1163     return true;
1164   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1165     // If this isn't switching on an invariant condition, we can't unswitch it.
1166     Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), currentLoop,
1167                                            Changed, MSSAU.get())
1168                           .first;
1169 
1170     // Unswitch only if the trivial condition itself is an LIV (not
1171     // partial LIV which could occur in and/or)
1172     if (!LoopCond || LoopCond != SI->getCondition())
1173       return false;
1174 
1175     // Check to see if a successor of the switch is guaranteed to go to the
1176     // latch block or exit through a one exit block without having any
1177     // side-effects.  If so, determine the value of Cond that causes it to do
1178     // this.
1179     // Note that we can't trivially unswitch on the default case or
1180     // on already unswitched cases.
1181     for (auto Case : SI->cases()) {
1182       BasicBlock *LoopExitCandidate;
1183       if ((LoopExitCandidate =
1184                isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
1185         // Okay, we found a trivial case, remember the value that is trivial.
1186         ConstantInt *CaseVal = Case.getCaseValue();
1187 
1188         // Check that it was not unswitched before, since already unswitched
1189         // trivial vals are looks trivial too.
1190         if (BranchesInfo.isUnswitched(SI, CaseVal))
1191           continue;
1192         LoopExitBB = LoopExitCandidate;
1193         CondVal = CaseVal;
1194         break;
1195       }
1196     }
1197 
1198     // If we didn't find a single unique LoopExit block, or if the loop exit
1199     // block contains phi nodes, this isn't trivial.
1200     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1201       return false;   // Can't handle this.
1202 
1203     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1204                              nullptr);
1205 
1206     // We are only unswitching full LIV.
1207     BranchesInfo.setUnswitched(SI, CondVal);
1208     ++NumSwitches;
1209     return true;
1210   }
1211   return false;
1212 }
1213 
1214 /// Split all of the edges from inside the loop to their exit blocks.
1215 /// Update the appropriate Phi nodes as we do so.
SplitExitEdges(Loop * L,const SmallVectorImpl<BasicBlock * > & ExitBlocks)1216 void LoopUnswitch::SplitExitEdges(Loop *L,
1217                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
1218 
1219   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1220     BasicBlock *ExitBlock = ExitBlocks[i];
1221     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1222                                        pred_end(ExitBlock));
1223 
1224     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1225     // general, if we call it on all predecessors of all exits then it does.
1226     SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
1227                            /*PreserveLCSSA*/ true);
1228   }
1229 }
1230 
1231 /// We determined that the loop is profitable to unswitch when LIC equal Val.
1232 /// Split it into loop versions and test the condition outside of either loop.
1233 /// Return the loops created as Out1/Out2.
UnswitchNontrivialCondition(Value * LIC,Constant * Val,Loop * L,Instruction * TI)1234 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
1235                                                Loop *L, Instruction *TI) {
1236   Function *F = loopHeader->getParent();
1237   LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1238                     << loopHeader->getName() << " [" << L->getBlocks().size()
1239                     << " blocks] in Function " << F->getName() << " when '"
1240                     << *Val << "' == " << *LIC << "\n");
1241 
1242   // We are going to make essential changes to CFG. This may invalidate cached
1243   // information for L or one of its parent loops in SCEV.
1244   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1245     SEWP->getSE().forgetTopmostLoop(L);
1246 
1247   LoopBlocks.clear();
1248   NewBlocks.clear();
1249 
1250   if (MSSAU && VerifyMemorySSA)
1251     MSSA->verifyMemorySSA();
1252 
1253   // First step, split the preheader and exit blocks, and add these blocks to
1254   // the LoopBlocks list.
1255   BasicBlock *NewPreheader =
1256       SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1257   LoopBlocks.push_back(NewPreheader);
1258 
1259   // We want the loop to come after the preheader, but before the exit blocks.
1260   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1261 
1262   SmallVector<BasicBlock*, 8> ExitBlocks;
1263   L->getUniqueExitBlocks(ExitBlocks);
1264 
1265   // Split all of the edges from inside the loop to their exit blocks.  Update
1266   // the appropriate Phi nodes as we do so.
1267   SplitExitEdges(L, ExitBlocks);
1268 
1269   // The exit blocks may have been changed due to edge splitting, recompute.
1270   ExitBlocks.clear();
1271   L->getUniqueExitBlocks(ExitBlocks);
1272 
1273   // Add exit blocks to the loop blocks.
1274   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
1275 
1276   // Next step, clone all of the basic blocks that make up the loop (including
1277   // the loop preheader and exit blocks), keeping track of the mapping between
1278   // the instructions and blocks.
1279   NewBlocks.reserve(LoopBlocks.size());
1280   ValueToValueMapTy VMap;
1281   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1282     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
1283 
1284     NewBlocks.push_back(NewBB);
1285     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
1286     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1287   }
1288 
1289   // Splice the newly inserted blocks into the function right before the
1290   // original preheader.
1291   F->getBasicBlockList().splice(NewPreheader->getIterator(),
1292                                 F->getBasicBlockList(),
1293                                 NewBlocks[0]->getIterator(), F->end());
1294 
1295   // Now we create the new Loop object for the versioned loop.
1296   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1297 
1298   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1299   // Probably clone more loop-unswitch related loop properties.
1300   BranchesInfo.cloneData(NewLoop, L, VMap);
1301 
1302   Loop *ParentLoop = L->getParentLoop();
1303   if (ParentLoop) {
1304     // Make sure to add the cloned preheader and exit blocks to the parent loop
1305     // as well.
1306     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1307   }
1308 
1309   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1310     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1311     // The new exit block should be in the same loop as the old one.
1312     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1313       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1314 
1315     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1316            "Exit block should have been split to have one successor!");
1317     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1318 
1319     // If the successor of the exit block had PHI nodes, add an entry for
1320     // NewExit.
1321     for (PHINode &PN : ExitSucc->phis()) {
1322       Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
1323       ValueToValueMapTy::iterator It = VMap.find(V);
1324       if (It != VMap.end()) V = It->second;
1325       PN.addIncoming(V, NewExit);
1326     }
1327 
1328     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1329       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1330                                     &*ExitSucc->getFirstInsertionPt());
1331 
1332       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1333            I != E; ++I) {
1334         BasicBlock *BB = *I;
1335         LandingPadInst *LPI = BB->getLandingPadInst();
1336         LPI->replaceAllUsesWith(PN);
1337         PN->addIncoming(LPI, BB);
1338       }
1339     }
1340   }
1341 
1342   // Rewrite the code to refer to itself.
1343   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1344     for (Instruction &I : *NewBlocks[i]) {
1345       RemapInstruction(&I, VMap,
1346                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1347       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1348         if (II->getIntrinsicID() == Intrinsic::assume)
1349           AC->registerAssumption(II);
1350     }
1351   }
1352 
1353   // Rewrite the original preheader to select between versions of the loop.
1354   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1355   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1356          "Preheader splitting did not work correctly!");
1357 
1358   if (MSSAU) {
1359     // Update MemorySSA after cloning, and before splitting to unreachables,
1360     // since that invalidates the 1:1 mapping of clones in VMap.
1361     LoopBlocksRPO LBRPO(L);
1362     LBRPO.perform(LI);
1363     MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1364   }
1365 
1366   // Emit the new branch that selects between the two versions of this loop.
1367   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1368                                  TI);
1369   LPM->deleteSimpleAnalysisValue(OldBR, L);
1370   if (MSSAU) {
1371     // Update MemoryPhis in Exit blocks.
1372     MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1373     if (VerifyMemorySSA)
1374       MSSA->verifyMemorySSA();
1375   }
1376 
1377   // The OldBr was replaced by a new one and removed (but not erased) by
1378   // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1379   delete OldBR;
1380 
1381   LoopProcessWorklist.push_back(NewLoop);
1382   redoLoop = true;
1383 
1384   // Keep a WeakTrackingVH holding onto LIC.  If the first call to
1385   // RewriteLoopBody
1386   // deletes the instruction (for example by simplifying a PHI that feeds into
1387   // the condition that we're unswitching on), we don't rewrite the second
1388   // iteration.
1389   WeakTrackingVH LICHandle(LIC);
1390 
1391   // Now we rewrite the original code to know that the condition is true and the
1392   // new code to know that the condition is false.
1393   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1394 
1395   // It's possible that simplifying one loop could cause the other to be
1396   // changed to another value or a constant.  If its a constant, don't simplify
1397   // it.
1398   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1399       LICHandle && !isa<Constant>(LICHandle))
1400     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1401 
1402   if (MSSA && VerifyMemorySSA)
1403     MSSA->verifyMemorySSA();
1404 }
1405 
1406 /// Remove all instances of I from the worklist vector specified.
RemoveFromWorklist(Instruction * I,std::vector<Instruction * > & Worklist)1407 static void RemoveFromWorklist(Instruction *I,
1408                                std::vector<Instruction*> &Worklist) {
1409 
1410   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1411                  Worklist.end());
1412 }
1413 
1414 /// When we find that I really equals V, remove I from the
1415 /// program, replacing all uses with V and update the worklist.
ReplaceUsesOfWith(Instruction * I,Value * V,std::vector<Instruction * > & Worklist,Loop * L,LPPassManager * LPM,MemorySSAUpdater * MSSAU)1416 static void ReplaceUsesOfWith(Instruction *I, Value *V,
1417                               std::vector<Instruction *> &Worklist, Loop *L,
1418                               LPPassManager *LPM, MemorySSAUpdater *MSSAU) {
1419   LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
1420 
1421   // Add uses to the worklist, which may be dead now.
1422   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1423     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1424       Worklist.push_back(Use);
1425 
1426   // Add users to the worklist which may be simplified now.
1427   for (User *U : I->users())
1428     Worklist.push_back(cast<Instruction>(U));
1429   LPM->deleteSimpleAnalysisValue(I, L);
1430   RemoveFromWorklist(I, Worklist);
1431   I->replaceAllUsesWith(V);
1432   if (!I->mayHaveSideEffects()) {
1433     if (MSSAU)
1434       MSSAU->removeMemoryAccess(I);
1435     I->eraseFromParent();
1436   }
1437   ++NumSimplify;
1438 }
1439 
1440 /// We know either that the value LIC has the value specified by Val in the
1441 /// specified loop, or we know it does NOT have that value.
1442 /// Rewrite any uses of LIC or of properties correlated to it.
RewriteLoopBodyWithConditionConstant(Loop * L,Value * LIC,Constant * Val,bool IsEqual)1443 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1444                                                         Constant *Val,
1445                                                         bool IsEqual) {
1446   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1447 
1448   // FIXME: Support correlated properties, like:
1449   //  for (...)
1450   //    if (li1 < li2)
1451   //      ...
1452   //    if (li1 > li2)
1453   //      ...
1454 
1455   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
1456   // selects, switches.
1457   std::vector<Instruction*> Worklist;
1458   LLVMContext &Context = Val->getContext();
1459 
1460   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1461   // in the loop with the appropriate one directly.
1462   if (IsEqual || (isa<ConstantInt>(Val) &&
1463       Val->getType()->isIntegerTy(1))) {
1464     Value *Replacement;
1465     if (IsEqual)
1466       Replacement = Val;
1467     else
1468       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1469                                      !cast<ConstantInt>(Val)->getZExtValue());
1470 
1471     for (User *U : LIC->users()) {
1472       Instruction *UI = dyn_cast<Instruction>(U);
1473       if (!UI || !L->contains(UI))
1474         continue;
1475       Worklist.push_back(UI);
1476     }
1477 
1478     for (Instruction *UI : Worklist)
1479       UI->replaceUsesOfWith(LIC, Replacement);
1480 
1481     SimplifyCode(Worklist, L);
1482     return;
1483   }
1484 
1485   // Otherwise, we don't know the precise value of LIC, but we do know that it
1486   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
1487   // can.  This case occurs when we unswitch switch statements.
1488   for (User *U : LIC->users()) {
1489     Instruction *UI = dyn_cast<Instruction>(U);
1490     if (!UI || !L->contains(UI))
1491       continue;
1492 
1493     // At this point, we know LIC is definitely not Val. Try to use some simple
1494     // logic to simplify the user w.r.t. to the context.
1495     if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1496       if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1497         // This in-loop instruction has been simplified w.r.t. its context,
1498         // i.e. LIC != Val, make sure we propagate its replacement value to
1499         // all its users.
1500         //
1501         // We can not yet delete UI, the LIC user, yet, because that would invalidate
1502         // the LIC->users() iterator !. However, we can make this instruction
1503         // dead by replacing all its users and push it onto the worklist so that
1504         // it can be properly deleted and its operands simplified.
1505         UI->replaceAllUsesWith(Replacement);
1506       }
1507     }
1508 
1509     // This is a LIC user, push it into the worklist so that SimplifyCode can
1510     // attempt to simplify it.
1511     Worklist.push_back(UI);
1512 
1513     // If we know that LIC is not Val, use this info to simplify code.
1514     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1515     if (!SI || !isa<ConstantInt>(Val)) continue;
1516 
1517     // NOTE: if a case value for the switch is unswitched out, we record it
1518     // after the unswitch finishes. We can not record it here as the switch
1519     // is not a direct user of the partial LIV.
1520     SwitchInst::CaseHandle DeadCase =
1521         *SI->findCaseValue(cast<ConstantInt>(Val));
1522     // Default case is live for multiple values.
1523     if (DeadCase == *SI->case_default())
1524       continue;
1525 
1526     // Found a dead case value.  Don't remove PHI nodes in the
1527     // successor if they become single-entry, those PHI nodes may
1528     // be in the Users list.
1529 
1530     BasicBlock *Switch = SI->getParent();
1531     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1532     BasicBlock *Latch = L->getLoopLatch();
1533 
1534     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
1535     // If the DeadCase successor dominates the loop latch, then the
1536     // transformation isn't safe since it will delete the sole predecessor edge
1537     // to the latch.
1538     if (Latch && DT->dominates(SISucc, Latch))
1539       continue;
1540 
1541     // FIXME: This is a hack.  We need to keep the successor around
1542     // and hooked up so as to preserve the loop structure, because
1543     // trying to update it is complicated.  So instead we preserve the
1544     // loop structure and put the block on a dead code path.
1545     SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1546     // Compute the successors instead of relying on the return value
1547     // of SplitEdge, since it may have split the switch successor
1548     // after PHI nodes.
1549     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1550     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1551     // Create an "unreachable" destination.
1552     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1553                                            Switch->getParent(),
1554                                            OldSISucc);
1555     new UnreachableInst(Context, Abort);
1556     // Force the new case destination to branch to the "unreachable"
1557     // block while maintaining a (dead) CFG edge to the old block.
1558     NewSISucc->getTerminator()->eraseFromParent();
1559     BranchInst::Create(Abort, OldSISucc,
1560                        ConstantInt::getTrue(Context), NewSISucc);
1561     // Release the PHI operands for this edge.
1562     for (PHINode &PN : NewSISucc->phis())
1563       PN.setIncomingValueForBlock(Switch, UndefValue::get(PN.getType()));
1564     // Tell the domtree about the new block. We don't fully update the
1565     // domtree here -- instead we force it to do a full recomputation
1566     // after the pass is complete -- but we do need to inform it of
1567     // new blocks.
1568     DT->addNewBlock(Abort, NewSISucc);
1569   }
1570 
1571   SimplifyCode(Worklist, L);
1572 }
1573 
1574 /// Now that we have simplified some instructions in the loop, walk over it and
1575 /// constant prop, dce, and fold control flow where possible. Note that this is
1576 /// effectively a very simple loop-structure-aware optimizer. During processing
1577 /// of this loop, L could very well be deleted, so it must not be used.
1578 ///
1579 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1580 /// pass.
1581 ///
SimplifyCode(std::vector<Instruction * > & Worklist,Loop * L)1582 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1583   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1584   while (!Worklist.empty()) {
1585     Instruction *I = Worklist.back();
1586     Worklist.pop_back();
1587 
1588     // Simple DCE.
1589     if (isInstructionTriviallyDead(I)) {
1590       LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
1591 
1592       // Add uses to the worklist, which may be dead now.
1593       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1594         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1595           Worklist.push_back(Use);
1596       LPM->deleteSimpleAnalysisValue(I, L);
1597       RemoveFromWorklist(I, Worklist);
1598       if (MSSAU)
1599         MSSAU->removeMemoryAccess(I);
1600       I->eraseFromParent();
1601       ++NumSimplify;
1602       continue;
1603     }
1604 
1605     // See if instruction simplification can hack this up.  This is common for
1606     // things like "select false, X, Y" after unswitching made the condition be
1607     // 'false'.  TODO: update the domtree properly so we can pass it here.
1608     if (Value *V = SimplifyInstruction(I, DL))
1609       if (LI->replacementPreservesLCSSAForm(I, V)) {
1610         ReplaceUsesOfWith(I, V, Worklist, L, LPM, MSSAU.get());
1611         continue;
1612       }
1613 
1614     // Special case hacks that appear commonly in unswitched code.
1615     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1616       if (BI->isUnconditional()) {
1617         // If BI's parent is the only pred of the successor, fold the two blocks
1618         // together.
1619         BasicBlock *Pred = BI->getParent();
1620         (void)Pred;
1621         BasicBlock *Succ = BI->getSuccessor(0);
1622         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1623         if (!SinglePred) continue;  // Nothing to do.
1624         assert(SinglePred == Pred && "CFG broken");
1625 
1626         // Make the LPM and Worklist updates specific to LoopUnswitch.
1627         LPM->deleteSimpleAnalysisValue(BI, L);
1628         RemoveFromWorklist(BI, Worklist);
1629         LPM->deleteSimpleAnalysisValue(Succ, L);
1630         auto SuccIt = Succ->begin();
1631         while (PHINode *PN = dyn_cast<PHINode>(SuccIt++)) {
1632           for (unsigned It = 0, E = PN->getNumOperands(); It != E; ++It)
1633             if (Instruction *Use = dyn_cast<Instruction>(PN->getOperand(It)))
1634               Worklist.push_back(Use);
1635           for (User *U : PN->users())
1636             Worklist.push_back(cast<Instruction>(U));
1637           LPM->deleteSimpleAnalysisValue(PN, L);
1638           RemoveFromWorklist(PN, Worklist);
1639           ++NumSimplify;
1640         }
1641         // Merge the block and make the remaining analyses updates.
1642         DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1643         MergeBlockIntoPredecessor(Succ, &DTU, LI, MSSAU.get());
1644         ++NumSimplify;
1645         continue;
1646       }
1647 
1648       continue;
1649     }
1650   }
1651 }
1652 
1653 /// Simple simplifications we can do given the information that Cond is
1654 /// definitely not equal to Val.
SimplifyInstructionWithNotEqual(Instruction * Inst,Value * Invariant,Constant * Val)1655 Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1656                                                      Value *Invariant,
1657                                                      Constant *Val) {
1658   // icmp eq cond, val -> false
1659   ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1660   if (CI && CI->isEquality()) {
1661     Value *Op0 = CI->getOperand(0);
1662     Value *Op1 = CI->getOperand(1);
1663     if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1664       LLVMContext &Ctx = Inst->getContext();
1665       if (CI->getPredicate() == CmpInst::ICMP_EQ)
1666         return ConstantInt::getFalse(Ctx);
1667       else
1668         return ConstantInt::getTrue(Ctx);
1669      }
1670   }
1671 
1672   // FIXME: there may be other opportunities, e.g. comparison with floating
1673   // point, or Invariant - Val != 0, etc.
1674   return nullptr;
1675 }
1676