LLVM API Documentation

JumpThreading.cpp

Go to the documentation of this file.
00001 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 file implements the Jump Threading pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "jump-threading"
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/IntrinsicInst.h"
00017 #include "llvm/Pass.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/ADT/STLExtras.h"
00021 #include "llvm/Analysis/ConstantFolding.h"
00022 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00023 #include "llvm/Transforms/Utils/Local.h"
00024 #include "llvm/Target/TargetData.h"
00025 #include "llvm/Support/CommandLine.h"
00026 #include "llvm/Support/Compiler.h"
00027 #include "llvm/Support/Debug.h"
00028 #include "llvm/ADT/SmallPtrSet.h"
00029 using namespace llvm;
00030 
00031 STATISTIC(NumThreads, "Number of jumps threaded");
00032 STATISTIC(NumFolds,   "Number of terminators folded");
00033 
00034 static cl::opt<unsigned>
00035 Threshold("jump-threading-threshold", 
00036           cl::desc("Max block size to duplicate for jump threading"),
00037           cl::init(6), cl::Hidden);
00038 
00039 namespace {
00040   /// This pass performs 'jump threading', which looks at blocks that have
00041   /// multiple predecessors and multiple successors.  If one or more of the
00042   /// predecessors of the block can be proven to always jump to one of the
00043   /// successors, we forward the edge from the predecessor to the successor by
00044   /// duplicating the contents of this block.
00045   ///
00046   /// An example of when this can occur is code like this:
00047   ///
00048   ///   if () { ...
00049   ///     X = 4;
00050   ///   }
00051   ///   if (X < 3) {
00052   ///
00053   /// In this case, the unconditional branch at the end of the first if can be
00054   /// revectored to the false side of the second if.
00055   ///
00056   class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
00057     TargetData *TD;
00058   public:
00059     static char ID; // Pass identification
00060     JumpThreading() : FunctionPass(&ID) {}
00061 
00062     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00063       AU.addRequired<TargetData>();
00064     }
00065 
00066     bool runOnFunction(Function &F);
00067     bool ProcessBlock(BasicBlock *BB);
00068     void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
00069     BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
00070     bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
00071     bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
00072 
00073     bool ProcessJumpOnPHI(PHINode *PN);
00074     bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
00075     bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
00076     
00077     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
00078   };
00079 }
00080 
00081 char JumpThreading::ID = 0;
00082 static RegisterPass<JumpThreading>
00083 X("jump-threading", "Jump Threading");
00084 
00085 // Public interface to the Jump Threading pass
00086 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
00087 
00088 /// runOnFunction - Top level algorithm.
00089 ///
00090 bool JumpThreading::runOnFunction(Function &F) {
00091   DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
00092   TD = &getAnalysis<TargetData>();
00093   
00094   bool AnotherIteration = true, EverChanged = false;
00095   while (AnotherIteration) {
00096     AnotherIteration = false;
00097     bool Changed = false;
00098     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
00099       BasicBlock *BB = I;
00100       while (ProcessBlock(BB))
00101         Changed = true;
00102       
00103       ++I;
00104       
00105       // If the block is trivially dead, zap it.  This eliminates the successor
00106       // edges which simplifies the CFG.
00107       if (pred_begin(BB) == pred_end(BB) &&
00108           BB != &BB->getParent()->getEntryBlock()) {
00109         DOUT << "  JT: Deleting dead block '" << BB->getNameStart()
00110              << "' with terminator: " << *BB->getTerminator();
00111         DeleteDeadBlock(BB);
00112         Changed = true;
00113       }
00114     }
00115     AnotherIteration = Changed;
00116     EverChanged |= Changed;
00117   }
00118   return EverChanged;
00119 }
00120 
00121 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
00122 /// value for the PHI, factor them together so we get one block to thread for
00123 /// the whole group.
00124 /// This is important for things like "phi i1 [true, true, false, true, x]"
00125 /// where we only need to clone the block for the true blocks once.
00126 ///
00127 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
00128   SmallVector<BasicBlock*, 16> CommonPreds;
00129   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00130     if (PN->getIncomingValue(i) == CstVal)
00131       CommonPreds.push_back(PN->getIncomingBlock(i));
00132   
00133   if (CommonPreds.size() == 1)
00134     return CommonPreds[0];
00135     
00136   DOUT << "  Factoring out " << CommonPreds.size()
00137        << " common predecessors.\n";
00138   return SplitBlockPredecessors(PN->getParent(),
00139                                 &CommonPreds[0], CommonPreds.size(),
00140                                 ".thr_comm", this);
00141 }
00142   
00143 
00144 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
00145 /// thread across it.
00146 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
00147   /// Ignore PHI nodes, these will be flattened when duplication happens.
00148   BasicBlock::const_iterator I = BB->getFirstNonPHI();
00149 
00150   // Sum up the cost of each instruction until we get to the terminator.  Don't
00151   // include the terminator because the copy won't include it.
00152   unsigned Size = 0;
00153   for (; !isa<TerminatorInst>(I); ++I) {
00154     // Debugger intrinsics don't incur code size.
00155     if (isa<DbgInfoIntrinsic>(I)) continue;
00156     
00157     // If this is a pointer->pointer bitcast, it is free.
00158     if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
00159       continue;
00160     
00161     // All other instructions count for at least one unit.
00162     ++Size;
00163     
00164     // Calls are more expensive.  If they are non-intrinsic calls, we model them
00165     // as having cost of 4.  If they are a non-vector intrinsic, we model them
00166     // as having cost of 2 total, and if they are a vector intrinsic, we model
00167     // them as having cost 1.
00168     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00169       if (!isa<IntrinsicInst>(CI))
00170         Size += 3;
00171       else if (isa<VectorType>(CI->getType()))
00172         Size += 1;
00173     }
00174   }
00175   
00176   // Threading through a switch statement is particularly profitable.  If this
00177   // block ends in a switch, decrease its cost to make it more likely to happen.
00178   if (isa<SwitchInst>(I))
00179     Size = Size > 6 ? Size-6 : 0;
00180   
00181   return Size;
00182 }
00183 
00184 /// ProcessBlock - If there are any predecessors whose control can be threaded
00185 /// through to a successor, transform them now.
00186 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
00187   // If this block has a single predecessor, and if that pred has a single
00188   // successor, merge the blocks.  This encourages recursive jump threading
00189   // because now the condition in this block can be threaded through
00190   // predecessors of our predecessor block.
00191   if (BasicBlock *SinglePred = BB->getSinglePredecessor())
00192     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
00193         SinglePred != BB) {
00194       // Remember if SinglePred was the entry block of the function.  If so, we
00195       // will need to move BB back to the entry position.
00196       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00197       MergeBasicBlockIntoOnlyPred(BB);
00198       
00199       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00200         BB->moveBefore(&BB->getParent()->getEntryBlock());
00201       return true;
00202     }
00203   
00204   // See if this block ends with a branch or switch.  If so, see if the
00205   // condition is a phi node.  If so, and if an entry of the phi node is a
00206   // constant, we can thread the block.
00207   Value *Condition;
00208   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
00209     // Can't thread an unconditional jump.
00210     if (BI->isUnconditional()) return false;
00211     Condition = BI->getCondition();
00212   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
00213     Condition = SI->getCondition();
00214   else
00215     return false; // Must be an invoke.
00216   
00217   // If the terminator of this block is branching on a constant, simplify the
00218   // terminator to an unconditional branch.  This can occur due to threading in
00219   // other blocks.
00220   if (isa<ConstantInt>(Condition)) {
00221     DOUT << "  In block '" << BB->getNameStart()
00222          << "' folding terminator: " << *BB->getTerminator();
00223     ++NumFolds;
00224     ConstantFoldTerminator(BB);
00225     return true;
00226   }
00227   
00228   // If the terminator is branching on an undef, we can pick any of the
00229   // successors to branch to.  Since this is arbitrary, we pick the successor
00230   // with the fewest predecessors.  This should reduce the in-degree of the
00231   // others.
00232   if (isa<UndefValue>(Condition)) {
00233     TerminatorInst *BBTerm = BB->getTerminator();
00234     unsigned MinSucc = 0;
00235     BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
00236     // Compute the successor with the minimum number of predecessors.
00237     unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00238     for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00239       TestBB = BBTerm->getSuccessor(i);
00240       unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00241       if (NumPreds < MinNumPreds)
00242         MinSucc = i;
00243     }
00244     
00245     // Fold the branch/switch.
00246     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00247       if (i == MinSucc) continue;
00248       BBTerm->getSuccessor(i)->removePredecessor(BB);
00249     }
00250     
00251     DOUT << "  In block '" << BB->getNameStart()
00252          << "' folding undef terminator: " << *BBTerm;
00253     BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
00254     BBTerm->eraseFromParent();
00255     return true;
00256   }
00257   
00258   Instruction *CondInst = dyn_cast<Instruction>(Condition);
00259 
00260   // If the condition is an instruction defined in another block, see if a
00261   // predecessor has the same condition:
00262   //     br COND, BBX, BBY
00263   //  BBX:
00264   //     br COND, BBZ, BBW
00265   if (!Condition->hasOneUse() && // Multiple uses.
00266       (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
00267     pred_iterator PI = pred_begin(BB), E = pred_end(BB);
00268     if (isa<BranchInst>(BB->getTerminator())) {
00269       for (; PI != E; ++PI)
00270         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
00271           if (PBI->isConditional() && PBI->getCondition() == Condition &&
00272               ProcessBranchOnDuplicateCond(*PI, BB))
00273             return true;
00274     } else {
00275       assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
00276       for (; PI != E; ++PI)
00277         if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
00278           if (PSI->getCondition() == Condition &&
00279               ProcessSwitchOnDuplicateCond(*PI, BB))
00280             return true;
00281     }
00282   }
00283 
00284   // If there is only a single predecessor of this block, nothing to fold.
00285   if (BB->getSinglePredecessor())
00286     return false;
00287   
00288   // All the rest of our checks depend on the condition being an instruction.
00289   if (CondInst == 0)
00290     return false;
00291   
00292   // See if this is a phi node in the current block.
00293   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
00294     if (PN->getParent() == BB)
00295       return ProcessJumpOnPHI(PN);
00296   
00297   // If this is a conditional branch whose condition is and/or of a phi, try to
00298   // simplify it.
00299   if ((CondInst->getOpcode() == Instruction::And || 
00300        CondInst->getOpcode() == Instruction::Or) &&
00301       isa<BranchInst>(BB->getTerminator()) &&
00302       ProcessBranchOnLogical(CondInst, BB,
00303                              CondInst->getOpcode() == Instruction::And))
00304     return true;
00305   
00306   // If we have "br (phi != 42)" and the phi node has any constant values as 
00307   // operands, we can thread through this block.
00308   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst))
00309     if (isa<PHINode>(CondCmp->getOperand(0)) &&
00310         isa<Constant>(CondCmp->getOperand(1)) &&
00311         ProcessBranchOnCompare(CondCmp, BB))
00312       return true;
00313 
00314   // Check for some cases that are worth simplifying.  Right now we want to look
00315   // for loads that are used by a switch or by the condition for the branch.  If
00316   // we see one, check to see if it's partially redundant.  If so, insert a PHI
00317   // which can then be used to thread the values.
00318   //
00319   // This is particularly important because reg2mem inserts loads and stores all
00320   // over the place, and this blocks jump threading if we don't zap them.
00321   Value *SimplifyValue = CondInst;
00322   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
00323     if (isa<Constant>(CondCmp->getOperand(1)))
00324       SimplifyValue = CondCmp->getOperand(0);
00325   
00326   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
00327     if (SimplifyPartiallyRedundantLoad(LI))
00328       return true;
00329   
00330   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
00331   // "(X == 4)" thread through this block.
00332   
00333   return false;
00334 }
00335 
00336 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
00337 /// block that jump on exactly the same condition.  This means that we almost
00338 /// always know the direction of the edge in the DESTBB:
00339 ///  PREDBB:
00340 ///     br COND, DESTBB, BBY
00341 ///  DESTBB:
00342 ///     br COND, BBZ, BBW
00343 ///
00344 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
00345 /// in DESTBB, we have to thread over it.
00346 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
00347                                                  BasicBlock *BB) {
00348   BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
00349   
00350   // If both successors of PredBB go to DESTBB, we don't know anything.  We can
00351   // fold the branch to an unconditional one, which allows other recursive
00352   // simplifications.
00353   bool BranchDir;
00354   if (PredBI->getSuccessor(1) != BB)
00355     BranchDir = true;
00356   else if (PredBI->getSuccessor(0) != BB)
00357     BranchDir = false;
00358   else {
00359     DOUT << "  In block '" << PredBB->getNameStart()
00360          << "' folding terminator: " << *PredBB->getTerminator();
00361     ++NumFolds;
00362     ConstantFoldTerminator(PredBB);
00363     return true;
00364   }
00365    
00366   BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
00367 
00368   // If the dest block has one predecessor, just fix the branch condition to a
00369   // constant and fold it.
00370   if (BB->getSinglePredecessor()) {
00371     DOUT << "  In block '" << BB->getNameStart()
00372          << "' folding condition to '" << BranchDir << "': "
00373          << *BB->getTerminator();
00374     ++NumFolds;
00375     DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
00376     ConstantFoldTerminator(BB);
00377     return true;
00378   }
00379   
00380   // Otherwise we need to thread from PredBB to DestBB's successor which
00381   // involves code duplication.  Check to see if it is worth it.
00382   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
00383   if (JumpThreadCost > Threshold) {
00384     DOUT << "  Not threading BB '" << BB->getNameStart()
00385          << "' - Cost is too high: " << JumpThreadCost << "\n";
00386     return false;
00387   }
00388   
00389   // Next, figure out which successor we are threading to.
00390   BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
00391   
00392   // If threading to the same block as we come from, we would infinite loop.
00393   if (SuccBB == BB) {
00394     DOUT << "  Not threading BB '" << BB->getNameStart()
00395          << "' - would thread to self!\n";
00396     return false;
00397   }
00398   
00399   // And finally, do it!
00400   DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
00401        << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
00402        << ", across block:\n    "
00403        << *BB << "\n";
00404   
00405   ThreadEdge(BB, PredBB, SuccBB);
00406   ++NumThreads;
00407   return true;
00408 }
00409 
00410 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
00411 /// block that switch on exactly the same condition.  This means that we almost
00412 /// always know the direction of the edge in the DESTBB:
00413 ///  PREDBB:
00414 ///     switch COND [... DESTBB, BBY ... ]
00415 ///  DESTBB:
00416 ///     switch COND [... BBZ, BBW ]
00417 ///
00418 /// Optimizing switches like this is very important, because simplifycfg builds
00419 /// switches out of repeated 'if' conditions.
00420 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
00421                                                  BasicBlock *DestBB) {
00422   // Can't thread edge to self.
00423   if (PredBB == DestBB)
00424     return false;
00425   
00426   
00427   SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
00428   SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
00429 
00430   // There are a variety of optimizations that we can potentially do on these
00431   // blocks: we order them from most to least preferable.
00432   
00433   // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
00434   // directly to their destination.  This does not introduce *any* code size
00435   // growth.
00436   
00437   // FIXME: Thread if it just contains a PHI.
00438   if (isa<SwitchInst>(DestBB->begin())) {
00439     bool MadeChange = false;
00440     // Ignore the default edge for now.
00441     for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
00442       ConstantInt *DestVal = DestSI->getCaseValue(i);
00443       BasicBlock *DestSucc = DestSI->getSuccessor(i);
00444       
00445       // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
00446       // PredSI has an explicit case for it.  If so, forward.  If it is covered
00447       // by the default case, we can't update PredSI.
00448       unsigned PredCase = PredSI->findCaseValue(DestVal);
00449       if (PredCase == 0) continue;
00450       
00451       // If PredSI doesn't go to DestBB on this value, then it won't reach the
00452       // case on this condition.
00453       if (PredSI->getSuccessor(PredCase) != DestBB &&
00454           DestSI->getSuccessor(i) != DestBB)
00455         continue;
00456 
00457       // Otherwise, we're safe to make the change.  Make sure that the edge from
00458       // DestSI to DestSucc is not critical and has no PHI nodes.
00459       DOUT << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI;
00460       DOUT << "THROUGH: " << *DestSI;
00461 
00462       // If the destination has PHI nodes, just split the edge for updating
00463       // simplicity.
00464       if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
00465         SplitCriticalEdge(DestSI, i, this);
00466         DestSucc = DestSI->getSuccessor(i);
00467       }
00468       FoldSingleEntryPHINodes(DestSucc);
00469       PredSI->setSuccessor(PredCase, DestSucc);
00470       MadeChange = true;
00471     }
00472     
00473     if (MadeChange)
00474       return true;
00475   }
00476   
00477   return false;
00478 }
00479 
00480 
00481 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
00482 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
00483 /// important optimization that encourages jump threading, and needs to be run
00484 /// interlaced with other jump threading tasks.
00485 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
00486   // Don't hack volatile loads.
00487   if (LI->isVolatile()) return false;
00488   
00489   // If the load is defined in a block with exactly one predecessor, it can't be
00490   // partially redundant.
00491   BasicBlock *LoadBB = LI->getParent();
00492   if (LoadBB->getSinglePredecessor())
00493     return false;
00494   
00495   Value *LoadedPtr = LI->getOperand(0);
00496 
00497   // If the loaded operand is defined in the LoadBB, it can't be available.
00498   // FIXME: Could do PHI translation, that would be fun :)
00499   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
00500     if (PtrOp->getParent() == LoadBB)
00501       return false;
00502   
00503   // Scan a few instructions up from the load, to see if it is obviously live at
00504   // the entry to its block.
00505   BasicBlock::iterator BBIt = LI;
00506 
00507   if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 
00508                                                      BBIt, 6)) {
00509     // If the value if the load is locally available within the block, just use
00510     // it.  This frequently occurs for reg2mem'd allocas.
00511     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
00512     
00513     // If the returned value is the load itself, replace with an undef. This can
00514     // only happen in dead loops.
00515     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
00516     LI->replaceAllUsesWith(AvailableVal);
00517     LI->eraseFromParent();
00518     return true;
00519   }
00520 
00521   // Otherwise, if we scanned the whole block and got to the top of the block,
00522   // we know the block is locally transparent to the load.  If not, something
00523   // might clobber its value.
00524   if (BBIt != LoadBB->begin())
00525     return false;
00526   
00527   
00528   SmallPtrSet<BasicBlock*, 8> PredsScanned;
00529   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
00530   AvailablePredsTy AvailablePreds;
00531   BasicBlock *OneUnavailablePred = 0;
00532   
00533   // If we got here, the loaded value is transparent through to the start of the
00534   // block.  Check to see if it is available in any of the predecessor blocks.
00535   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00536        PI != PE; ++PI) {
00537     BasicBlock *PredBB = *PI;
00538 
00539     // If we already scanned this predecessor, skip it.
00540     if (!PredsScanned.insert(PredBB))
00541       continue;
00542 
00543     // Scan the predecessor to see if the value is available in the pred.
00544     BBIt = PredBB->end();
00545     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
00546     if (!PredAvailable) {
00547       OneUnavailablePred = PredBB;
00548       continue;
00549     }
00550     
00551     // If so, this load is partially redundant.  Remember this info so that we
00552     // can create a PHI node.
00553     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
00554   }
00555   
00556   // If the loaded value isn't available in any predecessor, it isn't partially
00557   // redundant.
00558   if (AvailablePreds.empty()) return false;
00559   
00560   // Okay, the loaded value is available in at least one (and maybe all!)
00561   // predecessors.  If the value is unavailable in more than one unique
00562   // predecessor, we want to insert a merge block for those common predecessors.
00563   // This ensures that we only have to insert one reload, thus not increasing
00564   // code size.
00565   BasicBlock *UnavailablePred = 0;
00566   
00567   // If there is exactly one predecessor where the value is unavailable, the
00568   // already computed 'OneUnavailablePred' block is it.  If it ends in an
00569   // unconditional branch, we know that it isn't a critical edge.
00570   if (PredsScanned.size() == AvailablePreds.size()+1 &&
00571       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
00572     UnavailablePred = OneUnavailablePred;
00573   } else if (PredsScanned.size() != AvailablePreds.size()) {
00574     // Otherwise, we had multiple unavailable predecessors or we had a critical
00575     // edge from the one.
00576     SmallVector<BasicBlock*, 8> PredsToSplit;
00577     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
00578 
00579     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
00580       AvailablePredSet.insert(AvailablePreds[i].first);
00581 
00582     // Add all the unavailable predecessors to the PredsToSplit list.
00583     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00584          PI != PE; ++PI)
00585       if (!AvailablePredSet.count(*PI))
00586         PredsToSplit.push_back(*PI);
00587     
00588     // Split them out to their own block.
00589     UnavailablePred =
00590       SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
00591                              "thread-split", this);
00592   }
00593   
00594   // If the value isn't available in all predecessors, then there will be
00595   // exactly one where it isn't available.  Insert a load on that edge and add
00596   // it to the AvailablePreds list.
00597   if (UnavailablePred) {
00598     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
00599            "Can't handle critical edge here!");
00600     Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
00601                                  UnavailablePred->getTerminator());
00602     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
00603   }
00604   
00605   // Now we know that each predecessor of this block has a value in
00606   // AvailablePreds, sort them for efficient access as we're walking the preds.
00607   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
00608   
00609   // Create a PHI node at the start of the block for the PRE'd load value.
00610   PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
00611   PN->takeName(LI);
00612   
00613   // Insert new entries into the PHI for each predecessor.  A single block may
00614   // have multiple entries here.
00615   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
00616        ++PI) {
00617     AvailablePredsTy::iterator I = 
00618       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
00619                        std::make_pair(*PI, (Value*)0));
00620     
00621     assert(I != AvailablePreds.end() && I->first == *PI &&
00622            "Didn't find entry for predecessor!");
00623     
00624     PN->addIncoming(I->second, I->first);
00625   }
00626   
00627   //cerr << "PRE: " << *LI << *PN << "\n";
00628   
00629   LI->replaceAllUsesWith(PN);
00630   LI->eraseFromParent();
00631   
00632   return true;
00633 }
00634 
00635 
00636 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
00637 /// the current block.  See if there are any simplifications we can do based on
00638 /// inputs to the phi node.
00639 /// 
00640 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
00641   // See if the phi node has any constant values.  If so, we can determine where
00642   // the corresponding predecessor will branch.
00643   ConstantInt *PredCst = 0;
00644   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00645     if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
00646       break;
00647   
00648   // If no incoming value has a constant, we don't know the destination of any
00649   // predecessors.
00650   if (PredCst == 0)
00651     return false;
00652   
00653   // See if the cost of duplicating this block is low enough.
00654   BasicBlock *BB = PN->getParent();
00655   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
00656   if (JumpThreadCost > Threshold) {
00657     DOUT << "  Not threading BB '" << BB->getNameStart()
00658          << "' - Cost is too high: " << JumpThreadCost << "\n";
00659     return false;
00660   }
00661   
00662   // If so, we can actually do this threading.  Merge any common predecessors
00663   // that will act the same.
00664   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
00665   
00666   // Next, figure out which successor we are threading to.
00667   BasicBlock *SuccBB;
00668   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
00669     SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
00670   else {
00671     SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
00672     SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
00673   }
00674   
00675   // If threading to the same block as we come from, we would infinite loop.
00676   if (SuccBB == BB) {
00677     DOUT << "  Not threading BB '" << BB->getNameStart()
00678          << "' - would thread to self!\n";
00679     return false;
00680   }
00681   
00682   // And finally, do it!
00683   DOUT << "  Threading edge from '" << PredBB->getNameStart() << "' to '"
00684        << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
00685        << ", across block:\n    "
00686        << *BB << "\n";
00687        
00688   ThreadEdge(BB, PredBB, SuccBB);
00689   ++NumThreads;
00690   return true;
00691 }
00692 
00693 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
00694 /// whose condition is an AND/OR where one side is PN.  If PN has constant
00695 /// operands that permit us to evaluate the condition for some operand, thread
00696 /// through the block.  For example with:
00697 ///   br (and X, phi(Y, Z, false))
00698 /// the predecessor corresponding to the 'false' will always jump to the false
00699 /// destination of the branch.
00700 ///
00701 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
00702                                            bool isAnd) {
00703   // If this is a binary operator tree of the same AND/OR opcode, check the
00704   // LHS/RHS.
00705   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
00706     if ((isAnd && BO->getOpcode() == Instruction::And) ||
00707         (!isAnd && BO->getOpcode() == Instruction::Or)) {
00708       if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
00709         return true;
00710       if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
00711         return true;
00712     }
00713       
00714   // If this isn't a PHI node, we can't handle it.
00715   PHINode *PN = dyn_cast<PHINode>(V);
00716   if (!PN || PN->getParent() != BB) return false;
00717                                              
00718   // We can only do the simplification for phi nodes of 'false' with AND or
00719   // 'true' with OR.  See if we have any entries in the phi for this.
00720   unsigned PredNo = ~0U;
00721   ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
00722   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00723     if (PN->getIncomingValue(i) == PredCst) {
00724       PredNo = i;
00725       break;
00726     }
00727   }
00728   
00729   // If no match, bail out.
00730   if (PredNo == ~0U)
00731     return false;
00732   
00733   // See if the cost of duplicating this block is low enough.
00734   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
00735   if (JumpThreadCost > Threshold) {
00736     DOUT << "  Not threading BB '" << BB->getNameStart()
00737          << "' - Cost is too high: " << JumpThreadCost << "\n";
00738     return false;
00739   }
00740 
00741   // If so, we can actually do this threading.  Merge any common predecessors
00742   // that will act the same.
00743   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
00744   
00745   // Next, figure out which successor we are threading to.  If this was an AND,
00746   // the constant must be FALSE, and we must be targeting the 'false' block.
00747   // If this is an OR, the constant must be TRUE, and we must be targeting the
00748   // 'true' block.
00749   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
00750   
00751   // If threading to the same block as we come from, we would infinite loop.
00752   if (SuccBB == BB) {
00753     DOUT << "  Not threading BB '" << BB->getNameStart()
00754     << "' - would thread to self!\n";
00755     return false;
00756   }
00757   
00758   // And finally, do it!
00759   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
00760        << "' to '" << SuccBB->getNameStart() << "' with cost: "
00761        << JumpThreadCost << ", across block:\n    "
00762        << *BB << "\n";
00763   
00764   ThreadEdge(BB, PredBB, SuccBB);
00765   ++NumThreads;
00766   return true;
00767 }
00768 
00769 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
00770 /// node and a constant.  If the PHI node contains any constants as inputs, we
00771 /// can fold the compare for that edge and thread through it.
00772 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
00773   PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
00774   Constant *RHS = cast<Constant>(Cmp->getOperand(1));
00775   
00776   // If the phi isn't in the current block, an incoming edge to this block
00777   // doesn't control the destination.
00778   if (PN->getParent() != BB)
00779     return false;
00780   
00781   // We can do this simplification if any comparisons fold to true or false.
00782   // See if any do.
00783   Constant *PredCst = 0;
00784   bool TrueDirection = false;
00785   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00786     PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
00787     if (PredCst == 0) continue;
00788     
00789     Constant *Res;
00790     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
00791       Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
00792     else
00793       Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
00794                                   PredCst, RHS);
00795     // If this folded to a constant expr, we can't do anything.
00796     if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
00797       TrueDirection = ResC->getZExtValue();
00798       break;
00799     }
00800     // If this folded to undef, just go the false way.
00801     if (isa<UndefValue>(Res)) {
00802       TrueDirection = false;
00803       break;
00804     }
00805     
00806     // Otherwise, we can't fold this input.
00807     PredCst = 0;
00808   }
00809   
00810   // If no match, bail out.
00811   if (PredCst == 0)
00812     return false;
00813   
00814   // See if the cost of duplicating this block is low enough.
00815   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
00816   if (JumpThreadCost > Threshold) {
00817     DOUT << "  Not threading BB '" << BB->getNameStart()
00818          << "' - Cost is too high: " << JumpThreadCost << "\n";
00819     return false;
00820   }
00821   
00822   // If so, we can actually do this threading.  Merge any common predecessors
00823   // that will act the same.
00824   BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
00825   
00826   // Next, get our successor.
00827   BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
00828   
00829   // If threading to the same block as we come from, we would infinite loop.
00830   if (SuccBB == BB) {
00831     DOUT << "  Not threading BB '" << BB->getNameStart()
00832     << "' - would thread to self!\n";
00833     return false;
00834   }
00835   
00836   
00837   // And finally, do it!
00838   DOUT << "  Threading edge through bool from '" << PredBB->getNameStart()
00839        << "' to '" << SuccBB->getNameStart() << "' with cost: "
00840        << JumpThreadCost << ", across block:\n    "
00841        << *BB << "\n";
00842   
00843   ThreadEdge(BB, PredBB, SuccBB);
00844   ++NumThreads;
00845   return true;
00846 }
00847 
00848 
00849 /// ThreadEdge - We have decided that it is safe and profitable to thread an
00850 /// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
00851 /// change.
00852 void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, 
00853                                BasicBlock *SuccBB) {
00854 
00855   // Jump Threading can not update SSA properties correctly if the values
00856   // defined in the duplicated block are used outside of the block itself.  For
00857   // this reason, we spill all values that are used outside of BB to the stack.
00858   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
00859     if (!I->isUsedOutsideOfBlock(BB))
00860       continue;
00861     
00862     // We found a use of I outside of BB.  Create a new stack slot to
00863     // break this inter-block usage pattern.
00864     DemoteRegToStack(*I);
00865   }
00866  
00867   // We are going to have to map operands from the original BB block to the new
00868   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
00869   // account for entry from PredBB.
00870   DenseMap<Instruction*, Value*> ValueMapping;
00871   
00872   BasicBlock *NewBB =
00873     BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
00874   NewBB->moveAfter(PredBB);
00875   
00876   BasicBlock::iterator BI = BB->begin();
00877   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
00878     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
00879   
00880   // Clone the non-phi instructions of BB into NewBB, keeping track of the
00881   // mapping and using it to remap operands in the cloned instructions.
00882   for (; !isa<TerminatorInst>(BI); ++BI) {
00883     Instruction *New = BI->clone();
00884     New->setName(BI->getNameStart());
00885     NewBB->getInstList().push_back(New);
00886     ValueMapping[BI] = New;
00887    
00888     // Remap operands to patch up intra-block references.
00889     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
00890       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
00891         if (Value *Remapped = ValueMapping[Inst])
00892           New->setOperand(i, Remapped);
00893   }
00894   
00895   // We didn't copy the terminator from BB over to NewBB, because there is now
00896   // an unconditional jump to SuccBB.  Insert the unconditional jump.
00897   BranchInst::Create(SuccBB, NewBB);
00898   
00899   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
00900   // PHI nodes for NewBB now.
00901   for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
00902     PHINode *PN = cast<PHINode>(PNI);
00903     // Ok, we have a PHI node.  Figure out what the incoming value was for the
00904     // DestBlock.
00905     Value *IV = PN->getIncomingValueForBlock(BB);
00906     
00907     // Remap the value if necessary.
00908     if (Instruction *Inst = dyn_cast<Instruction>(IV))
00909       if (Value *MappedIV = ValueMapping[Inst])
00910         IV = MappedIV;
00911     PN->addIncoming(IV, NewBB);
00912   }
00913   
00914   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
00915   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
00916   // us to simplify any PHI nodes in BB.
00917   TerminatorInst *PredTerm = PredBB->getTerminator();
00918   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
00919     if (PredTerm->getSuccessor(i) == BB) {
00920       BB->removePredecessor(PredBB);
00921       PredTerm->setSuccessor(i, NewBB);
00922     }
00923   
00924   // At this point, the IR is fully up to date and consistent.  Do a quick scan
00925   // over the new instructions and zap any that are constants or dead.  This
00926   // frequently happens because of phi translation.
00927   BI = NewBB->begin();
00928   for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
00929     Instruction *Inst = BI++;
00930     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
00931       Inst->replaceAllUsesWith(C);
00932       Inst->eraseFromParent();
00933       continue;
00934     }
00935     
00936     RecursivelyDeleteTriviallyDeadInstructions(Inst);
00937   }
00938 }