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