Local.cpp revision 321a813c536e2f1f2f05bbe78a7fbf64046f0557
14d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===-- Local.cpp - Functions to perform local transformations ------------===//
2fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
94d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
104d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner// This family of functions perform various local transformations to the
114d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner// program.
124d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
134d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
144d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
154d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner#include "llvm/Transforms/Utils/Local.h"
1681ebc300891a81c305258aed980567514dff952dChris Lattner#include "llvm/Constants.h"
176cc8a93c486f889c5767278508bc655942ba408eChris Lattner#include "llvm/GlobalAlias.h"
18c79e1182470ed12f1f3d0d35c1725366519a9af7Devang Patel#include "llvm/GlobalVariable.h"
19c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/DerivedTypes.h"
207822c2ae077429d7bf6eb3f6ebf99d61f359b601Chris Lattner#include "llvm/Instructions.h"
21cf11035a6f9973d68d8eaf837d71dcf272d36b79Chris Lattner#include "llvm/Intrinsics.h"
22741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner#include "llvm/IntrinsicInst.h"
2319f2dc436df4f768484287a478973e83efd4202aChris Lattner#include "llvm/ADT/DenseMap.h"
24afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman#include "llvm/ADT/SmallPtrSet.h"
25cbbc6b74e357afbf8fb37fdeb177ed78021092d3Chris Lattner#include "llvm/Analysis/ConstantFolding.h"
2640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner#include "llvm/Analysis/InstructionSimplify.h"
27ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter#include "llvm/Analysis/ProfileInfo.h"
289fa038dc21e966dceb23f9410351e863e3ce1114Chris Lattner#include "llvm/Target/TargetData.h"
29dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/CFG.h"
30dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/Debug.h"
31c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/GetElementPtrTypeIterator.h"
32c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/MathExtras.h"
3319f2dc436df4f768484287a478973e83efd4202aChris Lattner#include "llvm/Support/ValueHandle.h"
34dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/raw_ostream.h"
35abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerusing namespace llvm;
36d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
374d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
386cc8a93c486f889c5767278508bc655942ba408eChris Lattner//  Local analysis.
396cc8a93c486f889c5767278508bc655942ba408eChris Lattner//
406cc8a93c486f889c5767278508bc655942ba408eChris Lattner
416cc8a93c486f889c5767278508bc655942ba408eChris Lattner/// isSafeToLoadUnconditionally - Return true if we know that executing a load
426cc8a93c486f889c5767278508bc655942ba408eChris Lattner/// from this value cannot trap.  If it is not obviously safe to load from the
436cc8a93c486f889c5767278508bc655942ba408eChris Lattner/// specified pointer, we do a quick local scan of the basic block containing
446cc8a93c486f889c5767278508bc655942ba408eChris Lattner/// ScanFrom, to determine if the address is already accessed.
456cc8a93c486f889c5767278508bc655942ba408eChris Lattnerbool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
466cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // If it is an alloca it is always safe to load from.
476cc8a93c486f889c5767278508bc655942ba408eChris Lattner  if (isa<AllocaInst>(V)) return true;
486cc8a93c486f889c5767278508bc655942ba408eChris Lattner
496cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // If it is a global variable it is mostly safe to load from.
506cc8a93c486f889c5767278508bc655942ba408eChris Lattner  if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
516cc8a93c486f889c5767278508bc655942ba408eChris Lattner    // Don't try to evaluate aliases.  External weak GV can be null.
526cc8a93c486f889c5767278508bc655942ba408eChris Lattner    return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
536cc8a93c486f889c5767278508bc655942ba408eChris Lattner
546cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // Otherwise, be a little bit agressive by scanning the local block where we
556cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // want to check to see if the pointer is already being loaded or stored
566cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // from/to.  If so, the previous load or store would have already trapped,
576cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // so there is no harm doing an extra load (also, CSE will later eliminate
586cc8a93c486f889c5767278508bc655942ba408eChris Lattner  // the load entirely).
596cc8a93c486f889c5767278508bc655942ba408eChris Lattner  BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
606cc8a93c486f889c5767278508bc655942ba408eChris Lattner
616cc8a93c486f889c5767278508bc655942ba408eChris Lattner  while (BBI != E) {
626cc8a93c486f889c5767278508bc655942ba408eChris Lattner    --BBI;
636cc8a93c486f889c5767278508bc655942ba408eChris Lattner
646cc8a93c486f889c5767278508bc655942ba408eChris Lattner    // If we see a free or a call which may write to memory (i.e. which might do
656cc8a93c486f889c5767278508bc655942ba408eChris Lattner    // a free) the pointer could be marked invalid.
66938e17663338b3b1b9f2dba21516c4c80876edb1Chris Lattner    if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
67938e17663338b3b1b9f2dba21516c4c80876edb1Chris Lattner        !isa<DbgInfoIntrinsic>(BBI))
686cc8a93c486f889c5767278508bc655942ba408eChris Lattner      return false;
696cc8a93c486f889c5767278508bc655942ba408eChris Lattner
706cc8a93c486f889c5767278508bc655942ba408eChris Lattner    if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
716cc8a93c486f889c5767278508bc655942ba408eChris Lattner      if (LI->getOperand(0) == V) return true;
726cc8a93c486f889c5767278508bc655942ba408eChris Lattner    } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
736cc8a93c486f889c5767278508bc655942ba408eChris Lattner      if (SI->getOperand(1) == V) return true;
746cc8a93c486f889c5767278508bc655942ba408eChris Lattner    }
756cc8a93c486f889c5767278508bc655942ba408eChris Lattner  }
766cc8a93c486f889c5767278508bc655942ba408eChris Lattner  return false;
776cc8a93c486f889c5767278508bc655942ba408eChris Lattner}
786cc8a93c486f889c5767278508bc655942ba408eChris Lattner
796cc8a93c486f889c5767278508bc655942ba408eChris Lattner
806cc8a93c486f889c5767278508bc655942ba408eChris Lattner//===----------------------------------------------------------------------===//
813481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner//  Local constant propagation.
824d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
834d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
844d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner// ConstantFoldTerminator - If a terminator instruction is predicated on a
854d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner// constant value, convert it into an unconditional branch to the constant
864d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner// destination.
874d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
88abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerbool llvm::ConstantFoldTerminator(BasicBlock *BB) {
8976ae3445f81164aaff9f95123426109c119f27c0Chris Lattner  TerminatorInst *T = BB->getTerminator();
90fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
914d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  // Branch - See if we are conditional jumping on constant
924d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
934d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
94c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest1 = BI->getSuccessor(0);
95c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest2 = BI->getSuccessor(1);
964d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
976b6b6ef1677fa71b1072c2911b4c1f9524a558c9Zhou Sheng    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
984d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Are we branching on constant?
994d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // YES.  Change to unconditional branch...
100579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
101579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
1024d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
103fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //cerr << "Function: " << T->getParent()->getParent()
104fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //     << "\nRemoving branch from " << T->getParent()
1054d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     << "\n\nTo: " << OldDest << endl;
1064d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1074d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of it.  Based on this,
1084d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // it will adjust it's PHI nodes.
1094d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
1104d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      OldDest->removePredecessor(BI->getParent());
1114d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1124d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Set the unconditional destination, and change the insn to be an
1134d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // unconditional branch.
1144d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      BI->setUnconditionalDest(Destination);
1154d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1160a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
1170a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1180a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (Dest2 == Dest1) {       // Conditional branch to same location?
119fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      // This branch matches something like this:
1204d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     br bool %cond, label %Dest, label %Dest
1214d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // and changes it into:  br label %Dest
1224d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1234d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of one copy of it.
1244d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
1254d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      Dest1->removePredecessor(BI->getParent());
1264d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1274d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Change a conditional branch to unconditional.
1284d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      BI->setUnconditionalDest(Dest1);
1294d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1304d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    }
1310a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1320a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
1330a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1340a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
13510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we are switching on a constant, we can convert the switch into a
13610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // single branch instruction!
13710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
13810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
1397d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner    BasicBlock *DefaultDest = TheOnlyDest;
1407d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner    assert(TheOnlyDest == SI->getDefaultDest() &&
1417d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner           "Default destination is not successor #0?");
14210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1430a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // Figure out which case it goes to.
14410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
14510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Found case matching a constant operand?
14610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      if (SI->getSuccessorValue(i) == CI) {
14710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        TheOnlyDest = SI->getSuccessor(i);
14810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        break;
14910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
15010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1517d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // Check to see if this branch is going to the same place as the default
1527d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // dest.  If so, eliminate it as an explicit compare.
1537d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      if (SI->getSuccessor(i) == DefaultDest) {
1540a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        // Remove this entry.
1557d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        DefaultDest->removePredecessor(SI->getParent());
1567d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        SI->removeCase(i);
1577d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        --i; --e;  // Don't skip an entry...
1587d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        continue;
1597d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      }
1607d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner
16110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, check to see if the switch only branches to one destination.
16210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
16310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // destinations.
16410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
16510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
166694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
16710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (CI && !TheOnlyDest) {
16810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Branching on a constant, but not any of the cases, go to the default
16910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // successor.
17010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      TheOnlyDest = SI->getDefaultDest();
171694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner    }
172694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
17310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we found a single destination that we can fold the switch into, do so
17410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // now.
17510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (TheOnlyDest) {
1760a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
177051a950000e21935165db56695e35bade668193bGabor Greif      BranchInst::Create(TheOnlyDest, SI);
17810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BasicBlock *BB = SI->getParent();
17910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
18010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Remove entries from PHI nodes which we no longer branch to...
18110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
18210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        // Found case matching a constant operand?
18310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        BasicBlock *Succ = SI->getSuccessor(i);
18410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        if (Succ == TheOnlyDest)
18510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
18610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        else
18710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          Succ->removePredecessor(BB);
18810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
18910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1900a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
19110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BB->getInstList().erase(SI);
19210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
1930a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
1940a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1950a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (SI->getNumSuccessors() == 2) {
19610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, we can fold this switch into a conditional branch
19710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // instruction if it has only one non-default destination.
198333c40096561218bc3597cf153c0a3895274414cOwen Anderson      Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
199333c40096561218bc3597cf153c0a3895274414cOwen Anderson                                 SI->getSuccessorValue(1), "cond");
2000a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
201051a950000e21935165db56695e35bade668193bGabor Greif      BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
20210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
2030a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
2041adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman      SI->eraseFromParent();
20510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
20610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
2070a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
2080a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
2090a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2100a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
2110a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // indirectbr blockaddress(@F, @BB) -> br label @BB
2120a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (BlockAddress *BA =
2130a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
2140a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BasicBlock *TheOnlyDest = BA->getBasicBlock();
2150a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
2160a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BranchInst::Create(TheOnlyDest, IBI);
2170a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2180a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2190a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        if (IBI->getDestination(i) == TheOnlyDest)
2200a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          TheOnlyDest = 0;
2210a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        else
2220a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          IBI->getDestination(i)->removePredecessor(IBI->getParent());
2230a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2240a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      IBI->eraseFromParent();
2250a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2260a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // If we didn't find our destination in the IBI successor list, then we
2270a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // have undefined behavior.  Replace the unconditional branch with an
2280a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // 'unreachable' instruction.
2290a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      if (TheOnlyDest) {
2300a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        BB->getTerminator()->eraseFromParent();
2310a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        new UnreachableInst(BB->getContext(), BB);
2320a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2330a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2340a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      return true;
2350a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
2364d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  }
2370a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2384d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  return false;
2394d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2404d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2414d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2424d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
24340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Local dead code elimination.
2444d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
2454d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2463481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// isInstructionTriviallyDead - Return true if the result produced by the
2473481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// instruction is not used, and the instruction has no side effects.
2483481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner///
249abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerbool llvm::isInstructionTriviallyDead(Instruction *I) {
250ec710c5b12af647ae90f53917122726269c18738Chris Lattner  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
25100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
252127a7936dea7b86e5cad337ad4b537bc115c2588Dale Johannesen  // We don't want debug info removed by anything this general.
253127a7936dea7b86e5cad337ad4b537bc115c2588Dale Johannesen  if (isa<DbgInfoIntrinsic>(I)) return false;
254ec710c5b12af647ae90f53917122726269c18738Chris Lattner
255a3da922a27da1b5db04bbbe6cbf4848a688b6786Duncan Sands  // Likewise for memory use markers.
256a3da922a27da1b5db04bbbe6cbf4848a688b6786Duncan Sands  if (isa<MemoryUseIntrinsic>(I)) return false;
257a3da922a27da1b5db04bbbe6cbf4848a688b6786Duncan Sands
2587af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  if (!I->mayHaveSideEffects()) return true;
2597af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands
2607af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // Special case intrinsics that "may have side effects" but can be deleted
2617af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // when dead.
262741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
263741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    // Safe to delete llvm.stacksave if dead.
264741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    if (II->getIntrinsicID() == Intrinsic::stacksave)
265741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner      return true;
266ec710c5b12af647ae90f53917122726269c18738Chris Lattner  return false;
2674d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2684d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2693481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
2703481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// trivially dead instruction, delete it.  If that makes any of its operands
27190fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// trivially dead, delete them too, recursively.  Return true if any
27290fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// instructions were deleted.
27390fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohmanbool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
2743481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
2757605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
27690fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
2773481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
2787605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  SmallVector<Instruction*, 16> DeadInsts;
2797605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  DeadInsts.push_back(I);
2803481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
281321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  do {
282e9d87f49063cb1bd213d8e9c339b9b63393cc2d9Dan Gohman    I = DeadInsts.pop_back_val();
2832872177834d83b42cd042a37299cb7089965f36bChris Lattner
2847605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // Null out all of the instruction's operands to see if any operand becomes
2857605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // dead as we go.
2867605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2877605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      Value *OpV = I->getOperand(i);
2887605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      I->setOperand(i, 0);
2897605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
2907605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (!OpV->use_empty()) continue;
2917605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
2927605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // If the operand is an instruction that became dead as we nulled out the
2937605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // operand, and if it is 'trivially' dead, delete it in a future loop
2947605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // iteration.
2957605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
2967605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner        if (isInstructionTriviallyDead(OpI))
2977605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner          DeadInsts.push_back(OpI);
2987605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    }
2997605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
3007605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    I->eraseFromParent();
301321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  } while (!DeadInsts.empty());
30290fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman
30390fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return true;
3044d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
305b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
306afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
307afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// dead PHI node, due to being a def-use chain of single-use nodes that
308afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// either forms a cycle or is terminated by a trivially dead instruction,
309afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// delete it.  If that makes any of its operands trivially dead, delete them
31090fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// too, recursively.  Return true if the PHI node is actually deleted.
31190fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohmanbool
31235738ac150afafe2359268d4b2169498c6c98c5fDan Gohmanllvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
313afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  // We can remove a PHI if it is on a cycle in the def-use graph
314afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  // where each node in the cycle has degree one, i.e. only one use,
315afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  // and is an instruction with no side effects.
316afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  if (!PN->hasOneUse())
31790fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
318afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman
31990fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  bool Changed = false;
320afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  SmallPtrSet<PHINode *, 4> PHIs;
321afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  PHIs.insert(PN);
322afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman  for (Instruction *J = cast<Instruction>(*PN->use_begin());
3237af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands       J->hasOneUse() && !J->mayHaveSideEffects();
324afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman       J = cast<Instruction>(*J->use_begin()))
325afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // If we find a PHI more than once, we're on a cycle that
326afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // won't prove fruitful.
327afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    if (PHINode *JP = dyn_cast<PHINode>(J))
328afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman      if (!PHIs.insert(cast<PHINode>(JP))) {
329afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman        // Break the cycle and delete the PHI and its operands.
3309e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
33190fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman        Changed |= RecursivelyDeleteTriviallyDeadInstructions(JP);
332afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman        break;
333afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman      }
33490fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return Changed;
335afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman}
3363481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
337b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//===----------------------------------------------------------------------===//
33840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Control Flow Graph Restructuring.
339b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//
340b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
34140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
34240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
34340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
34440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
34540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
34640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
34740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// nodes that collapse into identity values.  For example, if we have:
34840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   x = phi(1, 0, 0, 0)
34940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   y = and x, z
35040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
35140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
35240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// recursively fold the and to 0.
35340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattnervoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
35440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner                                        TargetData *TD) {
35540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // This only adjusts blocks with PHI nodes.
35640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  if (!isa<PHINode>(BB->begin()))
35740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    return;
35840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
35940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
36040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
36140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // that can be removed.
36240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  BB->removePredecessor(Pred, true);
36340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
36440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  WeakVH PhiIt = &BB->front();
36540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
36640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
36740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
36840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    Value *PNV = PN->hasConstantValue();
36940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    if (PNV == 0) continue;
37040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
37140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If we're able to simplify the phi to a single value, substitute the new
37240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // value into all of its uses.
37340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    assert(PNV != PN && "hasConstantValue broken");
37440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
37540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    ReplaceAndSimplifyAllUses(PN, PNV, TD);
37640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
37740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If recursive simplification ended up deleting the next PHI node we would
37840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
37940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // of the block.
38040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    if (PhiIt == 0) PhiIt = &BB->front();
38140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  }
38240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner}
38340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
38440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
385b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
386b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
387b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// between them, moving the instructions in the predecessor into DestBB and
388b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// deleting the predecessor block.
389b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner///
390ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustiftervoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
391b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // If BB has single-entry PHI nodes, fold them.
392b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
393b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    Value *NewVal = PN->getIncomingValue(0);
394b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    // Replace self referencing PHI with undef, it must be dead.
3959e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
396b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->replaceAllUsesWith(NewVal);
397b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->eraseFromParent();
398b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  }
399b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
400b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  BasicBlock *PredBB = DestBB->getSinglePredecessor();
401b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  assert(PredBB && "Block doesn't have a single predecessor!");
402b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
403b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Splice all the instructions from PredBB to DestBB.
404b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->getTerminator()->eraseFromParent();
405b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
406b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
407b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Anything that branched to PredBB now branches to DestBB.
408b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->replaceAllUsesWith(DestBB);
409b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
410ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  if (P) {
411ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
412ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    if (PI) {
413ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter      PI->replaceAllUses(PredBB, DestBB);
414ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter      PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
415ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    }
416ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  }
417b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Nuke BB.
418b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->eraseFromParent();
419b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner}
4204afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
421dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
422dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// almost-empty BB ending in an unconditional branch to Succ, into succ.
423dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
424dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// Assumption: Succ is the single successor for BB.
425dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
426dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
427dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
428dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
429fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
430dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        << Succ->getName() << "\n");
431dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there is only a single predecessor it must be BB and merging
432dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // is always safe
433dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (Succ->getSinglePredecessor()) return true;
434dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
435dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Make a list of the predecessors of BB
436dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
437dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BlockSet BBPreds(pred_begin(BB), pred_end(BB));
438dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
439dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Use that list to make another list of common predecessors of BB and Succ
440dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BlockSet CommonPreds;
441dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
442dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        PI != PE; ++PI)
443dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPreds.count(*PI))
444dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      CommonPreds.insert(*PI);
445dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
446dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there are no common predecessors, merging is always safe
447dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (CommonPreds.empty())
448dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    return true;
449dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
450dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Look at all the phi nodes in Succ, to see if they present a conflict when
451dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // merging these blocks
452dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
453dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *PN = cast<PHINode>(I);
454dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
455dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If the incoming value from BB is again a PHINode in
456dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // BB which has the same incoming value for *PI as PN does, we can
457dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // merge the phi nodes and then the blocks can still be merged
458dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
459dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPN && BBPN->getParent() == BB) {
460dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
461dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            PI != PE; PI++) {
462dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        if (BBPN->getIncomingValueForBlock(*PI)
463dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner              != PN->getIncomingValueForBlock(*PI)) {
464fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
465dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with "
466dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << BBPN->getName() << " with regard to common predecessor "
467dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << (*PI)->getName() << "\n");
468dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
469dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
470dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
471dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
472dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value* Val = PN->getIncomingValueForBlock(BB);
473dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
474dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            PI != PE; PI++) {
475dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // See if the incoming value for the common predecessor is equal to the
476dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // one for BB, in which case this phi node will not prevent the merging
477dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // of the block.
478dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        if (Val != PN->getIncomingValueForBlock(*PI)) {
479fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
480dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with regard to common "
481dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << "predecessor " << (*PI)->getName() << "\n");
482dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
483dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
484dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
485dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
486dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
487dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
488dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
489dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
490dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
491dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
492dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// unconditional branch, and contains no instructions other than PHI nodes,
493dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// potential debug intrinsics and the branch.  If possible, eliminate BB by
494dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// rewriting all the predecessors to branch to the successor block and return
495dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// true.  If we can't transform, return false.
496dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerbool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
497dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // We can't eliminate infinite loops.
498dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
499dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (BB == Succ) return false;
500dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
501dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check to see if merging these blocks would cause conflicts for any of the
502dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // phi nodes in BB or Succ. If not, we can safely merge.
503dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
504dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
505dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check for cases where Succ has multiple predecessors and a PHI node in BB
506dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // has uses which will not disappear when the PHI nodes are merged.  It is
507dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // possible to handle such cases, but difficult: it requires checking whether
508dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // BB dominates Succ, which is non-trivial to calculate in the case where
509dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Succ has multiple predecessors.  Also, it requires checking whether
510dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // constructing the necessary self-referential PHI node doesn't intoduce any
511dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // conflicts; this isn't too difficult, but the previous code for doing this
512dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // was incorrect.
513dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  //
514dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Note that if this check finds a live use, BB dominates Succ, so BB is
515dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
516dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // folding the branch isn't profitable in that case anyway.
517dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->getSinglePredecessor()) {
518dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    BasicBlock::iterator BBI = BB->begin();
519dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    while (isa<PHINode>(*BBI)) {
520dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
521dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner           UI != E; ++UI) {
522dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
523dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          if (PN->getIncomingBlock(UI) != BB)
524dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            return false;
525dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        } else {
526dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
527dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
528dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
529dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      ++BBI;
530dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
531dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
532dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
533fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
534dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
535dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (isa<PHINode>(Succ->begin())) {
536dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If there is more than one pred of succ, and there are PHI nodes in
537dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // the successor, then we need to add incoming edges for the PHI nodes
538dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    //
539dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
540dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
541dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // Loop over all of the PHI nodes in the successor of BB.
542dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
543dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PHINode *PN = cast<PHINode>(I);
544dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value *OldVal = PN->removeIncomingValue(BB, false);
545dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(OldVal && "No entry in PHI for Pred BB!");
546dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
547dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // If this incoming value is one of the PHI nodes in BB, the new entries
548dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // in the PHI node are the entries from the old PHI.
549dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
550dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        PHINode *OldValPN = cast<PHINode>(OldVal);
551dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
552dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // Note that, since we are merging phi nodes and BB and Succ might
553dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // have common predecessors, we could end up with a phi node with
554dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // identical incoming branches. This will be cleaned up later (and
555dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // will trigger asserts if we try to clean it up now, without also
556dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // simplifying the corresponding conditional branch).
557dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          PN->addIncoming(OldValPN->getIncomingValue(i),
558dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                          OldValPN->getIncomingBlock(i));
559dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      } else {
560dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // Add an incoming value for each of the new incoming values.
561dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
562dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          PN->addIncoming(OldVal, BBPreds[i]);
563dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
564dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
565dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
566dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
567dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
568dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (Succ->getSinglePredecessor()) {
569dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // BB is the only predecessor of Succ, so Succ will end up with exactly
570dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // the same predecessors BB had.
571dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Succ->getInstList().splice(Succ->begin(),
572dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                                 BB->getInstList(), BB->begin());
573dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
574dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
575dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(PN->use_empty() && "There shouldn't be any uses here!");
576dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PN->eraseFromParent();
577dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
578dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
579dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
580dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Everything that jumped to BB now goes to Succ.
581dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->replaceAllUsesWith(Succ);
582dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->hasName()) Succ->takeName(BB);
583dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->eraseFromParent();              // Delete the old basic block.
584dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
585dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
586dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
587dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
588dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
5894afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel/// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
5904afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel/// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
5914afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel/// with the DbgInfoIntrinsic that use the instruction I.
5924afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patelbool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
5934afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel                               SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
5944afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel  if (DbgInUses)
5954afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel    DbgInUses->clear();
5964afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
5974afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel  for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
5984afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel       ++UI) {
5994afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel    if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
6004afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel      if (DbgInUses)
6014afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel        DbgInUses->push_back(DI);
6024afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel    } else {
6034afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel      if (DbgInUses)
6044afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel        DbgInUses->clear();
6054afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel      return false;
6064afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel    }
6074afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel  }
6084afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel  return true;
6094afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel}
610c79e1182470ed12f1f3d0d35c1725366519a9af7Devang Patel
61143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
61243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// nodes in this block. This doesn't try to be clever about PHI nodes
61343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// which differ only in the order of the incoming values, but instcombine
61443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// orders them so it usually won't matter.
61543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach///
61643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbachbool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
61743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  bool Changed = false;
61843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
61943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // This implementation doesn't currently consider undef operands
62043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // specially. Theroetically, two phis which are identical except for
62143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // one having an undef where the other doesn't could be collapsed.
62243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
62343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Map from PHI hash values to PHI nodes. If multiple PHIs have
62443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // the same hash value, the element is the first PHI in the
62543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // linked list in CollisionMap.
62643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<uintptr_t, PHINode *> HashMap;
62743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
62843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Maintain linked lists of PHI nodes with common hash values.
62943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<PHINode *, PHINode *> CollisionMap;
63043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
63143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Examine each PHI.
63243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  for (BasicBlock::iterator I = BB->begin();
63343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach       PHINode *PN = dyn_cast<PHINode>(I++); ) {
63443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Compute a hash value on the operands. Instcombine will likely have sorted
63543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // them, which helps expose duplicates, but we have to check all the
63643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // operands to be safe in case instcombine hasn't run.
63743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    uintptr_t Hash = 0;
63843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
63943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // This hash algorithm is quite weak as hash functions go, but it seems
64043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // to do a good enough job for this particular purpose, and is very quick.
64143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
64243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
64343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
64443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // If we've never seen this hash value before, it's a unique PHI.
64543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
64643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      HashMap.insert(std::make_pair(Hash, PN));
64743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    if (Pair.second) continue;
64843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Otherwise it's either a duplicate or a hash collision.
64943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (PHINode *OtherPN = Pair.first->second; ; ) {
65043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (OtherPN->isIdenticalTo(PN)) {
65143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // A duplicate. Replace this PHI with its duplicate.
65243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->replaceAllUsesWith(OtherPN);
65343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->eraseFromParent();
65443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Changed = true;
65543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
65643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
65743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // A non-duplicate hash collision.
65843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
65943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (I == CollisionMap.end()) {
66043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // Set this PHI to be the head of the linked list of colliding PHIs.
66143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PHINode *Old = Pair.first->second;
66243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Pair.first->second = PN;
66343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        CollisionMap[PN] = Old;
66443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
66543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
66643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // Procede to the next PHI in the list.
66743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      OtherPN = I->second;
66843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
66943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  }
67043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
67143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  return Changed;
67243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach}
673