LLVM  mainline
LoopUnswitch.cpp
Go to the documentation of this file.
00001 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass transforms loops that contain branches on loop-invariant conditions
00011 // to have multiple loops.  For example, it turns the left into the right code:
00012 //
00013 //  for (...)                  if (lic)
00014 //    A                          for (...)
00015 //    if (lic)                     A; B; C
00016 //      B                      else
00017 //    C                          for (...)
00018 //                                 A; C
00019 //
00020 // This can increase the size of the code exponentially (doubling it every time
00021 // a loop is unswitched) so we only unswitch if the resultant code will be
00022 // smaller than a threshold.
00023 //
00024 // This pass expects LICM to be run before it to hoist invariant conditions out
00025 // of the loop, to make the unswitching opportunity obvious.
00026 //
00027 //===----------------------------------------------------------------------===//
00028 
00029 #include "llvm/Transforms/Scalar.h"
00030 #include "llvm/ADT/STLExtras.h"
00031 #include "llvm/ADT/SmallPtrSet.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/Analysis/AssumptionCache.h"
00034 #include "llvm/Analysis/CodeMetrics.h"
00035 #include "llvm/Analysis/InstructionSimplify.h"
00036 #include "llvm/Analysis/LoopInfo.h"
00037 #include "llvm/Analysis/LoopPass.h"
00038 #include "llvm/Analysis/ScalarEvolution.h"
00039 #include "llvm/Analysis/TargetTransformInfo.h"
00040 #include "llvm/IR/Constants.h"
00041 #include "llvm/IR/DerivedTypes.h"
00042 #include "llvm/IR/Dominators.h"
00043 #include "llvm/IR/Function.h"
00044 #include "llvm/IR/Instructions.h"
00045 #include "llvm/IR/Module.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/Support/raw_ostream.h"
00049 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00050 #include "llvm/Transforms/Utils/Cloning.h"
00051 #include "llvm/Transforms/Utils/Local.h"
00052 #include <algorithm>
00053 #include <map>
00054 #include <set>
00055 using namespace llvm;
00056 
00057 #define DEBUG_TYPE "loop-unswitch"
00058 
00059 STATISTIC(NumBranches, "Number of branches unswitched");
00060 STATISTIC(NumSwitches, "Number of switches unswitched");
00061 STATISTIC(NumSelects , "Number of selects unswitched");
00062 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
00063 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
00064 STATISTIC(TotalInsts,  "Total number of instructions analyzed");
00065 
00066 // The specific value of 100 here was chosen based only on intuition and a
00067 // few specific examples.
00068 static cl::opt<unsigned>
00069 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
00070           cl::init(100), cl::Hidden);
00071 
00072 namespace {
00073 
00074   class LUAnalysisCache {
00075 
00076     typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
00077       UnswitchedValsMap;
00078 
00079     typedef UnswitchedValsMap::iterator UnswitchedValsIt;
00080 
00081     struct LoopProperties {
00082       unsigned CanBeUnswitchedCount;
00083       unsigned SizeEstimation;
00084       UnswitchedValsMap UnswitchedVals;
00085     };
00086 
00087     // Here we use std::map instead of DenseMap, since we need to keep valid
00088     // LoopProperties pointer for current loop for better performance.
00089     typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
00090     typedef LoopPropsMap::iterator LoopPropsMapIt;
00091 
00092     LoopPropsMap LoopsProperties;
00093     UnswitchedValsMap *CurLoopInstructions;
00094     LoopProperties *CurrentLoopProperties;
00095 
00096     // Max size of code we can produce on remained iterations.
00097     unsigned MaxSize;
00098 
00099     public:
00100 
00101       LUAnalysisCache() :
00102         CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
00103         MaxSize(Threshold)
00104       {}
00105 
00106       // Analyze loop. Check its size, calculate is it possible to unswitch
00107       // it. Returns true if we can unswitch this loop.
00108       bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
00109                      AssumptionCache *AC);
00110 
00111       // Clean all data related to given loop.
00112       void forgetLoop(const Loop *L);
00113 
00114       // Mark case value as unswitched.
00115       // Since SI instruction can be partly unswitched, in order to avoid
00116       // extra unswitching in cloned loops keep track all unswitched values.
00117       void setUnswitched(const SwitchInst *SI, const Value *V);
00118 
00119       // Check was this case value unswitched before or not.
00120       bool isUnswitched(const SwitchInst *SI, const Value *V);
00121 
00122       // Clone all loop-unswitch related loop properties.
00123       // Redistribute unswitching quotas.
00124       // Note, that new loop data is stored inside the VMap.
00125       void cloneData(const Loop *NewLoop, const Loop *OldLoop,
00126                      const ValueToValueMapTy &VMap);
00127   };
00128 
00129   class LoopUnswitch : public LoopPass {
00130     LoopInfo *LI;  // Loop information
00131     LPPassManager *LPM;
00132     AssumptionCache *AC;
00133 
00134     // LoopProcessWorklist - Used to check if second loop needs processing
00135     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
00136     std::vector<Loop*> LoopProcessWorklist;
00137 
00138     LUAnalysisCache BranchesInfo;
00139 
00140     bool OptimizeForSize;
00141     bool redoLoop;
00142 
00143     Loop *currentLoop;
00144     DominatorTree *DT;
00145     BasicBlock *loopHeader;
00146     BasicBlock *loopPreheader;
00147 
00148     // LoopBlocks contains all of the basic blocks of the loop, including the
00149     // preheader of the loop, the body of the loop, and the exit blocks of the
00150     // loop, in that order.
00151     std::vector<BasicBlock*> LoopBlocks;
00152     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
00153     std::vector<BasicBlock*> NewBlocks;
00154 
00155   public:
00156     static char ID; // Pass ID, replacement for typeid
00157     explicit LoopUnswitch(bool Os = false) :
00158       LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
00159       currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
00160       loopPreheader(nullptr) {
00161         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
00162       }
00163 
00164     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00165     bool processCurrentLoop();
00166 
00167     /// This transformation requires natural loop information & requires that
00168     /// loop preheaders be inserted into the CFG.
00169     ///
00170     void getAnalysisUsage(AnalysisUsage &AU) const override {
00171       AU.addRequired<AssumptionCacheTracker>();
00172       AU.addRequiredID(LoopSimplifyID);
00173       AU.addPreservedID(LoopSimplifyID);
00174       AU.addRequired<LoopInfoWrapperPass>();
00175       AU.addPreserved<LoopInfoWrapperPass>();
00176       AU.addRequiredID(LCSSAID);
00177       AU.addPreservedID(LCSSAID);
00178       AU.addPreserved<DominatorTreeWrapperPass>();
00179       AU.addPreserved<ScalarEvolution>();
00180       AU.addRequired<TargetTransformInfoWrapperPass>();
00181     }
00182 
00183   private:
00184 
00185     void releaseMemory() override {
00186       BranchesInfo.forgetLoop(currentLoop);
00187     }
00188 
00189     void initLoopData() {
00190       loopHeader = currentLoop->getHeader();
00191       loopPreheader = currentLoop->getLoopPreheader();
00192     }
00193 
00194     /// Split all of the edges from inside the loop to their exit blocks.
00195     /// Update the appropriate Phi nodes as we do so.
00196     void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
00197 
00198     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
00199     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
00200                                   BasicBlock *ExitBlock);
00201     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
00202 
00203     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00204                                               Constant *Val, bool isEqual);
00205 
00206     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00207                                         BasicBlock *TrueDest,
00208                                         BasicBlock *FalseDest,
00209                                         Instruction *InsertPt);
00210 
00211     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
00212     bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
00213                                     BasicBlock **LoopExit = nullptr);
00214 
00215   };
00216 }
00217 
00218 // Analyze loop. Check its size, calculate is it possible to unswitch
00219 // it. Returns true if we can unswitch this loop.
00220 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
00221                                 AssumptionCache *AC) {
00222 
00223   LoopPropsMapIt PropsIt;
00224   bool Inserted;
00225   std::tie(PropsIt, Inserted) =
00226       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
00227 
00228   LoopProperties &Props = PropsIt->second;
00229 
00230   if (Inserted) {
00231     // New loop.
00232 
00233     // Limit the number of instructions to avoid causing significant code
00234     // expansion, and the number of basic blocks, to avoid loops with
00235     // large numbers of branches which cause loop unswitching to go crazy.
00236     // This is a very ad-hoc heuristic.
00237 
00238     SmallPtrSet<const Value *, 32> EphValues;
00239     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
00240 
00241     // FIXME: This is overly conservative because it does not take into
00242     // consideration code simplification opportunities and code that can
00243     // be shared by the resultant unswitched loops.
00244     CodeMetrics Metrics;
00245     for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00246          I != E; ++I)
00247       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
00248 
00249     Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
00250     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
00251     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
00252 
00253     if (Metrics.notDuplicatable) {
00254       DEBUG(dbgs() << "NOT unswitching loop %"
00255                    << L->getHeader()->getName() << ", contents cannot be "
00256                    << "duplicated!\n");
00257       return false;
00258     }
00259   }
00260 
00261   if (!Props.CanBeUnswitchedCount) {
00262     DEBUG(dbgs() << "NOT unswitching loop %"
00263                  << L->getHeader()->getName() << ", cost too high: "
00264                  << L->getBlocks().size() << "\n");
00265     return false;
00266   }
00267 
00268   // Be careful. This links are good only before new loop addition.
00269   CurrentLoopProperties = &Props;
00270   CurLoopInstructions = &Props.UnswitchedVals;
00271 
00272   return true;
00273 }
00274 
00275 // Clean all data related to given loop.
00276 void LUAnalysisCache::forgetLoop(const Loop *L) {
00277 
00278   LoopPropsMapIt LIt = LoopsProperties.find(L);
00279 
00280   if (LIt != LoopsProperties.end()) {
00281     LoopProperties &Props = LIt->second;
00282     MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
00283     LoopsProperties.erase(LIt);
00284   }
00285 
00286   CurrentLoopProperties = nullptr;
00287   CurLoopInstructions = nullptr;
00288 }
00289 
00290 // Mark case value as unswitched.
00291 // Since SI instruction can be partly unswitched, in order to avoid
00292 // extra unswitching in cloned loops keep track all unswitched values.
00293 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
00294   (*CurLoopInstructions)[SI].insert(V);
00295 }
00296 
00297 // Check was this case value unswitched before or not.
00298 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
00299   return (*CurLoopInstructions)[SI].count(V);
00300 }
00301 
00302 // Clone all loop-unswitch related loop properties.
00303 // Redistribute unswitching quotas.
00304 // Note, that new loop data is stored inside the VMap.
00305 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
00306                                 const ValueToValueMapTy &VMap) {
00307 
00308   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
00309   LoopProperties &OldLoopProps = *CurrentLoopProperties;
00310   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
00311 
00312   // Reallocate "can-be-unswitched quota"
00313 
00314   --OldLoopProps.CanBeUnswitchedCount;
00315   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
00316   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
00317   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
00318 
00319   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
00320 
00321   // Clone unswitched values info:
00322   // for new loop switches we clone info about values that was
00323   // already unswitched and has redundant successors.
00324   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
00325     const SwitchInst *OldInst = I->first;
00326     Value *NewI = VMap.lookup(OldInst);
00327     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
00328     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
00329 
00330     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
00331   }
00332 }
00333 
00334 char LoopUnswitch::ID = 0;
00335 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
00336                       false, false)
00337 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
00338 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00339 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00340 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00341 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00342 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
00343                       false, false)
00344 
00345 Pass *llvm::createLoopUnswitchPass(bool Os) {
00346   return new LoopUnswitch(Os);
00347 }
00348 
00349 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
00350 /// invariant in the loop, or has an invariant piece, return the invariant.
00351 /// Otherwise, return null.
00352 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
00353 
00354   // We started analyze new instruction, increment scanned instructions counter.
00355   ++TotalInsts;
00356 
00357   // We can never unswitch on vector conditions.
00358   if (Cond->getType()->isVectorTy())
00359     return nullptr;
00360 
00361   // Constants should be folded, not unswitched on!
00362   if (isa<Constant>(Cond)) return nullptr;
00363 
00364   // TODO: Handle: br (VARIANT|INVARIANT).
00365 
00366   // Hoist simple values out.
00367   if (L->makeLoopInvariant(Cond, Changed))
00368     return Cond;
00369 
00370   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
00371     if (BO->getOpcode() == Instruction::And ||
00372         BO->getOpcode() == Instruction::Or) {
00373       // If either the left or right side is invariant, we can unswitch on this,
00374       // which will cause the branch to go away in one loop and the condition to
00375       // simplify in the other one.
00376       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
00377         return LHS;
00378       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
00379         return RHS;
00380     }
00381 
00382   return nullptr;
00383 }
00384 
00385 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
00386   if (skipOptnoneFunction(L))
00387     return false;
00388 
00389   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
00390       *L->getHeader()->getParent());
00391   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00392   LPM = &LPM_Ref;
00393   DominatorTreeWrapperPass *DTWP =
00394       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00395   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00396   currentLoop = L;
00397   Function *F = currentLoop->getHeader()->getParent();
00398   bool Changed = false;
00399   do {
00400     assert(currentLoop->isLCSSAForm(*DT));
00401     redoLoop = false;
00402     Changed |= processCurrentLoop();
00403   } while(redoLoop);
00404 
00405   if (Changed) {
00406     // FIXME: Reconstruct dom info, because it is not preserved properly.
00407     if (DT)
00408       DT->recalculate(*F);
00409   }
00410   return Changed;
00411 }
00412 
00413 /// processCurrentLoop - Do actual work and unswitch loop if possible
00414 /// and profitable.
00415 bool LoopUnswitch::processCurrentLoop() {
00416   bool Changed = false;
00417 
00418   initLoopData();
00419 
00420   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
00421   if (!loopPreheader)
00422     return false;
00423 
00424   // Loops with indirectbr cannot be cloned.
00425   if (!currentLoop->isSafeToClone())
00426     return false;
00427 
00428   // Without dedicated exits, splitting the exit edge may fail.
00429   if (!currentLoop->hasDedicatedExits())
00430     return false;
00431 
00432   LLVMContext &Context = loopHeader->getContext();
00433 
00434   // Probably we reach the quota of branches for this loop. If so
00435   // stop unswitching.
00436   if (!BranchesInfo.countLoop(
00437           currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
00438                            *currentLoop->getHeader()->getParent()),
00439           AC))
00440     return false;
00441 
00442   // Loop over all of the basic blocks in the loop.  If we find an interior
00443   // block that is branching on a loop-invariant condition, we can unswitch this
00444   // loop.
00445   for (Loop::block_iterator I = currentLoop->block_begin(),
00446          E = currentLoop->block_end(); I != E; ++I) {
00447     TerminatorInst *TI = (*I)->getTerminator();
00448     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00449       // If this isn't branching on an invariant condition, we can't unswitch
00450       // it.
00451       if (BI->isConditional()) {
00452         // See if this, or some part of it, is loop invariant.  If so, we can
00453         // unswitch on it if we desire.
00454         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
00455                                                currentLoop, Changed);
00456         if (LoopCond && UnswitchIfProfitable(LoopCond,
00457                                              ConstantInt::getTrue(Context))) {
00458           ++NumBranches;
00459           return true;
00460         }
00461       }
00462     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00463       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
00464                                              currentLoop, Changed);
00465       unsigned NumCases = SI->getNumCases();
00466       if (LoopCond && NumCases) {
00467         // Find a value to unswitch on:
00468         // FIXME: this should chose the most expensive case!
00469         // FIXME: scan for a case with a non-critical edge?
00470         Constant *UnswitchVal = nullptr;
00471 
00472         // Do not process same value again and again.
00473         // At this point we have some cases already unswitched and
00474         // some not yet unswitched. Let's find the first not yet unswitched one.
00475         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00476              i != e; ++i) {
00477           Constant *UnswitchValCandidate = i.getCaseValue();
00478           if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
00479             UnswitchVal = UnswitchValCandidate;
00480             break;
00481           }
00482         }
00483 
00484         if (!UnswitchVal)
00485           continue;
00486 
00487         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
00488           ++NumSwitches;
00489           return true;
00490         }
00491       }
00492     }
00493 
00494     // Scan the instructions to check for unswitchable values.
00495     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
00496          BBI != E; ++BBI)
00497       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
00498         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
00499                                                currentLoop, Changed);
00500         if (LoopCond && UnswitchIfProfitable(LoopCond,
00501                                              ConstantInt::getTrue(Context))) {
00502           ++NumSelects;
00503           return true;
00504         }
00505       }
00506   }
00507   return Changed;
00508 }
00509 
00510 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
00511 /// loop with no side effects (including infinite loops).
00512 ///
00513 /// If true, we return true and set ExitBB to the block we
00514 /// exit through.
00515 ///
00516 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
00517                                          BasicBlock *&ExitBB,
00518                                          std::set<BasicBlock*> &Visited) {
00519   if (!Visited.insert(BB).second) {
00520     // Already visited. Without more analysis, this could indicate an infinite
00521     // loop.
00522     return false;
00523   }
00524   if (!L->contains(BB)) {
00525     // Otherwise, this is a loop exit, this is fine so long as this is the
00526     // first exit.
00527     if (ExitBB) return false;
00528     ExitBB = BB;
00529     return true;
00530   }
00531 
00532   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
00533   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
00534     // Check to see if the successor is a trivial loop exit.
00535     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
00536       return false;
00537   }
00538 
00539   // Okay, everything after this looks good, check to make sure that this block
00540   // doesn't include any side effects.
00541   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00542     if (I->mayHaveSideEffects())
00543       return false;
00544 
00545   return true;
00546 }
00547 
00548 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
00549 /// leads to an exit from the specified loop, and has no side-effects in the
00550 /// process.  If so, return the block that is exited to, otherwise return null.
00551 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
00552   std::set<BasicBlock*> Visited;
00553   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
00554   BasicBlock *ExitBB = nullptr;
00555   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
00556     return ExitBB;
00557   return nullptr;
00558 }
00559 
00560 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
00561 /// trivial: that is, that the condition controls whether or not the loop does
00562 /// anything at all.  If this is a trivial condition, unswitching produces no
00563 /// code duplications (equivalently, it produces a simpler loop and a new empty
00564 /// loop, which gets deleted).
00565 ///
00566 /// If this is a trivial condition, return true, otherwise return false.  When
00567 /// returning true, this sets Cond and Val to the condition that controls the
00568 /// trivial condition: when Cond dynamically equals Val, the loop is known to
00569 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
00570 /// Cond == Val.
00571 ///
00572 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
00573                                        BasicBlock **LoopExit) {
00574   BasicBlock *Header = currentLoop->getHeader();
00575   TerminatorInst *HeaderTerm = Header->getTerminator();
00576   LLVMContext &Context = Header->getContext();
00577 
00578   BasicBlock *LoopExitBB = nullptr;
00579   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
00580     // If the header block doesn't end with a conditional branch on Cond, we
00581     // can't handle it.
00582     if (!BI->isConditional() || BI->getCondition() != Cond)
00583       return false;
00584 
00585     // Check to see if a successor of the branch is guaranteed to
00586     // exit through a unique exit block without having any
00587     // side-effects.  If so, determine the value of Cond that causes it to do
00588     // this.
00589     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
00590                                              BI->getSuccessor(0)))) {
00591       if (Val) *Val = ConstantInt::getTrue(Context);
00592     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
00593                                                     BI->getSuccessor(1)))) {
00594       if (Val) *Val = ConstantInt::getFalse(Context);
00595     }
00596   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
00597     // If this isn't a switch on Cond, we can't handle it.
00598     if (SI->getCondition() != Cond) return false;
00599 
00600     // Check to see if a successor of the switch is guaranteed to go to the
00601     // latch block or exit through a one exit block without having any
00602     // side-effects.  If so, determine the value of Cond that causes it to do
00603     // this.
00604     // Note that we can't trivially unswitch on the default case or
00605     // on already unswitched cases.
00606     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00607          i != e; ++i) {
00608       BasicBlock *LoopExitCandidate;
00609       if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
00610                                                i.getCaseSuccessor()))) {
00611         // Okay, we found a trivial case, remember the value that is trivial.
00612         ConstantInt *CaseVal = i.getCaseValue();
00613 
00614         // Check that it was not unswitched before, since already unswitched
00615         // trivial vals are looks trivial too.
00616         if (BranchesInfo.isUnswitched(SI, CaseVal))
00617           continue;
00618         LoopExitBB = LoopExitCandidate;
00619         if (Val) *Val = CaseVal;
00620         break;
00621       }
00622     }
00623   }
00624 
00625   // If we didn't find a single unique LoopExit block, or if the loop exit block
00626   // contains phi nodes, this isn't trivial.
00627   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
00628     return false;   // Can't handle this.
00629 
00630   if (LoopExit) *LoopExit = LoopExitBB;
00631 
00632   // We already know that nothing uses any scalar values defined inside of this
00633   // loop.  As such, we just have to check to see if this loop will execute any
00634   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
00635   // part of the loop that the code *would* execute.  We already checked the
00636   // tail, check the header now.
00637   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
00638     if (I->mayHaveSideEffects())
00639       return false;
00640   return true;
00641 }
00642 
00643 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
00644 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
00645 /// unswitch the loop, reprocess the pieces, then return true.
00646 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
00647   Function *F = loopHeader->getParent();
00648   Constant *CondVal = nullptr;
00649   BasicBlock *ExitBlock = nullptr;
00650 
00651   if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
00652     // If the condition is trivial, always unswitch. There is no code growth
00653     // for this case.
00654     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
00655     return true;
00656   }
00657 
00658   // Check to see if it would be profitable to unswitch current loop.
00659 
00660   // Do not do non-trivial unswitch while optimizing for size.
00661   if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
00662     return false;
00663 
00664   UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
00665   return true;
00666 }
00667 
00668 /// CloneLoop - Recursively clone the specified loop and all of its children,
00669 /// mapping the blocks with the specified map.
00670 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
00671                        LoopInfo *LI, LPPassManager *LPM) {
00672   Loop *New = new Loop();
00673   LPM->insertLoop(New, PL);
00674 
00675   // Add all of the blocks in L to the new loop.
00676   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00677        I != E; ++I)
00678     if (LI->getLoopFor(*I) == L)
00679       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
00680 
00681   // Add all of the subloops to the new loop.
00682   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00683     CloneLoop(*I, New, VM, LI, LPM);
00684 
00685   return New;
00686 }
00687 
00688 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
00689 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
00690 /// code immediately before InsertPt.
00691 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00692                                                   BasicBlock *TrueDest,
00693                                                   BasicBlock *FalseDest,
00694                                                   Instruction *InsertPt) {
00695   // Insert a conditional branch on LIC to the two preheaders.  The original
00696   // code is the true version and the new code is the false version.
00697   Value *BranchVal = LIC;
00698   if (!isa<ConstantInt>(Val) ||
00699       Val->getType() != Type::getInt1Ty(LIC->getContext()))
00700     BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
00701   else if (Val != ConstantInt::getTrue(Val->getContext()))
00702     // We want to enter the new loop when the condition is true.
00703     std::swap(TrueDest, FalseDest);
00704 
00705   // Insert the new branch.
00706   BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
00707 
00708   // If either edge is critical, split it. This helps preserve LoopSimplify
00709   // form for enclosing loops.
00710   auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
00711   SplitCriticalEdge(BI, 0, Options);
00712   SplitCriticalEdge(BI, 1, Options);
00713 }
00714 
00715 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
00716 /// condition in it (a cond branch from its header block to its latch block,
00717 /// where the path through the loop that doesn't execute its body has no
00718 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
00719 /// moving the conditional branch outside of the loop and updating loop info.
00720 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
00721                                             Constant *Val,
00722                                             BasicBlock *ExitBlock) {
00723   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
00724         << loopHeader->getName() << " [" << L->getBlocks().size()
00725         << " blocks] in Function " << L->getHeader()->getParent()->getName()
00726         << " on cond: " << *Val << " == " << *Cond << "\n");
00727 
00728   // First step, split the preheader, so that we know that there is a safe place
00729   // to insert the conditional branch.  We will change loopPreheader to have a
00730   // conditional branch on Cond.
00731   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
00732 
00733   // Now that we have a place to insert the conditional branch, create a place
00734   // to branch to: this is the exit block out of the loop that we should
00735   // short-circuit to.
00736 
00737   // Split this block now, so that the loop maintains its exit block, and so
00738   // that the jump from the preheader can execute the contents of the exit block
00739   // without actually branching to it (the exit block should be dominated by the
00740   // loop header, not the preheader).
00741   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
00742   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
00743 
00744   // Okay, now we have a position to branch from and a position to branch to,
00745   // insert the new conditional branch.
00746   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
00747                                  loopPreheader->getTerminator());
00748   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
00749   loopPreheader->getTerminator()->eraseFromParent();
00750 
00751   // We need to reprocess this loop, it could be unswitched again.
00752   redoLoop = true;
00753 
00754   // Now that we know that the loop is never entered when this condition is a
00755   // particular value, rewrite the loop with this info.  We know that this will
00756   // at least eliminate the old branch.
00757   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
00758   ++NumTrivial;
00759 }
00760 
00761 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
00762 /// blocks.  Update the appropriate Phi nodes as we do so.
00763 void LoopUnswitch::SplitExitEdges(Loop *L,
00764                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
00765 
00766   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00767     BasicBlock *ExitBlock = ExitBlocks[i];
00768     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
00769                                        pred_end(ExitBlock));
00770 
00771     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
00772     // general, if we call it on all predecessors of all exits then it does.
00773     SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
00774                            /*AliasAnalysis*/ nullptr, DT, LI,
00775                            /*PreserveLCSSA*/ true);
00776   }
00777 }
00778 
00779 /// UnswitchNontrivialCondition - We determined that the loop is profitable
00780 /// to unswitch when LIC equal Val.  Split it into loop versions and test the
00781 /// condition outside of either loop.  Return the loops created as Out1/Out2.
00782 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
00783                                                Loop *L) {
00784   Function *F = loopHeader->getParent();
00785   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
00786         << loopHeader->getName() << " [" << L->getBlocks().size()
00787         << " blocks] in Function " << F->getName()
00788         << " when '" << *Val << "' == " << *LIC << "\n");
00789 
00790   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
00791     SE->forgetLoop(L);
00792 
00793   LoopBlocks.clear();
00794   NewBlocks.clear();
00795 
00796   // First step, split the preheader and exit blocks, and add these blocks to
00797   // the LoopBlocks list.
00798   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
00799   LoopBlocks.push_back(NewPreheader);
00800 
00801   // We want the loop to come after the preheader, but before the exit blocks.
00802   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
00803 
00804   SmallVector<BasicBlock*, 8> ExitBlocks;
00805   L->getUniqueExitBlocks(ExitBlocks);
00806 
00807   // Split all of the edges from inside the loop to their exit blocks.  Update
00808   // the appropriate Phi nodes as we do so.
00809   SplitExitEdges(L, ExitBlocks);
00810 
00811   // The exit blocks may have been changed due to edge splitting, recompute.
00812   ExitBlocks.clear();
00813   L->getUniqueExitBlocks(ExitBlocks);
00814 
00815   // Add exit blocks to the loop blocks.
00816   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
00817 
00818   // Next step, clone all of the basic blocks that make up the loop (including
00819   // the loop preheader and exit blocks), keeping track of the mapping between
00820   // the instructions and blocks.
00821   NewBlocks.reserve(LoopBlocks.size());
00822   ValueToValueMapTy VMap;
00823   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
00824     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
00825 
00826     NewBlocks.push_back(NewBB);
00827     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
00828     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
00829   }
00830 
00831   // Splice the newly inserted blocks into the function right before the
00832   // original preheader.
00833   F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
00834                                 NewBlocks[0], F->end());
00835 
00836   // FIXME: We could register any cloned assumptions instead of clearing the
00837   // whole function's cache.
00838   AC->clear();
00839 
00840   // Now we create the new Loop object for the versioned loop.
00841   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
00842 
00843   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
00844   // Probably clone more loop-unswitch related loop properties.
00845   BranchesInfo.cloneData(NewLoop, L, VMap);
00846 
00847   Loop *ParentLoop = L->getParentLoop();
00848   if (ParentLoop) {
00849     // Make sure to add the cloned preheader and exit blocks to the parent loop
00850     // as well.
00851     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
00852   }
00853 
00854   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00855     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
00856     // The new exit block should be in the same loop as the old one.
00857     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
00858       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
00859 
00860     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
00861            "Exit block should have been split to have one successor!");
00862     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
00863 
00864     // If the successor of the exit block had PHI nodes, add an entry for
00865     // NewExit.
00866     for (BasicBlock::iterator I = ExitSucc->begin();
00867          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00868       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
00869       ValueToValueMapTy::iterator It = VMap.find(V);
00870       if (It != VMap.end()) V = It->second;
00871       PN->addIncoming(V, NewExit);
00872     }
00873 
00874     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
00875       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
00876                                     ExitSucc->getFirstInsertionPt());
00877 
00878       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
00879            I != E; ++I) {
00880         BasicBlock *BB = *I;
00881         LandingPadInst *LPI = BB->getLandingPadInst();
00882         LPI->replaceAllUsesWith(PN);
00883         PN->addIncoming(LPI, BB);
00884       }
00885     }
00886   }
00887 
00888   // Rewrite the code to refer to itself.
00889   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
00890     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00891            E = NewBlocks[i]->end(); I != E; ++I)
00892       RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
00893 
00894   // Rewrite the original preheader to select between versions of the loop.
00895   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
00896   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
00897          "Preheader splitting did not work correctly!");
00898 
00899   // Emit the new branch that selects between the two versions of this loop.
00900   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
00901   LPM->deleteSimpleAnalysisValue(OldBR, L);
00902   OldBR->eraseFromParent();
00903 
00904   LoopProcessWorklist.push_back(NewLoop);
00905   redoLoop = true;
00906 
00907   // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
00908   // deletes the instruction (for example by simplifying a PHI that feeds into
00909   // the condition that we're unswitching on), we don't rewrite the second
00910   // iteration.
00911   WeakVH LICHandle(LIC);
00912 
00913   // Now we rewrite the original code to know that the condition is true and the
00914   // new code to know that the condition is false.
00915   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
00916 
00917   // It's possible that simplifying one loop could cause the other to be
00918   // changed to another value or a constant.  If its a constant, don't simplify
00919   // it.
00920   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
00921       LICHandle && !isa<Constant>(LICHandle))
00922     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
00923 }
00924 
00925 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
00926 /// specified.
00927 static void RemoveFromWorklist(Instruction *I,
00928                                std::vector<Instruction*> &Worklist) {
00929 
00930   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
00931                  Worklist.end());
00932 }
00933 
00934 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
00935 /// program, replacing all uses with V and update the worklist.
00936 static void ReplaceUsesOfWith(Instruction *I, Value *V,
00937                               std::vector<Instruction*> &Worklist,
00938                               Loop *L, LPPassManager *LPM) {
00939   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
00940 
00941   // Add uses to the worklist, which may be dead now.
00942   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00943     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
00944       Worklist.push_back(Use);
00945 
00946   // Add users to the worklist which may be simplified now.
00947   for (User *U : I->users())
00948     Worklist.push_back(cast<Instruction>(U));
00949   LPM->deleteSimpleAnalysisValue(I, L);
00950   RemoveFromWorklist(I, Worklist);
00951   I->replaceAllUsesWith(V);
00952   I->eraseFromParent();
00953   ++NumSimplify;
00954 }
00955 
00956 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
00957 // the value specified by Val in the specified loop, or we know it does NOT have
00958 // that value.  Rewrite any uses of LIC or of properties correlated to it.
00959 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00960                                                         Constant *Val,
00961                                                         bool IsEqual) {
00962   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
00963 
00964   // FIXME: Support correlated properties, like:
00965   //  for (...)
00966   //    if (li1 < li2)
00967   //      ...
00968   //    if (li1 > li2)
00969   //      ...
00970 
00971   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
00972   // selects, switches.
00973   std::vector<Instruction*> Worklist;
00974   LLVMContext &Context = Val->getContext();
00975 
00976   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
00977   // in the loop with the appropriate one directly.
00978   if (IsEqual || (isa<ConstantInt>(Val) &&
00979       Val->getType()->isIntegerTy(1))) {
00980     Value *Replacement;
00981     if (IsEqual)
00982       Replacement = Val;
00983     else
00984       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
00985                                      !cast<ConstantInt>(Val)->getZExtValue());
00986 
00987     for (User *U : LIC->users()) {
00988       Instruction *UI = dyn_cast<Instruction>(U);
00989       if (!UI || !L->contains(UI))
00990         continue;
00991       Worklist.push_back(UI);
00992     }
00993 
00994     for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
00995          UE = Worklist.end(); UI != UE; ++UI)
00996       (*UI)->replaceUsesOfWith(LIC, Replacement);
00997 
00998     SimplifyCode(Worklist, L);
00999     return;
01000   }
01001 
01002   // Otherwise, we don't know the precise value of LIC, but we do know that it
01003   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
01004   // can.  This case occurs when we unswitch switch statements.
01005   for (User *U : LIC->users()) {
01006     Instruction *UI = dyn_cast<Instruction>(U);
01007     if (!UI || !L->contains(UI))
01008       continue;
01009 
01010     Worklist.push_back(UI);
01011 
01012     // TODO: We could do other simplifications, for example, turning
01013     // 'icmp eq LIC, Val' -> false.
01014 
01015     // If we know that LIC is not Val, use this info to simplify code.
01016     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
01017     if (!SI || !isa<ConstantInt>(Val)) continue;
01018 
01019     SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
01020     // Default case is live for multiple values.
01021     if (DeadCase == SI->case_default()) continue;
01022 
01023     // Found a dead case value.  Don't remove PHI nodes in the
01024     // successor if they become single-entry, those PHI nodes may
01025     // be in the Users list.
01026 
01027     BasicBlock *Switch = SI->getParent();
01028     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
01029     BasicBlock *Latch = L->getLoopLatch();
01030 
01031     BranchesInfo.setUnswitched(SI, Val);
01032 
01033     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
01034     // If the DeadCase successor dominates the loop latch, then the
01035     // transformation isn't safe since it will delete the sole predecessor edge
01036     // to the latch.
01037     if (Latch && DT->dominates(SISucc, Latch))
01038       continue;
01039 
01040     // FIXME: This is a hack.  We need to keep the successor around
01041     // and hooked up so as to preserve the loop structure, because
01042     // trying to update it is complicated.  So instead we preserve the
01043     // loop structure and put the block on a dead code path.
01044     SplitEdge(Switch, SISucc, DT, LI);
01045     // Compute the successors instead of relying on the return value
01046     // of SplitEdge, since it may have split the switch successor
01047     // after PHI nodes.
01048     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
01049     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
01050     // Create an "unreachable" destination.
01051     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
01052                                            Switch->getParent(),
01053                                            OldSISucc);
01054     new UnreachableInst(Context, Abort);
01055     // Force the new case destination to branch to the "unreachable"
01056     // block while maintaining a (dead) CFG edge to the old block.
01057     NewSISucc->getTerminator()->eraseFromParent();
01058     BranchInst::Create(Abort, OldSISucc,
01059                        ConstantInt::getTrue(Context), NewSISucc);
01060     // Release the PHI operands for this edge.
01061     for (BasicBlock::iterator II = NewSISucc->begin();
01062          PHINode *PN = dyn_cast<PHINode>(II); ++II)
01063       PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
01064                            UndefValue::get(PN->getType()));
01065     // Tell the domtree about the new block. We don't fully update the
01066     // domtree here -- instead we force it to do a full recomputation
01067     // after the pass is complete -- but we do need to inform it of
01068     // new blocks.
01069     if (DT)
01070       DT->addNewBlock(Abort, NewSISucc);
01071   }
01072 
01073   SimplifyCode(Worklist, L);
01074 }
01075 
01076 /// SimplifyCode - Okay, now that we have simplified some instructions in the
01077 /// loop, walk over it and constant prop, dce, and fold control flow where
01078 /// possible.  Note that this is effectively a very simple loop-structure-aware
01079 /// optimizer.  During processing of this loop, L could very well be deleted, so
01080 /// it must not be used.
01081 ///
01082 /// FIXME: When the loop optimizer is more mature, separate this out to a new
01083 /// pass.
01084 ///
01085 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
01086   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
01087   while (!Worklist.empty()) {
01088     Instruction *I = Worklist.back();
01089     Worklist.pop_back();
01090 
01091     // Simple DCE.
01092     if (isInstructionTriviallyDead(I)) {
01093       DEBUG(dbgs() << "Remove dead instruction '" << *I);
01094 
01095       // Add uses to the worklist, which may be dead now.
01096       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01097         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
01098           Worklist.push_back(Use);
01099       LPM->deleteSimpleAnalysisValue(I, L);
01100       RemoveFromWorklist(I, Worklist);
01101       I->eraseFromParent();
01102       ++NumSimplify;
01103       continue;
01104     }
01105 
01106     // See if instruction simplification can hack this up.  This is common for
01107     // things like "select false, X, Y" after unswitching made the condition be
01108     // 'false'.  TODO: update the domtree properly so we can pass it here.
01109     if (Value *V = SimplifyInstruction(I, DL))
01110       if (LI->replacementPreservesLCSSAForm(I, V)) {
01111         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
01112         continue;
01113       }
01114 
01115     // Special case hacks that appear commonly in unswitched code.
01116     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
01117       if (BI->isUnconditional()) {
01118         // If BI's parent is the only pred of the successor, fold the two blocks
01119         // together.
01120         BasicBlock *Pred = BI->getParent();
01121         BasicBlock *Succ = BI->getSuccessor(0);
01122         BasicBlock *SinglePred = Succ->getSinglePredecessor();
01123         if (!SinglePred) continue;  // Nothing to do.
01124         assert(SinglePred == Pred && "CFG broken");
01125 
01126         DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
01127               << Succ->getName() << "\n");
01128 
01129         // Resolve any single entry PHI nodes in Succ.
01130         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
01131           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
01132 
01133         // If Succ has any successors with PHI nodes, update them to have
01134         // entries coming from Pred instead of Succ.
01135         Succ->replaceAllUsesWith(Pred);
01136 
01137         // Move all of the successor contents from Succ to Pred.
01138         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
01139                                    Succ->end());
01140         LPM->deleteSimpleAnalysisValue(BI, L);
01141         BI->eraseFromParent();
01142         RemoveFromWorklist(BI, Worklist);
01143 
01144         // Remove Succ from the loop tree.
01145         LI->removeBlock(Succ);
01146         LPM->deleteSimpleAnalysisValue(Succ, L);
01147         Succ->eraseFromParent();
01148         ++NumSimplify;
01149         continue;
01150       }
01151 
01152       continue;
01153     }
01154   }
01155 }