Local.cpp revision 4c5e43da7792f75567b693105cc53e3f1992ad98
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"
16d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/DenseMap.h"
173333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov#include "llvm/ADT/STLExtras.h"
1858a2cbef4aac9ee7d530dfb690c78d6fc11a2371Chandler Carruth#include "llvm/ADT/SmallPtrSet.h"
194f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne#include "llvm/ADT/Statistic.h"
20d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/InstructionSimplify.h"
214c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar#include "llvm/Analysis/LibCallSemantics.h"
22d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/MemoryBuiltins.h"
23d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/ValueTracking.h"
2436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/CFG.h"
250b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
2636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DIBuilder.h"
270b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
2836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DebugInfo.h"
290b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
3036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/Dominators.h"
3136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/GetElementPtrTypeIterator.h"
320b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalAlias.h"
330b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalVariable.h"
340b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
360b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
370b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Intrinsics.h"
380b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/MDBuilder.h"
390b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Metadata.h"
400b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Operator.h"
4136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/ValueHandle.h"
42dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/Debug.h"
43c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/MathExtras.h"
44dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/raw_ostream.h"
45abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerusing namespace llvm;
46d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
47dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#define DEBUG_TYPE "local"
48dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
494f96b7e1478be0b33cda589db40635a1e3a40c11Peter CollingbourneSTATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
514d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
523481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner//  Local constant propagation.
534d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
544d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
555649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// ConstantFoldTerminator - If a terminator instruction is predicated on a
565649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// constant value, convert it into an unconditional branch to the constant
575649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// destination.  This is a nontrivial operation because the successors of this
585649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// basic block must have their PHI nodes updated.
595649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
605649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// conditions and indirectbr addresses this might make dead if
615649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// DeleteDeadConditions is true.
628e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
638e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                  const TargetLibraryInfo *TLI) {
6476ae3445f81164aaff9f95123426109c119f27c0Chris Lattner  TerminatorInst *T = BB->getTerminator();
6562fb3556eab41d9d66994e92d15e3e707c181988Devang Patel  IRBuilder<> Builder(T);
66fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
674d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  // Branch - See if we are conditional jumping on constant
684d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
694d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
70c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest1 = BI->getSuccessor(0);
71c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest2 = BI->getSuccessor(1);
724d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
736b6b6ef1677fa71b1072c2911b4c1f9524a558c9Zhou Sheng    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
744d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Are we branching on constant?
754d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // YES.  Change to unconditional branch...
76579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
77579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
784d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
79fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //cerr << "Function: " << T->getParent()->getParent()
80fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //     << "\nRemoving branch from " << T->getParent()
814d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     << "\n\nTo: " << OldDest << endl;
824d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
834d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of it.  Based on this,
844d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // it will adjust it's PHI nodes.
851a0390253b3e7c2327139d81e5a8c16d5bf85aa8Jay Foad      OldDest->removePredecessor(BB);
864d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
878f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
8862fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Destination);
898f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
904d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
910a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
92a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
930a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (Dest2 == Dest1) {       // Conditional branch to same location?
94fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      // This branch matches something like this:
954d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     br bool %cond, label %Dest, label %Dest
964d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // and changes it into:  br label %Dest
974d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
984d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of one copy of it.
994d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
1004d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      Dest1->removePredecessor(BI->getParent());
1014d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1028f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
10362fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Dest1);
1045649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = BI->getCondition();
1058f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
1065649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
1078e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
1084d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1094d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    }
1100a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1110a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
112a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1130a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
114ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // If we are switching on a constant, we can convert the switch to an
115ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // unconditional branch.
11610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
117ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *DefaultDest = SI->getDefaultDest();
118ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *TheOnlyDest = DefaultDest;
119ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
120ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // If the default is unreachable, ignore it when searching for TheOnlyDest.
121ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
122ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        SI->getNumCases() > 0) {
123ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      TheOnlyDest = SI->case_begin().getCaseSuccessor();
124ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    }
12510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1260a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // Figure out which case it goes to.
1273d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
128c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy         i != e; ++i) {
12910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Found case matching a constant operand?
130c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseValue() == CI) {
131c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        TheOnlyDest = i.getCaseSuccessor();
13210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        break;
13310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
13410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1357d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // Check to see if this branch is going to the same place as the default
1367d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // dest.  If so, eliminate it as an explicit compare.
137c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseSuccessor() == DefaultDest) {
13837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
13936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        unsigned NCases = SI->getNumCases();
14036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Fold the case metadata into the default if there will be any branches
14136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // left, unless the metadata doesn't match the switch.
14236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
143ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Collect branch weights into a vector.
144ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SmallVector<uint32_t, 8> Weights;
145ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
146ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren               ++MD_i) {
147ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            ConstantInt *CI =
148ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
149ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            assert(CI);
150ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            Weights.push_back(CI->getValue().getZExtValue());
151ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          }
152ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Merge weight of this case to the default weight.
153ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          unsigned idx = i.getCaseIndex();
154ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights[0] += Weights[idx+1];
155ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Remove weight for this case.
156ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          std::swap(Weights[idx+1], Weights.back());
157ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights.pop_back();
158ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SI->setMetadata(LLVMContext::MD_prof,
159ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          MDBuilder(BB->getContext()).
160ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          createBranchWeights(Weights));
161ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren        }
1620a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        // Remove this entry.
1637d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        DefaultDest->removePredecessor(SI->getParent());
1647d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        SI->removeCase(i);
165c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        --i; --e;
1667d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        continue;
1677d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      }
1687d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner
16910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, check to see if the switch only branches to one destination.
17010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
17110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // destinations.
172dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
17310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
174694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
17510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (CI && !TheOnlyDest) {
17610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Branching on a constant, but not any of the cases, go to the default
17710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // successor.
17810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      TheOnlyDest = SI->getDefaultDest();
179694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner    }
180694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
18110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we found a single destination that we can fold the switch into, do so
18210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // now.
18310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (TheOnlyDest) {
1840a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
18562fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
18610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BasicBlock *BB = SI->getParent();
18710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
18810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Remove entries from PHI nodes which we no longer branch to...
18910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
19010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        // Found case matching a constant operand?
19110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        BasicBlock *Succ = SI->getSuccessor(i);
19210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        if (Succ == TheOnlyDest)
193dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
19410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        else
19510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          Succ->removePredecessor(BB);
19610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
19710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1980a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
1995649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = SI->getCondition();
2005649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      SI->eraseFromParent();
2015649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2028e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
20310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
2040a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
205a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
20624473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    if (SI->getNumCases() == 1) {
20710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, we can fold this switch into a conditional branch
20810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // instruction if it has only one non-default destination.
2093d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy      SwitchInst::CaseIt FirstCase = SI->case_begin();
210db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
211db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson          FirstCase.getCaseValue(), "cond");
212a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
213db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Insert the new branch.
214db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      BranchInst *NewBr = Builder.CreateCondBr(Cond,
215db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               FirstCase.getCaseSuccessor(),
216db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               SI->getDefaultDest());
21737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
218db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      if (MD && MD->getNumOperands() == 3) {
219ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        ConstantInt *SICase =
220ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
221ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        ConstantInt *SIDef =
222ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
223db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        assert(SICase && SIDef);
224db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        // The TrueWeight should be the weight for the single case of SI.
225db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        NewBr->setMetadata(LLVMContext::MD_prof,
226db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        MDBuilder(BB->getContext()).
227db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        createBranchWeights(SICase->getValue().getZExtValue(),
228db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                            SIDef->getValue().getZExtValue()));
229a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      }
230db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson
231db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Delete the old switch.
232db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      SI->eraseFromParent();
233db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      return true;
23410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
2350a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
2360a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
2370a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2380a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
2390a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // indirectbr blockaddress(@F, @BB) -> br label @BB
2400a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (BlockAddress *BA =
2410a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
2420a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BasicBlock *TheOnlyDest = BA->getBasicBlock();
2430a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
24462fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
245a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2460a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2470a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        if (IBI->getDestination(i) == TheOnlyDest)
248dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr;
2490a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        else
2500a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          IBI->getDestination(i)->removePredecessor(IBI->getParent());
2510a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2525649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Address = IBI->getAddress();
2530a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      IBI->eraseFromParent();
2545649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2558e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
256a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2570a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // If we didn't find our destination in the IBI successor list, then we
2580a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // have undefined behavior.  Replace the unconditional branch with an
2590a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // 'unreachable' instruction.
2600a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      if (TheOnlyDest) {
2610a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        BB->getTerminator()->eraseFromParent();
2620a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        new UnreachableInst(BB->getContext(), BB);
2630a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
264a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2650a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      return true;
2660a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
2674d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  }
268a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2694d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  return false;
2704d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2714d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2724d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2734d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
27440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Local dead code elimination.
2754d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
2764d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2773481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// isInstructionTriviallyDead - Return true if the result produced by the
2783481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// instruction is not used, and the instruction has no side effects.
2793481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner///
2808e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::isInstructionTriviallyDead(Instruction *I,
2818e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                      const TargetLibraryInfo *TLI) {
282ec710c5b12af647ae90f53917122726269c18738Chris Lattner  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
28300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
284187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  // We don't want the landingpad instruction removed by anything this general.
285187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  if (isa<LandingPadInst>(I))
286187b1924a4b68350a6492b116db0fb19c659222fBill Wendling    return false;
287187b1924a4b68350a6492b116db0fb19c659222fBill Wendling
2889c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // We don't want debug info removed by anything this general, unless
2899c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // debug info is empty.
2909c5822a966572ea78f4e818870d4229c7a855749Devang Patel  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
2913e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (DDI->getAddress())
2929c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
293b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2943e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
295b99462117ebd4be41788346246d7935fc90a11eeDevang Patel  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
2969c5822a966572ea78f4e818870d4229c7a855749Devang Patel    if (DVI->getValue())
2979c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
298b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2999c5822a966572ea78f4e818870d4229c7a855749Devang Patel  }
3009c5822a966572ea78f4e818870d4229c7a855749Devang Patel
3017af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  if (!I->mayHaveSideEffects()) return true;
3027af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands
3037af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // Special case intrinsics that "may have side effects" but can be deleted
3047af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // when dead.
3053e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
306741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    // Safe to delete llvm.stacksave if dead.
307741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    if (II->getIntrinsicID() == Intrinsic::stacksave)
308741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner      return true;
3093e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky
3103e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    // Lifetime intrinsics are dead when their right-hand is undef.
3113e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
3123e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky        II->getIntrinsicID() == Intrinsic::lifetime_end)
3133e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky      return isa<UndefValue>(II->getArgOperand(1));
31437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
31537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    // Assumptions are dead if their condition is trivially true.
31637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (II->getIntrinsicID() == Intrinsic::assume) {
31737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
31837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        return !Cond->isZero();
31937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
32037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      return false;
32137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
3223e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
3234a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3248e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (isAllocLikeFn(I, TLI)) return true;
3254a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3268e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (CallInst *CI = isFreeCall(I, TLI))
3274a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky    if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
3284a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky      return C->isNullValue() || isa<UndefValue>(C);
3294a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
330ec710c5b12af647ae90f53917122726269c18738Chris Lattner  return false;
3314d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
3324d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
3333481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
3343481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// trivially dead instruction, delete it.  If that makes any of its operands
33590fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// trivially dead, delete them too, recursively.  Return true if any
33690fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// instructions were deleted.
3378e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool
3388e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerllvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
3398e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                                 const TargetLibraryInfo *TLI) {
3403481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
3418e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
34290fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
343a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3447605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  SmallVector<Instruction*, 16> DeadInsts;
3457605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  DeadInsts.push_back(I);
346a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
347321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  do {
348e9d87f49063cb1bd213d8e9c339b9b63393cc2d9Dan Gohman    I = DeadInsts.pop_back_val();
3492872177834d83b42cd042a37299cb7089965f36bChris Lattner
3507605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // Null out all of the instruction's operands to see if any operand becomes
3517605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // dead as we go.
3527605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3537605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      Value *OpV = I->getOperand(i);
354dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      I->setOperand(i, nullptr);
355a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3567605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (!OpV->use_empty()) continue;
357a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3587605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // If the operand is an instruction that became dead as we nulled out the
3597605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // operand, and if it is 'trivially' dead, delete it in a future loop
3607605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // iteration.
3617605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
3628e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        if (isInstructionTriviallyDead(OpI, TLI))
3637605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner          DeadInsts.push_back(OpI);
3647605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    }
365a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3667605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    I->eraseFromParent();
367321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  } while (!DeadInsts.empty());
36890fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman
36990fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return true;
3704d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
371b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
3721a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// areAllUsesEqual - Check whether the uses of a value are all the same.
3731a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// This is similar to Instruction::hasOneUse() except this will also return
374b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// true when there are no uses or multiple uses that all refer to the same
375b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// value.
3761a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewyckystatic bool areAllUsesEqual(Instruction *I) {
37736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UI = I->user_begin();
37836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UE = I->user_end();
3791a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  if (UI == UE)
380b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    return true;
3811a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
3821a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  User *TheUse = *UI;
3831a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  for (++UI; UI != UE; ++UI) {
3841a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky    if (*UI != TheUse)
3851a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky      return false;
3861a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  }
3871a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  return true;
3881a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky}
3891a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
390afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
391afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// dead PHI node, due to being a def-use chain of single-use nodes that
392afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// either forms a cycle or is terminated by a trivially dead instruction,
393afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// delete it.  If that makes any of its operands trivially dead, delete them
3942cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands/// too, recursively.  Return true if a change was made.
3958e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
3968e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                        const TargetLibraryInfo *TLI) {
397b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  SmallPtrSet<Instruction*, 4> Visited;
398b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
39936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines       I = cast<Instruction>(*I->user_begin())) {
400b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    if (I->use_empty())
4018e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
402afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman
403b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    // If we find an instruction more than once, we're on a cycle that
404afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // won't prove fruitful.
40537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (!Visited.insert(I).second) {
406b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      // Break the cycle and delete the instruction and its operands.
407b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      I->replaceAllUsesWith(UndefValue::get(I->getType()));
4088e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
4092cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands      return true;
410b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    }
411b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  }
412b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  return false;
413afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman}
4143481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
415e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
416e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// simplify any instructions in it and recursively delete dead instructions.
417e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner///
418e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// This returns true if it changed the code, note that it can delete
419e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// instructions in other blocks as well in this block.
4204c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarbool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
4218e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                       const TargetLibraryInfo *TLI) {
422e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  bool MadeChange = false;
423acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
424acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#ifndef NDEBUG
425acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // In debug builds, ensure that the terminator of the block is never replaced
426acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // or deleted by these simplifications. The idea of simplification is that it
427acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // cannot introduce new instructions, and there is no way to replace the
428acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // terminator of a block without introducing a new instruction.
429acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  AssertingVH<Instruction> TerminatorVH(--BB->end());
430acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#endif
431acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
432858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth  for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
433858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth    assert(!BI->isTerminator());
434e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    Instruction *Inst = BI++;
4356b980541df5846ad335c377c8803b517968daee2Chandler Carruth
4366b980541df5846ad335c377c8803b517968daee2Chandler Carruth    WeakVH BIHandle(BI);
4374c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (recursivelySimplifyInstruction(Inst, TLI)) {
438e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      MadeChange = true;
43935a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner      if (BIHandle != BI)
440e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner        BI = BB->begin();
441e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      continue;
442e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    }
44371ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman
4448e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
44571ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman    if (BIHandle != BI)
44671ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman      BI = BB->begin();
447e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  }
448e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  return MadeChange;
449e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner}
450e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner
451b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//===----------------------------------------------------------------------===//
45240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Control Flow Graph Restructuring.
453b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//
454b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
45540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
45640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
45740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
45840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
45940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
46040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
46140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// nodes that collapse into identity values.  For example, if we have:
46240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   x = phi(1, 0, 0, 0)
46340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   y = and x, z
46440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
46540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
46640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// recursively fold the and to 0.
4674c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarvoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
46840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // This only adjusts blocks with PHI nodes.
46940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  if (!isa<PHINode>(BB->begin()))
47040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    return;
471a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
47240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
47340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
47440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // that can be removed.
47540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  BB->removePredecessor(Pred, true);
476a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
47740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  WeakVH PhiIt = &BB->front();
47840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
47940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
4806b980541df5846ad335c377c8803b517968daee2Chandler Carruth    Value *OldPhiIt = PhiIt;
4816ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
4824c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (!recursivelySimplifyInstruction(PN))
4836b980541df5846ad335c377c8803b517968daee2Chandler Carruth      continue;
4846ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
48540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If recursive simplification ended up deleting the next PHI node we would
48640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
48740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // of the block.
48835a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
48940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  }
49040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner}
49140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
49240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
493b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
494b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
495b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// between them, moving the instructions in the predecessor into DestBB and
496b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// deleting the predecessor block.
497b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner///
498ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesvoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
499b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // If BB has single-entry PHI nodes, fold them.
500b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
501b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    Value *NewVal = PN->getIncomingValue(0);
502b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    // Replace self referencing PHI with undef, it must be dead.
5039e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
504b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->replaceAllUsesWith(NewVal);
505b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->eraseFromParent();
506b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  }
507a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
508b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  BasicBlock *PredBB = DestBB->getSinglePredecessor();
509b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  assert(PredBB && "Block doesn't have a single predecessor!");
510a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
51137914c8e83c43d710925263b66014159f03fa355Chris Lattner  // Zap anything that took the address of DestBB.  Not doing this will give the
51237914c8e83c43d710925263b66014159f03fa355Chris Lattner  // address an invalid value.
51337914c8e83c43d710925263b66014159f03fa355Chris Lattner  if (DestBB->hasAddressTaken()) {
51437914c8e83c43d710925263b66014159f03fa355Chris Lattner    BlockAddress *BA = BlockAddress::get(DestBB);
51537914c8e83c43d710925263b66014159f03fa355Chris Lattner    Constant *Replacement =
51637914c8e83c43d710925263b66014159f03fa355Chris Lattner      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
51737914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
51837914c8e83c43d710925263b66014159f03fa355Chris Lattner                                                     BA->getType()));
51937914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->destroyConstant();
52037914c8e83c43d710925263b66014159f03fa355Chris Lattner  }
521a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
522b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Anything that branched to PredBB now branches to DestBB.
523b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->replaceAllUsesWith(DestBB);
524a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
52595c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  // Splice all the instructions from PredBB to DestBB.
52695c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  PredBB->getTerminator()->eraseFromParent();
5273e033f29239e48c190f29cdf3a02cdfbaf2fe72bBill Wendling  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
52895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
52937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // If the PredBB is the entry block of the function, move DestBB up to
53037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // become the entry block after we erase PredBB.
53137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  if (PredBB == &DestBB->getParent()->getEntryBlock())
53237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DestBB->moveAfter(PredBB);
53337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
534ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (DT) {
535ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
536ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DT->changeImmediateDominator(DestBB, PredBBIDom);
537ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DT->eraseNode(PredBB);
538ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  }
539b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Nuke BB.
540b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->eraseFromParent();
541b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner}
5424afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
543c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// CanMergeValues - Return true if we can choose one of these values to use
544c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// in place of the other. Note that we will always choose the non-undef
545c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// value to keep.
546c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic bool CanMergeValues(Value *First, Value *Second) {
547c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
548c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
549c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
550dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
5511b6e10f53bec0cd261924734bd5eb58c75c8f550Mark Lacey/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
552dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
553dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// Assumption: Succ is the single successor for BB.
554dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
555dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
556dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
557dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
558a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
559dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        << Succ->getName() << "\n");
560dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there is only a single predecessor it must be BB and merging
561dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // is always safe
562dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (Succ->getSinglePredecessor()) return true;
563dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
564dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Make a list of the predecessors of BB
56588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer  SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
566dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
567dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Look at all the phi nodes in Succ, to see if they present a conflict when
568dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // merging these blocks
569dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
570dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *PN = cast<PHINode>(I);
571dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
572dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If the incoming value from BB is again a PHINode in
573dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // BB which has the same incoming value for *PI as PN does, we can
574dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // merge the phi nodes and then the blocks can still be merged
575dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
576dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPN && BBPN->getParent() == BB) {
57788c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
57888c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
57988c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        if (BBPreds.count(IBB) &&
580c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
581c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                            PN->getIncomingValue(PI))) {
582a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
583a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak                << Succ->getName() << " is conflicting with "
584dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << BBPN->getName() << " with regard to common predecessor "
58588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << IBB->getName() << "\n");
586dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
587dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
588dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
589dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
590dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value* Val = PN->getIncomingValueForBlock(BB);
59188c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
592dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // See if the incoming value for the common predecessor is equal to the
593dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // one for BB, in which case this phi node will not prevent the merging
594dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // of the block.
59588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
596c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands        if (BBPreds.count(IBB) &&
597c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(Val, PN->getIncomingValue(PI))) {
598a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
599dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with regard to common "
60088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << "predecessor " << IBB->getName() << "\n");
601dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
602dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
603dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
604dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
605dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
606dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
607dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
608dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
609dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
610c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef SmallVector<BasicBlock *, 16> PredBlockVector;
611c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
612c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
613c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Determines the value to use as the phi node input for a block.
614c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
615c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Select between \p OldVal any value that we know flows from \p BB
616c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// to a particular phi on the basis of which one (if either) is not
617c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// undef. Update IncomingValues based on the selected value.
618c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
619c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param OldVal The value we are considering selecting.
620c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block that the value flows in from.
621c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block-to-value for other phi inputs
622c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// that we have examined.
623c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
624c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \returns the selected value.
625c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
626c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                          IncomingValueMap &IncomingValues) {
627c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (!isa<UndefValue>(OldVal)) {
628c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    assert((!IncomingValues.count(BB) ||
629c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            IncomingValues.find(BB)->second == OldVal) &&
630c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands           "Expected OldVal to match incoming value from BB!");
631c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
632c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValues.insert(std::make_pair(BB, OldVal));
633c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    return OldVal;
634c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
635c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
636c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap::const_iterator It = IncomingValues.find(BB);
637c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (It != IncomingValues.end()) return It->second;
638c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
639c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return OldVal;
640c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
641c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
642c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Create a map from block to value for the operands of a
643c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// given phi.
644c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
645c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Create a map from block to value for each non-undef value flowing
646c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// into \p PN.
647c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
648c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are collecting the map for.
649c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues [out] The map from block to value for this phi.
650c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void gatherIncomingValuesToPhi(PHINode *PN,
651c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                      IncomingValueMap &IncomingValues) {
652c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
653c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
654c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
655c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
656c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V))
657c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      IncomingValues.insert(std::make_pair(BB, V));
658c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
659c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
660c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
661c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace the incoming undef values to a phi with the values
662c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// from a block-to-value map.
663c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
664c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are replacing the undefs in.
665c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block to value.
666c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void replaceUndefValuesInPhi(PHINode *PN,
667c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                    const IncomingValueMap &IncomingValues) {
668c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
669c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
670c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
671c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V)) continue;
672c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
673c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
674c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValueMap::const_iterator It = IncomingValues.find(BB);
675c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (It == IncomingValues.end()) continue;
676c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
677c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PN->setIncomingValue(i, It->second);
678c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
679c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
680c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
681c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace a value flowing from a block to a phi with
682c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// potentially multiple instances of that value flowing from the
683c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// block's predecessors to the phi.
684c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
685c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block with the value flowing into the phi.
686c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BBPreds The predecessors of BB.
687c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi that we are updating.
688c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
689c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                const PredBlockVector &BBPreds,
690c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                PHINode *PN) {
691c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  Value *OldVal = PN->removeIncomingValue(BB, false);
692c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  assert(OldVal && "No entry in PHI for Pred BB!");
693c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
694c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap IncomingValues;
695c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
696c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // We are merging two blocks - BB, and the block containing PN - and
697c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // as a result we need to redirect edges from the predecessors of BB
698c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // to go to the block containing PN, and update PN
699c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // accordingly. Since we allow merging blocks in the case where the
700c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // predecessor and successor blocks both share some predecessors,
701c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // and where some of those common predecessors might have undef
702c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // values flowing into PN, we want to rewrite those values to be
703c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // consistent with the non-undef values.
704c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
705c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  gatherIncomingValuesToPhi(PN, IncomingValues);
706c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
707c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // If this incoming value is one of the PHI nodes in BB, the new entries
708c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // in the PHI node are the entries from the old PHI.
709c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
710c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PHINode *OldValPN = cast<PHINode>(OldVal);
711c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
712c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Note that, since we are merging phi nodes and BB and Succ might
713c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // have common predecessors, we could end up with a phi node with
714c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // identical incoming branches. This will be cleaned up later (and
715c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // will trigger asserts if we try to clean it up now, without also
716c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // simplifying the corresponding conditional branch).
717c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
718c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *PredVal = OldValPN->getIncomingValue(i);
719c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
720c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
721c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
722c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
723c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
724c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
725c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
726c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  } else {
727c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
728c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Update existing incoming values in PN for this
729c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // predecessor of BB.
730c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = BBPreds[i];
731c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
732c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
733c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
734c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
735c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
736c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
737c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
738c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
739c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
740c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  replaceUndefValuesInPhi(PN, IncomingValues);
741c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
742c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
743dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
744dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// unconditional branch, and contains no instructions other than PHI nodes,
74577a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// potential side-effect free intrinsics and the branch.  If possible,
74677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// eliminate BB by rewriting all the predecessors to branch to the successor
74777a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// block and return true.  If we can't transform, return false.
748dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerbool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
749e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman  assert(BB != &BB->getParent()->getEntryBlock() &&
750e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
751e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman
752dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // We can't eliminate infinite loops.
753dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
754dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (BB == Succ) return false;
755a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
756dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check to see if merging these blocks would cause conflicts for any of the
757dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // phi nodes in BB or Succ. If not, we can safely merge.
758dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
759dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
760dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check for cases where Succ has multiple predecessors and a PHI node in BB
761dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // has uses which will not disappear when the PHI nodes are merged.  It is
762dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // possible to handle such cases, but difficult: it requires checking whether
763dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // BB dominates Succ, which is non-trivial to calculate in the case where
764dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Succ has multiple predecessors.  Also, it requires checking whether
7653a19999413b18304d1a00cbdbe73fc43ea9cb75fAlexey Samsonov  // constructing the necessary self-referential PHI node doesn't introduce any
766dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // conflicts; this isn't too difficult, but the previous code for doing this
767dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // was incorrect.
768dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  //
769dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Note that if this check finds a live use, BB dominates Succ, so BB is
770dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
771dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // folding the branch isn't profitable in that case anyway.
772dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->getSinglePredecessor()) {
773dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    BasicBlock::iterator BBI = BB->begin();
774dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    while (isa<PHINode>(*BBI)) {
77536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (Use &U : BBI->uses()) {
77636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
77736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          if (PN->getIncomingBlock(U) != BB)
778dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            return false;
779dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        } else {
780dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
781dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
782dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
783dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      ++BBI;
784dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
785dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
786dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
787fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
788a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
789dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (isa<PHINode>(Succ->begin())) {
790dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If there is more than one pred of succ, and there are PHI nodes in
791dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // the successor, then we need to add incoming edges for the PHI nodes
792dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    //
793c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
794a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
795dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // Loop over all of the PHI nodes in the successor of BB.
796dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
797dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PHINode *PN = cast<PHINode>(I);
798c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
799c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
800dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
801dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
802a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
80377a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  if (Succ->getSinglePredecessor()) {
80477a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // BB is the only predecessor of Succ, so Succ will end up with exactly
80577a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // the same predecessors BB had.
80677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola
80777a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // Copy over any phi, debug or lifetime instruction.
80877a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    BB->getTerminator()->eraseFromParent();
80977a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
81077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  } else {
81177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
812dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
813dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(PN->use_empty() && "There shouldn't be any uses here!");
814dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PN->eraseFromParent();
815dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
816dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
817a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
818dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Everything that jumped to BB now goes to Succ.
819dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->replaceAllUsesWith(Succ);
820dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->hasName()) Succ->takeName(BB);
821dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->eraseFromParent();              // Delete the old basic block.
822dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
823dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
824dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
82543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
82643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// nodes in this block. This doesn't try to be clever about PHI nodes
82743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// which differ only in the order of the incoming values, but instcombine
82843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// orders them so it usually won't matter.
82943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach///
83043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbachbool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
83143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  bool Changed = false;
83243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
83343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // This implementation doesn't currently consider undef operands
83489991d44136414c4c74eee7c6dfbdbeab287b881Nick Lewycky  // specially. Theoretically, two phis which are identical except for
83543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // one having an undef where the other doesn't could be collapsed.
83643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
83743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Map from PHI hash values to PHI nodes. If multiple PHIs have
83843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // the same hash value, the element is the first PHI in the
83943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // linked list in CollisionMap.
84043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<uintptr_t, PHINode *> HashMap;
84143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
84243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Maintain linked lists of PHI nodes with common hash values.
84343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<PHINode *, PHINode *> CollisionMap;
84443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
84543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Examine each PHI.
84643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  for (BasicBlock::iterator I = BB->begin();
84743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach       PHINode *PN = dyn_cast<PHINode>(I++); ) {
84843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Compute a hash value on the operands. Instcombine will likely have sorted
84943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // them, which helps expose duplicates, but we have to check all the
85043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // operands to be safe in case instcombine hasn't run.
85143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    uintptr_t Hash = 0;
85295c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // This hash algorithm is quite weak as hash functions go, but it seems
85395c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // to do a good enough job for this particular purpose, and is very quick.
85443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
85543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
85643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
85743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
85895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
85995c3e48f9557adb6064d580684bb14cacec2f826Jay Foad         I != E; ++I) {
86095c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
86195c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
86295c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    }
8632bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
8642bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    Hash >>= 1;
86543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // If we've never seen this hash value before, it's a unique PHI.
86643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
86743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      HashMap.insert(std::make_pair(Hash, PN));
86843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    if (Pair.second) continue;
86943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Otherwise it's either a duplicate or a hash collision.
87043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (PHINode *OtherPN = Pair.first->second; ; ) {
87143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (OtherPN->isIdenticalTo(PN)) {
87243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // A duplicate. Replace this PHI with its duplicate.
87343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->replaceAllUsesWith(OtherPN);
87443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->eraseFromParent();
87543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Changed = true;
87643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
87743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
87843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // A non-duplicate hash collision.
87943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
88043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (I == CollisionMap.end()) {
88143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // Set this PHI to be the head of the linked list of colliding PHIs.
88243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PHINode *Old = Pair.first->second;
88343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Pair.first->second = PN;
88443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        CollisionMap[PN] = Old;
88543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
88643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
887d9b0b025612992a0b724eeca8bdf10b1d7a5c355Benjamin Kramer      // Proceed to the next PHI in the list.
88843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      OtherPN = I->second;
88943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
89043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  }
89143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
89243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  return Changed;
89343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach}
894687140c818ba4b896329a83324714140b6580ef8Chris Lattner
895687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// enforceKnownAlignment - If the specified pointer points to an object that
896687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we control, modify the object's alignment to PrefAlign. This isn't
897687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// often possible though. If alignment is important, a more reliable approach
898687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// is to simply align all global variables and allocation instructions to
899687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// their preferred alignment from the beginning.
900687140c818ba4b896329a83324714140b6580ef8Chris Lattner///
90119282365147f498a60463d250dbed2f8e1b81861Benjamin Kramerstatic unsigned enforceKnownAlignment(Value *V, unsigned Align,
9024c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                      unsigned PrefAlign,
9034c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                      const DataLayout &DL) {
904b53c7937c5651e5500b554186657b27838137365Eli Friedman  V = V->stripPointerCasts();
905687140c818ba4b896329a83324714140b6580ef8Chris Lattner
906b53c7937c5651e5500b554186657b27838137365Eli Friedman  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
907bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // If the preferred alignment is greater than the natural stack alignment
908bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // then don't round up. This avoids dynamic stack realignment.
9094c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (DL.exceedsNaturalStackAlignment(PrefAlign))
910bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames      return Align;
911687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a requested alignment and if this is an alloca, round up.
912687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (AI->getAlignment() >= PrefAlign)
913687140c818ba4b896329a83324714140b6580ef8Chris Lattner      return AI->getAlignment();
914687140c818ba4b896329a83324714140b6580ef8Chris Lattner    AI->setAlignment(PrefAlign);
915687140c818ba4b896329a83324714140b6580ef8Chris Lattner    return PrefAlign;
916687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
917687140c818ba4b896329a83324714140b6580ef8Chris Lattner
918dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (auto *GO = dyn_cast<GlobalObject>(V)) {
919687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a large requested alignment and we can, bump up the alignment
920687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // of the global.
921dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->isDeclaration())
922dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return Align;
923d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // If the memory we set aside for the global may not be the memory used by
924d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // the final program then it is impossible for us to reliably enforce the
925d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // preferred alignment.
926dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->isWeakForLinker())
927dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return Align;
928a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
929dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->getAlignment() >= PrefAlign)
930dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return GO->getAlignment();
931687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // We can only increase the alignment of the global if it has no alignment
932687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // specified or if it is not assigned a section.  If it is assigned a
933687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, the global could be densely packed with other objects in the
934687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, increasing the alignment could cause padding issues.
935dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!GO->hasSection() || GO->getAlignment() == 0)
936dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      GO->setAlignment(PrefAlign);
937dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return GO->getAlignment();
938687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
939687140c818ba4b896329a83324714140b6580ef8Chris Lattner
940687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
941687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
942687140c818ba4b896329a83324714140b6580ef8Chris Lattner
943687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
944687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
945687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// and it is more than the alignment of the ultimate object, see if we can
946687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// increase the alignment of the ultimate object, making this check succeed.
947687140c818ba4b896329a83324714140b6580ef8Chris Lattnerunsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
9484c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                          const DataLayout &DL,
94937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const Instruction *CxtI,
9504c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                          AssumptionCache *AC,
95137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const DominatorTree *DT) {
952687140c818ba4b896329a83324714140b6580ef8Chris Lattner  assert(V->getType()->isPointerTy() &&
953687140c818ba4b896329a83324714140b6580ef8Chris Lattner         "getOrEnforceKnownAlignment expects a pointer!");
9544c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
955186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault
956687140c818ba4b896329a83324714140b6580ef8Chris Lattner  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
957ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
958687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned TrailZ = KnownZero.countTrailingOnes();
959a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
96059a3878c525657701e83bd516d27236814e29f25Matt Arsenault  // Avoid trouble with ridiculously large TrailZ values, such as
961687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // those computed from a null pointer.
962687140c818ba4b896329a83324714140b6580ef8Chris Lattner  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
963a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
964687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
965a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
966687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // LLVM doesn't support alignments larger than this currently.
967687140c818ba4b896329a83324714140b6580ef8Chris Lattner  Align = std::min(Align, +Value::MaximumAlignment);
968a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
969687140c818ba4b896329a83324714140b6580ef8Chris Lattner  if (PrefAlign > Align)
970186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault    Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
971a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
972687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // We don't need to make any adjustment.
973687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
974687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
975687140c818ba4b896329a83324714140b6580ef8Chris Lattner
9765ee20680c7ebc765950983633e19fafab5235245Devang Patel///===---------------------------------------------------------------------===//
9775ee20680c7ebc765950983633e19fafab5235245Devang Patel///  Dbg Intrinsic utilities
9785ee20680c7ebc765950983633e19fafab5235245Devang Patel///
9795ee20680c7ebc765950983633e19fafab5235245Devang Patel
980163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl/// See if there is a dbg.value intrinsic for DIVar before I.
981163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantlstatic bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
982163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // Since we can't guarantee that the original dbg.declare instrinsic
983163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // is removed by LowerDbgDeclare(), we need to make sure that we are
984163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // not inserting the same dbg.value intrinsic over and over.
985163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  llvm::BasicBlock::InstListType::iterator PrevI(I);
986163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (PrevI != I->getParent()->getInstList().begin()) {
987163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    --PrevI;
988163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
989163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl      if (DVI->getValue() == I->getOperand(0) &&
990163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getOffset() == 0 &&
991163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getVariable() == DIVar)
992163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl        return true;
993163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  }
994163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  return false;
995163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl}
996163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
9979d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
9985ee20680c7ebc765950983633e19fafab5235245Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
9995ee20680c7ebc765950983633e19fafab5235245Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
10005ee20680c7ebc765950983633e19fafab5235245Devang Patel                                           StoreInst *SI, DIBuilder &Builder) {
10015ee20680c7ebc765950983633e19fafab5235245Devang Patel  DIVariable DIVar(DDI->getVariable());
100237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
1003cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  assert((!DIVar || DIVar.isVariable()) &&
1004cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
1005cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
10065ee20680c7ebc765950983633e19fafab5235245Devang Patel    return false;
10075ee20680c7ebc765950983633e19fafab5235245Devang Patel
1008163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, SI))
1009163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1010163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1011dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Instruction *DbgVal = nullptr;
1012227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // If an argument is zero extended then use argument directly. The ZExt
1013227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // may be zapped by an optimization pass in future.
1014dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Argument *ExtendedArg = nullptr;
1015227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1016227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1017227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1018227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1019227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ExtendedArg)
102037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr, SI);
1021227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  else
102237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar,
102337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                             DIExpr, SI);
1024dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  DbgVal->setDebugLoc(DDI->getDebugLoc());
10255ee20680c7ebc765950983633e19fafab5235245Devang Patel  return true;
10265ee20680c7ebc765950983633e19fafab5235245Devang Patel}
10275ee20680c7ebc765950983633e19fafab5235245Devang Patel
10289d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
102936fae67831517f132255118b45b21a8cf199a012Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
103036fae67831517f132255118b45b21a8cf199a012Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
103136fae67831517f132255118b45b21a8cf199a012Devang Patel                                           LoadInst *LI, DIBuilder &Builder) {
103236fae67831517f132255118b45b21a8cf199a012Devang Patel  DIVariable DIVar(DDI->getVariable());
103337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
1034a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  assert((!DIVar || DIVar.isVariable()) &&
1035cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
1036cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
103736fae67831517f132255118b45b21a8cf199a012Devang Patel    return false;
103836fae67831517f132255118b45b21a8cf199a012Devang Patel
1039163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, LI))
1040163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1041163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1042a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  Instruction *DbgVal =
104337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr, LI);
1044dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  DbgVal->setDebugLoc(DDI->getDebugLoc());
104536fae67831517f132255118b45b21a8cf199a012Devang Patel  return true;
104636fae67831517f132255118b45b21a8cf199a012Devang Patel}
104736fae67831517f132255118b45b21a8cf199a012Devang Patel
1048dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines/// Determine whether this alloca is either a VLA or an array.
1049dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hinesstatic bool isArray(AllocaInst *AI) {
1050dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return AI->isArrayAllocation() ||
1051dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    AI->getType()->getElementType()->isArrayTy();
1052dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines}
1053dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
1054813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1055813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// of llvm.dbg.value intrinsics.
1056813c9a0f19c0d27085a3ea81eb44033747007741Devang Patelbool llvm::LowerDbgDeclare(Function &F) {
1057ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1058813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  SmallVector<DbgDeclareInst *, 4> Dbgs;
105936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &FI : F)
106036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (BasicBlock::iterator BI : FI)
106136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
1062813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel        Dbgs.push_back(DDI);
106336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1064813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  if (Dbgs.empty())
1065813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    return false;
1066813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel
106736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &I : Dbgs) {
106836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    DbgDeclareInst *DDI = I;
1069940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1070940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // If this is an alloca for a scalar variable, insert a dbg.value
1071940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // at each load and store to the alloca and erase the dbg.declare.
1072dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // The dbg.values allow tracking a variable even if it is not
1073dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // stored on the stack, while the dbg.declare can only describe
1074dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // the stack slot (and at a lexical-scope granularity). Later
1075dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // passes will attempt to elide the stack slot.
1076dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (AI && !isArray(AI)) {
107736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (User *U : AI->users())
107836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (StoreInst *SI = dyn_cast<StoreInst>(U))
1079813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
108036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        else if (LoadInst *LI = dyn_cast<LoadInst>(U))
108136fae67831517f132255118b45b21a8cf199a012Devang Patel          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1082dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        else if (CallInst *CI = dyn_cast<CallInst>(U)) {
108337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // This is a call by-value or some other instruction that
108437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // takes a pointer to the variable. Insert a *value*
108537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // intrinsic that describes the alloca.
108637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          auto DbgVal = DIB.insertDbgValueIntrinsic(
108737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines              AI, 0, DIVariable(DDI->getVariable()),
108837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines              DIExpression(DDI->getExpression()), CI);
108937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          DbgVal->setDebugLoc(DDI->getDebugLoc());
109037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
1091dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      DDI->eraseFromParent();
1092813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    }
1093813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  }
1094813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  return true;
1095813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel}
1096c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1097c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1098c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// alloca 'V', if any.
1099c827939046670a9800659b83e2048f1d3a79a531Cameron ZwarichDbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1100ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (auto *L = LocalAsMetadata::getIfExists(V))
1101ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1102ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      for (User *U : MDV->users())
1103ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1104ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines          return DDI;
1105c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1106dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return nullptr;
1107c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich}
11081afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
11091afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonovbool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1110ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                                      DIBuilder &Builder, bool Deref) {
11111afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
11121afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  if (!DDI)
11131afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    return false;
1114ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  DebugLoc Loc = DDI->getDebugLoc();
11151afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DIVariable DIVar(DDI->getVariable());
111637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
1117a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  assert((!DIVar || DIVar.isVariable()) &&
1118cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
1119cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
11201afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    return false;
11211afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
1122ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (Deref) {
1123ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // Create a copy of the original DIDescriptor for user variable, prepending
1124ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // "deref" operation to a list of address elements, as new llvm.dbg.declare
1125ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // will take a value storing address of the memory for variable, not
1126ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // alloca itself.
1127ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SmallVector<uint64_t, 4> NewDIExpr;
1128ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    NewDIExpr.push_back(dwarf::DW_OP_deref);
1129ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (DIExpr)
1130ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      for (unsigned i = 0, n = DIExpr.getNumElements(); i < n; ++i)
1131ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        NewDIExpr.push_back(DIExpr.getElement(i));
1132ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DIExpr = Builder.createExpression(NewDIExpr);
11331afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  }
11341afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
11351afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // Insert llvm.dbg.declare in the same basic block as the original alloca,
11361afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // and remove old llvm.dbg.declare.
11371afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  BasicBlock *BB = AI->getParent();
1138ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  Builder.insertDeclare(NewAllocaAddress, DIVar, DIExpr, BB)
1139ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    ->setDebugLoc(Loc);
11401afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DDI->eraseFromParent();
11411afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  return true;
11421afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov}
11433333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
11444f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// changeToUnreachable - Insert an unreachable instruction before the specified
11454f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// instruction, making it and the rest of the code in the block dead.
11464f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
11474f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BasicBlock *BB = I->getParent();
11484f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the successors, removing BB's entry from any PHI
11494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // nodes.
11504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
11514f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    (*SI)->removePredecessor(BB);
11524f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Insert a call to llvm.trap right before this.  This turns the undefined
11544f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // behavior into a hard fail instead of falling through into random code.
11554f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  if (UseLLVMTrap) {
11564f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Function *TrapFn =
11574f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
11584f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
11594f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallTrap->setDebugLoc(I->getDebugLoc());
11604f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
11614f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  new UnreachableInst(I->getContext(), I);
11624f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11634f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // All instructions after this are dead.
11644f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BasicBlock::iterator BBI = I, BBE = BB->end();
11654f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  while (BBI != BBE) {
11664f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (!BBI->use_empty())
11674f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
11684f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->getInstList().erase(BBI++);
11694f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
11704f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
11714f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11724f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// changeToCall - Convert the specified invoke into a normal call.
11734f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic void changeToCall(InvokeInst *II) {
11744f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
11754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
11764f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->takeName(II);
11774f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setCallingConv(II->getCallingConv());
11784f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setAttributes(II->getAttributes());
11794f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setDebugLoc(II->getDebugLoc());
11804f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->replaceAllUsesWith(NewCall);
11814f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11824f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Follow the call by a branch to the normal destination.
11834f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BranchInst::Create(II->getNormalDest(), II);
11844f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11854f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Update PHI nodes in the unwind destination
11864f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->getUnwindDest()->removePredecessor(II->getParent());
11874f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->eraseFromParent();
11884f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
11894f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11904f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic bool markAliveBlocks(BasicBlock *BB,
119137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                            SmallPtrSetImpl<BasicBlock*> &Reachable) {
11924f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11933333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  SmallVector<BasicBlock*, 128> Worklist;
11944f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Worklist.push_back(BB);
11954f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Reachable.insert(BB);
11964f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  bool Changed = false;
11973333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  do {
11984f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB = Worklist.pop_back_val();
11994f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12004f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Do a quick scan of the basic block, turning any obviously unreachable
12014f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // instructions into LLVM unreachable insts.  The instruction combining pass
12024f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // canonicalizes unreachable insts into stores to null or undef.
12034f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
120437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Assumptions that are known to be false are equivalent to unreachable.
120537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Also, if the condition is undefined, then we make the choice most
120637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // beneficial to the optimizer, and choose that to also be unreachable.
120737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
120837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        if (II->getIntrinsicID() == Intrinsic::assume) {
120937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          bool MakeUnreachable = false;
121037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (isa<UndefValue>(II->getArgOperand(0)))
121137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = true;
121237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          else if (ConstantInt *Cond =
121337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                   dyn_cast<ConstantInt>(II->getArgOperand(0)))
121437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = Cond->isZero();
121537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
121637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (MakeUnreachable) {
121737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            // Don't insert a call to llvm.trap right before the unreachable.
121837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            changeToUnreachable(BBI, false);
121937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            Changed = true;
122037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            break;
122137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          }
122237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
122337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
12244f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
12254f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (CI->doesNotReturn()) {
12264f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // If we found a call to a no-return function, insert an unreachable
12274f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // instruction after it.  Make sure there isn't *already* one there
12284f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // though.
12294f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          ++BBI;
12304f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          if (!isa<UnreachableInst>(BBI)) {
12314f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            // Don't insert a call to llvm.trap right before the unreachable.
12324f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            changeToUnreachable(BBI, false);
12334f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            Changed = true;
12344f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          }
12354f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
12364f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
12374f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12384f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12394f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // Store to undef and store to null are undefined and used to signal that
12404f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // they should be changed to unreachable by passes that can't modify the
12414f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // CFG.
12424f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
12434f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        // Don't touch volatile stores.
12444f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (SI->isVolatile()) continue;
12454f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12464f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Value *Ptr = SI->getOperand(1);
12474f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12484f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (isa<UndefValue>(Ptr) ||
12494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            (isa<ConstantPointerNull>(Ptr) &&
12504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne             SI->getPointerAddressSpace() == 0)) {
12514f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToUnreachable(SI, true);
12524f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          Changed = true;
12534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
12544f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
12554f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12564f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
12574f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12584f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Turn invokes that call 'nounwind' functions into ordinary calls.
12594f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
12604f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Value *Callee = II->getCalledValue();
12614f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
12624f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        changeToUnreachable(II, true);
12634f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
1264ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(II)) {
12654f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (II->use_empty() && II->onlyReadsMemory()) {
12664f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // jump to the normal destination branch.
12674f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          BranchInst::Create(II->getNormalDest(), II);
12684f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->getUnwindDest()->removePredecessor(II->getParent());
12694f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->eraseFromParent();
12704f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        } else
12714f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToCall(II);
12724f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
12734f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12744f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
12754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12764f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Changed |= ConstantFoldTerminator(BB, true);
12773333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
127837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (Reachable.insert(*SI).second)
12793333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov        Worklist.push_back(*SI);
12803333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  } while (!Worklist.empty());
12814f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  return Changed;
12824f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
12834f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12844f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
12854f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// if they are in a dead cycle.  Return true if a change was made, false
12864f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// otherwise.
12874f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournebool llvm::removeUnreachableBlocks(Function &F) {
12884f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  SmallPtrSet<BasicBlock*, 128> Reachable;
12894f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  bool Changed = markAliveBlocks(F.begin(), Reachable);
12903333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
12914f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // If there are unreachable blocks in the CFG...
12923333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  if (Reachable.size() == F.size())
12934f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    return Changed;
12943333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
12953333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  assert(Reachable.size() < F.size());
12964f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NumRemoved += F.size()-Reachable.size();
12974f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12984f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the basic blocks that are not reachable, dropping all of
12994f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // their internal references...
13004f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
13014f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (Reachable.count(BB))
13023333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      continue;
13033333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13044f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
13053333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      if (Reachable.count(*SI))
13064f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        (*SI)->removePredecessor(BB);
13074f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->dropAllReferences();
13087541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov  }
13093333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13104f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator I = ++F.begin(); I != F.end();)
13117541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov    if (!Reachable.count(I))
13127541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      I = F.getBasicBlockList().erase(I);
13137541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov    else
13147541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      ++I;
13153333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13163333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  return true;
13173333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov}
131837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
131937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hinesvoid llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
132037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
132137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  K->dropUnknownMetadata(KnownIDs);
132237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  K->getAllMetadataOtherThanDebugLoc(Metadata);
132337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
132437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    unsigned Kind = Metadata[i].first;
132537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *JMD = J->getMetadata(Kind);
132637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *KMD = Metadata[i].second;
132737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
132837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    switch (Kind) {
132937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      default:
133037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, nullptr); // Remove unknown metadata
133137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
133237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_dbg:
133337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
133437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_tbaa:
133537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
133637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
133737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_alias_scope:
1338ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1339ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        break;
134037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_noalias:
134137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
134237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
134337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_range:
134437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
134537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
134637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_fpmath:
134737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
134837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
134937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_invariant_load:
135037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !invariant.load if it is present in both instructions.
135137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
135237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
135337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_nonnull:
135437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !nonnull if it is present in both instructions.
135537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
135637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
135737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
135837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  }
135937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines}
1360