JumpThreading.cpp revision c69908695af9cf509bf498a492854db5f0556e0f
18383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
28383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
38383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//                     The LLVM Compiler Infrastructure
48383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
58383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// This file is distributed under the University of Illinois Open Source
68383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// License. See LICENSE.TXT for details.
78383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
88383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
98383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
10177480b7ede0441135572d641a2497df25a7d95fChris Lattner// This file implements the Jump Threading pass.
118383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
128383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
138383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
148383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#define DEBUG_TYPE "jump-threading"
158383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Transforms/Scalar.h"
16fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/DenseMap.h"
17cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson#include "llvm/ADT/DenseSet.h"
18fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/STLExtras.h"
19fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallPtrSet.h"
20fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallSet.h"
21d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/Statistic.h"
22d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/ConstantFolding.h"
23d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/InstructionSimplify.h"
24d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/LazyValueInfo.h"
25d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/Loads.h"
26d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/DataLayout.h"
27d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/IntrinsicInst.h"
28d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/LLVMContext.h"
29d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Pass.h"
308383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Support/CommandLine.h"
31177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/Support/Debug.h"
325660846f15847e540066ae320a4adef7357d597dChris Lattner#include "llvm/Support/ValueHandle.h"
3393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar#include "llvm/Support/raw_ostream.h"
34d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Target/TargetLibraryInfo.h"
35d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Transforms/Utils/Local.h"
37d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Transforms/Utils/SSAUpdater.h"
388383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerusing namespace llvm;
398383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
40bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumThreads, "Number of jumps threaded");
41bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumFolds,   "Number of terminators folded");
4278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSTATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
438383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
44177480b7ede0441135572d641a2497df25a7d95fChris Lattnerstatic cl::opt<unsigned>
456f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van BommelThreshold("jump-threading-threshold",
46177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::desc("Max block size to duplicate for jump threading"),
47177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::init(6), cl::Hidden);
48177480b7ede0441135572d641a2497df25a7d95fChris Lattner
498383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnernamespace {
50ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // These are at global scope so static functions can use them too.
51ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
52ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
53ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel
546033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // This is used to keep track of what kind of constant we're currently hoping
556033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // to find.
566033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  enum ConstantPreference {
576033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    WantInteger,
586033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    WantBlockAddress
596033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  };
606033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel
6194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// This pass performs 'jump threading', which looks at blocks that have
6294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// multiple predecessors and multiple successors.  If one or more of the
6394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// predecessors of the block can be proven to always jump to one of the
6494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// successors, we forward the edge from the predecessor to the successor by
6594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// duplicating the contents of this block.
6694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
6794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// An example of when this can occur is code like this:
6894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
6994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if () { ...
7094019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///     X = 4;
7194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   }
7294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if (X < 3) {
7394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
7494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// In this case, the unconditional branch at the end of the first if can be
7594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// revectored to the false side of the second if.
7694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
773e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  class JumpThreading : public FunctionPass {
783574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow    DataLayout *TD;
79aab8e28d5e470711d80276bbf717408c3ab966fdChad Rosier    TargetLibraryInfo *TLI;
80cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    LazyValueInfo *LVI;
81fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#ifdef NDEBUG
82fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallPtrSet<BasicBlock*, 16> LoopHeaders;
83fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#else
84fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
85fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#endif
86cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson    DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
876f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
889ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson    // RAII helper for updating the recursion stack.
899ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson    struct RecursionSetRemover {
909ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
919ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      std::pair<Value*, BasicBlock*> ThePair;
926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
939ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
949ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson                          std::pair<Value*, BasicBlock*> P)
959ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson        : TheSet(S), ThePair(P) { }
966f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
979ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      ~RecursionSetRemover() {
989ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson        TheSet.erase(ThePair);
999ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      }
1009ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson    };
1018383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  public:
1028383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    static char ID; // Pass identification
103081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson    JumpThreading() : FunctionPass(ID) {
104081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson      initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
105081c34b725980f995be9080eaec24cd3dfaaf065Owen Anderson    }
1068383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
1078383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    bool runOnFunction(Function &F);
1086f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
109cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      AU.addRequired<LazyValueInfo>();
111c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      AU.addPreserved<LazyValueInfo>();
112aab8e28d5e470711d80276bbf717408c3ab966fdChad Rosier      AU.addRequired<TargetLibraryInfo>();
113cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    }
1146f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
115cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    void FindLoopHeaders(Function &F);
116c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    bool ProcessBlock(BasicBlock *BB);
1175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
1185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    BasicBlock *SuccBB);
11978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1202249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner                                  const SmallVectorImpl<BasicBlock *> &PredBBs);
1216f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
1236033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                         PredValueInfo &Result,
1246033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                         ConstantPreference Preference);
1256033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1266033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                ConstantPreference Preference);
1276f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12877beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner    bool ProcessBranchOnPHI(PHINode *PN);
1292249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    bool ProcessBranchOnXOR(BinaryOperator *BO);
1306f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
13169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
1328383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  };
1338383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
1348383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
135844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar JumpThreading::ID = 0;
1362ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
1372ab36d350293c77fc8941ce1023e4899df7e3a82Owen Anderson                "Jump Threading", false, false)
1382ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
139aab8e28d5e470711d80276bbf717408c3ab966fdChad RosierINITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1402ab36d350293c77fc8941ce1023e4899df7e3a82Owen AndersonINITIALIZE_PASS_END(JumpThreading, "jump-threading",
141ce665bd2e2b581ab0858d1afe359192bac96b868Owen Anderson                "Jump Threading", false, false)
142844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
1438383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// Public interface to the Jump Threading pass
1448383a7b7a6acdae478d4b4c2520915153b73f676Chris LattnerFunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
1458383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
1468383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// runOnFunction - Top level algorithm.
1478383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner///
1488383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerbool JumpThreading::runOnFunction(Function &F) {
149fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene  DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
1503574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  TD = getAnalysisIfAvailable<DataLayout>();
151aab8e28d5e470711d80276bbf717408c3ab966fdChad Rosier  TLI = &getAnalysis<TargetLibraryInfo>();
152c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson  LVI = &getAnalysis<LazyValueInfo>();
1536f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
154fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindLoopHeaders(F);
1556f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
15666b581ef4965ca3a6c72450ee9916a5c2ab44461Benjamin Kramer  bool Changed, EverChanged = false;
15766b581ef4965ca3a6c72450ee9916a5c2ab44461Benjamin Kramer  do {
15866b581ef4965ca3a6c72450ee9916a5c2ab44461Benjamin Kramer    Changed = false;
159421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
160421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BasicBlock *BB = I;
1616f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel      // Thread all of the branches we can over this block.
162421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      while (ProcessBlock(BB))
163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Changed = true;
1646f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
165421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ++I;
1666f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
167421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // If the block is trivially dead, zap it.  This eliminates the successor
168421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // edges which simplifies the CFG.
169421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      if (pred_begin(BB) == pred_end(BB) &&
17020fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner          BB != &BB->getParent()->getEntryBlock()) {
171fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene        DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
17278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              << "' with terminator: " << *BB->getTerminator() << '\n');
173fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.erase(BB);
174c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson        LVI->eraseBlock(BB);
175421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        DeleteDeadBlock(BB);
176421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        Changed = true;
177e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        continue;
178e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      }
179f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson
180e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
181f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson
182e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      // Can't thread an unconditional jump, but if the block is "almost
183e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      // empty", we can replace uses of it with uses of the successor and make
184e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      // this dead.
185e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner      if (BI && BI->isUnconditional() &&
186e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          BB != &BB->getParent()->getEntryBlock() &&
187f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          // If the terminator is the only non-phi instruction, try to nuke it.
188e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          BB->getFirstNonPHIOrDbg()->isTerminator()) {
189e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
190e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // block, we have to make sure it isn't in the LoopHeaders set.  We
191e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // reinsert afterward if needed.
192e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
193e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        BasicBlock *Succ = BI->getSuccessor(0);
194e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner
195e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // FIXME: It is always conservatively correct to drop the info
196e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // for a block even if it doesn't get erased.  This isn't totally
197e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // awesome, but it allows us to use AssertingVH to prevent nasty
198e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        // dangling pointer issues within LazyValueInfo.
199e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        LVI->eraseBlock(BB);
200e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
201e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          Changed = true;
202e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          // If we deleted BB and BB was the header of a loop, then the
203e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          // successor is now the header of the loop.
204e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          BB = Succ;
205f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        }
206e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner
207e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner        if (ErasedFromLoopHeaders)
208e991b5fdd5ab583531300097cf35e1087d479ef0Chris Lattner          LoopHeaders.insert(BB);
209421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      }
210421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
211bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EverChanged |= Changed;
21266b581ef4965ca3a6c72450ee9916a5c2ab44461Benjamin Kramer  } while (Changed);
2136f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
214fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  LoopHeaders.clear();
215bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  return EverChanged;
2168383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
217177480b7ede0441135572d641a2497df25a7d95fChris Lattner
21878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
219c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem/// thread across it. Stop scanning the block when passing the threshold.
220c69908695af9cf509bf498a492854db5f0556e0fNadav Rotemstatic unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
221c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem                                             unsigned Threshold) {
22278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  /// Ignore PHI nodes, these will be flattened when duplication happens.
22378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::const_iterator I = BB->getFirstNonPHI();
2246f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
225b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner  // FIXME: THREADING will delete values that are just used to compute the
226b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner  // branch, so they shouldn't count against the duplication cost.
2276f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
22878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Sum up the cost of each instruction until we get to the terminator.  Don't
22978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // include the terminator because the copy won't include it.
23078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned Size = 0;
23178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; !isa<TerminatorInst>(I); ++I) {
232c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem
233c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem    // Stop scanning the block if we've reached the threshold.
234c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem    if (Size > Threshold)
235c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem      return Size;
236c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem
23778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Debugger intrinsics don't incur code size.
23878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<DbgInfoIntrinsic>(I)) continue;
2396f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
24078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If this is a pointer->pointer bitcast, it is free.
2411df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands    if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
24278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
2436f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
24478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // All other instructions count for at least one unit.
24578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ++Size;
2466f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
24778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Calls are more expensive.  If they are non-intrinsic calls, we model them
24878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 4.  If they are a non-vector intrinsic, we model them
24978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 2 total, and if they are a vector intrinsic, we model
25078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // them as having cost 1.
25178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
25278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (!isa<IntrinsicInst>(CI))
25378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 3;
2541df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands      else if (!CI->getType()->isVectorTy())
25578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 1;
25678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
25778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
2586f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
25978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Threading through a switch statement is particularly profitable.  If this
26078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // block ends in a switch, decrease its cost to make it more likely to happen.
26178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(I))
26278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Size = Size > 6 ? Size-6 : 0;
2636f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
2646033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // The same holds for indirect branches, but slightly more so.
2656033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (isa<IndirectBrInst>(I))
2666033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    Size = Size > 8 ? Size-8 : 0;
2676033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel
26878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return Size;
26978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
27078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
271fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// FindLoopHeaders - We do not want jump threading to turn proper loop
272fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// structures into irreducible loops.  Doing this breaks up the loop nesting
273fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// hierarchy and pessimizes later transformations.  To prevent this from
274fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// happening, we first have to find the loop headers.  Here we approximate this
275fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// by finding targets of backedges in the CFG.
276fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
277fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// Note that there definitely are cases when we want to allow threading of
278fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edges across a loop header.  For example, threading a jump from outside the
279fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// loop (the preheader) to an exit block of the loop is definitely profitable.
280fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// It is also almost always profitable to thread backedges from within the loop
281fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// to exit blocks, and is often profitable to thread backedges to other blocks
282fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// within the loop (forming a nested loop).  This simple analysis is not rich
283fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// enough to track all of these properties and keep it up-to-date as the CFG
284fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// mutates, so we don't allow any of these transformations.
285fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
286fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpvoid JumpThreading::FindLoopHeaders(Function &F) {
287fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
288fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindFunctionBackedges(F, Edges);
2896f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
290fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
291fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
292fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
293fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
294ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel/// getKnownConstant - Helper method to determine if we can thread over a
295ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel/// terminator with the given value as its condition, and if so what value to
2966033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel/// use for that. What kind of value this is depends on whether we want an
2976033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel/// integer or a block address, but an undef is always accepted.
298ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel/// Returns null if Val is null or not an appropriate constant.
2996033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommelstatic Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
300ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  if (!Val)
301ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    return 0;
302ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel
303ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // Undef is "known" enough.
304ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  if (UndefValue *U = dyn_cast<UndefValue>(Val))
305ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    return U;
306ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel
3076033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (Preference == WantBlockAddress)
3086033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    return dyn_cast<BlockAddress>(Val->stripPointerCasts());
309ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel
3106033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  return dyn_cast<ConstantInt>(Val);
3110eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson}
3120eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson
3135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
3146033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel/// if we can infer that the value is a known ConstantInt/BlockAddress or undef
3156033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel/// in any of our predecessors.  If so, return the known list of value and pred
3166033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel/// BB in the result vector.
3175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
3185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// This returns true if there were any known values.
3195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
3205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::
3216033b346e20d6932cc62c754cf23ae51786724d6Frits van BommelComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
3226033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                ConstantPreference Preference) {
3239ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // This method walks up use-def chains recursively.  Because of this, we could
3249ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // get into an infinite loop going around loops in the use-def chain.  To
3259ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // prevent this, keep track of what (value, block) pairs we've already visited
3269ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // and terminate the search if we loop back to them
327cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson  if (!RecursionSet.insert(std::make_pair(V, BB)).second)
328cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson    return false;
3296f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
3309ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // An RAII help to remove this pair from the recursion set once the recursion
3319ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  // stack pops back out again.
3329ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson  RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
3336f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
334ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // If V is a constant, then it is known in all predecessors.
3356033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (Constant *KC = getKnownConstant(V, Preference)) {
336cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
337ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      Result.push_back(std::make_pair(KC, *PI));
3386f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
3395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return true;
3405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3416f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
3425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a non-instruction value, or an instruction in a different block,
3435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // then it can't be derived from a PHI.
3445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
345cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  if (I == 0 || I->getParent() != BB) {
3466f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
347cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // Okay, if this is a live-in value, see if it has a known value at the end
348cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // of any of our predecessors.
349cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    //
350cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // FIXME: This should be an edge property, not a block end property.
351cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    /// TODO: Per PR2563, we could infer value range information about a
352cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    /// predecessor based on its terminator.
353cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    //
354c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
355c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    // "I" is a non-local compare-with-a-constant instruction.  This would be
356c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    // able to handle value inequalities better, for example if the compare is
357c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
358c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    // Perhaps getConstantOnEdge should be smart enough to do this?
3596f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
360c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
361c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      BasicBlock *P = *PI;
362c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      // If the value is known by LazyValueInfo to be a constant in a
363c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      // predecessor, use that information to try to thread this block.
364c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
3656033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      if (Constant *KC = getKnownConstant(PredCst, Preference))
366ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        Result.push_back(std::make_pair(KC, P));
367cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    }
3686f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
369c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    return !Result.empty();
370cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  }
3716f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
3725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// If I is a PHI node, then we know the incoming values for any constants.
3735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PHINode *PN = dyn_cast<PHINode>(I)) {
3745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Value *InVal = PN->getIncomingValue(i);
3766033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      if (Constant *KC = getKnownConstant(InVal, Preference)) {
377ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
378c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      } else {
37962efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        Constant *CI = LVI->getConstantOnEdge(InVal,
38062efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson                                              PN->getIncomingBlock(i), BB);
3816033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel        if (Constant *KC = getKnownConstant(CI, Preference))
3826033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel          Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
3835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3856f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
3865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return !Result.empty();
3875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3886f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
389ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  PredValueInfoTy LHSVals, RHSVals;
3905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle some boolean conditions.
3926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel  if (I->getType()->getPrimitiveSizeInBits() == 1) {
3936033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    assert(Preference == WantInteger && "One-bit non-integer type?");
3945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X | true -> true
3955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X & false -> false
3965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (I->getOpcode() == Instruction::Or ||
3975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        I->getOpcode() == Instruction::And) {
3986033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
3996033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                      WantInteger);
4006033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
4016033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                      WantInteger);
4026f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4039ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      if (LHSVals.empty() && RHSVals.empty())
4045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return false;
4056f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ConstantInt *InterestingVal;
4075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (I->getOpcode() == Instruction::Or)
4085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getTrue(I->getContext());
4095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      else
4105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getFalse(I->getContext());
4116f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4122fa7b48eb594db245dc6af6060c92bbd2b19546bChris Lattner      SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
4136f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4141e452650c6044735b6aa922d41736bda5721adccChris Lattner      // Scan for the sentinel.  If we find an undef, force it to the
4151e452650c6044735b6aa922d41736bda5721adccChris Lattner      // interesting value: x|undef -> true and x&undef -> false.
4165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
417ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        if (LHSVals[i].first == InterestingVal ||
418ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel            isa<UndefValue>(LHSVals[i].first)) {
4195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(LHSVals[i]);
4201e452650c6044735b6aa922d41736bda5721adccChris Lattner          Result.back().first = InterestingVal;
4212fa7b48eb594db245dc6af6060c92bbd2b19546bChris Lattner          LHSKnownBBs.insert(LHSVals[i].second);
4221e452650c6044735b6aa922d41736bda5721adccChris Lattner        }
4235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
424ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        if (RHSVals[i].first == InterestingVal ||
425ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel            isa<UndefValue>(RHSVals[i].first)) {
4260a96144aac449114330a5264b649eb449dc19a37Chris Lattner          // If we already inferred a value for this block on the LHS, don't
4270a96144aac449114330a5264b649eb449dc19a37Chris Lattner          // re-add it.
4282fa7b48eb594db245dc6af6060c92bbd2b19546bChris Lattner          if (!LHSKnownBBs.count(RHSVals[i].second)) {
4290a96144aac449114330a5264b649eb449dc19a37Chris Lattner            Result.push_back(RHSVals[i]);
4300a96144aac449114330a5264b649eb449dc19a37Chris Lattner            Result.back().first = InterestingVal;
4310a96144aac449114330a5264b649eb449dc19a37Chris Lattner          }
4321e452650c6044735b6aa922d41736bda5721adccChris Lattner        }
4336f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
4355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
4366f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
437055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    // Handle the NOT form of XOR.
438055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    if (I->getOpcode() == Instruction::Xor &&
439055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        isa<ConstantInt>(I->getOperand(1)) &&
440055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        cast<ConstantInt>(I->getOperand(1))->isOne()) {
4416033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
4426033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                      WantInteger);
4439ba353627a11349b1da7b596fe44e73cd5fe7a48Owen Anderson      if (Result.empty())
444055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        return false;
445055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner
446055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      // Invert the known values.
447055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      for (unsigned i = 0, e = Result.size(); i != e; ++i)
448ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        Result[i].first = ConstantExpr::getNot(Result[i].first);
4496f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
450055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      return true;
451055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    }
4526f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
45362efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson  // Try to simplify some other binary operator values.
45462efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson  } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
4556033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    assert(Preference != WantBlockAddress
4566033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel            && "A binary operator creating a block address?");
4570eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson    if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
458ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      PredValueInfoTy LHSVals;
4596033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
4606033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                      WantInteger);
4616f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
462cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson      // Try to use constant folding to simplify the binary operator.
463cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
464906a675db8af7bacdd78708453fc7f7558e64033Chris Lattner        Constant *V = LHSVals[i].first;
4650eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson        Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
4666f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4676033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel        if (Constant *KC = getKnownConstant(Folded, WantInteger))
4686033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel          Result.push_back(std::make_pair(KC, LHSVals[i].second));
469cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson      }
47062efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson    }
4716f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
472cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson    return !Result.empty();
4735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4746f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle compare with phi operand, where the PHI is defined in this block.
4765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4776033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    assert(Preference == WantInteger && "Compares only produce integers");
4785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
4795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PN && PN->getParent() == BB) {
4805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // We can do this simplification if any comparisons fold to true or false.
4815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // See if any do.
4825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        BasicBlock *PredBB = PN->getIncomingBlock(i);
4845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *LHS = PN->getIncomingValue(i);
4855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
4866f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4872ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
48866c04c48debfd4357beaf9310346b2b24046b685Chris Lattner        if (Res == 0) {
489c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson          if (!isa<Constant>(RHS))
49066c04c48debfd4357beaf9310346b2b24046b685Chris Lattner            continue;
4916f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
4926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel          LazyValueInfo::Tristate
49366c04c48debfd4357beaf9310346b2b24046b685Chris Lattner            ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
49466c04c48debfd4357beaf9310346b2b24046b685Chris Lattner                                           cast<Constant>(RHS), PredBB, BB);
49566c04c48debfd4357beaf9310346b2b24046b685Chris Lattner          if (ResT == LazyValueInfo::Unknown)
49666c04c48debfd4357beaf9310346b2b24046b685Chris Lattner            continue;
49766c04c48debfd4357beaf9310346b2b24046b685Chris Lattner          Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
49866c04c48debfd4357beaf9310346b2b24046b685Chris Lattner        }
4996f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
5006033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel        if (Constant *KC = getKnownConstant(Res, WantInteger))
5016033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel          Result.push_back(std::make_pair(KC, PredBB));
5025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
5036f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
5045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
5055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
5066f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
5076f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
5082ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    // If comparing a live-in value against a constant, see if we know the
5092ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    // live-in value on any predecessors.
510c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
51162efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson      if (!isa<Instruction>(Cmp->getOperand(0)) ||
512327ca7bec274e25c05a0a4ae5b51a8a2062012c7Owen Anderson          cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
51362efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
514ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif
51562efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
51662efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          BasicBlock *P = *PI;
51762efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          // If the value is known by LazyValueInfo to be a constant in a
51862efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          // predecessor, use that information to try to thread this block.
51962efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          LazyValueInfo::Tristate Res =
52062efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson            LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
52162efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson                                    RHSCst, P, BB);
52262efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          if (Res == LazyValueInfo::Unknown)
52362efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson            continue;
5240e0ff29271df58e3bc545e40f5432c436e8bd76bChris Lattner
52562efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson          Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
526ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel          Result.push_back(std::make_pair(ResC, P));
52762efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        }
528ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif
52962efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        return !Result.empty();
53062efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson      }
5316f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
532cb21190cbd8ae1aece5b833ebe3814ada4260627Owen Anderson      // Try to find a constant value for the LHS of a comparison,
53362efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson      // and evaluate it statically if we can.
534327ca7bec274e25c05a0a4ae5b51a8a2062012c7Owen Anderson      if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
535ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        PredValueInfoTy LHSVals;
5366033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel        ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
5376033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                        WantInteger);
5386f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
53962efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
540906a675db8af7bacdd78708453fc7f7558e64033Chris Lattner          Constant *V = LHSVals[i].first;
5410eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson          Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
5420eb355ab6be61ebd7adb407e02a3604be032b99eOwen Anderson                                                      V, CmpConst);
5436033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel          if (Constant *KC = getKnownConstant(Folded, WantInteger))
5446033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel            Result.push_back(std::make_pair(KC, LHSVals[i].second));
54562efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        }
5466f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
54762efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson        return !Result.empty();
54862efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson      }
5492ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    }
5505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
5516f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
55226e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel  if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
55326e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    // Handle select instructions where at least one operand is a known constant
55426e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    // and we can figure out the condition value for any predecessor block.
55526e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
55626e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
55726e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    PredValueInfoTy Conds;
55826e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    if ((TrueVal || FalseVal) &&
55926e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
56026e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel                                        WantInteger)) {
56126e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel      for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
56226e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        Constant *Cond = Conds[i].first;
56326e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel
56426e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        // Figure out what value to use for the condition.
56526e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        bool KnownCond;
56626e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
56726e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          // A known boolean.
56826e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          KnownCond = CI->isOne();
56926e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        } else {
57026e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          assert(isa<UndefValue>(Cond) && "Unexpected condition value");
57126e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          // Either operand will do, so be sure to pick the one that's a known
57226e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          // constant.
57326e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          // FIXME: Do this more cleverly if both values are known constants?
57426e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          KnownCond = (TrueVal != 0);
57526e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        }
57626e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel
57726e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        // See if the select has a known constant value for this predecessor.
57826e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel        if (Constant *Val = KnownCond ? TrueVal : FalseVal)
57926e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel          Result.push_back(std::make_pair(Val, Conds[i].second));
58026e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel      }
58126e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel
58226e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel      return !Result.empty();
58326e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel    }
58426e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel  }
58526e097ca4bdb31000655ff9ec39fe7d9b7ea226dFrits van Bommel
586c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson  // If all else fails, see if LVI can figure out a constant value for us.
587c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson  Constant *CI = LVI->getConstant(V, BB);
5886033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (Constant *KC = getKnownConstant(CI, Preference)) {
589c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
590ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      Result.push_back(std::make_pair(KC, *PI));
59162efd3b38576536cf06ed5bf2f39535eb7961e99Owen Anderson  }
5926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
593c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson  return !Result.empty();
5945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
5955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5976bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
598e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
599e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// in an undefined jump, decide which block is best to revector to.
600e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
601e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// Since we can pick an arbitrary destination, we pick the successor with the
602e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// fewest predecessors.  This should reduce the in-degree of the others.
603e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
604e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattnerstatic unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
605e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  TerminatorInst *BBTerm = BB->getTerminator();
606e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinSucc = 0;
607e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
608e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // Compute the successor with the minimum number of predecessors.
609e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
610e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
611e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TestBB = BBTerm->getSuccessor(i);
612e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
613f227b50a8e30598464c244a675d8e857b62a52acJakub Staszak    if (NumPreds < MinNumPreds) {
614e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      MinSucc = i;
615f227b50a8e30598464c244a675d8e857b62a52acJakub Staszak      MinNumPreds = NumPreds;
616f227b50a8e30598464c244a675d8e857b62a52acJakub Staszak    }
617e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
6186f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
619e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  return MinSucc;
620e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner}
621e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
62278f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattnerstatic bool hasAddressTakenAndUsed(BasicBlock *BB) {
62378f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  if (!BB->hasAddressTaken()) return false;
624f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson
62578f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  // If the block has its address taken, it may be a tree of dead constants
62678f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  // hanging off of it.  These shouldn't keep the block alive.
62778f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  BlockAddress *BA = BlockAddress::get(BB);
62878f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  BA->removeDeadConstantUsers();
62978f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner  return !BA->use_empty();
63078f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner}
63178f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner
632c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner/// ProcessBlock - If there are any predecessors whose control can be threaded
633177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// through to a successor, transform them now.
634c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattnerbool JumpThreading::ProcessBlock(BasicBlock *BB) {
6358231fd1e6ca940511843381ea5f0dbfbc740b1e6Chris Lattner  // If the block is trivially dead, just return and let the caller nuke it.
6368231fd1e6ca940511843381ea5f0dbfbc740b1e6Chris Lattner  // This simplifies other transformations.
6378231fd1e6ca940511843381ea5f0dbfbc740b1e6Chris Lattner  if (pred_begin(BB) == pred_end(BB) &&
6388231fd1e6ca940511843381ea5f0dbfbc740b1e6Chris Lattner      BB != &BB->getParent()->getEntryBlock())
6398231fd1e6ca940511843381ea5f0dbfbc740b1e6Chris Lattner    return false;
6406f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
64169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If this block has a single predecessor, and if that pred has a single
64269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // successor, merge the blocks.  This encourages recursive jump threading
64369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // because now the condition in this block can be threaded through
64469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors of our predecessor block.
6455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
646f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
64778f7a25f9826ba66610b5bca83ebea71793abf59Chris Lattner        SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
648fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // If SinglePred was a loop header, BB becomes one.
649fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      if (LoopHeaders.erase(SinglePred))
650fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.insert(BB);
6516f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
6523d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Remember if SinglePred was the entry block of the function.  If so, we
6533d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // will need to move BB back to the entry position.
6543d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
655c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson      LVI->eraseBlock(SinglePred);
65669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      MergeBasicBlockIntoOnlyPred(BB);
6576f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
6583d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      if (isEntry && BB != &BB->getParent()->getEntryBlock())
6593d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner        BB->moveBefore(&BB->getParent()->getEntryBlock());
66069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
66169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
6625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
6635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
6646033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // What kind of constant we're looking for.
6656033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  ConstantPreference Preference = WantInteger;
6666033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel
6676033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // Look to see if the terminator is a conditional branch, switch or indirect
6686033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  // branch, if not we can't thread it.
669177480b7ede0441135572d641a2497df25a7d95fChris Lattner  Value *Condition;
6706033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  Instruction *Terminator = BB->getTerminator();
6716033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
672bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Can't thread an unconditional jump.
673bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (BI->isUnconditional()) return false;
674177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = BI->getCondition();
6756033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
676177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = SI->getCondition();
6776033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
678dd2fb6c10b30e70ab8f910e21e583be3e90bb88cRichard Osborne    // Can't thread indirect branch with no successors.
679dd2fb6c10b30e70ab8f910e21e583be3e90bb88cRichard Osborne    if (IB->getNumSuccessors() == 0) return false;
6806033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    Condition = IB->getAddress()->stripPointerCasts();
6816033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    Preference = WantBlockAddress;
6826033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  } else {
683177480b7ede0441135572d641a2497df25a7d95fChris Lattner    return false; // Must be an invoke.
6846033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  }
6856f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
686f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson  // Run constant folding to see if we can reduce the condition to a simple
687f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson  // constant.
688f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson  if (Instruction *I = dyn_cast<Instruction>(Condition)) {
689aab8e28d5e470711d80276bbf717408c3ab966fdChad Rosier    Value *SimpleVal = ConstantFoldInstruction(I, TD, TLI);
690f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson    if (SimpleVal) {
691f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson      I->replaceAllUsesWith(SimpleVal);
692f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson      I->eraseFromParent();
693f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson      Condition = SimpleVal;
694f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson    }
695f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson  }
696f6832bbda08b6975caa264de183bf3ee1d472acaOwen Anderson
697421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the terminator is branching on an undef, we can pick any of the
698e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
699421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (isa<UndefValue>(Condition)) {
700e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
7016f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
702421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Fold the branch/switch.
703e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TerminatorInst *BBTerm = BB->getTerminator();
704421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
705e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (i == BestSucc) continue;
70636c4debc94e7c68c769dfda781851a0c963dd746Owen Anderson      BBTerm->getSuccessor(i)->removePredecessor(BB, true);
707421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
7086f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
709fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  In block '" << BB->getName()
71078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding undef terminator: " << *BBTerm << '\n');
711e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
712421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BBTerm->eraseFromParent();
713421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
714421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
7156f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
716ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // If the terminator of this block is branching on a constant, simplify the
717ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // terminator to an unconditional branch.  This can occur due to threading in
718ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  // other blocks.
7196033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (getKnownConstant(Condition, Preference)) {
720ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    DEBUG(dbgs() << "  In block '" << BB->getName()
721ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel          << "' folding terminator: " << *BB->getTerminator() << '\n');
722ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    ++NumFolds;
7235649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel    ConstantFoldTerminator(BB, true);
724ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    return true;
725ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  }
726ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel
727421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Instruction *CondInst = dyn_cast<Instruction>(Condition);
728421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
729421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // All the rest of our checks depend on the condition being an instruction.
73087e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner  if (CondInst == 0) {
73187e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner    // FIXME: Unify this with code below.
7326033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    if (ProcessThreadableEdges(Condition, BB, Preference))
73387e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner      return true;
734421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return false;
7356f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel  }
7366f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
7376f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
7389683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
739660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson    // For a comparison where the LHS is outside this block, it's possible
740fc2fb17fb764470626f3d7ecf2fb68fe73b0d757Owen Anderson    // that we've branched on it before.  Used LVI to see if we can simplify
741660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson    // the branch based on that.
742660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson    BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
743660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson    Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
744c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson    pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
745c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson    if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
746660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson        (!isa<Instruction>(CondCmp->getOperand(0)) ||
747660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson         cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
748660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson      // For predecessor edge, determine if the comparison is true or false
749660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson      // on that edge.  If they're all true or all false, we can simplify the
750660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson      // branch.
751660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson      // FIXME: We could handle mixed true/false by duplicating code.
7526f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel      LazyValueInfo::Tristate Baseline =
753c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
754c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson                                CondConst, *PI, BB);
755c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson      if (Baseline != LazyValueInfo::Unknown) {
756c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        // Check that all remaining incoming values match the first one.
757c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        while (++PI != PE) {
758bdabacdccae980b82b5d92e10697b8aeb3b94cfaChris Lattner          LazyValueInfo::Tristate Ret =
759bdabacdccae980b82b5d92e10697b8aeb3b94cfaChris Lattner            LVI->getPredicateOnEdge(CondCmp->getPredicate(),
760bdabacdccae980b82b5d92e10697b8aeb3b94cfaChris Lattner                                    CondCmp->getOperand(0), CondConst, *PI, BB);
761c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          if (Ret != Baseline) break;
762c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        }
7636f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
764c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        // If we terminated early, then one of the values didn't match.
765c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        if (PI == PE) {
766c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
767c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
76836c4debc94e7c68c769dfda781851a0c963dd746Owen Anderson          CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
769c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
770c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          CondBr->eraseFromParent();
771c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson          return true;
772c1bdac66fff1e65aba02ec853cc0693dcc967f33Owen Anderson        }
773660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson      }
774660cab32fe5105bcaa17daa4704c24065ac0a7e6Owen Anderson    }
7759683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  }
77669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Check for some cases that are worth simplifying.  Right now we want to look
77869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // for loads that are used by a switch or by the condition for the branch.  If
77969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we see one, check to see if it's partially redundant.  If so, insert a PHI
78069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // which can then be used to thread the values.
78169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //
782421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Value *SimplifyValue = CondInst;
78369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
78469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (isa<Constant>(CondCmp->getOperand(1)))
78569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SimplifyValue = CondCmp->getOperand(0);
7866f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
7874e447ebc5897a466c37bd2e9f5514d3fc5135789Chris Lattner  // TODO: There are other places where load PRE would be profitable, such as
7884e447ebc5897a466c37bd2e9f5514d3fc5135789Chris Lattner  // more complex comparisons.
78969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
79069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (SimplifyPartiallyRedundantLoad(LI))
79169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
7926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
7936f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
7945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle a variety of cases where we are branching on something derived from
7955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a PHI node in the current block.  If we can prove that any predecessors
7965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // compute a predictable value based on a PHI node, thread those predecessors.
7975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  //
7986033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (ProcessThreadableEdges(CondInst, BB, Preference))
799cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    return true;
8006f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
80177beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // If this is an otherwise-unfoldable branch on a phi node in the current
80277beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // block, see if we can simplify.
80377beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
80477beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner    if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
80577beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner      return ProcessBranchOnPHI(PN);
8066f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
8076f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
8082249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
8092249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  if (CondInst->getOpcode() == Instruction::Xor &&
8102249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
8112249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
8126f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
8136f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
81469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
81577beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // "(X == 4)", thread through this block.
8166f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
817d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  return false;
818d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner}
819d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner
8203cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
82169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
82269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// load instruction, eliminate it by replacing it with a PHI node.  This is an
82369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// important optimization that encourages jump threading, and needs to be run
82469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// interlaced with other jump threading tasks.
82569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattnerbool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
8262bc3d52b9ab422ee9f7e42a1a4e3b818e623a5f7Eli Friedman  // Don't hack volatile/atomic loads.
8272bc3d52b9ab422ee9f7e42a1a4e3b818e623a5f7Eli Friedman  if (!LI->isSimple()) return false;
8286f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
82969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the load is defined in a block with exactly one predecessor, it can't be
83069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // partially redundant.
83169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *LoadBB = LI->getParent();
83269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadBB->getSinglePredecessor())
83369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
8346f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
83569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Value *LoadedPtr = LI->getOperand(0);
83669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded operand is defined in the LoadBB, it can't be available.
8384e447ebc5897a466c37bd2e9f5514d3fc5135789Chris Lattner  // TODO: Could do simple PHI translation, that would be fun :)
83969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
84069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (PtrOp->getParent() == LoadBB)
84169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return false;
8426f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
84369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Scan a few instructions up from the load, to see if it is obviously live at
84469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // the entry to its block.
84569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock::iterator BBIt = LI;
84669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
8476f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel  if (Value *AvailableVal =
8484e447ebc5897a466c37bd2e9f5514d3fc5135789Chris Lattner        FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
84969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If the value if the load is locally available within the block, just use
85069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // it.  This frequently occurs for reg2mem'd allocas.
85169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
8526f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
8532a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // If the returned value is the load itself, replace with an undef. This can
8542a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // only happen in dead loops.
8559e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
85669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->replaceAllUsesWith(AvailableVal);
85769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->eraseFromParent();
85869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return true;
85969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
86069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Otherwise, if we scanned the whole block and got to the top of the block,
86269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we know the block is locally transparent to the load.  If not, something
86369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // might clobber its value.
86469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BBIt != LoadBB->begin())
86569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
8666f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
8675161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner  // If all of the loads and stores that feed the value have the same TBAA tag,
8685161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner  // then we can propagate it onto any newly inserted loads.
869a94d6e87c4c49f2e81b01d66d8bfb591277f8f96Nadav Rotem  MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
8706f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
87169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SmallPtrSet<BasicBlock*, 8> PredsScanned;
87269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
87369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  AvailablePredsTy AvailablePreds;
87469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *OneUnavailablePred = 0;
8756f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
87669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If we got here, the loaded value is transparent through to the start of the
87769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // block.  Check to see if it is available in any of the predecessor blocks.
87869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
87969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       PI != PE; ++PI) {
88069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BasicBlock *PredBB = *PI;
88169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
88269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If we already scanned this predecessor, skip it.
88369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredsScanned.insert(PredBB))
88469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
88569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
88669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Scan the predecessor to see if the value is available in the pred.
88769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BBIt = PredBB->end();
8885161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner    MDNode *ThisTBAATag = 0;
8895161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
8905161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner                                                    0, &ThisTBAATag);
89169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredAvailable) {
89269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred = PredBB;
89369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
89469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
895a94d6e87c4c49f2e81b01d66d8bfb591277f8f96Nadav Rotem
8965161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner    // If tbaa tags disagree or are not present, forget about them.
8975161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner    if (TBAATag != ThisTBAATag) TBAATag = 0;
8986f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
89969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If so, this load is partially redundant.  Remember this info so that we
90069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // can create a PHI node.
90169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
90269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
9036f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
90469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded value isn't available in any predecessor, it isn't partially
90569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // redundant.
90669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (AvailablePreds.empty()) return false;
9076f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
90869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Okay, the loaded value is available in at least one (and maybe all!)
90969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors.  If the value is unavailable in more than one unique
91069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessor, we want to insert a merge block for those common predecessors.
91169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This ensures that we only have to insert one reload, thus not increasing
91269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // code size.
91369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *UnavailablePred = 0;
9146f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
91569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If there is exactly one predecessor where the value is unavailable, the
91669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // already computed 'OneUnavailablePred' block is it.  If it ends in an
91769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // unconditional branch, we know that it isn't a critical edge.
91869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (PredsScanned.size() == AvailablePreds.size()+1 &&
91969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
92069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred = OneUnavailablePred;
92169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  } else if (PredsScanned.size() != AvailablePreds.size()) {
92269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Otherwise, we had multiple unavailable predecessors or we had a critical
92369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // edge from the one.
92469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<BasicBlock*, 8> PredsToSplit;
92569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
92669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
92769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
92869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      AvailablePredSet.insert(AvailablePreds[i].first);
92969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
93069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Add all the unavailable predecessors to the PredsToSplit list.
93169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
932e58867e55e472d81bbf5b1d26310a5b3918d2fb6Chris Lattner         PI != PE; ++PI) {
933ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif      BasicBlock *P = *PI;
934e58867e55e472d81bbf5b1d26310a5b3918d2fb6Chris Lattner      // If the predecessor is an indirect goto, we can't split the edge.
935ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif      if (isa<IndirectBrInst>(P->getTerminator()))
936e58867e55e472d81bbf5b1d26310a5b3918d2fb6Chris Lattner        return false;
9376f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
938ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif      if (!AvailablePredSet.count(P))
939ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif        PredsToSplit.push_back(P);
940e58867e55e472d81bbf5b1d26310a5b3918d2fb6Chris Lattner    }
9416f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
94269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Split them out to their own block.
94369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred =
9442fac1d5d61a83c45dcf44119c41dce15ef10e9dcJakub Staszak      SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", this);
94569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
9466f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
94769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the value isn't available in all predecessors, then there will be
94869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // exactly one where it isn't available.  Insert a load on that edge and add
94969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // it to the AvailablePreds list.
95069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (UnavailablePred) {
95169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
95269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Can't handle critical edge here!");
95395a7de6b916e49265ebdae04a32f6beda7f89028Devang Patel    LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
9544e447ebc5897a466c37bd2e9f5514d3fc5135789Chris Lattner                                 LI->getAlignment(),
95569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 UnavailablePred->getTerminator());
95695a7de6b916e49265ebdae04a32f6beda7f89028Devang Patel    NewVal->setDebugLoc(LI->getDebugLoc());
9575161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner    if (TBAATag)
9585161de6ebbd36b0532bd980483d757f5a3014611Chris Lattner      NewVal->setMetadata(LLVMContext::MD_tbaa, TBAATag);
959a94d6e87c4c49f2e81b01d66d8bfb591277f8f96Nadav Rotem
96069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
96169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
9626f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
96369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Now we know that each predecessor of this block has a value in
96469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // AvailablePreds, sort them for efficient access as we're walking the preds.
965a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
9666f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
96769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Create a PHI node at the start of the block for the PRE'd load value.
968d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
9693ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad  PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
9703ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                LoadBB->begin());
97169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PN->takeName(LI);
97295a7de6b916e49265ebdae04a32f6beda7f89028Devang Patel  PN->setDebugLoc(LI->getDebugLoc());
9736f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
97469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Insert new entries into the PHI for each predecessor.  A single block may
97569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // have multiple entries here.
976d8b4fb4aab4d6fedb2b14bed1b846451b17bde7cJay Foad  for (pred_iterator PI = PB; PI != PE; ++PI) {
977ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif    BasicBlock *P = *PI;
9786f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel    AvailablePredsTy::iterator I =
97969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
980ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif                       std::make_pair(P, (Value*)0));
9816f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
982ee1f44fba3f2ba01657f217d159b4d09f249e46dGabor Greif    assert(I != AvailablePreds.end() && I->first == P &&
98369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Didn't find entry for predecessor!");
9846f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
98569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    PN->addIncoming(I->second, I->first);
98669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
9876f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
98869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //cerr << "PRE: " << *LI << *PN << "\n";
9896f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
99069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->replaceAllUsesWith(PN);
99169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->eraseFromParent();
9926f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
99369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  return true;
99469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner}
99569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
9965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// FindMostPopularDest - The specified list contains multiple possible
9975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// threadable destinations.  Pick the one that occurs the most frequently in
9985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the list.
9995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerstatic BasicBlock *
10005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerFindMostPopularDest(BasicBlock *BB,
10015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    const SmallVectorImpl<std::pair<BasicBlock*,
10025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  BasicBlock*> > &PredToDestList) {
10035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredToDestList.empty());
10046f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine popularity.  If there are multiple possible destinations, we
10065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // explicitly choose to ignore 'undef' destinations.  We prefer to thread
10075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // blocks with known and real destinations to threading undef.  We'll handle
10085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // them later if interesting.
10095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned> DestPopularity;
10105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
10115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second)
10125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestPopularity[PredToDestList[i].second]++;
10136f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Find the most popular dest.
10155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
10165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = DPI->first;
10175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned Popularity = DPI->second;
10185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 4> SamePopularity;
10196f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (++DPI; DPI != DestPopularity.end(); ++DPI) {
10215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the popularity of this entry isn't higher than the popularity we've
10225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // seen so far, ignore it.
10235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (DPI->second < Popularity)
10245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ; // ignore.
10255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (DPI->second == Popularity) {
10265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is the same as what we've seen so far, keep track of it.
10275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.push_back(DPI->first);
10285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    } else {
10295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is more popular, remember it.
10305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.clear();
10315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = DPI->first;
10325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Popularity = DPI->second;
10336f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel    }
103478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
10356f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
103601abcf339f8d42921c680fefb2ff988cfeee1198Frits van Bommel  // Okay, now we know the most popular destination.  If there is more than one
10375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // destination, we need to determine one.  This is arbitrary, but we need
10385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to make a deterministic decision.  Pick the first one that appears in the
10395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // successor list.
10405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!SamePopularity.empty()) {
10415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SamePopularity.push_back(MostPopularDest);
10425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    TerminatorInst *TI = BB->getTerminator();
10435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0; ; ++i) {
10445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
10456f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (std::find(SamePopularity.begin(), SamePopularity.end(),
10475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    TI->getSuccessor(i)) == SamePopularity.end())
10485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        continue;
10496f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = TI->getSuccessor(i);
105112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      break;
105212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
105312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
10546f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, we have finally picked the most popular destination.
10565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return MostPopularDest;
10575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
10585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10596033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommelbool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
10606033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                           ConstantPreference Preference) {
10615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If threading this would thread across a loop header, don't even try to
10625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // thread the edge.
10635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (LoopHeaders.count(BB))
106412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
10656f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1066ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  PredValueInfoTy PredValues;
10676033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference))
106812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
10696f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredValues.empty() &&
10715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         "ComputeValueKnownInPredecessors returned true with no values");
10725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
1073fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene  DEBUG(dbgs() << "IN BB: " << *BB;
10745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1075ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel          dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
1076ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel            << *PredValues[i].first
1077ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel            << " for pred '" << PredValues[i].second->getName() << "'.\n";
10785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        });
10796f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Decide what we want to thread through.  Convert our list of known values to
10815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a list of known destinations for each pred.  This also discards duplicate
10825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors and keeps track of the undefined inputs (which are represented
1083e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // as a null dest in the PredToDestList).
10845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallPtrSet<BasicBlock*, 16> SeenPreds;
10855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
10866f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *OnlyDest = 0;
10885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
10896f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
10915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *Pred = PredValues[i].second;
10925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!SeenPreds.insert(Pred))
10935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      continue;  // Duplicate predecessor entry.
10946f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
10955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the predecessor ends with an indirect goto, we can't change its
10965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // destination.
10975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (isa<IndirectBrInst>(Pred->getTerminator()))
109812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      continue;
10996f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1100ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    Constant *Val = PredValues[i].first;
11016f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *DestBB;
1103ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    if (isa<UndefValue>(Val))
11045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = 0;
11055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1106ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
110724473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1108c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
110924473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    } else {
11106033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      assert(isa<IndirectBrInst>(BB->getTerminator())
11116033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel              && "Unexpected terminator");
11126033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel      DestBB = cast<BlockAddress>(Val)->getBasicBlock();
111312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
11145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
11155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If we have exactly one destination, remember it for efficiency below.
111601abcf339f8d42921c680fefb2ff988cfeee1198Frits van Bommel    if (PredToDestList.empty())
11175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = DestBB;
11185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (OnlyDest != DestBB)
11195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = MultipleDestSentinel;
11206f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredToDestList.push_back(std::make_pair(Pred, DestBB));
112212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
11236f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If all edges were unthreadable, we fail.
11255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredToDestList.empty())
112612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
11276f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine which is the most common successor.  If we have many inputs and
11295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // this block is a switch, we want to start by threading the batch that goes
11305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to the most popular destination first.  If we only know about one
11315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threadable destination (the common case) we can avoid this.
11325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = OnlyDest;
11336f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == MultipleDestSentinel)
11355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = FindMostPopularDest(BB, PredToDestList);
11366f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Now that we know what the most popular destination is, factor all
11385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors that will jump to it into a single predecessor.
11395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 16> PredsToFactor;
11405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
11415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second == MostPopularDest) {
11425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      BasicBlock *Pred = PredToDestList[i].first;
11436f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // This predecessor may be a switch or something else that has multiple
11455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // edges to the block.  Factor each of these edges by listing them
11465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // according to # occurrences in PredsToFactor.
11475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      TerminatorInst *PredTI = Pred->getTerminator();
11485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
11495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (PredTI->getSuccessor(i) == BB)
11505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          PredsToFactor.push_back(Pred);
11515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
11525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
11535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If the threadable edges are branching on an undefined value, we get to pick
11545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // the destination that these predecessors should get to.
11555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == 0)
11565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = BB->getTerminator()->
11575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            getSuccessor(GetBestDestForJumpOnUndef(BB));
11586f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
115912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  // Ok, try to thread it!
11605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, PredsToFactor, MostPopularDest);
11615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
11625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
116377beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
116477beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner/// a PHI node in the current block.  See if there are any simplifications we
116577beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner/// can do based on inputs to the phi node.
11666f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel///
116777beb479f556093c5f1b4854fcbb095cda34f202Chris Lattnerbool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
11685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *BB = PN->getParent();
11696f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11702249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // TODO: We could make use of this to do it once for blocks with common PHI
11712249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // values.
11722249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  SmallVector<BasicBlock*, 1> PredBBs;
11732249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  PredBBs.resize(1);
11746f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
11755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If any of the predecessor blocks end in an unconditional branch, we can
117677beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // *duplicate* the conditional branch into that block in order to further
117777beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // encourage jump threading and to eliminate cases where we have branch on a
117877beb479f556093c5f1b4854fcbb095cda34f202Chris Lattner  // phi of an icmp (branch on icmp is much better).
11795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *PredBB = PN->getIncomingBlock(i);
11815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
11822249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      if (PredBr->isUnconditional()) {
11832249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner        PredBBs[0] = PredBB;
11842249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner        // Try to duplicate BB into PredBB.
11852249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner        if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
11862249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner          return true;
11872249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      }
11885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
11895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
11905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
119112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel}
119212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
11932249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
11942249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner/// a xor instruction in the current block.  See if there are any
11952249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner/// simplifications we can do based on inputs to the xor.
11966f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel///
11972249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattnerbool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
11982249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  BasicBlock *BB = BO->getParent();
11996f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12002249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // If either the LHS or RHS of the xor is a constant, don't do this
12012249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // optimization.
12022249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  if (isa<ConstantInt>(BO->getOperand(0)) ||
12032249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      isa<ConstantInt>(BO->getOperand(1)))
12042249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    return false;
12056f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12062dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  // If the first instruction in BB isn't a phi, we won't be able to infer
12072dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  // anything special about any particular predecessor.
12082dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  if (!isa<PHINode>(BB->front()))
12092dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    return false;
12106f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12112249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // If we have a xor as the branch input to this block, and we know that the
12122249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // LHS or RHS of the xor in any predecessor is true/false, then we can clone
12132249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // the condition into the predecessor and fix that value to true, saving some
12142249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // logical ops on that path and encouraging other paths to simplify.
12152249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //
12162249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // This copies something like this:
12172249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //
12182249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //  BB:
12192249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    %X = phi i1 [1],  [%X']
12202249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    %Y = icmp eq i32 %A, %B
12212249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    %Z = xor i1 %X, %Y
12222249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    br i1 %Z, ...
12232249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //
12242249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Into:
12252249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //  BB':
12262249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    %Y = icmp ne i32 %A, %B
12272249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  //    br i1 %Z, ...
12282249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
1229ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel  PredValueInfoTy XorOpValues;
12302249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  bool isLHS = true;
12316033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel  if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
12326033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                       WantInteger)) {
12332249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    assert(XorOpValues.empty());
12346033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel    if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
12356033b346e20d6932cc62c754cf23ae51786724d6Frits van Bommel                                         WantInteger))
12362249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      return false;
12372249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    isLHS = false;
12382249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  }
12396f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12402249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  assert(!XorOpValues.empty() &&
12412249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner         "ComputeValueKnownInPredecessors returned true with no values");
12422249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
12432249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Scan the information to see which is most popular: true or false.  The
12442249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // predecessors can be of the set true, false, or undef.
12452249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  unsigned NumTrue = 0, NumFalse = 0;
12462249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1247ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    if (isa<UndefValue>(XorOpValues[i].first))
1248ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      // Ignore undefs for the count.
1249ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      continue;
1250ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
12512249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      ++NumFalse;
12522249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    else
12532249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner      ++NumTrue;
12542249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  }
12556f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12562249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Determine which value to split on, true, false, or undef if neither.
12572249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  ConstantInt *SplitVal = 0;
12582249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  if (NumTrue > NumFalse)
12592249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    SplitVal = ConstantInt::getTrue(BB->getContext());
12602249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  else if (NumTrue != 0 || NumFalse != 0)
12612249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    SplitVal = ConstantInt::getFalse(BB->getContext());
12626f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12632249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Collect all of the blocks that this can be folded into so that we can
12642249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // factor this once and clone it once.
12652249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  SmallVector<BasicBlock*, 8> BlocksToFoldInto;
12662249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1267ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel    if (XorOpValues[i].first != SplitVal &&
1268ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel        !isa<UndefValue>(XorOpValues[i].first))
1269ea388f217b8368db13f598e4c547bab5582eb82aFrits van Bommel      continue;
12702249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
12712249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    BlocksToFoldInto.push_back(XorOpValues[i].second);
12722249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  }
12736f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12742dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  // If we inferred a value for all of the predecessors, then duplication won't
12752dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  // help us.  However, we can just replace the LHS or RHS with the constant.
12762dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  if (BlocksToFoldInto.size() ==
12772dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      cast<PHINode>(BB->front()).getNumIncomingValues()) {
12782dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    if (SplitVal == 0) {
12792dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      // If all preds provide undef, just nuke the xor, because it is undef too.
12802dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
12812dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      BO->eraseFromParent();
12822dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    } else if (SplitVal->isZero()) {
12832dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      // If all preds provide 0, replace the xor with the other input.
12842dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      BO->replaceAllUsesWith(BO->getOperand(isLHS));
12852dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      BO->eraseFromParent();
12862dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    } else {
12872dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      // If all preds provide 1, set the computed value to 1.
12882dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner      BO->setOperand(!isLHS, SplitVal);
12892dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    }
12906f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12912dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner    return true;
12922dd7657a5b063e6f77c34f418b7e23654b6fe4a0Chris Lattner  }
12936f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
12942249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Try to duplicate BB into PredBB.
1295797c440caf24e92b16b9a87a39ef2f5c4cfb60f0Chris Lattner  return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
12962249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner}
12972249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
12982249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
129978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
130078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
130178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// NewPred using the entries from OldPred (suitably mapped).
130278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
130378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *OldPred,
130478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *NewPred,
130578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                     DenseMap<Instruction*, Value*> &ValueMap) {
130678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator PNI = PHIBB->begin();
130778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner       PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
130878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Ok, we have a PHI node.  Figure out what the incoming value was for the
130978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // DestBlock.
131078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Value *IV = PN->getIncomingValueForBlock(OldPred);
13116f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
131278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap the value if necessary.
131378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
131478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
131578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (I != ValueMap.end())
131678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        IV = I->second;
1317bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    }
13186f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
131978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PN->addIncoming(IV, NewPred);
1320bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  }
1321fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
1322fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
13235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ThreadEdge - We have decided that it is safe and profitable to factor the
13245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
13255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// across BB.  Transform the IR to reflect this change.
13266f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommelbool JumpThreading::ThreadEdge(BasicBlock *BB,
13276f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel                               const SmallVectorImpl<BasicBlock*> &PredBBs,
1328bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner                               BasicBlock *SuccBB) {
1329eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  // If threading to the same block as we come from, we would infinite loop.
1330eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  if (SuccBB == BB) {
1331fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
133293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - would thread to self!\n");
1333eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner    return false;
1334eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  }
13356f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1336fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // If threading this would thread across a loop header, don't thread the edge.
1337fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // See the comments above FindLoopHeaders for justifications and caveats.
1338fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (LoopHeaders.count(BB)) {
1339fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
134093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' to dest BB '" << SuccBB->getName()
134193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - it might create an irreducible loop!\n");
1342fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    return false;
1343fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
1344fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1345c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, Threshold);
134678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (JumpThreadCost > Threshold) {
1347fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
134878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << JumpThreadCost << "\n");
134978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
135078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
13516f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
13525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // And finally, do it!  Start by factoring the predecessors is needed.
13535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *PredBB;
13545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredBBs.size() == 1)
13555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = PredBBs[0];
13565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  else {
1357fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
13585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << " common predecessors.\n");
13592fac1d5d61a83c45dcf44119c41dce15ef10e9dcJakub Staszak    PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
13605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
13616f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1362a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // And finally, do it!
1363fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene  DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1364460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar        << SuccBB->getName() << "' with cost: " << JumpThreadCost
136593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << ", across block:\n    "
136693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << *BB << "\n");
13676f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1368c809d90bca41a5578012959ea2e493f9d949f969Owen Anderson  LVI->threadEdge(PredBB, BB, SuccBB);
13696f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1370bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We are going to have to map operands from the original BB block to the new
1371bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1372bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // account for entry from PredBB.
1373bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
13746f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
13756f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
13766f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel                                         BB->getName()+".thread",
13771d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getParent(), BB);
1378bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  NewBB->moveAfter(PredBB);
13796f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1380bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BasicBlock::iterator BI = BB->begin();
1381bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1382bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
13836f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1384bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Clone the non-phi instructions of BB into NewBB, keeping track of the
1385bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
1386bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; !isa<TerminatorInst>(BI); ++BI) {
13876776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky    Instruction *New = BI->clone();
1388460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar    New->setName(BI->getName());
1389bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    NewBB->getInstList().push_back(New);
1390bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[BI] = New;
13916f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1392bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Remap operands to patch up intra-block references.
1393bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1394f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1395f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1396f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        if (I != ValueMapping.end())
1397f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman          New->setOperand(i, I->second);
1398f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      }
1399bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
14006f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1401bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We didn't copy the terminator from BB over to NewBB, because there is now
1402bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // an unconditional jump to SuccBB.  Insert the unconditional jump.
140395a7de6b916e49265ebdae04a32f6beda7f89028Devang Patel  BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
140495a7de6b916e49265ebdae04a32f6beda7f89028Devang Patel  NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
14056f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1406bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1407bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // PHI nodes for NewBB now.
140878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
14096f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1410433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // If there were values defined in BB that are used outside the block, then we
1411433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // now have to update all uses of the value to use either the original value,
1412433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
1413433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
1414433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SSAUpdater SSAUpdate;
1415433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SmallVector<Use*, 16> UsesToRename;
1416433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1417433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // Scan all uses of this instruction to see if it is used outside of its
1418433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // block, and if so, record them in UsesToRename.
1419433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1420433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner         ++UI) {
1421433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Instruction *User = cast<Instruction>(*UI);
1422433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1423433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
1424433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          continue;
1425433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      } else if (User->getParent() == BB)
1426433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        continue;
14276f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1428433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      UsesToRename.push_back(&UI.getUse());
1429433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    }
14306f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1431433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // If there are no uses outside the block, we're done with this instruction.
1432433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    if (UsesToRename.empty())
1433433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      continue;
14346f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1435fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
1436433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1437433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
1438433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1439433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // with the two values we know.
1440fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands    SSAUpdate.Initialize(I->getType(), I->getName());
1441433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(BB, I);
1442433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
14436f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1444433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    while (!UsesToRename.empty())
1445433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1446fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "\n");
1447433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  }
14486f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
14496f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1450ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1451bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1452bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // us to simplify any PHI nodes in BB.
1453bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  TerminatorInst *PredTerm = PredBB->getTerminator();
1454bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1455bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (PredTerm->getSuccessor(i) == BB) {
145636c4debc94e7c68c769dfda781851a0c963dd746Owen Anderson      BB->removePredecessor(PredBB, true);
1457bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      PredTerm->setSuccessor(i, NewBB);
1458bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
14596f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1460ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // At this point, the IR is fully up to date and consistent.  Do a quick scan
1461ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // over the new instructions and zap any that are constants or dead.  This
1462ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // frequently happens because of phi translation.
14638e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  SimplifyInstructionsInBlock(NewBB, TD, TLI);
14646f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1465fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Threaded an edge!
1466fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  ++NumThreads;
1467fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return true;
1468177480b7ede0441135572d641a2497df25a7d95fChris Lattner}
146978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
147078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
147178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
147278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// If we can duplicate the contents of BB up into PredBB do so now, this
147378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// improves the odds that the branch will be on an analyzable instruction like
147478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// a compare.
147578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerbool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
14762249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner                                 const SmallVectorImpl<BasicBlock *> &PredBBs) {
14772249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  assert(!PredBBs.empty() && "Can't handle an empty set");
14782249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner
147978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If BB is a loop header, then duplicating this block outside the loop would
148078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // cause us to transform this into an irreducible loop, don't do this.
148178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // See the comments above FindLoopHeaders for justifications and caveats.
148278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (LoopHeaders.count(BB)) {
1483fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
14842249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner          << "' into predecessor block '" << PredBBs[0]->getName()
148578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - it might create an irreducible loop!\n");
148678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
148778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
14886f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1489c69908695af9cf509bf498a492854db5f0556e0fNadav Rotem  unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, Threshold);
149078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (DuplicationCost > Threshold) {
1491fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
149278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << DuplicationCost << "\n");
149378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
149478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
14956f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
14962249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // And finally, do it!  Start by factoring the predecessors is needed.
14972249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  BasicBlock *PredBB;
14982249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  if (PredBBs.size() == 1)
14992249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    PredBB = PredBBs[0];
15002249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  else {
15012249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
15022249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner          << " common predecessors.\n");
15032fac1d5d61a83c45dcf44119c41dce15ef10e9dcJakub Staszak    PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
15042249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  }
15056f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
150678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Okay, we decided to do this!  Clone all the instructions in BB onto the end
150778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // of PredBB.
1508fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene  DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
150978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
151078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << DuplicationCost << " block is:" << *BB << "\n");
15116f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
15122249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // Unless PredBB ends with an unconditional branch, split the edge so that we
15132249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  // can just clone the bits from BB into the end of the new PredBB.
1514d668839cb9b5db6865fd98e5e7dfccd64abf3e95Chris Lattner  BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
15156f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1516d668839cb9b5db6865fd98e5e7dfccd64abf3e95Chris Lattner  if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
15172249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    PredBB = SplitEdge(PredBB, BB, this);
15182249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner    OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
15192249a0b1bd0941e61c0b87f2f64a5c8cab45f14cChris Lattner  }
15206f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
152178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We are going to have to map operands from the original BB block into the
152278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB block.  Evaluate PHI nodes in BB.
152378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
15246f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
152578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::iterator BI = BB->begin();
152678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
152778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
15286f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
152978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Clone the non-phi instructions of BB into PredBB, keeping track of the
153078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
153178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; BI != BB->end(); ++BI) {
153278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Instruction *New = BI->clone();
15336f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
153478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap operands to patch up intra-block references.
153578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
153678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
153778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
153878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (I != ValueMapping.end())
153978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          New->setOperand(i, I->second);
154078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
1541972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner
1542972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    // If this instruction can be simplified after the operands are updated,
1543972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    // just use the simplified value instead.  This frequently happens due to
1544972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    // phi translation.
1545972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    if (Value *IV = SimplifyInstruction(New, TD)) {
1546972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      delete New;
1547972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      ValueMapping[BI] = IV;
1548972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    } else {
1549972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      // Otherwise, insert the new instruction into the block.
1550972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      New->setName(BI->getName());
1551972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      PredBB->getInstList().insert(OldPredBranch, New);
1552972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner      ValueMapping[BI] = New;
1553972a46c96a06ecb0e8ce73c796c313175abe76bbChris Lattner    }
155478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
15556f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
155678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Check to see if the targets of the branch had PHI nodes. If so, we need to
155778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // add entries to the PHI nodes for branch from PredBB now.
155878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
155978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
156078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
156178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
156278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
15636f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
156478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If there were values defined in BB that are used outside the block, then we
156578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // now have to update all uses of the value to use either the original value,
156678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
156778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
156878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SSAUpdater SSAUpdate;
156978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<Use*, 16> UsesToRename;
157078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
157178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Scan all uses of this instruction to see if it is used outside of its
157278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // block, and if so, record them in UsesToRename.
157378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
157478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner         ++UI) {
157578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Instruction *User = cast<Instruction>(*UI);
157678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
157778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
157878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          continue;
157978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else if (User->getParent() == BB)
158078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        continue;
15816f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
158278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      UsesToRename.push_back(&UI.getUse());
158378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
15846f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
158578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If there are no uses outside the block, we're done with this instruction.
158678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (UsesToRename.empty())
158778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
15886f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
1589fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
15906f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
159178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
159278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
159378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // with the two values we know.
1594fc6e29d4ab52b7d3efd83846ed495a9ca7e51e49Duncan Sands    SSAUpdate.Initialize(I->getType(), I->getName());
159578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(BB, I);
159678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
15976f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
159878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    while (!UsesToRename.empty())
159978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1600fe7fe6603fea2ca121282cd329f5300ea7d9fd51David Greene    DEBUG(dbgs() << "\n");
160178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
16026f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
160378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
160478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // that we nuked.
160536c4debc94e7c68c769dfda781851a0c963dd746Owen Anderson  BB->removePredecessor(PredBB, true);
16066f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
160778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Remove the unconditional branch at the end of the PredBB block.
160878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  OldPredBranch->eraseFromParent();
16096f9a8307e087110d57b1e63dae154d351f6b0f6bFrits van Bommel
161078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  ++NumDupes;
161178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return true;
161278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
161378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
161478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1615