JumpThreading.cpp revision fddcf47a249fe3a1102257deddc996ee327a85cb
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"
16177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/IntrinsicInst.h"
171ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson#include "llvm/LLVMContext.h"
188383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Pass.h"
199819ef7742cc2e3af92a0b760fa33e30218ff7bbChris Lattner#include "llvm/Analysis/InstructionSimplify.h"
202cc675180b06d0a2173365a4015606933f1a285dChris Lattner#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21bd3401fa98b578080e227afce940bca80137dea6Chris Lattner#include "llvm/Transforms/Utils/Local.h"
22433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner#include "llvm/Transforms/Utils/SSAUpdater.h"
23ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner#include "llvm/Target/TargetData.h"
24fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/DenseMap.h"
25fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/Statistic.h"
26fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/STLExtras.h"
27fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallPtrSet.h"
28fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallSet.h"
298383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Support/CommandLine.h"
30177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/Support/Debug.h"
3193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar#include "llvm/Support/raw_ostream.h"
328383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerusing namespace llvm;
338383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
34bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumThreads, "Number of jumps threaded");
35bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumFolds,   "Number of terminators folded");
3678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSTATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
378383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
38177480b7ede0441135572d641a2497df25a7d95fChris Lattnerstatic cl::opt<unsigned>
39177480b7ede0441135572d641a2497df25a7d95fChris LattnerThreshold("jump-threading-threshold",
40177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::desc("Max block size to duplicate for jump threading"),
41177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::init(6), cl::Hidden);
42177480b7ede0441135572d641a2497df25a7d95fChris Lattner
438383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnernamespace {
4494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// This pass performs 'jump threading', which looks at blocks that have
4594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// multiple predecessors and multiple successors.  If one or more of the
4694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// predecessors of the block can be proven to always jump to one of the
4794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// successors, we forward the edge from the predecessor to the successor by
4894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// duplicating the contents of this block.
4994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5094019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// An example of when this can occur is code like this:
5194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if () { ...
5394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///     X = 4;
5494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   }
5594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if (X < 3) {
5694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// In this case, the unconditional branch at the end of the first if can be
5894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// revectored to the false side of the second if.
5994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
603e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  class JumpThreading : public FunctionPass {
61ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    TargetData *TD;
62fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#ifdef NDEBUG
63fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#else
65fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#endif
678383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  public:
688383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    static char ID; // Pass identification
69ae73dc1448d25b02cabc7c64c86c64371453dda8Dan Gohman    JumpThreading() : FunctionPass(&ID) {}
708383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
718383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    bool runOnFunction(Function &F);
72fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    void FindLoopHeaders(Function &F);
73fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
74c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    bool ProcessBlock(BasicBlock *BB);
755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    BasicBlock *SuccBB);
7778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
7878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                          BasicBlock *PredBB);
795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    typedef SmallVectorImpl<std::pair<ConstantInt*,
815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      BasicBlock*> > PredValueInfo;
825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                         PredValueInfo &Result);
855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
88421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
906bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
91d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner    bool ProcessJumpOnPHI(PHINode *PN);
9269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
9369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
948383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  };
958383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
968383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
97844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar JumpThreading::ID = 0;
98844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<JumpThreading>
99844731a7f1909f55935e3514c9e713a62d67662eDan GohmanX("jump-threading", "Jump Threading");
100844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
1018383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// Public interface to the Jump Threading pass
1028383a7b7a6acdae478d4b4c2520915153b73f676Chris LattnerFunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
1038383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
1048383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// runOnFunction - Top level algorithm.
1058383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner///
1068383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerbool JumpThreading::runOnFunction(Function &F) {
10793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
10802a436c48ecff9e34d50ce0a2f861e5acdd9bf3fDan Gohman  TD = getAnalysisIfAvailable<TargetData>();
109bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
110fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindLoopHeaders(F);
111fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
112bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  bool AnotherIteration = true, EverChanged = false;
113bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  while (AnotherIteration) {
114bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = false;
115bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    bool Changed = false;
116421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
117421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BasicBlock *BB = I;
118421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      while (ProcessBlock(BB))
119bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Changed = true;
120421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
121421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ++I;
122421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
123421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // If the block is trivially dead, zap it.  This eliminates the successor
124421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // edges which simplifies the CFG.
125421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      if (pred_begin(BB) == pred_end(BB) &&
12620fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner          BB != &BB->getParent()->getEntryBlock()) {
12793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        DEBUG(errs() << "  JT: Deleting dead block '" << BB->getName()
12878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              << "' with terminator: " << *BB->getTerminator() << '\n');
129fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.erase(BB);
130421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        DeleteDeadBlock(BB);
131421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        Changed = true;
132421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      }
133421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
134bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = Changed;
135bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EverChanged |= Changed;
136bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
137fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
138fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  LoopHeaders.clear();
139bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  return EverChanged;
1408383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
141177480b7ede0441135572d641a2497df25a7d95fChris Lattner
14278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
14378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// thread across it.
14478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
14578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  /// Ignore PHI nodes, these will be flattened when duplication happens.
14678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::const_iterator I = BB->getFirstNonPHI();
14778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
14878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Sum up the cost of each instruction until we get to the terminator.  Don't
14978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // include the terminator because the copy won't include it.
15078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned Size = 0;
15178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; !isa<TerminatorInst>(I); ++I) {
15278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Debugger intrinsics don't incur code size.
15378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<DbgInfoIntrinsic>(I)) continue;
15478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
15578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If this is a pointer->pointer bitcast, it is free.
15678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
15778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
15878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
15978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // All other instructions count for at least one unit.
16078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ++Size;
16178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
16278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Calls are more expensive.  If they are non-intrinsic calls, we model them
16378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 4.  If they are a non-vector intrinsic, we model them
16478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 2 total, and if they are a vector intrinsic, we model
16578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // them as having cost 1.
16678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
16778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (!isa<IntrinsicInst>(CI))
16878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 3;
16978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      else if (!isa<VectorType>(CI->getType()))
17078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 1;
17178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
17278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
17378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Threading through a switch statement is particularly profitable.  If this
17578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // block ends in a switch, decrease its cost to make it more likely to happen.
17678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(I))
17778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Size = Size > 6 ? Size-6 : 0;
17878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return Size;
18078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
18178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
18278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
183c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner//===----------------------------------------------------------------------===//
184c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
185fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
186fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// delete the From instruction.  In addition to a basic RAUW, this does a
187fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// recursive simplification of the newly formed instructions.  This catches
188fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// things where one simplification exposes other opportunities.  This only
189fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// simplifies and deletes scalar operations, it does not change the CFG.
190fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner///
191fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattnerstatic void ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
192fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner                                      const TargetData *TD) {
193fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
194fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
195fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // FromHandle - This keeps a weakvh on the from value so that we can know if
196fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // it gets deleted out from under us in a recursive simplification.
197fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  WeakVH FromHandle(From);
198fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
199fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  while (!From->use_empty()) {
200fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // Update the instruction to use the new value.
201fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    Use &U = From->use_begin().getUse();
202fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    Instruction *User = cast<Instruction>(U.getUser());
203fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    U = To;
204fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
205fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // See if we can simplify it.
206fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    if (Value *V = SimplifyInstruction(User, TD)) {
207fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // Recursively simplify this.
208fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      ReplaceAndSimplifyAllUses(User, V, TD);
209fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
210fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // If the recursive simplification ended up revisiting and deleting 'From'
211fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // then we're done.
212fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (FromHandle == 0)
213fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        return;
214fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    }
215fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  }
216fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  From->eraseFromParent();
217fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner}
218fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
219c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
220c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
221c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
222c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
223c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///
224c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
225c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// nodes that collapse into identity values.  For example, if we have:
226c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///   x = phi(1, 0, 0, 0)
227c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///   y = and x, z
228c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///
229c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
230c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// recursively fold the and to 0.
231c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattnerstatic void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
232c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                                         TargetData *TD) {
233c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // This only adjusts blocks with PHI nodes.
234c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  if (!isa<PHINode>(BB->begin()))
235c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    return;
236c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
237c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
238c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
239c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // that can be removed.
240c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  BB->removePredecessor(Pred, true);
241c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
242c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  WeakVH PhiIt = &BB->front();
243c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
244c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
245c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
246c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    Value *PNV = PN->hasConstantValue();
247c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    if (PNV == 0) continue;
248c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
249fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // If we're able to simplify the phi to a single value, substitute the new
250fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // value into all of its uses.
251c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    assert(PNV != PN && "hasConstantValue broken");
252c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
253fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    ReplaceAndSimplifyAllUses(PN, PNV, TD);
254c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
255c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // If recursive simplification ended up deleting the next PHI node we would
256c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
257c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // of the block.
258c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    if (PhiIt == 0) PhiIt = &BB->front();
259c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  }
260c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner}
261c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
262c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner//===----------------------------------------------------------------------===//
263c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
26478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
265fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// FindLoopHeaders - We do not want jump threading to turn proper loop
266fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// structures into irreducible loops.  Doing this breaks up the loop nesting
267fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// hierarchy and pessimizes later transformations.  To prevent this from
268fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// happening, we first have to find the loop headers.  Here we approximate this
269fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// by finding targets of backedges in the CFG.
270fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
271fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// Note that there definitely are cases when we want to allow threading of
272fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edges across a loop header.  For example, threading a jump from outside the
273fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// loop (the preheader) to an exit block of the loop is definitely profitable.
274fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// It is also almost always profitable to thread backedges from within the loop
275fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// to exit blocks, and is often profitable to thread backedges to other blocks
276fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// within the loop (forming a nested loop).  This simple analysis is not rich
277fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// enough to track all of these properties and keep it up-to-date as the CFG
278fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// mutates, so we don't allow any of these transformations.
279fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
280fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpvoid JumpThreading::FindLoopHeaders(Function &F) {
281fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
282fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindFunctionBackedges(F, Edges);
283fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
284fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
285fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
286fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
287fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
2885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
2895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// if we can infer that the value is a known ConstantInt in any of our
290e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner/// predecessors.  If so, return the known list of value and pred BB in the
2915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// result vector.  If a value is known to be undef, it is returned as null.
2925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
2935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// The BB basic block is known to start with a PHI node.
2945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
2955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// This returns true if there were any known values.
2965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
297785672534d32d196d04ad022c111fde3864e0d28Chris Lattner///
2985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// TODO: Per PR2563, we could infer value range information about a predecessor
2995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// based on its terminator.
3005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::
3015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
3025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
3035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a constantint, then it is known in all predecessors.
3055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
3065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(V);
3075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    Result.resize(TheFirstPHI->getNumIncomingValues());
3085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = Result.size(); i != e; ++i)
3095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
3105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return true;
3115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a non-instruction value, or an instruction in a different block,
3145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // then it can't be derived from a PHI.
3155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
3165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (I == 0 || I->getParent() != BB)
3175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
3185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// If I is a PHI node, then we know the incoming values for any constants.
3205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PHINode *PN = dyn_cast<PHINode>(I)) {
3215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Value *InVal = PN->getIncomingValue(i);
3235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
3245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
3255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
3265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return !Result.empty();
3295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
3325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle some boolean conditions.
3345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (I->getType()->getPrimitiveSizeInBits() == 1) {
3355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X | true -> true
3365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X & false -> false
3375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (I->getOpcode() == Instruction::Or ||
3385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        I->getOpcode() == Instruction::And) {
3395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
3405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
3415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (LHSVals.empty() && RHSVals.empty())
3435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return false;
3445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ConstantInt *InterestingVal;
3465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (I->getOpcode() == Instruction::Or)
3475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getTrue(I->getContext());
3485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      else
3495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getFalse(I->getContext());
3505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Scan for the sentinel.
3525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
3535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
3545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(LHSVals[i]);
3555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
3565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
3575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(RHSVals[i]);
3585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
3595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
360785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
3615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // TODO: Should handle the NOT form of XOR.
3625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
36412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
3655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle compare with phi operand, where the PHI is defined in this block.
3665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
3685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PN && PN->getParent() == BB) {
3695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // We can do this simplification if any comparisons fold to true or false.
3705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // See if any do.
3715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        BasicBlock *PredBB = PN->getIncomingBlock(i);
3735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *LHS = PN->getIncomingValue(i);
3745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
3755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3769dbb42944c4d7caddab21016b24cca31019a3fafChris Lattner        Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS);
3775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (Res == 0) continue;
3785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (isa<UndefValue>(Res))
3805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
3815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
3825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair(CI, PredBB));
3835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
3865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // TODO: We could also recurse to see if we can determine constants another
3895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // way.
3905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
3925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
3935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3956bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
396e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
397e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// in an undefined jump, decide which block is best to revector to.
398e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
399e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// Since we can pick an arbitrary destination, we pick the successor with the
400e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// fewest predecessors.  This should reduce the in-degree of the others.
401e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
402e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattnerstatic unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
403e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  TerminatorInst *BBTerm = BB->getTerminator();
404e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinSucc = 0;
405e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
406e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // Compute the successor with the minimum number of predecessors.
407e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
408e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
409e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TestBB = BBTerm->getSuccessor(i);
410e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
411e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (NumPreds < MinNumPreds)
412e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      MinSucc = i;
413e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
414e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
415e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  return MinSucc;
416e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner}
417e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
418c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner/// ProcessBlock - If there are any predecessors whose control can be threaded
419177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// through to a successor, transform them now.
420c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattnerbool JumpThreading::ProcessBlock(BasicBlock *BB) {
42169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If this block has a single predecessor, and if that pred has a single
42269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // successor, merge the blocks.  This encourages recursive jump threading
42369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // because now the condition in this block can be threaded through
42469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors of our predecessor block.
4255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
426f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
427f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner        SinglePred != BB) {
428fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // If SinglePred was a loop header, BB becomes one.
429fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      if (LoopHeaders.erase(SinglePred))
430fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.insert(BB);
431fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
4323d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Remember if SinglePred was the entry block of the function.  If so, we
4333d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // will need to move BB back to the entry position.
4343d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
43569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      MergeBasicBlockIntoOnlyPred(BB);
4363d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner
4373d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      if (isEntry && BB != &BB->getParent()->getEntryBlock())
4383d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner        BB->moveBefore(&BB->getParent()->getEntryBlock());
43969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
44069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
4415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look to see if the terminator is a branch of switch, if not we can't thread
4445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // it.
445177480b7ede0441135572d641a2497df25a7d95fChris Lattner  Value *Condition;
446bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
447bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Can't thread an unconditional jump.
448bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (BI->isUnconditional()) return false;
449177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = BI->getCondition();
450bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
451177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = SI->getCondition();
452177480b7ede0441135572d641a2497df25a7d95fChris Lattner  else
453177480b7ede0441135572d641a2497df25a7d95fChris Lattner    return false; // Must be an invoke.
454bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
455bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // If the terminator of this block is branching on a constant, simplify the
456037c781de797242ba652db775f1f2c5d2d4eb19bChris Lattner  // terminator to an unconditional branch.  This can occur due to threading in
457bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // other blocks.
458bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (isa<ConstantInt>(Condition)) {
45993b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
46078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *BB->getTerminator() << '\n');
461bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ++NumFolds;
462bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ConstantFoldTerminator(BB);
463bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    return true;
464bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
465bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
466421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the terminator is branching on an undef, we can pick any of the
467e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
468421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (isa<UndefValue>(Condition)) {
469e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
470421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
471421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Fold the branch/switch.
472e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TerminatorInst *BBTerm = BB->getTerminator();
473421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
474e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (i == BestSucc) continue;
475c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD);
476421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
477421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
47893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
47978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding undef terminator: " << *BBTerm << '\n');
480e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
481421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BBTerm->eraseFromParent();
482421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
483421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
484421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
485421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Instruction *CondInst = dyn_cast<Instruction>(Condition);
486421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
487421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the condition is an instruction defined in another block, see if a
488421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // predecessor has the same condition:
489421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBX, BBY
490421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //  BBX:
491421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBZ, BBW
492421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (!Condition->hasOneUse() && // Multiple uses.
493421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
494421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
495421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (isa<BranchInst>(BB->getTerminator())) {
496421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      for (; PI != E; ++PI)
497421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
498421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner          if (PBI->isConditional() && PBI->getCondition() == Condition &&
499421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner              ProcessBranchOnDuplicateCond(*PI, BB))
500421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner            return true;
5013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    } else {
5023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
5033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      for (; PI != E; ++PI)
5043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
5053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          if (PSI->getCondition() == Condition &&
5063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner              ProcessSwitchOnDuplicateCond(*PI, BB))
5073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner            return true;
508421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
509421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
510421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
511421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // All the rest of our checks depend on the condition being an instruction.
512421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (CondInst == 0)
513421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return false;
514421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
515177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // See if this is a phi node in the current block.
516421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
517421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (PN->getParent() == BB)
518421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      return ProcessJumpOnPHI(PN);
519177480b7ede0441135572d641a2497df25a7d95fChris Lattner
5209683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
5215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!isa<PHINode>(CondCmp->getOperand(0)) ||
5225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
5235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If we have a comparison, loop over the predecessors to see if there is
5245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // a condition with a lexically identical value.
5255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      pred_iterator PI = pred_begin(BB), E = pred_end(BB);
5265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (; PI != E; ++PI)
5275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PBI->isConditional() && *PI != BB) {
5295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
5305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              if (CI->getOperand(0) == CondCmp->getOperand(0) &&
5315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getOperand(1) == CondCmp->getOperand(1) &&
5325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getPredicate() == CondCmp->getPredicate()) {
5335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                // TODO: Could handle things like (x != 4) --> (x == 17)
5345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                if (ProcessBranchOnDuplicateCond(*PI, BB))
5355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  return true;
5365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              }
53779c740ff479dde322aceafe15887b162c19ea195Chris Lattner            }
53879c740ff479dde322aceafe15887b162c19ea195Chris Lattner          }
5395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
5409683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  }
54169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
54269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Check for some cases that are worth simplifying.  Right now we want to look
54369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // for loads that are used by a switch or by the condition for the branch.  If
54469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we see one, check to see if it's partially redundant.  If so, insert a PHI
54569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // which can then be used to thread the values.
54669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //
54769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This is particularly important because reg2mem inserts loads and stores all
54869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // over the place, and this blocks jump threading if we don't zap them.
549421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Value *SimplifyValue = CondInst;
55069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
55169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (isa<Constant>(CondCmp->getOperand(1)))
55269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SimplifyValue = CondCmp->getOperand(0);
55369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
55469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
55569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (SimplifyPartiallyRedundantLoad(LI))
55669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
55769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
5585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle a variety of cases where we are branching on something derived from
5605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a PHI node in the current block.  If we can prove that any predecessors
5615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // compute a predictable value based on a PHI node, thread those predecessors.
5625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  //
5635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // We only bother doing this if the current block has a PHI node and if the
5645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // conditional instruction lives in the current block.  If either condition
565e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // fails, this won't be a computable value anyway.
5665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
5675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (ProcessThreadableEdges(CondInst, BB))
5685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return true;
5695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
57169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
57269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // "(X == 4)" thread through this block.
573a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
574d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  return false;
575d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner}
576d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner
577421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
578421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// block that jump on exactly the same condition.  This means that we almost
579421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// always know the direction of the edge in the DESTBB:
580421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  PREDBB:
581421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, DESTBB, BBY
582421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  DESTBB:
583421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, BBZ, BBW
584421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///
585421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// If DESTBB has multiple predecessors, we can't just constant fold the branch
586421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// in DESTBB, we have to thread over it.
587421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattnerbool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
588421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                                 BasicBlock *BB) {
589421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
590421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
591421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If both successors of PredBB go to DESTBB, we don't know anything.  We can
592421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // fold the branch to an unconditional one, which allows other recursive
593421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // simplifications.
594421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  bool BranchDir;
595421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PredBI->getSuccessor(1) != BB)
596421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = true;
597421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else if (PredBI->getSuccessor(0) != BB)
598421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = false;
599421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else {
60093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << PredBB->getName()
60178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *PredBB->getTerminator() << '\n');
602421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
603421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(PredBB);
604421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
605421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
606421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
607421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
608421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
609421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the dest block has one predecessor, just fix the branch condition to a
610421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // constant and fold it.
611421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (BB->getSinglePredecessor()) {
61293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
61393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' folding condition to '" << BranchDir << "': "
61478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << *BB->getTerminator() << '\n');
615421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
6165a06cf644f35b873686c8694968192ad3385e36aChris Lattner    Value *OldCond = DestBI->getCondition();
6171d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
6181d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                          BranchDir));
619421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(BB);
6205a06cf644f35b873686c8694968192ad3385e36aChris Lattner    RecursivelyDeleteTriviallyDeadInstructions(OldCond);
621421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
622421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
623bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
624421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
625421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Next, figure out which successor we are threading to.
626421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
627421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 2> Preds;
6295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Preds.push_back(PredBB);
6305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
631fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
6325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, Preds, SuccBB);
633421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
634421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6353cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
6363cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// block that switch on exactly the same condition.  This means that we almost
6373cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// always know the direction of the edge in the DESTBB:
6383cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  PREDBB:
6393cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... DESTBB, BBY ... ]
6403cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  DESTBB:
6413cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... BBZ, BBW ]
6423cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///
6433cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// Optimizing switches like this is very important, because simplifycfg builds
6443cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// switches out of repeated 'if' conditions.
6453cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattnerbool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
6463cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                                 BasicBlock *DestBB) {
6472c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  // Can't thread edge to self.
6482c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  if (PredBB == DestBB)
6492c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner    return false;
6502c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner
6513cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
6523cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
6533cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6543cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // There are a variety of optimizations that we can potentially do on these
6553cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // blocks: we order them from most to least preferable.
6563cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6573cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
6583cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // directly to their destination.  This does not introduce *any* code size
6596b233395025069f63156ea2b524cdb708a14731fDale Johannesen  // growth.  Skip debug info first.
6606b233395025069f63156ea2b524cdb708a14731fDale Johannesen  BasicBlock::iterator BBI = DestBB->begin();
6616b233395025069f63156ea2b524cdb708a14731fDale Johannesen  while (isa<DbgInfoIntrinsic>(BBI))
6626b233395025069f63156ea2b524cdb708a14731fDale Johannesen    BBI++;
6633cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6643cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // FIXME: Thread if it just contains a PHI.
6656b233395025069f63156ea2b524cdb708a14731fDale Johannesen  if (isa<SwitchInst>(BBI)) {
6663cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool MadeChange = false;
6673cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    // Ignore the default edge for now.
6683cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
6693cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      ConstantInt *DestVal = DestSI->getCaseValue(i);
6703cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      BasicBlock *DestSucc = DestSI->getSuccessor(i);
6713cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6723cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
6733cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // PredSI has an explicit case for it.  If so, forward.  If it is covered
6743cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // by the default case, we can't update PredSI.
6753cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      unsigned PredCase = PredSI->findCaseValue(DestVal);
6763cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredCase == 0) continue;
6773cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6783cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If PredSI doesn't go to DestBB on this value, then it won't reach the
6793cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // case on this condition.
6803cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredSI->getSuccessor(PredCase) != DestBB &&
6813cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          DestSI->getSuccessor(i) != DestBB)
6823cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        continue;
6833cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6843cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Otherwise, we're safe to make the change.  Make sure that the edge from
6853cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // DestSI to DestSucc is not critical and has no PHI nodes.
68693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
68793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "THROUGH: " << *DestSI);
6883cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If the destination has PHI nodes, just split the edge for updating
6903cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // simplicity.
6913cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
6923cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        SplitCriticalEdge(DestSI, i, this);
6933cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        DestSucc = DestSI->getSuccessor(i);
6943cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      }
6953cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      FoldSingleEntryPHINodes(DestSucc);
6963cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      PredSI->setSuccessor(PredCase, DestSucc);
6973cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      MadeChange = true;
6983cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    }
6993cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7003cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (MadeChange)
7013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      return true;
7023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  }
7033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  return false;
7053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner}
7063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
70869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
70969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// load instruction, eliminate it by replacing it with a PHI node.  This is an
71069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// important optimization that encourages jump threading, and needs to be run
71169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// interlaced with other jump threading tasks.
71269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattnerbool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
71369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Don't hack volatile loads.
71469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LI->isVolatile()) return false;
71569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
71669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the load is defined in a block with exactly one predecessor, it can't be
71769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // partially redundant.
71869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *LoadBB = LI->getParent();
71969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadBB->getSinglePredecessor())
72069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
72169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
72269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Value *LoadedPtr = LI->getOperand(0);
72369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
72469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded operand is defined in the LoadBB, it can't be available.
72569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // FIXME: Could do PHI translation, that would be fun :)
72669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
72769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (PtrOp->getParent() == LoadBB)
72869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return false;
72969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
73069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Scan a few instructions up from the load, to see if it is obviously live at
73169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // the entry to its block.
73269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock::iterator BBIt = LI;
73369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
73452c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner  if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
73552c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner                                                     BBIt, 6)) {
73669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If the value if the load is locally available within the block, just use
73769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // it.  This frequently occurs for reg2mem'd allocas.
73869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
7392a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner
7402a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // If the returned value is the load itself, replace with an undef. This can
7412a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // only happen in dead loops.
7429e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
74369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->replaceAllUsesWith(AvailableVal);
74469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->eraseFromParent();
74569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return true;
74669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
74769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Otherwise, if we scanned the whole block and got to the top of the block,
74969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we know the block is locally transparent to the load.  If not, something
75069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // might clobber its value.
75169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BBIt != LoadBB->begin())
75269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
75369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
75469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
75569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SmallPtrSet<BasicBlock*, 8> PredsScanned;
75669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
75769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  AvailablePredsTy AvailablePreds;
75869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *OneUnavailablePred = 0;
75969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
76069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If we got here, the loaded value is transparent through to the start of the
76169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // block.  Check to see if it is available in any of the predecessor blocks.
76269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
76369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       PI != PE; ++PI) {
76469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BasicBlock *PredBB = *PI;
76569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
76669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If we already scanned this predecessor, skip it.
76769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredsScanned.insert(PredBB))
76869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
76969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Scan the predecessor to see if the value is available in the pred.
77169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BBIt = PredBB->end();
77252c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
77369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredAvailable) {
77469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred = PredBB;
77569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
77669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
77769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If so, this load is partially redundant.  Remember this info so that we
77969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // can create a PHI node.
78069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
78169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
78269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
78369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded value isn't available in any predecessor, it isn't partially
78469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // redundant.
78569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (AvailablePreds.empty()) return false;
78669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
78769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Okay, the loaded value is available in at least one (and maybe all!)
78869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors.  If the value is unavailable in more than one unique
78969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessor, we want to insert a merge block for those common predecessors.
79069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This ensures that we only have to insert one reload, thus not increasing
79169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // code size.
79269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *UnavailablePred = 0;
79369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
79469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If there is exactly one predecessor where the value is unavailable, the
79569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // already computed 'OneUnavailablePred' block is it.  If it ends in an
79669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // unconditional branch, we know that it isn't a critical edge.
79769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (PredsScanned.size() == AvailablePreds.size()+1 &&
79869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
79969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred = OneUnavailablePred;
80069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  } else if (PredsScanned.size() != AvailablePreds.size()) {
80169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Otherwise, we had multiple unavailable predecessors or we had a critical
80269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // edge from the one.
80369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<BasicBlock*, 8> PredsToSplit;
80469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
80569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
80669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
80769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      AvailablePredSet.insert(AvailablePreds[i].first);
80869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
80969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Add all the unavailable predecessors to the PredsToSplit list.
81069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
81169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner         PI != PE; ++PI)
81269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!AvailablePredSet.count(*PI))
81369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        PredsToSplit.push_back(*PI);
81469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Split them out to their own block.
81669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred =
81769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
81869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                             "thread-split", this);
81969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
82069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
82169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the value isn't available in all predecessors, then there will be
82269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // exactly one where it isn't available.  Insert a load on that edge and add
82369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // it to the AvailablePreds list.
82469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (UnavailablePred) {
82569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
82669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Can't handle critical edge here!");
82769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
82869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 UnavailablePred->getTerminator());
82969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
83069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
83169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Now we know that each predecessor of this block has a value in
83369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // AvailablePreds, sort them for efficient access as we're walking the preds.
834a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
83569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Create a PHI node at the start of the block for the PRE'd load value.
83769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
83869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PN->takeName(LI);
83969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
84069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Insert new entries into the PHI for each predecessor.  A single block may
84169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // have multiple entries here.
84269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
84369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       ++PI) {
84469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePredsTy::iterator I =
84569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
84669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                       std::make_pair(*PI, (Value*)0));
84769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
84869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(I != AvailablePreds.end() && I->first == *PI &&
84969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Didn't find entry for predecessor!");
85069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    PN->addIncoming(I->second, I->first);
85269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
85369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //cerr << "PRE: " << *LI << *PN << "\n";
85569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->replaceAllUsesWith(PN);
85769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->eraseFromParent();
85869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  return true;
86069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner}
86169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
8625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// FindMostPopularDest - The specified list contains multiple possible
8635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// threadable destinations.  Pick the one that occurs the most frequently in
8645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the list.
8655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerstatic BasicBlock *
8665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerFindMostPopularDest(BasicBlock *BB,
8675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    const SmallVectorImpl<std::pair<BasicBlock*,
8685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  BasicBlock*> > &PredToDestList) {
8695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredToDestList.empty());
870785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine popularity.  If there are multiple possible destinations, we
8725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // explicitly choose to ignore 'undef' destinations.  We prefer to thread
8735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // blocks with known and real destinations to threading undef.  We'll handle
8745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // them later if interesting.
8755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned> DestPopularity;
8765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
8775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second)
8785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestPopularity[PredToDestList[i].second]++;
879785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Find the most popular dest.
8815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
8825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = DPI->first;
8835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned Popularity = DPI->second;
8845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 4> SamePopularity;
88578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
8865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (++DPI; DPI != DestPopularity.end(); ++DPI) {
8875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the popularity of this entry isn't higher than the popularity we've
8885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // seen so far, ignore it.
8895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (DPI->second < Popularity)
8905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ; // ignore.
8915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (DPI->second == Popularity) {
8925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is the same as what we've seen so far, keep track of it.
8935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.push_back(DPI->first);
8945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    } else {
8955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is more popular, remember it.
8965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.clear();
8975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = DPI->first;
8985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Popularity = DPI->second;
8995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
90078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
9015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, now we know the most popular destination.  If there is more than
9035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // destination, we need to determine one.  This is arbitrary, but we need
9045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to make a deterministic decision.  Pick the first one that appears in the
9055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // successor list.
9065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!SamePopularity.empty()) {
9075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SamePopularity.push_back(MostPopularDest);
9085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    TerminatorInst *TI = BB->getTerminator();
9095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0; ; ++i) {
9105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
91112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (std::find(SamePopularity.begin(), SamePopularity.end(),
9135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    TI->getSuccessor(i)) == SamePopularity.end())
9145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        continue;
9155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = TI->getSuccessor(i);
91712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      break;
91812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
91912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
92012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, we have finally picked the most popular destination.
9225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return MostPopularDest;
9235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
9245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
9265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                           BasicBlock *BB) {
9275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If threading this would thread across a loop header, don't even try to
9285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // thread the edge.
9295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (LoopHeaders.count(BB))
93012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
93112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
9335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
93412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
9355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredValues.empty() &&
9365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         "ComputeValueKnownInPredecessors returned true with no values");
9375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DEBUG(errs() << "IN BB: " << *BB;
9395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << "  BB '" << BB->getName() << "': FOUND condition = ";
9415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PredValues[i].first)
9425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << *PredValues[i].first;
9435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          else
9445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << "UNDEF";
9455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << " for pred '" << PredValues[i].second->getName()
9465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << "'.\n";
9475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        });
94812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Decide what we want to thread through.  Convert our list of known values to
9505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a list of known destinations for each pred.  This also discards duplicate
9515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors and keeps track of the undefined inputs (which are represented
952e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // as a null dest in the PredToDestList).
9535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallPtrSet<BasicBlock*, 16> SeenPreds;
9545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
9555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *OnlyDest = 0;
9575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
9585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *Pred = PredValues[i].second;
9615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!SeenPreds.insert(Pred))
9625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      continue;  // Duplicate predecessor entry.
96312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the predecessor ends with an indirect goto, we can't change its
9655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // destination.
9665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (isa<IndirectBrInst>(Pred->getTerminator()))
96712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      continue;
96812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *Val = PredValues[i].first;
9705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *DestBB;
9725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (Val == 0)      // Undef.
9735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = 0;
9745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
9755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = BI->getSuccessor(Val->isZero());
9765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else {
9775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
9785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = SI->getSuccessor(SI->findCaseValue(Val));
97912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
9805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If we have exactly one destination, remember it for efficiency below.
9825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (i == 0)
9835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = DestBB;
9845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (OnlyDest != DestBB)
9855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = MultipleDestSentinel;
98612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredToDestList.push_back(std::make_pair(Pred, DestBB));
98812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
98912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If all edges were unthreadable, we fail.
9915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredToDestList.empty())
99212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
99312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine which is the most common successor.  If we have many inputs and
9955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // this block is a switch, we want to start by threading the batch that goes
9965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to the most popular destination first.  If we only know about one
9975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threadable destination (the common case) we can avoid this.
9985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = OnlyDest;
99912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == MultipleDestSentinel)
10015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = FindMostPopularDest(BB, PredToDestList);
100212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Now that we know what the most popular destination is, factor all
10045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors that will jump to it into a single predecessor.
10055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 16> PredsToFactor;
10065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
10075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second == MostPopularDest) {
10085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      BasicBlock *Pred = PredToDestList[i].first;
10095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // This predecessor may be a switch or something else that has multiple
10115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // edges to the block.  Factor each of these edges by listing them
10125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // according to # occurrences in PredsToFactor.
10135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      TerminatorInst *PredTI = Pred->getTerminator();
10145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
10155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (PredTI->getSuccessor(i) == BB)
10165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          PredsToFactor.push_back(Pred);
10175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
10185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If the threadable edges are branching on an undefined value, we get to pick
10205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // the destination that these predecessors should get to.
10215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == 0)
10225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = BB->getTerminator()->
10235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            getSuccessor(GetBestDestForJumpOnUndef(BB));
10245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
102512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  // Ok, try to thread it!
10265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, PredsToFactor, MostPopularDest);
10275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
10285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
10305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the current block.  See if there are any simplifications we can do based on
10315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// inputs to the phi node.
10325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
10335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
10345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *BB = PN->getParent();
10355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If any of the predecessor blocks end in an unconditional branch, we can
10375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // *duplicate* the jump into that block in order to further encourage jump
10385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threading and to eliminate cases where we have branch on a phi of an icmp
10395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // (branch on icmp is much better).
10405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // We don't want to do this tranformation for switches, because we don't
10425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // really want to duplicate a switch.
10435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<SwitchInst>(BB->getTerminator()))
10445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
10455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look for unconditional branch predecessors.
10475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *PredBB = PN->getIncomingBlock(i);
10495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
10505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (PredBr->isUnconditional() &&
10515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          // Try to duplicate BB into PredBB.
10525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
10535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return true;
10545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
10555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
105712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel}
105812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
105912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
106078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
106178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
106278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// NewPred using the entries from OldPred (suitably mapped).
106378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
106478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *OldPred,
106578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *NewPred,
106678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                     DenseMap<Instruction*, Value*> &ValueMap) {
106778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator PNI = PHIBB->begin();
106878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner       PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
106978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Ok, we have a PHI node.  Figure out what the incoming value was for the
107078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // DestBlock.
107178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Value *IV = PN->getIncomingValueForBlock(OldPred);
1072bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
107378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap the value if necessary.
107478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
107578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
107678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (I != ValueMap.end())
107778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        IV = I->second;
1078bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    }
107978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
108078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PN->addIncoming(IV, NewPred);
1081bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  }
1082fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
1083fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
10845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ThreadEdge - We have decided that it is safe and profitable to factor the
10855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
10865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// across BB.  Transform the IR to reflect this change.
10875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ThreadEdge(BasicBlock *BB,
10885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                               const SmallVectorImpl<BasicBlock*> &PredBBs,
1089bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner                               BasicBlock *SuccBB) {
1090eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  // If threading to the same block as we come from, we would infinite loop.
1091eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  if (SuccBB == BB) {
109293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  Not threading across BB '" << BB->getName()
109393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - would thread to self!\n");
1094eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner    return false;
1095eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  }
1096eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner
1097fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // If threading this would thread across a loop header, don't thread the edge.
1098fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // See the comments above FindLoopHeaders for justifications and caveats.
1099fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (LoopHeaders.count(BB)) {
11005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Not threading across loop header BB '" << BB->getName()
110193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' to dest BB '" << SuccBB->getName()
110293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - it might create an irreducible loop!\n");
1103fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    return false;
1104fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
1105fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
110678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
110778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (JumpThreadCost > Threshold) {
110878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not threading BB '" << BB->getName()
110978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << JumpThreadCost << "\n");
111078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
111178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
111278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
11135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // And finally, do it!  Start by factoring the predecessors is needed.
11145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *PredBB;
11155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredBBs.size() == 1)
11165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = PredBBs[0];
11175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  else {
11185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Factoring out " << PredBBs.size()
11195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << " common predecessors.\n");
11205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
11215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                    ".thr_comm", this);
11225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
11235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
1124a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // And finally, do it!
112593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1126460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar        << SuccBB->getName() << "' with cost: " << JumpThreadCost
112793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << ", across block:\n    "
112893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << *BB << "\n");
1129a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
1130bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We are going to have to map operands from the original BB block to the new
1131bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1132bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // account for entry from PredBB.
1133bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
1134bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
11351d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
11361d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getName()+".thread",
11371d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getParent(), BB);
1138bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  NewBB->moveAfter(PredBB);
1139bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1140bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BasicBlock::iterator BI = BB->begin();
1141bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1142bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1143bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1144bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Clone the non-phi instructions of BB into NewBB, keeping track of the
1145bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
1146bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; !isa<TerminatorInst>(BI); ++BI) {
11476776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky    Instruction *New = BI->clone();
1148460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar    New->setName(BI->getName());
1149bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    NewBB->getInstList().push_back(New);
1150bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[BI] = New;
1151bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1152bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Remap operands to patch up intra-block references.
1153bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1154f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1155f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1156f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        if (I != ValueMapping.end())
1157f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman          New->setOperand(i, I->second);
1158f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      }
1159bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
1160bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1161bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We didn't copy the terminator from BB over to NewBB, because there is now
1162bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // an unconditional jump to SuccBB.  Insert the unconditional jump.
1163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BranchInst::Create(SuccBB, NewBB);
1164bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1165bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1166bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // PHI nodes for NewBB now.
116778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1168177480b7ede0441135572d641a2497df25a7d95fChris Lattner
1169433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // If there were values defined in BB that are used outside the block, then we
1170433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // now have to update all uses of the value to use either the original value,
1171433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
1172433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
1173433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SSAUpdater SSAUpdate;
1174433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SmallVector<Use*, 16> UsesToRename;
1175433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1176433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // Scan all uses of this instruction to see if it is used outside of its
1177433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // block, and if so, record them in UsesToRename.
1178433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1179433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner         ++UI) {
1180433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Instruction *User = cast<Instruction>(*UI);
1181433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1182433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
1183433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          continue;
1184433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      } else if (User->getParent() == BB)
1185433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        continue;
1186433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1187433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      UsesToRename.push_back(&UI.getUse());
1188433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    }
1189433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1190433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // If there are no uses outside the block, we're done with this instruction.
1191433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    if (UsesToRename.empty())
1192433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      continue;
1193433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1194433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1195433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1196433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
1197433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1198433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // with the two values we know.
1199433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.Initialize(I);
1200433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(BB, I);
1201433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1202433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1203433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    while (!UsesToRename.empty())
1204433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1205433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "\n");
1206433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  }
1207433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1208433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1209ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1210bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1211bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // us to simplify any PHI nodes in BB.
1212bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  TerminatorInst *PredTerm = PredBB->getTerminator();
1213bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1214bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (PredTerm->getSuccessor(i) == BB) {
1215c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BB, PredBB, TD);
1216bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      PredTerm->setSuccessor(i, NewBB);
1217bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1218ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1219ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // At this point, the IR is fully up to date and consistent.  Do a quick scan
1220ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // over the new instructions and zap any that are constants or dead.  This
1221ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // frequently happens because of phi translation.
1222ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  BI = NewBB->begin();
1223ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1224ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    Instruction *Inst = BI++;
1225fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
1226e34537856a544c83513e390ac9552a8bc3823346Chris Lattner    if (Value *V = SimplifyInstruction(Inst, TD)) {
1227fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      WeakVH BIHandle(BI);
1228fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      ReplaceAndSimplifyAllUses(Inst, V, TD);
1229fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (BIHandle == 0)
1230fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        BI = NewBB->begin();
1231ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      continue;
1232ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    }
1233ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1234ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    RecursivelyDeleteTriviallyDeadInstructions(Inst);
1235ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  }
1236fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1237fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Threaded an edge!
1238fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  ++NumThreads;
1239fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return true;
1240177480b7ede0441135572d641a2497df25a7d95fChris Lattner}
124178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
124278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
124378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
124478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// If we can duplicate the contents of BB up into PredBB do so now, this
124578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// improves the odds that the branch will be on an analyzable instruction like
124678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// a compare.
124778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerbool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
124878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                     BasicBlock *PredBB) {
124978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If BB is a loop header, then duplicating this block outside the loop would
125078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // cause us to transform this into an irreducible loop, don't do this.
125178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // See the comments above FindLoopHeaders for justifications and caveats.
125278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (LoopHeaders.count(BB)) {
125378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating loop header '" << BB->getName()
125478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' into predecessor block '" << PredBB->getName()
125578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - it might create an irreducible loop!\n");
125678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
125778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
125878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
125978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
126078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (DuplicationCost > Threshold) {
126178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating BB '" << BB->getName()
126278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << DuplicationCost << "\n");
126378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
126478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
126578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
126678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Okay, we decided to do this!  Clone all the instructions in BB onto the end
126778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // of PredBB.
126878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DEBUG(errs() << "  Duplicating block '" << BB->getName() << "' into end of '"
126978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
127078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << DuplicationCost << " block is:" << *BB << "\n");
127178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
127278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We are going to have to map operands from the original BB block into the
127378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB block.  Evaluate PHI nodes in BB.
127478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
127578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
127678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::iterator BI = BB->begin();
127778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
127878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
127978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
128178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Clone the non-phi instructions of BB into PredBB, keeping track of the
128378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
128478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; BI != BB->end(); ++BI) {
128578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Instruction *New = BI->clone();
128678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    New->setName(BI->getName());
128778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PredBB->getInstList().insert(OldPredBranch, New);
128878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[BI] = New;
128978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap operands to patch up intra-block references.
129178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
129278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
129378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
129478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (I != ValueMapping.end())
129578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          New->setOperand(i, I->second);
129678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
129778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
129878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Check to see if the targets of the branch had PHI nodes. If so, we need to
130078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // add entries to the PHI nodes for branch from PredBB now.
130178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
130278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
130378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
130478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
130578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
130678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If there were values defined in BB that are used outside the block, then we
130878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // now have to update all uses of the value to use either the original value,
130978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
131078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
131178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SSAUpdater SSAUpdate;
131278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<Use*, 16> UsesToRename;
131378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
131478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Scan all uses of this instruction to see if it is used outside of its
131578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // block, and if so, record them in UsesToRename.
131678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
131778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner         ++UI) {
131878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Instruction *User = cast<Instruction>(*UI);
131978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
132078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
132178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          continue;
132278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else if (User->getParent() == BB)
132378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        continue;
132478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
132578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      UsesToRename.push_back(&UI.getUse());
132678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
132778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
132878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If there are no uses outside the block, we're done with this instruction.
132978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (UsesToRename.empty())
133078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
133178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
133378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
133578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
133678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // with the two values we know.
133778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.Initialize(I);
133878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(BB, I);
133978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
134078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    while (!UsesToRename.empty())
134278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
134378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "\n");
134478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
134578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
134778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // that we nuked.
1348c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  RemovePredecessorAndSimplify(BB, PredBB, TD);
134978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Remove the unconditional branch at the end of the PredBB block.
135178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  OldPredBranch->eraseFromParent();
135278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  ++NumDupes;
135478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return true;
135578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
135678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1358