Local.cpp revision 37ed9c199ca639565f6ce88105f9e39e898d82d0
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"
21d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/MemoryBuiltins.h"
22d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/ValueTracking.h"
2336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/CFG.h"
240b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
2536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DIBuilder.h"
260b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
2736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DebugInfo.h"
280b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
2936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/Dominators.h"
3036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/GetElementPtrTypeIterator.h"
310b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalAlias.h"
320b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalVariable.h"
330b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
340b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
360b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Intrinsics.h"
370b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/MDBuilder.h"
380b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Metadata.h"
390b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Operator.h"
4036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/ValueHandle.h"
41dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/Debug.h"
42c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/MathExtras.h"
43dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/raw_ostream.h"
44abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerusing namespace llvm;
45d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
46dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#define DEBUG_TYPE "local"
47dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
484f96b7e1478be0b33cda589db40635a1e3a40c11Peter CollingbourneSTATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
504d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
513481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner//  Local constant propagation.
524d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
534d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
545649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// ConstantFoldTerminator - If a terminator instruction is predicated on a
555649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// constant value, convert it into an unconditional branch to the constant
565649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// destination.  This is a nontrivial operation because the successors of this
575649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// basic block must have their PHI nodes updated.
585649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
595649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// conditions and indirectbr addresses this might make dead if
605649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// DeleteDeadConditions is true.
618e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
628e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                  const TargetLibraryInfo *TLI) {
6376ae3445f81164aaff9f95123426109c119f27c0Chris Lattner  TerminatorInst *T = BB->getTerminator();
6462fb3556eab41d9d66994e92d15e3e707c181988Devang Patel  IRBuilder<> Builder(T);
65fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
664d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  // Branch - See if we are conditional jumping on constant
674d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
684d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
69c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest1 = BI->getSuccessor(0);
70c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest2 = BI->getSuccessor(1);
714d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
726b6b6ef1677fa71b1072c2911b4c1f9524a558c9Zhou Sheng    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
734d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Are we branching on constant?
744d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // YES.  Change to unconditional branch...
75579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
76579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
774d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
78fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //cerr << "Function: " << T->getParent()->getParent()
79fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //     << "\nRemoving branch from " << T->getParent()
804d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     << "\n\nTo: " << OldDest << endl;
814d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
824d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of it.  Based on this,
834d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // it will adjust it's PHI nodes.
841a0390253b3e7c2327139d81e5a8c16d5bf85aa8Jay Foad      OldDest->removePredecessor(BB);
854d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
868f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
8762fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Destination);
888f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
894d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
900a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
91a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
920a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (Dest2 == Dest1) {       // Conditional branch to same location?
93fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      // This branch matches something like this:
944d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     br bool %cond, label %Dest, label %Dest
954d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // and changes it into:  br label %Dest
964d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
974d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of one copy of it.
984d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
994d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      Dest1->removePredecessor(BI->getParent());
1004d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1018f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
10262fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Dest1);
1035649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = BI->getCondition();
1048f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
1055649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
1068e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
1074d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1084d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    }
1090a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1100a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
111a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1120a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
11310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we are switching on a constant, we can convert the switch into a
11410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // single branch instruction!
11510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
116c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy    BasicBlock *TheOnlyDest = SI->getDefaultDest();
1177d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner    BasicBlock *DefaultDest = TheOnlyDest;
11810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1190a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // Figure out which case it goes to.
1203d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
121c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy         i != e; ++i) {
12210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Found case matching a constant operand?
123c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseValue() == CI) {
124c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        TheOnlyDest = i.getCaseSuccessor();
12510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        break;
12610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
12710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1287d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // Check to see if this branch is going to the same place as the default
1297d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // dest.  If so, eliminate it as an explicit compare.
130c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseSuccessor() == DefaultDest) {
13137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
13236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        unsigned NCases = SI->getNumCases();
13336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Fold the case metadata into the default if there will be any branches
13436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // left, unless the metadata doesn't match the switch.
13536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
136ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Collect branch weights into a vector.
137ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SmallVector<uint32_t, 8> Weights;
138ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
139ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren               ++MD_i) {
140ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
141ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            assert(CI);
142ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            Weights.push_back(CI->getValue().getZExtValue());
143ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          }
144ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Merge weight of this case to the default weight.
145ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          unsigned idx = i.getCaseIndex();
146ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights[0] += Weights[idx+1];
147ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Remove weight for this case.
148ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          std::swap(Weights[idx+1], Weights.back());
149ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights.pop_back();
150ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SI->setMetadata(LLVMContext::MD_prof,
151ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          MDBuilder(BB->getContext()).
152ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          createBranchWeights(Weights));
153ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren        }
1540a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        // Remove this entry.
1557d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        DefaultDest->removePredecessor(SI->getParent());
1567d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        SI->removeCase(i);
157c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        --i; --e;
1587d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        continue;
1597d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      }
1607d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner
16110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, check to see if the switch only branches to one destination.
16210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
16310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // destinations.
164dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
16510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
166694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
16710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (CI && !TheOnlyDest) {
16810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Branching on a constant, but not any of the cases, go to the default
16910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // successor.
17010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      TheOnlyDest = SI->getDefaultDest();
171694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner    }
172694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
17310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we found a single destination that we can fold the switch into, do so
17410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // now.
17510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (TheOnlyDest) {
1760a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
17762fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
17810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BasicBlock *BB = SI->getParent();
17910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
18010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Remove entries from PHI nodes which we no longer branch to...
18110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
18210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        // Found case matching a constant operand?
18310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        BasicBlock *Succ = SI->getSuccessor(i);
18410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        if (Succ == TheOnlyDest)
185dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
18610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        else
18710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          Succ->removePredecessor(BB);
18810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
18910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1900a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
1915649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = SI->getCondition();
1925649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      SI->eraseFromParent();
1935649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
1948e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
19510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
1960a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
197a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
19824473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    if (SI->getNumCases() == 1) {
19910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, we can fold this switch into a conditional branch
20010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // instruction if it has only one non-default destination.
2013d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy      SwitchInst::CaseIt FirstCase = SI->case_begin();
202db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
203db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson          FirstCase.getCaseValue(), "cond");
204a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
205db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Insert the new branch.
206db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      BranchInst *NewBr = Builder.CreateCondBr(Cond,
207db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               FirstCase.getCaseSuccessor(),
208db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               SI->getDefaultDest());
20937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
210db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      if (MD && MD->getNumOperands() == 3) {
211db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        ConstantInt *SICase = dyn_cast<ConstantInt>(MD->getOperand(2));
212db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        ConstantInt *SIDef = dyn_cast<ConstantInt>(MD->getOperand(1));
213db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        assert(SICase && SIDef);
214db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        // The TrueWeight should be the weight for the single case of SI.
215db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        NewBr->setMetadata(LLVMContext::MD_prof,
216db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        MDBuilder(BB->getContext()).
217db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        createBranchWeights(SICase->getValue().getZExtValue(),
218db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                            SIDef->getValue().getZExtValue()));
219a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      }
220db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson
221db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Delete the old switch.
222db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      SI->eraseFromParent();
223db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      return true;
22410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
2250a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
2260a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
2270a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2280a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
2290a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // indirectbr blockaddress(@F, @BB) -> br label @BB
2300a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (BlockAddress *BA =
2310a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
2320a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BasicBlock *TheOnlyDest = BA->getBasicBlock();
2330a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
23462fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
235a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2360a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2370a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        if (IBI->getDestination(i) == TheOnlyDest)
238dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr;
2390a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        else
2400a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          IBI->getDestination(i)->removePredecessor(IBI->getParent());
2410a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2425649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Address = IBI->getAddress();
2430a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      IBI->eraseFromParent();
2445649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2458e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
246a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2470a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // If we didn't find our destination in the IBI successor list, then we
2480a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // have undefined behavior.  Replace the unconditional branch with an
2490a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // 'unreachable' instruction.
2500a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      if (TheOnlyDest) {
2510a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        BB->getTerminator()->eraseFromParent();
2520a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        new UnreachableInst(BB->getContext(), BB);
2530a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
254a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2550a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      return true;
2560a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
2574d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  }
258a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2594d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  return false;
2604d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2614d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2624d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2634d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
26440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Local dead code elimination.
2654d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
2664d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2673481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// isInstructionTriviallyDead - Return true if the result produced by the
2683481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// instruction is not used, and the instruction has no side effects.
2693481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner///
2708e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::isInstructionTriviallyDead(Instruction *I,
2718e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                      const TargetLibraryInfo *TLI) {
272ec710c5b12af647ae90f53917122726269c18738Chris Lattner  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
27300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
274187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  // We don't want the landingpad instruction removed by anything this general.
275187b1924a4b68350a6492b116db0fb19c659222fBill Wendling  if (isa<LandingPadInst>(I))
276187b1924a4b68350a6492b116db0fb19c659222fBill Wendling    return false;
277187b1924a4b68350a6492b116db0fb19c659222fBill Wendling
2789c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // We don't want debug info removed by anything this general, unless
2799c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // debug info is empty.
2809c5822a966572ea78f4e818870d4229c7a855749Devang Patel  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
2813e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (DDI->getAddress())
2829c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
283b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2843e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
285b99462117ebd4be41788346246d7935fc90a11eeDevang Patel  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
2869c5822a966572ea78f4e818870d4229c7a855749Devang Patel    if (DVI->getValue())
2879c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
288b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
2899c5822a966572ea78f4e818870d4229c7a855749Devang Patel  }
2909c5822a966572ea78f4e818870d4229c7a855749Devang Patel
2917af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  if (!I->mayHaveSideEffects()) return true;
2927af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands
2937af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // Special case intrinsics that "may have side effects" but can be deleted
2947af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // when dead.
2953e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
296741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    // Safe to delete llvm.stacksave if dead.
297741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    if (II->getIntrinsicID() == Intrinsic::stacksave)
298741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner      return true;
2993e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky
3003e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    // Lifetime intrinsics are dead when their right-hand is undef.
3013e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
3023e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky        II->getIntrinsicID() == Intrinsic::lifetime_end)
3033e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky      return isa<UndefValue>(II->getArgOperand(1));
30437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
30537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    // Assumptions are dead if their condition is trivially true.
30637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (II->getIntrinsicID() == Intrinsic::assume) {
30737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
30837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        return !Cond->isZero();
30937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
31037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      return false;
31137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
3123e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
3134a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3148e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (isAllocLikeFn(I, TLI)) return true;
3154a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3168e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (CallInst *CI = isFreeCall(I, TLI))
3174a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky    if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
3184a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky      return C->isNullValue() || isa<UndefValue>(C);
3194a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
320ec710c5b12af647ae90f53917122726269c18738Chris Lattner  return false;
3214d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
3224d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
3233481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
3243481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// trivially dead instruction, delete it.  If that makes any of its operands
32590fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// trivially dead, delete them too, recursively.  Return true if any
32690fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// instructions were deleted.
3278e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool
3288e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerllvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
3298e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                                 const TargetLibraryInfo *TLI) {
3303481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
3318e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
33290fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
333a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3347605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  SmallVector<Instruction*, 16> DeadInsts;
3357605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  DeadInsts.push_back(I);
336a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
337321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  do {
338e9d87f49063cb1bd213d8e9c339b9b63393cc2d9Dan Gohman    I = DeadInsts.pop_back_val();
3392872177834d83b42cd042a37299cb7089965f36bChris Lattner
3407605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // Null out all of the instruction's operands to see if any operand becomes
3417605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // dead as we go.
3427605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3437605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      Value *OpV = I->getOperand(i);
344dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      I->setOperand(i, nullptr);
345a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3467605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (!OpV->use_empty()) continue;
347a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3487605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // If the operand is an instruction that became dead as we nulled out the
3497605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // operand, and if it is 'trivially' dead, delete it in a future loop
3507605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // iteration.
3517605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
3528e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        if (isInstructionTriviallyDead(OpI, TLI))
3537605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner          DeadInsts.push_back(OpI);
3547605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    }
355a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3567605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    I->eraseFromParent();
357321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  } while (!DeadInsts.empty());
35890fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman
35990fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return true;
3604d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
361b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
3621a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// areAllUsesEqual - Check whether the uses of a value are all the same.
3631a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// This is similar to Instruction::hasOneUse() except this will also return
364b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// true when there are no uses or multiple uses that all refer to the same
365b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// value.
3661a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewyckystatic bool areAllUsesEqual(Instruction *I) {
36736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UI = I->user_begin();
36836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UE = I->user_end();
3691a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  if (UI == UE)
370b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    return true;
3711a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
3721a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  User *TheUse = *UI;
3731a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  for (++UI; UI != UE; ++UI) {
3741a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky    if (*UI != TheUse)
3751a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky      return false;
3761a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  }
3771a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  return true;
3781a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky}
3791a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
380afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
381afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// dead PHI node, due to being a def-use chain of single-use nodes that
382afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// either forms a cycle or is terminated by a trivially dead instruction,
383afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// delete it.  If that makes any of its operands trivially dead, delete them
3842cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands/// too, recursively.  Return true if a change was made.
3858e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
3868e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                        const TargetLibraryInfo *TLI) {
387b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  SmallPtrSet<Instruction*, 4> Visited;
388b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
38936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines       I = cast<Instruction>(*I->user_begin())) {
390b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    if (I->use_empty())
3918e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
392afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman
393b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    // If we find an instruction more than once, we're on a cycle that
394afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // won't prove fruitful.
39537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (!Visited.insert(I).second) {
396b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      // Break the cycle and delete the instruction and its operands.
397b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      I->replaceAllUsesWith(UndefValue::get(I->getType()));
3988e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
3992cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands      return true;
400b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    }
401b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  }
402b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  return false;
403afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman}
4043481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
405e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
406e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// simplify any instructions in it and recursively delete dead instructions.
407e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner///
408e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// This returns true if it changed the code, note that it can delete
409e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// instructions in other blocks as well in this block.
4103574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmowbool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
4118e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                       const TargetLibraryInfo *TLI) {
412e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  bool MadeChange = false;
413acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
414acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#ifndef NDEBUG
415acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // In debug builds, ensure that the terminator of the block is never replaced
416acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // or deleted by these simplifications. The idea of simplification is that it
417acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // cannot introduce new instructions, and there is no way to replace the
418acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // terminator of a block without introducing a new instruction.
419acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  AssertingVH<Instruction> TerminatorVH(--BB->end());
420acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#endif
421acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
422858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth  for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
423858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth    assert(!BI->isTerminator());
424e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    Instruction *Inst = BI++;
4256b980541df5846ad335c377c8803b517968daee2Chandler Carruth
4266b980541df5846ad335c377c8803b517968daee2Chandler Carruth    WeakVH BIHandle(BI);
427d721520e4c5d8ad71310a34727a567c3d74e7c08Benjamin Kramer    if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
428e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      MadeChange = true;
42935a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner      if (BIHandle != BI)
430e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner        BI = BB->begin();
431e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner      continue;
432e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner    }
43371ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman
4348e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
43571ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman    if (BIHandle != BI)
43671ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman      BI = BB->begin();
437e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  }
438e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  return MadeChange;
439e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner}
440e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner
441b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//===----------------------------------------------------------------------===//
44240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Control Flow Graph Restructuring.
443b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//
444b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
44540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
44640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
44740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
44840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
44940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
45040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
45140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// nodes that collapse into identity values.  For example, if we have:
45240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   x = phi(1, 0, 0, 0)
45340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   y = and x, z
45440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
45540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
45640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// recursively fold the and to 0.
45740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattnervoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
4583574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow                                        DataLayout *TD) {
45940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // This only adjusts blocks with PHI nodes.
46040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  if (!isa<PHINode>(BB->begin()))
46140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    return;
462a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
46340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
46440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
46540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // that can be removed.
46640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  BB->removePredecessor(Pred, true);
467a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
46840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  WeakVH PhiIt = &BB->front();
46940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
47040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
4716b980541df5846ad335c377c8803b517968daee2Chandler Carruth    Value *OldPhiIt = PhiIt;
4726ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
4736b980541df5846ad335c377c8803b517968daee2Chandler Carruth    if (!recursivelySimplifyInstruction(PN, TD))
4746b980541df5846ad335c377c8803b517968daee2Chandler Carruth      continue;
4756ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
47640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If recursive simplification ended up deleting the next PHI node we would
47740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
47840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // of the block.
47935a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
48040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  }
48140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner}
48240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
48340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
484b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
485b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
486b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// between them, moving the instructions in the predecessor into DestBB and
487b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// deleting the predecessor block.
488b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner///
489ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustiftervoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
490b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // If BB has single-entry PHI nodes, fold them.
491b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
492b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    Value *NewVal = PN->getIncomingValue(0);
493b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    // Replace self referencing PHI with undef, it must be dead.
4949e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
495b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->replaceAllUsesWith(NewVal);
496b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->eraseFromParent();
497b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  }
498a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
499b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  BasicBlock *PredBB = DestBB->getSinglePredecessor();
500b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  assert(PredBB && "Block doesn't have a single predecessor!");
501a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
50237914c8e83c43d710925263b66014159f03fa355Chris Lattner  // Zap anything that took the address of DestBB.  Not doing this will give the
50337914c8e83c43d710925263b66014159f03fa355Chris Lattner  // address an invalid value.
50437914c8e83c43d710925263b66014159f03fa355Chris Lattner  if (DestBB->hasAddressTaken()) {
50537914c8e83c43d710925263b66014159f03fa355Chris Lattner    BlockAddress *BA = BlockAddress::get(DestBB);
50637914c8e83c43d710925263b66014159f03fa355Chris Lattner    Constant *Replacement =
50737914c8e83c43d710925263b66014159f03fa355Chris Lattner      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
50837914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
50937914c8e83c43d710925263b66014159f03fa355Chris Lattner                                                     BA->getType()));
51037914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->destroyConstant();
51137914c8e83c43d710925263b66014159f03fa355Chris Lattner  }
512a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
513b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Anything that branched to PredBB now branches to DestBB.
514b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->replaceAllUsesWith(DestBB);
515a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
51695c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  // Splice all the instructions from PredBB to DestBB.
51795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  PredBB->getTerminator()->eraseFromParent();
5183e033f29239e48c190f29cdf3a02cdfbaf2fe72bBill Wendling  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
51995c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
52037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // If the PredBB is the entry block of the function, move DestBB up to
52137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // become the entry block after we erase PredBB.
52237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  if (PredBB == &DestBB->getParent()->getEntryBlock())
52337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DestBB->moveAfter(PredBB);
52437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
525ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  if (P) {
52636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (DominatorTreeWrapperPass *DTWP =
52736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines            P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
52836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      DominatorTree &DT = DTWP->getDomTree();
52936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      BasicBlock *PredBBIDom = DT.getNode(PredBB)->getIDom()->getBlock();
53036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      DT.changeImmediateDominator(DestBB, PredBBIDom);
53136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      DT.eraseNode(PredBB);
53280f6a507d4e11ba066ad0e53e12ad25ad8cf07baCameron Zwarich    }
533ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  }
534b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Nuke BB.
535b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->eraseFromParent();
536b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner}
5374afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
538c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// CanMergeValues - Return true if we can choose one of these values to use
539c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// in place of the other. Note that we will always choose the non-undef
540c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// value to keep.
541c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic bool CanMergeValues(Value *First, Value *Second) {
542c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
543c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
544c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
545dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
5461b6e10f53bec0cd261924734bd5eb58c75c8f550Mark Lacey/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
547dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
548dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// Assumption: Succ is the single successor for BB.
549dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
550dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
551dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
552dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
553a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
554dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        << Succ->getName() << "\n");
555dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there is only a single predecessor it must be BB and merging
556dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // is always safe
557dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (Succ->getSinglePredecessor()) return true;
558dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
559dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Make a list of the predecessors of BB
56088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer  SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
561dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
562dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Look at all the phi nodes in Succ, to see if they present a conflict when
563dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // merging these blocks
564dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
565dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *PN = cast<PHINode>(I);
566dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
567dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If the incoming value from BB is again a PHINode in
568dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // BB which has the same incoming value for *PI as PN does, we can
569dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // merge the phi nodes and then the blocks can still be merged
570dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
571dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPN && BBPN->getParent() == BB) {
57288c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
57388c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
57488c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        if (BBPreds.count(IBB) &&
575c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
576c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                            PN->getIncomingValue(PI))) {
577a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
578a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak                << Succ->getName() << " is conflicting with "
579dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << BBPN->getName() << " with regard to common predecessor "
58088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << IBB->getName() << "\n");
581dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
582dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
583dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
584dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
585dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value* Val = PN->getIncomingValueForBlock(BB);
58688c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
587dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // See if the incoming value for the common predecessor is equal to the
588dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // one for BB, in which case this phi node will not prevent the merging
589dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // of the block.
59088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
591c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands        if (BBPreds.count(IBB) &&
592c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(Val, PN->getIncomingValue(PI))) {
593a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
594dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with regard to common "
59588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << "predecessor " << IBB->getName() << "\n");
596dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
597dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
598dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
599dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
600dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
601dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
602dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
603dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
604dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
605c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef SmallVector<BasicBlock *, 16> PredBlockVector;
606c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
607c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
608c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Determines the value to use as the phi node input for a block.
609c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
610c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Select between \p OldVal any value that we know flows from \p BB
611c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// to a particular phi on the basis of which one (if either) is not
612c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// undef. Update IncomingValues based on the selected value.
613c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
614c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param OldVal The value we are considering selecting.
615c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block that the value flows in from.
616c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block-to-value for other phi inputs
617c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// that we have examined.
618c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
619c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \returns the selected value.
620c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
621c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                          IncomingValueMap &IncomingValues) {
622c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (!isa<UndefValue>(OldVal)) {
623c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    assert((!IncomingValues.count(BB) ||
624c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            IncomingValues.find(BB)->second == OldVal) &&
625c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands           "Expected OldVal to match incoming value from BB!");
626c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
627c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValues.insert(std::make_pair(BB, OldVal));
628c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    return OldVal;
629c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
630c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
631c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap::const_iterator It = IncomingValues.find(BB);
632c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (It != IncomingValues.end()) return It->second;
633c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
634c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return OldVal;
635c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
636c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
637c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Create a map from block to value for the operands of a
638c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// given phi.
639c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
640c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Create a map from block to value for each non-undef value flowing
641c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// into \p PN.
642c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
643c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are collecting the map for.
644c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues [out] The map from block to value for this phi.
645c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void gatherIncomingValuesToPhi(PHINode *PN,
646c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                      IncomingValueMap &IncomingValues) {
647c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
648c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
649c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
650c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
651c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V))
652c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      IncomingValues.insert(std::make_pair(BB, V));
653c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
654c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
655c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
656c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace the incoming undef values to a phi with the values
657c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// from a block-to-value map.
658c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
659c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are replacing the undefs in.
660c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block to value.
661c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void replaceUndefValuesInPhi(PHINode *PN,
662c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                    const IncomingValueMap &IncomingValues) {
663c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
664c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
665c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
666c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V)) continue;
667c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
668c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
669c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValueMap::const_iterator It = IncomingValues.find(BB);
670c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (It == IncomingValues.end()) continue;
671c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
672c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PN->setIncomingValue(i, It->second);
673c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
674c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
675c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
676c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace a value flowing from a block to a phi with
677c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// potentially multiple instances of that value flowing from the
678c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// block's predecessors to the phi.
679c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
680c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block with the value flowing into the phi.
681c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BBPreds The predecessors of BB.
682c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi that we are updating.
683c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
684c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                const PredBlockVector &BBPreds,
685c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                PHINode *PN) {
686c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  Value *OldVal = PN->removeIncomingValue(BB, false);
687c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  assert(OldVal && "No entry in PHI for Pred BB!");
688c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
689c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap IncomingValues;
690c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
691c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // We are merging two blocks - BB, and the block containing PN - and
692c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // as a result we need to redirect edges from the predecessors of BB
693c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // to go to the block containing PN, and update PN
694c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // accordingly. Since we allow merging blocks in the case where the
695c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // predecessor and successor blocks both share some predecessors,
696c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // and where some of those common predecessors might have undef
697c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // values flowing into PN, we want to rewrite those values to be
698c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // consistent with the non-undef values.
699c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
700c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  gatherIncomingValuesToPhi(PN, IncomingValues);
701c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
702c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // If this incoming value is one of the PHI nodes in BB, the new entries
703c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // in the PHI node are the entries from the old PHI.
704c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
705c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PHINode *OldValPN = cast<PHINode>(OldVal);
706c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
707c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Note that, since we are merging phi nodes and BB and Succ might
708c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // have common predecessors, we could end up with a phi node with
709c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // identical incoming branches. This will be cleaned up later (and
710c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // will trigger asserts if we try to clean it up now, without also
711c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // simplifying the corresponding conditional branch).
712c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
713c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *PredVal = OldValPN->getIncomingValue(i);
714c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
715c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
716c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
717c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
718c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
719c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
720c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
721c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  } else {
722c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
723c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Update existing incoming values in PN for this
724c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // predecessor of BB.
725c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = BBPreds[i];
726c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
727c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
728c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
729c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
730c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
731c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
732c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
733c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
734c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
735c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  replaceUndefValuesInPhi(PN, IncomingValues);
736c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
737c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
738dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
739dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// unconditional branch, and contains no instructions other than PHI nodes,
74077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// potential side-effect free intrinsics and the branch.  If possible,
74177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// eliminate BB by rewriting all the predecessors to branch to the successor
74277a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// block and return true.  If we can't transform, return false.
743dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerbool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
744e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman  assert(BB != &BB->getParent()->getEntryBlock() &&
745e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
746e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman
747dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // We can't eliminate infinite loops.
748dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
749dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (BB == Succ) return false;
750a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
751dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check to see if merging these blocks would cause conflicts for any of the
752dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // phi nodes in BB or Succ. If not, we can safely merge.
753dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
754dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
755dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check for cases where Succ has multiple predecessors and a PHI node in BB
756dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // has uses which will not disappear when the PHI nodes are merged.  It is
757dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // possible to handle such cases, but difficult: it requires checking whether
758dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // BB dominates Succ, which is non-trivial to calculate in the case where
759dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Succ has multiple predecessors.  Also, it requires checking whether
7603a19999413b18304d1a00cbdbe73fc43ea9cb75fAlexey Samsonov  // constructing the necessary self-referential PHI node doesn't introduce any
761dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // conflicts; this isn't too difficult, but the previous code for doing this
762dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // was incorrect.
763dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  //
764dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Note that if this check finds a live use, BB dominates Succ, so BB is
765dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
766dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // folding the branch isn't profitable in that case anyway.
767dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->getSinglePredecessor()) {
768dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    BasicBlock::iterator BBI = BB->begin();
769dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    while (isa<PHINode>(*BBI)) {
77036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (Use &U : BBI->uses()) {
77136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
77236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          if (PN->getIncomingBlock(U) != BB)
773dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            return false;
774dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        } else {
775dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
776dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
777dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
778dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      ++BBI;
779dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
780dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
781dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
782fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
783a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
784dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (isa<PHINode>(Succ->begin())) {
785dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If there is more than one pred of succ, and there are PHI nodes in
786dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // the successor, then we need to add incoming edges for the PHI nodes
787dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    //
788c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
789a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
790dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // Loop over all of the PHI nodes in the successor of BB.
791dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
792dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PHINode *PN = cast<PHINode>(I);
793c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
794c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
795dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
796dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
797a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
79877a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  if (Succ->getSinglePredecessor()) {
79977a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // BB is the only predecessor of Succ, so Succ will end up with exactly
80077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // the same predecessors BB had.
80177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola
80277a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // Copy over any phi, debug or lifetime instruction.
80377a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    BB->getTerminator()->eraseFromParent();
80477a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
80577a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  } else {
80677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
807dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
808dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(PN->use_empty() && "There shouldn't be any uses here!");
809dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PN->eraseFromParent();
810dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
811dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
812a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
813dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Everything that jumped to BB now goes to Succ.
814dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->replaceAllUsesWith(Succ);
815dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->hasName()) Succ->takeName(BB);
816dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->eraseFromParent();              // Delete the old basic block.
817dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
818dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
819dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
82043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
82143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// nodes in this block. This doesn't try to be clever about PHI nodes
82243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// which differ only in the order of the incoming values, but instcombine
82343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// orders them so it usually won't matter.
82443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach///
82543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbachbool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
82643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  bool Changed = false;
82743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
82843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // This implementation doesn't currently consider undef operands
82989991d44136414c4c74eee7c6dfbdbeab287b881Nick Lewycky  // specially. Theoretically, two phis which are identical except for
83043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // one having an undef where the other doesn't could be collapsed.
83143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
83243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Map from PHI hash values to PHI nodes. If multiple PHIs have
83343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // the same hash value, the element is the first PHI in the
83443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // linked list in CollisionMap.
83543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<uintptr_t, PHINode *> HashMap;
83643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
83743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Maintain linked lists of PHI nodes with common hash values.
83843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  DenseMap<PHINode *, PHINode *> CollisionMap;
83943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
84043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Examine each PHI.
84143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  for (BasicBlock::iterator I = BB->begin();
84243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach       PHINode *PN = dyn_cast<PHINode>(I++); ) {
84343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Compute a hash value on the operands. Instcombine will likely have sorted
84443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // them, which helps expose duplicates, but we have to check all the
84543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // operands to be safe in case instcombine hasn't run.
84643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    uintptr_t Hash = 0;
84795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // This hash algorithm is quite weak as hash functions go, but it seems
84895c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    // to do a good enough job for this particular purpose, and is very quick.
84943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
85043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
85143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
85243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
85395c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
85495c3e48f9557adb6064d580684bb14cacec2f826Jay Foad         I != E; ++I) {
85595c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
85695c3e48f9557adb6064d580684bb14cacec2f826Jay Foad      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
85795c3e48f9557adb6064d580684bb14cacec2f826Jay Foad    }
8582bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
8592bc2a08b1bf6b5dcbfa515acc85999d6f884ec1aJakob Stoklund Olesen    Hash >>= 1;
86043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // If we've never seen this hash value before, it's a unique PHI.
86143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
86243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      HashMap.insert(std::make_pair(Hash, PN));
86343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    if (Pair.second) continue;
86443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    // Otherwise it's either a duplicate or a hash collision.
86543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    for (PHINode *OtherPN = Pair.first->second; ; ) {
86643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (OtherPN->isIdenticalTo(PN)) {
86743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // A duplicate. Replace this PHI with its duplicate.
86843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->replaceAllUsesWith(OtherPN);
86943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PN->eraseFromParent();
87043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Changed = true;
87143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
87243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
87343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      // A non-duplicate hash collision.
87443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
87543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      if (I == CollisionMap.end()) {
87643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        // Set this PHI to be the head of the linked list of colliding PHIs.
87743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        PHINode *Old = Pair.first->second;
87843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        Pair.first->second = PN;
87943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        CollisionMap[PN] = Old;
88043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach        break;
88143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      }
882d9b0b025612992a0b724eeca8bdf10b1d7a5c355Benjamin Kramer      // Proceed to the next PHI in the list.
88343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach      OtherPN = I->second;
88443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
88543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  }
88643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
88743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  return Changed;
88843a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach}
889687140c818ba4b896329a83324714140b6580ef8Chris Lattner
890687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// enforceKnownAlignment - If the specified pointer points to an object that
891687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we control, modify the object's alignment to PrefAlign. This isn't
892687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// often possible though. If alignment is important, a more reliable approach
893687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// is to simply align all global variables and allocation instructions to
894687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// their preferred alignment from the beginning.
895687140c818ba4b896329a83324714140b6580ef8Chris Lattner///
89619282365147f498a60463d250dbed2f8e1b81861Benjamin Kramerstatic unsigned enforceKnownAlignment(Value *V, unsigned Align,
8973574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow                                      unsigned PrefAlign, const DataLayout *TD) {
898b53c7937c5651e5500b554186657b27838137365Eli Friedman  V = V->stripPointerCasts();
899687140c818ba4b896329a83324714140b6580ef8Chris Lattner
900b53c7937c5651e5500b554186657b27838137365Eli Friedman  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
901bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // If the preferred alignment is greater than the natural stack alignment
902bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // then don't round up. This avoids dynamic stack realignment.
903bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
904bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames      return Align;
905687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a requested alignment and if this is an alloca, round up.
906687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (AI->getAlignment() >= PrefAlign)
907687140c818ba4b896329a83324714140b6580ef8Chris Lattner      return AI->getAlignment();
908687140c818ba4b896329a83324714140b6580ef8Chris Lattner    AI->setAlignment(PrefAlign);
909687140c818ba4b896329a83324714140b6580ef8Chris Lattner    return PrefAlign;
910687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
911687140c818ba4b896329a83324714140b6580ef8Chris Lattner
912dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (auto *GO = dyn_cast<GlobalObject>(V)) {
913687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a large requested alignment and we can, bump up the alignment
914687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // of the global.
915dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->isDeclaration())
916dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return Align;
917d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // If the memory we set aside for the global may not be the memory used by
918d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // the final program then it is impossible for us to reliably enforce the
919d3a38ccfbb6be0edad037961df77649db2cb9597Duncan Sands    // preferred alignment.
920dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->isWeakForLinker())
921dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return Align;
922a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
923dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->getAlignment() >= PrefAlign)
924dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return GO->getAlignment();
925687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // We can only increase the alignment of the global if it has no alignment
926687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // specified or if it is not assigned a section.  If it is assigned a
927687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, the global could be densely packed with other objects in the
928687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, increasing the alignment could cause padding issues.
929dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!GO->hasSection() || GO->getAlignment() == 0)
930dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      GO->setAlignment(PrefAlign);
931dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return GO->getAlignment();
932687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
933687140c818ba4b896329a83324714140b6580ef8Chris Lattner
934687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
935687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
936687140c818ba4b896329a83324714140b6580ef8Chris Lattner
937687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
938687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
939687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// and it is more than the alignment of the ultimate object, see if we can
940687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// increase the alignment of the ultimate object, making this check succeed.
941687140c818ba4b896329a83324714140b6580ef8Chris Lattnerunsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
94237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const DataLayout *DL,
94337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          AssumptionTracker *AT,
94437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const Instruction *CxtI,
94537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const DominatorTree *DT) {
946687140c818ba4b896329a83324714140b6580ef8Chris Lattner  assert(V->getType()->isPointerTy() &&
947687140c818ba4b896329a83324714140b6580ef8Chris Lattner         "getOrEnforceKnownAlignment expects a pointer!");
948186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault  unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
949186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault
950687140c818ba4b896329a83324714140b6580ef8Chris Lattner  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
95137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  computeKnownBits(V, KnownZero, KnownOne, DL, 0, AT, CxtI, DT);
952687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned TrailZ = KnownZero.countTrailingOnes();
953a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
95459a3878c525657701e83bd516d27236814e29f25Matt Arsenault  // Avoid trouble with ridiculously large TrailZ values, such as
955687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // those computed from a null pointer.
956687140c818ba4b896329a83324714140b6580ef8Chris Lattner  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
957a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
958687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
959a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
960687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // LLVM doesn't support alignments larger than this currently.
961687140c818ba4b896329a83324714140b6580ef8Chris Lattner  Align = std::min(Align, +Value::MaximumAlignment);
962a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
963687140c818ba4b896329a83324714140b6580ef8Chris Lattner  if (PrefAlign > Align)
964186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault    Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
965a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
966687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // We don't need to make any adjustment.
967687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
968687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
969687140c818ba4b896329a83324714140b6580ef8Chris Lattner
9705ee20680c7ebc765950983633e19fafab5235245Devang Patel///===---------------------------------------------------------------------===//
9715ee20680c7ebc765950983633e19fafab5235245Devang Patel///  Dbg Intrinsic utilities
9725ee20680c7ebc765950983633e19fafab5235245Devang Patel///
9735ee20680c7ebc765950983633e19fafab5235245Devang Patel
974163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl/// See if there is a dbg.value intrinsic for DIVar before I.
975163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantlstatic bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
976163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // Since we can't guarantee that the original dbg.declare instrinsic
977163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // is removed by LowerDbgDeclare(), we need to make sure that we are
978163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // not inserting the same dbg.value intrinsic over and over.
979163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  llvm::BasicBlock::InstListType::iterator PrevI(I);
980163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (PrevI != I->getParent()->getInstList().begin()) {
981163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    --PrevI;
982163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
983163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl      if (DVI->getValue() == I->getOperand(0) &&
984163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getOffset() == 0 &&
985163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getVariable() == DIVar)
986163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl        return true;
987163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  }
988163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  return false;
989163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl}
990163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
9919d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
9925ee20680c7ebc765950983633e19fafab5235245Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
9935ee20680c7ebc765950983633e19fafab5235245Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
9945ee20680c7ebc765950983633e19fafab5235245Devang Patel                                           StoreInst *SI, DIBuilder &Builder) {
9955ee20680c7ebc765950983633e19fafab5235245Devang Patel  DIVariable DIVar(DDI->getVariable());
99637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
997cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  assert((!DIVar || DIVar.isVariable()) &&
998cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
999cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
10005ee20680c7ebc765950983633e19fafab5235245Devang Patel    return false;
10015ee20680c7ebc765950983633e19fafab5235245Devang Patel
1002163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, SI))
1003163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1004163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1005dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Instruction *DbgVal = nullptr;
1006227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // If an argument is zero extended then use argument directly. The ZExt
1007227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // may be zapped by an optimization pass in future.
1008dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Argument *ExtendedArg = nullptr;
1009227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1010227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1011227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1012227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1013227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ExtendedArg)
101437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr, SI);
1015227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  else
101637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar,
101737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                             DIExpr, SI);
1018dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  DbgVal->setDebugLoc(DDI->getDebugLoc());
10195ee20680c7ebc765950983633e19fafab5235245Devang Patel  return true;
10205ee20680c7ebc765950983633e19fafab5235245Devang Patel}
10215ee20680c7ebc765950983633e19fafab5235245Devang Patel
10229d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
102336fae67831517f132255118b45b21a8cf199a012Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
102436fae67831517f132255118b45b21a8cf199a012Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
102536fae67831517f132255118b45b21a8cf199a012Devang Patel                                           LoadInst *LI, DIBuilder &Builder) {
102636fae67831517f132255118b45b21a8cf199a012Devang Patel  DIVariable DIVar(DDI->getVariable());
102737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
1028a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  assert((!DIVar || DIVar.isVariable()) &&
1029cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
1030cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
103136fae67831517f132255118b45b21a8cf199a012Devang Patel    return false;
103236fae67831517f132255118b45b21a8cf199a012Devang Patel
1033163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, LI))
1034163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1035163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1036a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  Instruction *DbgVal =
103737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr, LI);
1038dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  DbgVal->setDebugLoc(DDI->getDebugLoc());
103936fae67831517f132255118b45b21a8cf199a012Devang Patel  return true;
104036fae67831517f132255118b45b21a8cf199a012Devang Patel}
104136fae67831517f132255118b45b21a8cf199a012Devang Patel
1042dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines/// Determine whether this alloca is either a VLA or an array.
1043dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hinesstatic bool isArray(AllocaInst *AI) {
1044dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return AI->isArrayAllocation() ||
1045dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    AI->getType()->getElementType()->isArrayTy();
1046dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines}
1047dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
1048813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1049813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// of llvm.dbg.value intrinsics.
1050813c9a0f19c0d27085a3ea81eb44033747007741Devang Patelbool llvm::LowerDbgDeclare(Function &F) {
1051813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  DIBuilder DIB(*F.getParent());
1052813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  SmallVector<DbgDeclareInst *, 4> Dbgs;
105336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &FI : F)
105436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (BasicBlock::iterator BI : FI)
105536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
1056813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel        Dbgs.push_back(DDI);
105736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1058813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  if (Dbgs.empty())
1059813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    return false;
1060813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel
106136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &I : Dbgs) {
106236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    DbgDeclareInst *DDI = I;
1063940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1064940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // If this is an alloca for a scalar variable, insert a dbg.value
1065940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // at each load and store to the alloca and erase the dbg.declare.
1066dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // The dbg.values allow tracking a variable even if it is not
1067dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // stored on the stack, while the dbg.declare can only describe
1068dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // the stack slot (and at a lexical-scope granularity). Later
1069dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // passes will attempt to elide the stack slot.
1070dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (AI && !isArray(AI)) {
107136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (User *U : AI->users())
107236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (StoreInst *SI = dyn_cast<StoreInst>(U))
1073813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
107436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        else if (LoadInst *LI = dyn_cast<LoadInst>(U))
107536fae67831517f132255118b45b21a8cf199a012Devang Patel          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1076dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        else if (CallInst *CI = dyn_cast<CallInst>(U)) {
107737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // This is a call by-value or some other instruction that
107837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // takes a pointer to the variable. Insert a *value*
107937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // intrinsic that describes the alloca.
108037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          auto DbgVal = DIB.insertDbgValueIntrinsic(
108137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines              AI, 0, DIVariable(DDI->getVariable()),
108237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines              DIExpression(DDI->getExpression()), CI);
108337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          DbgVal->setDebugLoc(DDI->getDebugLoc());
108437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
1085dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      DDI->eraseFromParent();
1086813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    }
1087813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  }
1088813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  return true;
1089813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel}
1090c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1091c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1092c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// alloca 'V', if any.
1093c827939046670a9800659b83e2048f1d3a79a531Cameron ZwarichDbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1094c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich  if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
109536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (User *U : DebugNode->users())
109636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1097c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich        return DDI;
1098c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1099dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return nullptr;
1100c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich}
11011afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
11021afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonovbool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
11031afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov                                      DIBuilder &Builder) {
11041afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
11051afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  if (!DDI)
11061afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    return false;
11071afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DIVariable DIVar(DDI->getVariable());
110837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  DIExpression DIExpr(DDI->getExpression());
1109a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  assert((!DIVar || DIVar.isVariable()) &&
1110cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren         "Variable in DbgDeclareInst should be either null or a DIVariable.");
1111cbafae6d33031a72ba8219c28cb0e852511f79a3Manman Ren  if (!DIVar)
11121afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    return false;
11131afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
11141afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // Create a copy of the original DIDescriptor for user variable, appending
11151afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // "deref" operation to a list of address elements, as new llvm.dbg.declare
11161afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // will take a value storing address of the memory for variable, not
11171afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // alloca itself.
111837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  SmallVector<int64_t, 4> NewDIExpr;
111937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  if (DIExpr) {
112037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    for (unsigned i = 0, n = DIExpr.getNumElements(); i < n; ++i) {
112137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      NewDIExpr.push_back(DIExpr.getElement(i));
11221afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    }
11231afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  }
112437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  NewDIExpr.push_back(dwarf::DW_OP_deref);
11251afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
11261afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // Insert llvm.dbg.declare in the same basic block as the original alloca,
11271afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  // and remove old llvm.dbg.declare.
11281afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  BasicBlock *BB = AI->getParent();
112937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  Builder.insertDeclare(NewAllocaAddress, DIVar,
113037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                        Builder.createExpression(NewDIExpr), BB);
11311afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DDI->eraseFromParent();
11321afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  return true;
11331afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov}
11343333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
11354f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// changeToUnreachable - Insert an unreachable instruction before the specified
11364f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// instruction, making it and the rest of the code in the block dead.
11374f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
11384f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BasicBlock *BB = I->getParent();
11394f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the successors, removing BB's entry from any PHI
11404f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // nodes.
11414f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
11424f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    (*SI)->removePredecessor(BB);
11434f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11444f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Insert a call to llvm.trap right before this.  This turns the undefined
11454f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // behavior into a hard fail instead of falling through into random code.
11464f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  if (UseLLVMTrap) {
11474f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Function *TrapFn =
11484f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
11494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
11504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallTrap->setDebugLoc(I->getDebugLoc());
11514f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
11524f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  new UnreachableInst(I->getContext(), I);
11534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11544f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // All instructions after this are dead.
11554f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BasicBlock::iterator BBI = I, BBE = BB->end();
11564f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  while (BBI != BBE) {
11574f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (!BBI->use_empty())
11584f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
11594f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->getInstList().erase(BBI++);
11604f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
11614f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
11624f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11634f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// changeToCall - Convert the specified invoke into a normal call.
11644f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic void changeToCall(InvokeInst *II) {
11654f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
11664f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
11674f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->takeName(II);
11684f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setCallingConv(II->getCallingConv());
11694f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setAttributes(II->getAttributes());
11704f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setDebugLoc(II->getDebugLoc());
11714f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->replaceAllUsesWith(NewCall);
11724f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11734f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Follow the call by a branch to the normal destination.
11744f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BranchInst::Create(II->getNormalDest(), II);
11754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11764f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Update PHI nodes in the unwind destination
11774f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->getUnwindDest()->removePredecessor(II->getParent());
11784f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->eraseFromParent();
11794f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
11804f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11814f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic bool markAliveBlocks(BasicBlock *BB,
118237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                            SmallPtrSetImpl<BasicBlock*> &Reachable) {
11834f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11843333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  SmallVector<BasicBlock*, 128> Worklist;
11854f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Worklist.push_back(BB);
11864f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Reachable.insert(BB);
11874f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  bool Changed = false;
11883333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  do {
11894f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB = Worklist.pop_back_val();
11904f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11914f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Do a quick scan of the basic block, turning any obviously unreachable
11924f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // instructions into LLVM unreachable insts.  The instruction combining pass
11934f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // canonicalizes unreachable insts into stores to null or undef.
11944f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
119537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Assumptions that are known to be false are equivalent to unreachable.
119637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Also, if the condition is undefined, then we make the choice most
119737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // beneficial to the optimizer, and choose that to also be unreachable.
119837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
119937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        if (II->getIntrinsicID() == Intrinsic::assume) {
120037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          bool MakeUnreachable = false;
120137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (isa<UndefValue>(II->getArgOperand(0)))
120237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = true;
120337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          else if (ConstantInt *Cond =
120437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                   dyn_cast<ConstantInt>(II->getArgOperand(0)))
120537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = Cond->isZero();
120637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
120737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (MakeUnreachable) {
120837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            // Don't insert a call to llvm.trap right before the unreachable.
120937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            changeToUnreachable(BBI, false);
121037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            Changed = true;
121137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            break;
121237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          }
121337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
121437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
12154f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
12164f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (CI->doesNotReturn()) {
12174f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // If we found a call to a no-return function, insert an unreachable
12184f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // instruction after it.  Make sure there isn't *already* one there
12194f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // though.
12204f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          ++BBI;
12214f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          if (!isa<UnreachableInst>(BBI)) {
12224f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            // Don't insert a call to llvm.trap right before the unreachable.
12234f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            changeToUnreachable(BBI, false);
12244f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            Changed = true;
12254f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          }
12264f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
12274f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
12284f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12294f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12304f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // Store to undef and store to null are undefined and used to signal that
12314f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // they should be changed to unreachable by passes that can't modify the
12324f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // CFG.
12334f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
12344f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        // Don't touch volatile stores.
12354f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (SI->isVolatile()) continue;
12364f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12374f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Value *Ptr = SI->getOperand(1);
12384f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12394f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (isa<UndefValue>(Ptr) ||
12404f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            (isa<ConstantPointerNull>(Ptr) &&
12414f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne             SI->getPointerAddressSpace() == 0)) {
12424f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToUnreachable(SI, true);
12434f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          Changed = true;
12444f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
12454f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
12464f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12474f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
12484f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Turn invokes that call 'nounwind' functions into ordinary calls.
12504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
12514f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Value *Callee = II->getCalledValue();
12524f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
12534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        changeToUnreachable(II, true);
12544f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
12554f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      } else if (II->doesNotThrow()) {
12564f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (II->use_empty() && II->onlyReadsMemory()) {
12574f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // jump to the normal destination branch.
12584f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          BranchInst::Create(II->getNormalDest(), II);
12594f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->getUnwindDest()->removePredecessor(II->getParent());
12604f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->eraseFromParent();
12614f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        } else
12624f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToCall(II);
12634f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
12644f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12654f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
12664f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12674f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Changed |= ConstantFoldTerminator(BB, true);
12683333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
126937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (Reachable.insert(*SI).second)
12703333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov        Worklist.push_back(*SI);
12713333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  } while (!Worklist.empty());
12724f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  return Changed;
12734f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
12744f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
12764f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// if they are in a dead cycle.  Return true if a change was made, false
12774f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// otherwise.
12784f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournebool llvm::removeUnreachableBlocks(Function &F) {
12794f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  SmallPtrSet<BasicBlock*, 128> Reachable;
12804f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  bool Changed = markAliveBlocks(F.begin(), Reachable);
12813333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
12824f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // If there are unreachable blocks in the CFG...
12833333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  if (Reachable.size() == F.size())
12844f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    return Changed;
12853333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
12863333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  assert(Reachable.size() < F.size());
12874f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NumRemoved += F.size()-Reachable.size();
12884f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12894f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the basic blocks that are not reachable, dropping all of
12904f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // their internal references...
12914f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
12924f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (Reachable.count(BB))
12933333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      continue;
12943333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
12954f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
12963333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      if (Reachable.count(*SI))
12974f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        (*SI)->removePredecessor(BB);
12984f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->dropAllReferences();
12997541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov  }
13003333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13014f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator I = ++F.begin(); I != F.end();)
13027541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov    if (!Reachable.count(I))
13037541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      I = F.getBasicBlockList().erase(I);
13047541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov    else
13057541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      ++I;
13063333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13073333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  return true;
13083333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov}
130937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
131037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hinesvoid llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
131137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
131237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  K->dropUnknownMetadata(KnownIDs);
131337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  K->getAllMetadataOtherThanDebugLoc(Metadata);
131437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
131537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    unsigned Kind = Metadata[i].first;
131637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *JMD = J->getMetadata(Kind);
131737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *KMD = Metadata[i].second;
131837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
131937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    switch (Kind) {
132037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      default:
132137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, nullptr); // Remove unknown metadata
132237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
132337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_dbg:
132437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
132537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_tbaa:
132637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
132737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
132837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_alias_scope:
132937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_noalias:
133037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
133137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
133237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_range:
133337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
133437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
133537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_fpmath:
133637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
133737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
133837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_invariant_load:
133937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !invariant.load if it is present in both instructions.
134037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
134137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
134237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_nonnull:
134337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !nonnull if it is present in both instructions.
134437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
134537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
134637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
134737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  }
134837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines}
1349