LLVM API Documentation

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