Local.cpp revision a2067fbe22930be8413584ae58c5ef78bd032190
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"
23c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich#include "llvm/Metadata.h"
24562b84b3aea359d1f918184e355da82bf05eb290Jay Foad#include "llvm/Operator.h"
2519f2dc436df4f768484287a478973e83efd4202aChris Lattner#include "llvm/ADT/DenseMap.h"
26afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman#include "llvm/ADT/SmallPtrSet.h"
275ee20680c7ebc765950983633e19fafab5235245Devang Patel#include "llvm/Analysis/DebugInfo.h"
285ee20680c7ebc765950983633e19fafab5235245Devang Patel#include "llvm/Analysis/DIBuilder.h"
2980f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich#include "llvm/Analysis/Dominators.h"
3040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner#include "llvm/Analysis/InstructionSimplify.h"
314a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky#include "llvm/Analysis/MemoryBuiltins.h"
32ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter#include "llvm/Analysis/ProfileInfo.h"
33687140c818ba4b896329a83324714140b6580ef8Chris Lattner#include "llvm/Analysis/ValueTracking.h"
349fa038dc21e966dceb23f9410351e863e3ce1114Chris Lattner#include "llvm/Target/TargetData.h"
35dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/CFG.h"
36dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/Debug.h"
37c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/GetElementPtrTypeIterator.h"
38f88ad9aeeeb861a82f590f44484a055fcaf25b5cMatt Beaumont-Gay#include "llvm/Support/IRBuilder.h"
39c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/MathExtras.h"
4019f2dc436df4f768484287a478973e83efd4202aChris Lattner#include "llvm/Support/ValueHandle.h"
41dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/raw_ostream.h"
42abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerusing namespace llvm;
43d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
444d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
453481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner//  Local constant propagation.
464d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
474d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
485649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// ConstantFoldTerminator - If a terminator instruction is predicated on a
495649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// constant value, convert it into an unconditional branch to the constant
505649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// destination.  This is a nontrivial operation because the successors of this
515649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// basic block must have their PHI nodes updated.
525649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
535649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// conditions and indirectbr addresses this might make dead if
545649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// DeleteDeadConditions is true.
555649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommelbool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions) {
5676ae3445f81164aaff9f95123426109c119f27c0Chris Lattner  TerminatorInst *T = BB->getTerminator();
5762fb3556eab41d9d66994e92d15e3e707c181988Devang Patel  IRBuilder<> Builder(T);
58fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
594d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  // Branch - See if we are conditional jumping on constant
604d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
614d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
62c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest1 = BI->getSuccessor(0);
63c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest2 = BI->getSuccessor(1);
644d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
656b6b6ef1677fa71b1072c2911b4c1f9524a558c9Zhou Sheng    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
664d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Are we branching on constant?
674d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // YES.  Change to unconditional branch...
68579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
69579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
704d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
71fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //cerr << "Function: " << T->getParent()->getParent()
72fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //     << "\nRemoving branch from " << T->getParent()
734d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     << "\n\nTo: " << OldDest << endl;
744d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
754d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of it.  Based on this,
764d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // it will adjust it's PHI nodes.
771a0390253b3e7c2327139d81e5a8c16d5bf85aa8Jay Foad      OldDest->removePredecessor(BB);
784d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
798f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
8062fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Destination);
818f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
824d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
830a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
840a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
850a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (Dest2 == Dest1) {       // Conditional branch to same location?
86fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      // This branch matches something like this:
874d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     br bool %cond, label %Dest, label %Dest
884d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // and changes it into:  br label %Dest
894d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
904d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of one copy of it.
914d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
924d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      Dest1->removePredecessor(BI->getParent());
934d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
948f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
9562fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Dest1);
965649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = BI->getCondition();
978f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
985649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
995649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel        RecursivelyDeleteTriviallyDeadInstructions(Cond);
1004d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1014d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    }
1020a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1030a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
1040a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1050a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
10610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we are switching on a constant, we can convert the switch into a
10710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // single branch instruction!
10810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
109c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy    BasicBlock *TheOnlyDest = SI->getDefaultDest();
1107d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner    BasicBlock *DefaultDest = TheOnlyDest;
11110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1120a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // Figure out which case it goes to.
1133d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
114c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy         i != e; ++i) {
11510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Found case matching a constant operand?
116c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseValue() == CI) {
117c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        TheOnlyDest = i.getCaseSuccessor();
11810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        break;
11910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
12010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1217d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // Check to see if this branch is going to the same place as the default
1227d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // dest.  If so, eliminate it as an explicit compare.
123c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseSuccessor() == DefaultDest) {
1240a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        // Remove this entry.
1257d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        DefaultDest->removePredecessor(SI->getParent());
1267d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        SI->removeCase(i);
127c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        --i; --e;
1287d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        continue;
1297d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      }
1307d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner
13110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, check to see if the switch only branches to one destination.
13210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
13310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // destinations.
134c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = 0;
13510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
136694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
13710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (CI && !TheOnlyDest) {
13810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Branching on a constant, but not any of the cases, go to the default
13910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // successor.
14010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      TheOnlyDest = SI->getDefaultDest();
141694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner    }
142694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
14310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we found a single destination that we can fold the switch into, do so
14410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // now.
14510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (TheOnlyDest) {
1460a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
14762fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
14810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BasicBlock *BB = SI->getParent();
14910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
15010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Remove entries from PHI nodes which we no longer branch to...
15110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
15210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        // Found case matching a constant operand?
15310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        BasicBlock *Succ = SI->getSuccessor(i);
15410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        if (Succ == TheOnlyDest)
15510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
15610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        else
15710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          Succ->removePredecessor(BB);
15810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
15910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1600a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
1615649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = SI->getCondition();
1625649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      SI->eraseFromParent();
1635649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
1645649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel        RecursivelyDeleteTriviallyDeadInstructions(Cond);
16510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
1660a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
1670a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
16824473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    if (SI->getNumCases() == 1) {
16910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, we can fold this switch into a conditional branch
17010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // instruction if it has only one non-default destination.
1713d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy      SwitchInst::CaseIt FirstCase = SI->case_begin();
172a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      ConstantRangesSet CRS = FirstCase.getCaseValueEx();
173a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      if (CRS.getNumItems() == 1 && CRS.isSingleNumber(0)) {
174a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
175a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy            CRS.getItem(0).Low, "cond");
176a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
177a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        // Insert the new branch.
178a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        Builder.CreateCondBr(Cond, FirstCase.getCaseSuccessor(),
179a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy                             SI->getDefaultDest());
180a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
181a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        // Delete the old switch.
182a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        SI->eraseFromParent();
183a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy        return true;
184a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
185a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      }
18610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
1870a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1880a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
1890a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1900a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
1910a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // indirectbr blockaddress(@F, @BB) -> br label @BB
1920a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (BlockAddress *BA =
1930a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
1940a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BasicBlock *TheOnlyDest = BA->getBasicBlock();
1950a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
19662fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
1970a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
1980a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
1990a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        if (IBI->getDestination(i) == TheOnlyDest)
2000a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          TheOnlyDest = 0;
2010a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        else
2020a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          IBI->getDestination(i)->removePredecessor(IBI->getParent());
2030a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2045649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Address = IBI->getAddress();
2050a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      IBI->eraseFromParent();
2065649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2075649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel        RecursivelyDeleteTriviallyDeadInstructions(Address);
2080a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2090a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // If we didn't find our destination in the IBI successor list, then we
2100a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // have undefined behavior.  Replace the unconditional branch with an
2110a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // 'unreachable' instruction.
2120a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      if (TheOnlyDest) {
2130a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        BB->getTerminator()->eraseFromParent();
2140a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        new UnreachableInst(BB->getContext(), BB);
2150a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2160a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2170a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      return true;
2180a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
2194d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  }
2200a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2214d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  return false;
2224d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2234d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2244d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2254d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
22640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Local dead code elimination.
2274d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
2284d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2293481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// isInstructionTriviallyDead - Return true if the result produced by the
2303481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// instruction is not used, and the instruction has no side effects.
2313481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner///
232abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerbool llvm::isInstructionTriviallyDead(Instruction *I) {
233ec710c5b12af647ae90f53917122726269c18738Chris Lattner  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
23400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
235187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  // We don't want the landingpad instruction removed by anything this general.
236187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  if (isa<LandingPadInst>(I))
237187b1924a4b68350a6492b116db0fb19c659222fBill Wendling    return false;
238187b1924a4b68350a6492b116db0fb19c659222fBill Wendling
2399c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // We don't want debug info removed by anything this general, unless
2409c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // debug info is empty.
2419c5822a966572ea78f4e818870d4229c7a855749Devang Patel  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
2423e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (DDI->getAddress())
2439c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
244b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2453e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
246b99462117ebd4be41788346246d7935fc90a11eeDevang Patel  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
2479c5822a966572ea78f4e818870d4229c7a855749Devang Patel    if (DVI->getValue())
2489c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
249b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2509c5822a966572ea78f4e818870d4229c7a855749Devang Patel  }
2519c5822a966572ea78f4e818870d4229c7a855749Devang Patel
2527af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  if (!I->mayHaveSideEffects()) return true;
2537af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands
2547af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // Special case intrinsics that "may have side effects" but can be deleted
2557af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // when dead.
2563e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
257741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    // Safe to delete llvm.stacksave if dead.
258741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    if (II->getIntrinsicID() == Intrinsic::stacksave)
259741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner      return true;
2603e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky
2613e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    // Lifetime intrinsics are dead when their right-hand is undef.
2623e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2633e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky        II->getIntrinsicID() == Intrinsic::lifetime_end)
2643e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky      return isa<UndefValue>(II->getArgOperand(1));
2653e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
2664a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
267e54874471cf565bbacdca69c95ae7287badc578fNuno Lopes  if (extractMallocCall(I) || extractCallocCall(I)) return true;
2684a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
2694a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky  if (CallInst *CI = isFreeCall(I))
2704a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky    if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
2714a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky      return C->isNullValue() || isa<UndefValue>(C);
2724a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
273ec710c5b12af647ae90f53917122726269c18738Chris Lattner  return false;
2744d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2754d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2763481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
2773481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// trivially dead instruction, delete it.  If that makes any of its operands
27890fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// trivially dead, delete them too, recursively.  Return true if any
27990fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// instructions were deleted.
28090fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohmanbool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
2813481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
2827605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
28390fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
2843481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
2857605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  SmallVector<Instruction*, 16> DeadInsts;
2867605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  DeadInsts.push_back(I);
2873481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
288321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  do {
289e9d87f49063cb1bd213d8e9c339b9b63393cc2d9Dan Gohman    I = DeadInsts.pop_back_val();
2902872177834d83b42cd042a37299cb7089965f36bChris Lattner
2917605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // Null out all of the instruction's operands to see if any operand becomes
2927605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // dead as we go.
2937605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2947605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      Value *OpV = I->getOperand(i);
2957605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      I->setOperand(i, 0);
2967605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
2977605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (!OpV->use_empty()) continue;
2987605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
2997605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // If the operand is an instruction that became dead as we nulled out the
3007605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // operand, and if it is 'trivially' dead, delete it in a future loop
3017605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // iteration.
3027605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
3037605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner        if (isInstructionTriviallyDead(OpI))
3047605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner          DeadInsts.push_back(OpI);
3057605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    }
3067605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner
3077605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    I->eraseFromParent();
308321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  } while (!DeadInsts.empty());
30990fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman
31090fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return true;
3114d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
312b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
3131a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// areAllUsesEqual - Check whether the uses of a value are all the same.
3141a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// This is similar to Instruction::hasOneUse() except this will also return
315b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// true when there are no uses or multiple uses that all refer to the same
316b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// value.
3171a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewyckystatic bool areAllUsesEqual(Instruction *I) {
3181a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  Value::use_iterator UI = I->use_begin();
3191a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  Value::use_iterator UE = I->use_end();
3201a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  if (UI == UE)
321b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    return true;
3221a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
3231a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  User *TheUse = *UI;
3241a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  for (++UI; UI != UE; ++UI) {
3251a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky    if (*UI != TheUse)
3261a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky      return false;
3271a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  }
3281a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  return true;
3291a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky}
3301a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
331afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
332afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// dead PHI node, due to being a def-use chain of single-use nodes that
333afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// either forms a cycle or is terminated by a trivially dead instruction,
334afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// delete it.  If that makes any of its operands trivially dead, delete them
3352cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands/// too, recursively.  Return true if a change was made.
3361a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewyckybool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
337b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  SmallPtrSet<Instruction*, 4> Visited;
338b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
339b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands       I = cast<Instruction>(*I->use_begin())) {
340b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    if (I->use_empty())
341b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      return RecursivelyDeleteTriviallyDeadInstructions(I);
342afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman
343b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    // If we find an instruction more than once, we're on a cycle that
344afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // won't prove fruitful.
345b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    if (!Visited.insert(I)) {
346b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      // Break the cycle and delete the instruction and its operands.
347b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      I->replaceAllUsesWith(UndefValue::get(I->getType()));
3482cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands      (void)RecursivelyDeleteTriviallyDeadInstructions(I);
3492cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands      return true;
350b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    }
351b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  }
352b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  return false;
353afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman}
3543481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
355e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
356e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// simplify any instructions in it and recursively delete dead instructions.
357e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner///
358e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// This returns true if it changed the code, note that it can delete
359e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// instructions in other blocks as well in this block.
360e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattnerbool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
361e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  bool MadeChange = false;
362acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
363acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#ifndef NDEBUG
364acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // In debug builds, ensure that the terminator of the block is never replaced
365acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // or deleted by these simplifications. The idea of simplification is that it
366acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // cannot introduce new instructions, and there is no way to replace the
367acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // terminator of a block without introducing a new instruction.
368acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  AssertingVH<Instruction> TerminatorVH(--BB->end());
369acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#endif
370acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
371858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth  for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
372858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth    assert(!BI->isTerminator());
373e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    Instruction *Inst = BI++;
3746b980541df5846ad335c377c8803b517968daee2Chandler Carruth
3756b980541df5846ad335c377c8803b517968daee2Chandler Carruth    WeakVH BIHandle(BI);
3766b980541df5846ad335c377c8803b517968daee2Chandler Carruth    if (recursivelySimplifyInstruction(Inst, TD)) {
377e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      MadeChange = true;
37835a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner      if (BIHandle != BI)
379e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner        BI = BB->begin();
380e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      continue;
381e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    }
38271ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman
383e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
38471ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman    if (BIHandle != BI)
38571ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman      BI = BB->begin();
386e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  }
387e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  return MadeChange;
388e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner}
389e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner
390b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//===----------------------------------------------------------------------===//
39140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Control Flow Graph Restructuring.
392b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//
393b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
39440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
39540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
39640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
39740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
39840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
39940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
40040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// nodes that collapse into identity values.  For example, if we have:
40140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   x = phi(1, 0, 0, 0)
40240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   y = and x, z
40340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
40440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
40540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// recursively fold the and to 0.
40640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattnervoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
40740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner                                        TargetData *TD) {
40840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // This only adjusts blocks with PHI nodes.
40940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  if (!isa<PHINode>(BB->begin()))
41040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    return;
41140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
41240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
41340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
41440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // that can be removed.
41540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  BB->removePredecessor(Pred, true);
41640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
41740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  WeakVH PhiIt = &BB->front();
41840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
41940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
4206b980541df5846ad335c377c8803b517968daee2Chandler Carruth    Value *OldPhiIt = PhiIt;
4216ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
4226b980541df5846ad335c377c8803b517968daee2Chandler Carruth    if (!recursivelySimplifyInstruction(PN, TD))
4236b980541df5846ad335c377c8803b517968daee2Chandler Carruth      continue;
4246ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
42540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If recursive simplification ended up deleting the next PHI node we would
42640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
42740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // of the block.
42835a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
42940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  }
43040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner}
43140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
43240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
433b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
434b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
435b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// between them, moving the instructions in the predecessor into DestBB and
436b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// deleting the predecessor block.
437b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner///
438ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustiftervoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
439b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // If BB has single-entry PHI nodes, fold them.
440b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
441b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    Value *NewVal = PN->getIncomingValue(0);
442b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    // Replace self referencing PHI with undef, it must be dead.
4439e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
444b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->replaceAllUsesWith(NewVal);
445b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->eraseFromParent();
446b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  }
447b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
448b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  BasicBlock *PredBB = DestBB->getSinglePredecessor();
449b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  assert(PredBB && "Block doesn't have a single predecessor!");
450b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
45137914c8e83c43d710925263b66014159f03fa355Chris Lattner  // Zap anything that took the address of DestBB.  Not doing this will give the
45237914c8e83c43d710925263b66014159f03fa355Chris Lattner  // address an invalid value.
45337914c8e83c43d710925263b66014159f03fa355Chris Lattner  if (DestBB->hasAddressTaken()) {
45437914c8e83c43d710925263b66014159f03fa355Chris Lattner    BlockAddress *BA = BlockAddress::get(DestBB);
45537914c8e83c43d710925263b66014159f03fa355Chris Lattner    Constant *Replacement =
45637914c8e83c43d710925263b66014159f03fa355Chris Lattner      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
45737914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
45837914c8e83c43d710925263b66014159f03fa355Chris Lattner                                                     BA->getType()));
45937914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->destroyConstant();
46037914c8e83c43d710925263b66014159f03fa355Chris Lattner  }
461b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
462b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Anything that branched to PredBB now branches to DestBB.
463b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->replaceAllUsesWith(DestBB);
464b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
46595c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  // Splice all the instructions from PredBB to DestBB.
46695c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  PredBB->getTerminator()->eraseFromParent();
46795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
46895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
469ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  if (P) {
47080f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich    DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
47180f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich    if (DT) {
47280f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich      BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
47380f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich      DT->changeImmediateDominator(DestBB, PredBBIDom);
47480f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich      DT->eraseNode(PredBB);
47580f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich    }
476ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
477ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    if (PI) {
478ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter      PI->replaceAllUses(PredBB, DestBB);
479ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter      PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
480ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter    }
481ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  }
482b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Nuke BB.
483b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->eraseFromParent();
484b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner}
4854afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
486dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
487dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// almost-empty BB ending in an unconditional branch to Succ, into succ.
488dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
489dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// Assumption: Succ is the single successor for BB.
490dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
491dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
492dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
493dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
494fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
495dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        << Succ->getName() << "\n");
496dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there is only a single predecessor it must be BB and merging
497dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // is always safe
498dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (Succ->getSinglePredecessor()) return true;
499dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
500dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Make a list of the predecessors of BB
50188c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer  SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
502dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
503dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Look at all the phi nodes in Succ, to see if they present a conflict when
504dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // merging these blocks
505dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
506dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *PN = cast<PHINode>(I);
507dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
508dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If the incoming value from BB is again a PHINode in
509dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // BB which has the same incoming value for *PI as PN does, we can
510dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // merge the phi nodes and then the blocks can still be merged
511dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
512dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPN && BBPN->getParent() == BB) {
51388c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
51488c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
51588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        if (BBPreds.count(IBB) &&
51688c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer            BBPN->getIncomingValueForBlock(IBB) != PN->getIncomingValue(PI)) {
517fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
518dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with "
519dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << BBPN->getName() << " with regard to common predecessor "
52088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << IBB->getName() << "\n");
521dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
522dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
523dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
524dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
525dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value* Val = PN->getIncomingValueForBlock(BB);
52688c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
527dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // See if the incoming value for the common predecessor is equal to the
528dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // one for BB, in which case this phi node will not prevent the merging
529dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // of the block.
53088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
53188c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        if (BBPreds.count(IBB) && Val != PN->getIncomingValue(PI)) {
532fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
533dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with regard to common "
53488c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << "predecessor " << IBB->getName() << "\n");
535dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
536dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
537dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
538dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
539dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
540dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
541dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
542dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
543dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
544dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
545dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// unconditional branch, and contains no instructions other than PHI nodes,
54677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// potential side-effect free intrinsics and the branch.  If possible,
54777a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// eliminate BB by rewriting all the predecessors to branch to the successor
54877a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// block and return true.  If we can't transform, return false.
549dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerbool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
550e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman  assert(BB != &BB->getParent()->getEntryBlock() &&
551e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
552e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman
553dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // We can't eliminate infinite loops.
554dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
555dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (BB == Succ) return false;
556dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
557dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check to see if merging these blocks would cause conflicts for any of the
558dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // phi nodes in BB or Succ. If not, we can safely merge.
559dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
560dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
561dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check for cases where Succ has multiple predecessors and a PHI node in BB
562dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // has uses which will not disappear when the PHI nodes are merged.  It is
563dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // possible to handle such cases, but difficult: it requires checking whether
564dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // BB dominates Succ, which is non-trivial to calculate in the case where
565dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Succ has multiple predecessors.  Also, it requires checking whether
566dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // constructing the necessary self-referential PHI node doesn't intoduce any
567dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // conflicts; this isn't too difficult, but the previous code for doing this
568dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // was incorrect.
569dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  //
570dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Note that if this check finds a live use, BB dominates Succ, so BB is
571dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
572dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // folding the branch isn't profitable in that case anyway.
573dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->getSinglePredecessor()) {
574dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    BasicBlock::iterator BBI = BB->begin();
575dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    while (isa<PHINode>(*BBI)) {
576dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
577dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner           UI != E; ++UI) {
578dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
579dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          if (PN->getIncomingBlock(UI) != BB)
580dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            return false;
581dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        } else {
582dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
583dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
584dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
585dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      ++BBI;
586dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
587dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
588dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
589fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
590dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
591dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (isa<PHINode>(Succ->begin())) {
592dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If there is more than one pred of succ, and there are PHI nodes in
593dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // the successor, then we need to add incoming edges for the PHI nodes
594dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    //
595dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
596dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
597dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // Loop over all of the PHI nodes in the successor of BB.
598dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
599dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PHINode *PN = cast<PHINode>(I);
600dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value *OldVal = PN->removeIncomingValue(BB, false);
601dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(OldVal && "No entry in PHI for Pred BB!");
602dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
603dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // If this incoming value is one of the PHI nodes in BB, the new entries
604dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // in the PHI node are the entries from the old PHI.
605dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
606dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        PHINode *OldValPN = cast<PHINode>(OldVal);
607dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
608dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // Note that, since we are merging phi nodes and BB and Succ might
609dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // have common predecessors, we could end up with a phi node with
610dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // identical incoming branches. This will be cleaned up later (and
611dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // will trigger asserts if we try to clean it up now, without also
612dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          // simplifying the corresponding conditional branch).
613dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          PN->addIncoming(OldValPN->getIncomingValue(i),
614dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                          OldValPN->getIncomingBlock(i));
615dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      } else {
616dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // Add an incoming value for each of the new incoming values.
617dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
618dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          PN->addIncoming(OldVal, BBPreds[i]);
619dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
620dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
621dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
622dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
62377a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  if (Succ->getSinglePredecessor()) {
62477a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // BB is the only predecessor of Succ, so Succ will end up with exactly
62577a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // the same predecessors BB had.
62677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola
62777a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // Copy over any phi, debug or lifetime instruction.
62877a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    BB->getTerminator()->eraseFromParent();
62977a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
63077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  } else {
63177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
632dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
633dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(PN->use_empty() && "There shouldn't be any uses here!");
634dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PN->eraseFromParent();
635dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
636dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
637dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
638dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Everything that jumped to BB now goes to Succ.
639dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->replaceAllUsesWith(Succ);
640dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->hasName()) Succ->takeName(BB);
641dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->eraseFromParent();              // Delete the old basic block.
642dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
643dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
644dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
64543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
64643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// nodes in this block. This doesn't try to be clever about PHI nodes
64743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// which differ only in the order of the incoming values, but instcombine
64843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// orders them so it usually won't matter.
64943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach///
65043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbachbool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
65143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  bool Changed = false;
65243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
65343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // This implementation doesn't currently consider undef operands
65489991d44136414c4c74eee7c6dfbdbeab287b881Nick Lewycky  // specially. Theoretically, two phis which are identical except for
65543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // one having an undef where the other doesn't could be collapsed.
65643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
65743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Map from PHI hash values to PHI nodes. If multiple PHIs have
65843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // the same hash value, the element is the first PHI in the
65943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // linked list in CollisionMap.
66043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<uintptr_t, PHINode *> HashMap;
66143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
66243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Maintain linked lists of PHI nodes with common hash values.
66343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<PHINode *, PHINode *> CollisionMap;
66443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
66543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Examine each PHI.
66643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  for (BasicBlock::iterator I = BB->begin();
66743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach       PHINode *PN = dyn_cast<PHINode>(I++); ) {
66843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Compute a hash value on the operands. Instcombine will likely have sorted
66943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // them, which helps expose duplicates, but we have to check all the
67043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // operands to be safe in case instcombine hasn't run.
67143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    uintptr_t Hash = 0;
67295c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // This hash algorithm is quite weak as hash functions go, but it seems
67395c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // to do a good enough job for this particular purpose, and is very quick.
67443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
67543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
67643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
67743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
67895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
67995c3e48f9557adb6064d580684bb14cacec2f826Jay Foad         I != E; ++I) {
68095c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
68195c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
68295c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    }
6832bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
6842bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    Hash >>= 1;
68543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // If we've never seen this hash value before, it's a unique PHI.
68643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
68743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      HashMap.insert(std::make_pair(Hash, PN));
68843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    if (Pair.second) continue;
68943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Otherwise it's either a duplicate or a hash collision.
69043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (PHINode *OtherPN = Pair.first->second; ; ) {
69143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (OtherPN->isIdenticalTo(PN)) {
69243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // A duplicate. Replace this PHI with its duplicate.
69343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->replaceAllUsesWith(OtherPN);
69443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->eraseFromParent();
69543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Changed = true;
69643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
69743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
69843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // A non-duplicate hash collision.
69943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
70043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (I == CollisionMap.end()) {
70143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // Set this PHI to be the head of the linked list of colliding PHIs.
70243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PHINode *Old = Pair.first->second;
70343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Pair.first->second = PN;
70443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        CollisionMap[PN] = Old;
70543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
70643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
70743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // Procede to the next PHI in the list.
70843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      OtherPN = I->second;
70943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
71043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  }
71143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
71243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  return Changed;
71343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach}
714687140c818ba4b896329a83324714140b6580ef8Chris Lattner
715687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// enforceKnownAlignment - If the specified pointer points to an object that
716687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we control, modify the object's alignment to PrefAlign. This isn't
717687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// often possible though. If alignment is important, a more reliable approach
718687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// is to simply align all global variables and allocation instructions to
719687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// their preferred alignment from the beginning.
720687140c818ba4b896329a83324714140b6580ef8Chris Lattner///
72119282365147f498a60463d250dbed2f8e1b81861Benjamin Kramerstatic unsigned enforceKnownAlignment(Value *V, unsigned Align,
722bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames                                      unsigned PrefAlign, const TargetData *TD) {
723b53c7937c5651e5500b554186657b27838137365Eli Friedman  V = V->stripPointerCasts();
724687140c818ba4b896329a83324714140b6580ef8Chris Lattner
725b53c7937c5651e5500b554186657b27838137365Eli Friedman  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
726bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // If the preferred alignment is greater than the natural stack alignment
727bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // then don't round up. This avoids dynamic stack realignment.
728bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
729bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames      return Align;
730687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a requested alignment and if this is an alloca, round up.
731687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (AI->getAlignment() >= PrefAlign)
732687140c818ba4b896329a83324714140b6580ef8Chris Lattner      return AI->getAlignment();
733687140c818ba4b896329a83324714140b6580ef8Chris Lattner    AI->setAlignment(PrefAlign);
734687140c818ba4b896329a83324714140b6580ef8Chris Lattner    return PrefAlign;
735687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
736687140c818ba4b896329a83324714140b6580ef8Chris Lattner
737687140c818ba4b896329a83324714140b6580ef8Chris Lattner  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
738687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a large requested alignment and we can, bump up the alignment
739687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // of the global.
740687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (GV->isDeclaration()) return Align;
741d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // If the memory we set aside for the global may not be the memory used by
742d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // the final program then it is impossible for us to reliably enforce the
743d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // preferred alignment.
744d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    if (GV->isWeakForLinker()) return Align;
745687140c818ba4b896329a83324714140b6580ef8Chris Lattner
746687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (GV->getAlignment() >= PrefAlign)
747687140c818ba4b896329a83324714140b6580ef8Chris Lattner      return GV->getAlignment();
748687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // We can only increase the alignment of the global if it has no alignment
749687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // specified or if it is not assigned a section.  If it is assigned a
750687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, the global could be densely packed with other objects in the
751687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, increasing the alignment could cause padding issues.
752687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (!GV->hasSection() || GV->getAlignment() == 0)
753687140c818ba4b896329a83324714140b6580ef8Chris Lattner      GV->setAlignment(PrefAlign);
754687140c818ba4b896329a83324714140b6580ef8Chris Lattner    return GV->getAlignment();
755687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
756687140c818ba4b896329a83324714140b6580ef8Chris Lattner
757687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
758687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
759687140c818ba4b896329a83324714140b6580ef8Chris Lattner
760687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
761687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
762687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// and it is more than the alignment of the ultimate object, see if we can
763687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// increase the alignment of the ultimate object, making this check succeed.
764687140c818ba4b896329a83324714140b6580ef8Chris Lattnerunsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
765687140c818ba4b896329a83324714140b6580ef8Chris Lattner                                          const TargetData *TD) {
766687140c818ba4b896329a83324714140b6580ef8Chris Lattner  assert(V->getType()->isPointerTy() &&
767687140c818ba4b896329a83324714140b6580ef8Chris Lattner         "getOrEnforceKnownAlignment expects a pointer!");
768687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
769687140c818ba4b896329a83324714140b6580ef8Chris Lattner  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
77026c8dcc692fb2addd475446cfff24d6a4e958bcaRafael Espindola  ComputeMaskedBits(V, KnownZero, KnownOne, TD);
771687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned TrailZ = KnownZero.countTrailingOnes();
772687140c818ba4b896329a83324714140b6580ef8Chris Lattner
773687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // Avoid trouble with rediculously large TrailZ values, such as
774687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // those computed from a null pointer.
775687140c818ba4b896329a83324714140b6580ef8Chris Lattner  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
776687140c818ba4b896329a83324714140b6580ef8Chris Lattner
777687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
778687140c818ba4b896329a83324714140b6580ef8Chris Lattner
779687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // LLVM doesn't support alignments larger than this currently.
780687140c818ba4b896329a83324714140b6580ef8Chris Lattner  Align = std::min(Align, +Value::MaximumAlignment);
781687140c818ba4b896329a83324714140b6580ef8Chris Lattner
782687140c818ba4b896329a83324714140b6580ef8Chris Lattner  if (PrefAlign > Align)
783bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    Align = enforceKnownAlignment(V, Align, PrefAlign, TD);
784687140c818ba4b896329a83324714140b6580ef8Chris Lattner
785687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // We don't need to make any adjustment.
786687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
787687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
788687140c818ba4b896329a83324714140b6580ef8Chris Lattner
7895ee20680c7ebc765950983633e19fafab5235245Devang Patel///===---------------------------------------------------------------------===//
7905ee20680c7ebc765950983633e19fafab5235245Devang Patel///  Dbg Intrinsic utilities
7915ee20680c7ebc765950983633e19fafab5235245Devang Patel///
7925ee20680c7ebc765950983633e19fafab5235245Devang Patel
7935ee20680c7ebc765950983633e19fafab5235245Devang Patel/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
7945ee20680c7ebc765950983633e19fafab5235245Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
7955ee20680c7ebc765950983633e19fafab5235245Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
7965ee20680c7ebc765950983633e19fafab5235245Devang Patel                                           StoreInst *SI, DIBuilder &Builder) {
7975ee20680c7ebc765950983633e19fafab5235245Devang Patel  DIVariable DIVar(DDI->getVariable());
7985ee20680c7ebc765950983633e19fafab5235245Devang Patel  if (!DIVar.Verify())
7995ee20680c7ebc765950983633e19fafab5235245Devang Patel    return false;
8005ee20680c7ebc765950983633e19fafab5235245Devang Patel
801227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  Instruction *DbgVal = NULL;
802227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // If an argument is zero extended then use argument directly. The ZExt
803227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // may be zapped by an optimization pass in future.
804227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  Argument *ExtendedArg = NULL;
805227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
806227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
807227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
808227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
809227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ExtendedArg)
810227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
811227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  else
812227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
813227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel
8145ee20680c7ebc765950983633e19fafab5235245Devang Patel  // Propagate any debug metadata from the store onto the dbg.value.
8155ee20680c7ebc765950983633e19fafab5235245Devang Patel  DebugLoc SIDL = SI->getDebugLoc();
8165ee20680c7ebc765950983633e19fafab5235245Devang Patel  if (!SIDL.isUnknown())
8175ee20680c7ebc765950983633e19fafab5235245Devang Patel    DbgVal->setDebugLoc(SIDL);
8185ee20680c7ebc765950983633e19fafab5235245Devang Patel  // Otherwise propagate debug metadata from dbg.declare.
8195ee20680c7ebc765950983633e19fafab5235245Devang Patel  else
8205ee20680c7ebc765950983633e19fafab5235245Devang Patel    DbgVal->setDebugLoc(DDI->getDebugLoc());
8215ee20680c7ebc765950983633e19fafab5235245Devang Patel  return true;
8225ee20680c7ebc765950983633e19fafab5235245Devang Patel}
8235ee20680c7ebc765950983633e19fafab5235245Devang Patel
82436fae67831517f132255118b45b21a8cf199a012Devang Patel/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
82536fae67831517f132255118b45b21a8cf199a012Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
82636fae67831517f132255118b45b21a8cf199a012Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
82736fae67831517f132255118b45b21a8cf199a012Devang Patel                                           LoadInst *LI, DIBuilder &Builder) {
82836fae67831517f132255118b45b21a8cf199a012Devang Patel  DIVariable DIVar(DDI->getVariable());
82936fae67831517f132255118b45b21a8cf199a012Devang Patel  if (!DIVar.Verify())
83036fae67831517f132255118b45b21a8cf199a012Devang Patel    return false;
83136fae67831517f132255118b45b21a8cf199a012Devang Patel
83236fae67831517f132255118b45b21a8cf199a012Devang Patel  Instruction *DbgVal =
83336fae67831517f132255118b45b21a8cf199a012Devang Patel    Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
83436fae67831517f132255118b45b21a8cf199a012Devang Patel                                    DIVar, LI);
83536fae67831517f132255118b45b21a8cf199a012Devang Patel
83636fae67831517f132255118b45b21a8cf199a012Devang Patel  // Propagate any debug metadata from the store onto the dbg.value.
83736fae67831517f132255118b45b21a8cf199a012Devang Patel  DebugLoc LIDL = LI->getDebugLoc();
83836fae67831517f132255118b45b21a8cf199a012Devang Patel  if (!LIDL.isUnknown())
83936fae67831517f132255118b45b21a8cf199a012Devang Patel    DbgVal->setDebugLoc(LIDL);
84036fae67831517f132255118b45b21a8cf199a012Devang Patel  // Otherwise propagate debug metadata from dbg.declare.
84136fae67831517f132255118b45b21a8cf199a012Devang Patel  else
84236fae67831517f132255118b45b21a8cf199a012Devang Patel    DbgVal->setDebugLoc(DDI->getDebugLoc());
84336fae67831517f132255118b45b21a8cf199a012Devang Patel  return true;
84436fae67831517f132255118b45b21a8cf199a012Devang Patel}
84536fae67831517f132255118b45b21a8cf199a012Devang Patel
846813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
847813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// of llvm.dbg.value intrinsics.
848813c9a0f19c0d27085a3ea81eb44033747007741Devang Patelbool llvm::LowerDbgDeclare(Function &F) {
849813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  DIBuilder DIB(*F.getParent());
850813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  SmallVector<DbgDeclareInst *, 4> Dbgs;
851813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
852813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
853813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
854813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel        Dbgs.push_back(DDI);
855813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    }
856813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  if (Dbgs.empty())
857813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    return false;
858813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel
859813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
860813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel         E = Dbgs.end(); I != E; ++I) {
861813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    DbgDeclareInst *DDI = *I;
862813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
86381ad03c020d7c1f73a78ce41ca713f1e425efe3dDevang Patel      bool RemoveDDI = true;
864813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel      for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
865813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel           UI != E; ++UI)
866813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel        if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
867813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
86836fae67831517f132255118b45b21a8cf199a012Devang Patel        else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
86936fae67831517f132255118b45b21a8cf199a012Devang Patel          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
87081ad03c020d7c1f73a78ce41ca713f1e425efe3dDevang Patel        else
87181ad03c020d7c1f73a78ce41ca713f1e425efe3dDevang Patel          RemoveDDI = false;
87281ad03c020d7c1f73a78ce41ca713f1e425efe3dDevang Patel      if (RemoveDDI)
87381ad03c020d7c1f73a78ce41ca713f1e425efe3dDevang Patel        DDI->eraseFromParent();
874813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    }
875813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  }
876813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  return true;
877813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel}
878c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
879c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
880c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// alloca 'V', if any.
881c827939046670a9800659b83e2048f1d3a79a531Cameron ZwarichDbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
882c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich  if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
883c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich    for (Value::use_iterator UI = DebugNode->use_begin(),
884c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich         E = DebugNode->use_end(); UI != E; ++UI)
885c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
886c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich        return DDI;
887c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
888c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich  return 0;
889c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich}
890