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"
17cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar#include "llvm/ADT/DenseSet.h"
18cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar#include "llvm/ADT/Hashing.h"
193333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov#include "llvm/ADT/STLExtras.h"
20cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar#include "llvm/ADT/SetVector.h"
2158a2cbef4aac9ee7d530dfb690c78d6fc11a2371Chandler Carruth#include "llvm/ADT/SmallPtrSet.h"
224f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne#include "llvm/ADT/Statistic.h"
23cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar#include "llvm/Analysis/EHPersonalities.h"
24d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/InstructionSimplify.h"
25d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/MemoryBuiltins.h"
26d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Analysis/ValueTracking.h"
2736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/CFG.h"
280b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Constants.h"
2936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DIBuilder.h"
300b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
3136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/DebugInfo.h"
320b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DerivedTypes.h"
3336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/Dominators.h"
3436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/GetElementPtrTypeIterator.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalAlias.h"
360b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/GlobalVariable.h"
370b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
380b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Instructions.h"
390b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
400b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Intrinsics.h"
410b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/MDBuilder.h"
420b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Metadata.h"
430b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Operator.h"
4436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/IR/ValueHandle.h"
45dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/Debug.h"
46c5f52e6da18e6e8ccb62aac2a4cb431df98e7d6dChris Lattner#include "llvm/Support/MathExtras.h"
47dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner#include "llvm/Support/raw_ostream.h"
48abbc2dd77908f146f73f4cd1abfdfe47faacf43dChris Lattnerusing namespace llvm;
49d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
50dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#define DEBUG_TYPE "local"
51dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
524f96b7e1478be0b33cda589db40635a1e3a40c11Peter CollingbourneSTATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
544d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
553481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner//  Local constant propagation.
564d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
574d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
585649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// ConstantFoldTerminator - If a terminator instruction is predicated on a
595649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// constant value, convert it into an unconditional branch to the constant
605649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// destination.  This is a nontrivial operation because the successors of this
615649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// basic block must have their PHI nodes updated.
625649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
635649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// conditions and indirectbr addresses this might make dead if
645649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel/// DeleteDeadConditions is true.
658e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
668e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                  const TargetLibraryInfo *TLI) {
6776ae3445f81164aaff9f95123426109c119f27c0Chris Lattner  TerminatorInst *T = BB->getTerminator();
6862fb3556eab41d9d66994e92d15e3e707c181988Devang Patel  IRBuilder<> Builder(T);
69fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
704d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  // Branch - See if we are conditional jumping on constant
714d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
724d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
73c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest1 = BI->getSuccessor(0);
74c1bb13f1b8794aa6f3219b3ac567f569ad78a6d1Gabor Greif    BasicBlock *Dest2 = BI->getSuccessor(1);
754d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
766b6b6ef1677fa71b1072c2911b4c1f9524a558c9Zhou Sheng    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
774d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Are we branching on constant?
784d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // YES.  Change to unconditional branch...
79579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
80579dca12c2cfd60bc18aaadbd5331897d48fec29Reid Spencer      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
814d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
82fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //cerr << "Function: " << T->getParent()->getParent()
83fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      //     << "\nRemoving branch from " << T->getParent()
844d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     << "\n\nTo: " << OldDest << endl;
854d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
864d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of it.  Based on this,
874d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // it will adjust it's PHI nodes.
881a0390253b3e7c2327139d81e5a8c16d5bf85aa8Jay Foad      OldDest->removePredecessor(BB);
894d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
908f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
9162fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Destination);
928f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
934d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
940a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
95a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
960a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (Dest2 == Dest1) {       // Conditional branch to same location?
97fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman      // This branch matches something like this:
984d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      //     br bool %cond, label %Dest, label %Dest
994d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // and changes it into:  br label %Dest
1004d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1014d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      // Let the basic block know that we are letting go of one copy of it.
1024d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      assert(BI->getParent() && "Terminator not inserted in block!");
1034d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      Dest1->removePredecessor(BI->getParent());
1044d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
1058f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      // Replace the conditional branch with an unconditional one.
10662fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(Dest1);
1075649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = BI->getCondition();
1088f9ffbd056172da470bcd3a9f1d5b4c2414fce59Jay Foad      BI->eraseFromParent();
1095649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
1108e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
1114d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner      return true;
1124d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner    }
1130a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
1140a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
115a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1160a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
117ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // If we are switching on a constant, we can convert the switch to an
118ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // unconditional branch.
11910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
120ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *DefaultDest = SI->getDefaultDest();
121ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *TheOnlyDest = DefaultDest;
122ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines
123ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // If the default is unreachable, ignore it when searching for TheOnlyDest.
124ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
125ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        SI->getNumCases() > 0) {
126ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      TheOnlyDest = SI->case_begin().getCaseSuccessor();
127ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    }
12810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1290a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // Figure out which case it goes to.
1303d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
131c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy         i != e; ++i) {
13210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Found case matching a constant operand?
133c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseValue() == CI) {
134c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        TheOnlyDest = i.getCaseSuccessor();
13510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        break;
13610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
13710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
1387d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // Check to see if this branch is going to the same place as the default
1397d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      // dest.  If so, eliminate it as an explicit compare.
140c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy      if (i.getCaseSuccessor() == DefaultDest) {
14137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
14236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        unsigned NCases = SI->getNumCases();
14336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Fold the case metadata into the default if there will be any branches
14436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // left, unless the metadata doesn't match the switch.
14536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
146ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Collect branch weights into a vector.
147ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SmallVector<uint32_t, 8> Weights;
148ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
149ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren               ++MD_i) {
150ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            ConstantInt *CI =
151ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines                mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
152ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            assert(CI);
153ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren            Weights.push_back(CI->getValue().getZExtValue());
154ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          }
155ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Merge weight of this case to the default weight.
156ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          unsigned idx = i.getCaseIndex();
157ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights[0] += Weights[idx+1];
158ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          // Remove weight for this case.
159ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          std::swap(Weights[idx+1], Weights.back());
160ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          Weights.pop_back();
161ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren          SI->setMetadata(LLVMContext::MD_prof,
162ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          MDBuilder(BB->getContext()).
163ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren                          createBranchWeights(Weights));
164ee99c7f1bfe115f8fe2d1b118010a82c1ce83f18Manman Ren        }
1650a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        // Remove this entry.
1667d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        DefaultDest->removePredecessor(SI->getParent());
1677d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        SI->removeCase(i);
168c10fa6c801e48771b5eade50afc2fe6abaf08227Stepan Dyatkovskiy        --i; --e;
1697d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner        continue;
1707d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner      }
1717d6c24cdbf41522818ec9ae7b8d3b624660853c1Chris Lattner
17210b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, check to see if the switch only branches to one destination.
17310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
17410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // destinations.
175dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
17610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
177694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
17810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (CI && !TheOnlyDest) {
17910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Branching on a constant, but not any of the cases, go to the default
18010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // successor.
18110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      TheOnlyDest = SI->getDefaultDest();
182694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner    }
183694e37f08a7c09ccc24642532106295cf7b3a1e3Chris Lattner
18410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // If we found a single destination that we can fold the switch into, do so
18510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    // now.
18610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    if (TheOnlyDest) {
1870a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
18862fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
18910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      BasicBlock *BB = SI->getParent();
19010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
19110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Remove entries from PHI nodes which we no longer branch to...
192cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      for (BasicBlock *Succ : SI->successors()) {
19310b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        // Found case matching a constant operand?
19410b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        if (Succ == TheOnlyDest)
195dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
19610b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner        else
19710b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner          Succ->removePredecessor(BB);
19810b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      }
19910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner
2000a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Delete the old switch.
2015649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Cond = SI->getCondition();
2025649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      SI->eraseFromParent();
2035649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2048e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
20510b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      return true;
2060a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
207a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
20824473120a253a05f3601cd3373403b47e6d03d41Stepan Dyatkovskiy    if (SI->getNumCases() == 1) {
20910b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // Otherwise, we can fold this switch into a conditional branch
21010b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner      // instruction if it has only one non-default destination.
2113d3abe0852d5f499bed7ab014519dd582a0a795dStepan Dyatkovskiy      SwitchInst::CaseIt FirstCase = SI->case_begin();
212db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
213db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson          FirstCase.getCaseValue(), "cond");
214a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy
215db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Insert the new branch.
216db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      BranchInst *NewBr = Builder.CreateCondBr(Cond,
217db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               FirstCase.getCaseSuccessor(),
218db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                               SI->getDefaultDest());
21937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
220db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      if (MD && MD->getNumOperands() == 3) {
221ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        ConstantInt *SICase =
222ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
223ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        ConstantInt *SIDef =
224ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines            mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
225db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        assert(SICase && SIDef);
226db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        // The TrueWeight should be the weight for the single case of SI.
227db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson        NewBr->setMetadata(LLVMContext::MD_prof,
228db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        MDBuilder(BB->getContext()).
229db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                        createBranchWeights(SICase->getValue().getZExtValue(),
230db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson                                            SIDef->getValue().getZExtValue()));
231a2067fbe22930be8413584ae58c5ef78bd032190Stepan Dyatkovskiy      }
232db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson
233cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // Update make.implicit metadata to the newly-created conditional branch.
234cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
235cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (MakeImplicitMD)
236cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
237cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
238db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      // Delete the old switch.
239db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      SI->eraseFromParent();
240db3a9e64f856e3a233a427da1f3969fd3a65a438Bob Wilson      return true;
24110b1f5a94196f27c75c950ba7ed26bd0a62c91e9Chris Lattner    }
2420a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    return false;
2430a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  }
2440a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner
2450a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
2460a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    // indirectbr blockaddress(@F, @BB) -> br label @BB
2470a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    if (BlockAddress *BA =
2480a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
2490a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      BasicBlock *TheOnlyDest = BA->getBasicBlock();
2500a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // Insert the new branch.
25162fb3556eab41d9d66994e92d15e3e707c181988Devang Patel      Builder.CreateBr(TheOnlyDest);
252a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2530a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2540a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        if (IBI->getDestination(i) == TheOnlyDest)
255dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          TheOnlyDest = nullptr;
2560a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        else
2570a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner          IBI->getDestination(i)->removePredecessor(IBI->getParent());
2580a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
2595649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      Value *Address = IBI->getAddress();
2600a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      IBI->eraseFromParent();
2615649ba70fb39f2fda4791d255ae8bb373071874fFrits van Bommel      if (DeleteDeadConditions)
2628e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
263a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2640a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // If we didn't find our destination in the IBI successor list, then we
2650a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // have undefined behavior.  Replace the unconditional branch with an
2660a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      // 'unreachable' instruction.
2670a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      if (TheOnlyDest) {
2680a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        BB->getTerminator()->eraseFromParent();
2690a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner        new UnreachableInst(BB->getContext(), BB);
2700a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      }
271a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2720a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner      return true;
2730a4c6789d5adafb6eb33080fe1833b416a152d7cChris Lattner    }
2744d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  }
275a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
2764d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner  return false;
2774d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
2784d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2794d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2804d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//===----------------------------------------------------------------------===//
28140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Local dead code elimination.
2824d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner//
2834d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
2843481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// isInstructionTriviallyDead - Return true if the result produced by the
2853481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// instruction is not used, and the instruction has no side effects.
2863481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner///
2878e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::isInstructionTriviallyDead(Instruction *I,
2888e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                      const TargetLibraryInfo *TLI) {
289ec710c5b12af647ae90f53917122726269c18738Chris Lattner  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
29000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
291cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // We don't want the landingpad-like instructions removed by anything this
292cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // general.
293cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (I->isEHPad())
294187b1924a4b68350a6492b116db0fb19c659222fBill Wendling    return false;
295187b1924a4b68350a6492b116db0fb19c659222fBill Wendling
2969c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // We don't want debug info removed by anything this general, unless
2979c5822a966572ea78f4e818870d4229c7a855749Devang Patel  // debug info is empty.
2989c5822a966572ea78f4e818870d4229c7a855749Devang Patel  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
2993e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (DDI->getAddress())
3009c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
301b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
3023e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
303b99462117ebd4be41788346246d7935fc90a11eeDevang Patel  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
3049c5822a966572ea78f4e818870d4229c7a855749Devang Patel    if (DVI->getValue())
3059c5822a966572ea78f4e818870d4229c7a855749Devang Patel      return false;
306b99462117ebd4be41788346246d7935fc90a11eeDevang Patel    return true;
3079c5822a966572ea78f4e818870d4229c7a855749Devang Patel  }
3089c5822a966572ea78f4e818870d4229c7a855749Devang Patel
3097af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  if (!I->mayHaveSideEffects()) return true;
3107af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands
3117af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // Special case intrinsics that "may have side effects" but can be deleted
3127af1c78b98d2df7d0ab9154461ca3d835706716eDuncan Sands  // when dead.
3133e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
314741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    // Safe to delete llvm.stacksave if dead.
315741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner    if (II->getIntrinsicID() == Intrinsic::stacksave)
316741c0aea08feab0ebd1932aaa8dd38836b2073eaChris Lattner      return true;
3173e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky
3183e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    // Lifetime intrinsics are dead when their right-hand is undef.
3193e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky    if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
3203e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky        II->getIntrinsicID() == Intrinsic::lifetime_end)
3213e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky      return isa<UndefValue>(II->getArgOperand(1));
32237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
32337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    // Assumptions are dead if their condition is trivially true.
32437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (II->getIntrinsicID() == Intrinsic::assume) {
32537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
32637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        return !Cond->isZero();
32737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
32837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      return false;
32937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
3303e69c13c301acee99c8bde7e692777bf856a6362Nick Lewycky  }
3314a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3328e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (isAllocLikeFn(I, TLI)) return true;
3334a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
3348e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (CallInst *CI = isFreeCall(I, TLI))
3354a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky    if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
3364a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky      return C->isNullValue() || isa<UndefValue>(C);
3374a3935c27e5315081844a5b7ae1f7097efc234b0Nick Lewycky
338ec710c5b12af647ae90f53917122726269c18738Chris Lattner  return false;
3394d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
3404d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner
3413481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
3423481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner/// trivially dead instruction, delete it.  If that makes any of its operands
34390fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// trivially dead, delete them too, recursively.  Return true if any
34490fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman/// instructions were deleted.
3458e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool
3468e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerllvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
3478e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                                 const TargetLibraryInfo *TLI) {
3483481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
3498e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
35090fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman    return false;
351a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3527605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  SmallVector<Instruction*, 16> DeadInsts;
3537605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner  DeadInsts.push_back(I);
354a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
355321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  do {
356e9d87f49063cb1bd213d8e9c339b9b63393cc2d9Dan Gohman    I = DeadInsts.pop_back_val();
3572872177834d83b42cd042a37299cb7089965f36bChris Lattner
3587605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // Null out all of the instruction's operands to see if any operand becomes
3597605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    // dead as we go.
3607605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3617605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      Value *OpV = I->getOperand(i);
362dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      I->setOperand(i, nullptr);
363a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3647605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (!OpV->use_empty()) continue;
365a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3667605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // If the operand is an instruction that became dead as we nulled out the
3677605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // operand, and if it is 'trivially' dead, delete it in a future loop
3687605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      // iteration.
3697605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
3708e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer        if (isInstructionTriviallyDead(OpI, TLI))
3717605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner          DeadInsts.push_back(OpI);
3727605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    }
373a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
3747605730ba8eaf248a8285bb2055e131f13c15b63Chris Lattner    I->eraseFromParent();
375321a813c536e2f1f2f05bbe78a7fbf64046f0557Dan Gohman  } while (!DeadInsts.empty());
37690fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman
37790fe0bd68cdbeb980c08628c4992dffad0dc728fDan Gohman  return true;
3784d1e46e7b06534cde262d32fad038135f406b6b7Chris Lattner}
379b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
3801a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// areAllUsesEqual - Check whether the uses of a value are all the same.
3811a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky/// This is similar to Instruction::hasOneUse() except this will also return
382b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// true when there are no uses or multiple uses that all refer to the same
383b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands/// value.
3841a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewyckystatic bool areAllUsesEqual(Instruction *I) {
38536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UI = I->user_begin();
38636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Value::user_iterator UE = I->user_end();
3871a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  if (UI == UE)
388b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    return true;
3891a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
3901a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  User *TheUse = *UI;
3911a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  for (++UI; UI != UE; ++UI) {
3921a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky    if (*UI != TheUse)
3931a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky      return false;
3941a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  }
3951a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky  return true;
3961a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky}
3971a4021a2be4a59e9f9010776cb6f72107241aeb5Nick Lewycky
398afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
399afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// dead PHI node, due to being a def-use chain of single-use nodes that
400afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// either forms a cycle or is terminated by a trivially dead instruction,
401afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman/// delete it.  If that makes any of its operands trivially dead, delete them
4022cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands/// too, recursively.  Return true if a change was made.
4038e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramerbool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
4048e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                        const TargetLibraryInfo *TLI) {
405b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  SmallPtrSet<Instruction*, 4> Visited;
406b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
40736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines       I = cast<Instruction>(*I->user_begin())) {
408b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    if (I->use_empty())
4098e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
410afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman
411b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    // If we find an instruction more than once, we're on a cycle that
412afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman    // won't prove fruitful.
41337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    if (!Visited.insert(I).second) {
414b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      // Break the cycle and delete the instruction and its operands.
415b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands      I->replaceAllUsesWith(UndefValue::get(I->getType()));
4168e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer      (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
4172cfbf018a938d14126b9cb10c600e025f9831d2dDuncan Sands      return true;
418b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands    }
419b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  }
420b4098ba03d51a3845bde5aeb4fca893d1a90d3f8Duncan Sands  return false;
421afc36a9520971832dfbebc0333593bf5d3098296Dan Gohman}
4223481f24c06b3c9de48bdd99c37547471ca8e761eChris Lattner
423cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarstatic bool
424cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga NainarsimplifyAndDCEInstruction(Instruction *I,
425cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                          SmallSetVector<Instruction *, 16> &WorkList,
426cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                          const DataLayout &DL,
427cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                          const TargetLibraryInfo *TLI) {
428cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (isInstructionTriviallyDead(I, TLI)) {
429cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // Null out all of the instruction's operands to see if any operand becomes
430cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // dead as we go.
431cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
432cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      Value *OpV = I->getOperand(i);
433cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      I->setOperand(i, nullptr);
434cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
435cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (!OpV->use_empty() || I == OpV)
436cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        continue;
437cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
438cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // If the operand is an instruction that became dead as we nulled out the
439cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // operand, and if it is 'trivially' dead, delete it in a future loop
440cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // iteration.
441cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
442cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        if (isInstructionTriviallyDead(OpI, TLI))
443cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          WorkList.insert(OpI);
444cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
445cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
446cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    I->eraseFromParent();
447cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
448cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return true;
449cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
450cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
451cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (Value *SimpleV = SimplifyInstruction(I, DL)) {
452cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // Add the users to the worklist. CAREFUL: an instruction can use itself,
453cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // in the case of a phi node.
454cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (User *U : I->users())
455cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (U != I)
456cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        WorkList.insert(cast<Instruction>(U));
457cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
458cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // Replace the instruction with its simplified value.
459cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    I->replaceAllUsesWith(SimpleV);
460cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    I->eraseFromParent();
461cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return true;
462cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
463cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return false;
464cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
465cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
466e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
467e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// simplify any instructions in it and recursively delete dead instructions.
468e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner///
469e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// This returns true if it changed the code, note that it can delete
470e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner/// instructions in other blocks as well in this block.
4714c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarbool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
4728e0d1c03ca7fd86e6879b4e37d0d7f0e982feef6Benjamin Kramer                                       const TargetLibraryInfo *TLI) {
473e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  bool MadeChange = false;
474cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  const DataLayout &DL = BB->getModule()->getDataLayout();
475acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
476acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#ifndef NDEBUG
477acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // In debug builds, ensure that the terminator of the block is never replaced
478acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // or deleted by these simplifications. The idea of simplification is that it
479acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // cannot introduce new instructions, and there is no way to replace the
480acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth  // terminator of a block without introducing a new instruction.
481cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  AssertingVH<Instruction> TerminatorVH(&BB->back());
482acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth#endif
483acdae3e25a03e4e08039cb18f50b7788f71c0b2eChandler Carruth
484cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  SmallSetVector<Instruction *, 16> WorkList;
485cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Iterate over the original function, only adding insts to the worklist
486cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // if they actually need to be revisited. This avoids having to pre-init
487cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // the worklist with the entire function's worth of instructions.
488cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end()); BI != E;) {
489858cd1c33c6ba47cf3401b1e00862aa22302af10Chandler Carruth    assert(!BI->isTerminator());
490cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Instruction *I = &*BI;
491cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    ++BI;
4926b980541df5846ad335c377c8803b517968daee2Chandler Carruth
493cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // We're visiting this instruction now, so make sure it's not in the
494cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // worklist from an earlier visit.
495cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!WorkList.count(I))
496cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
497cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
49871ad2c9eda710bc26ec1621a9afefad11dd7fad2Eli Friedman
499cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  while (!WorkList.empty()) {
500cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Instruction *I = WorkList.pop_back_val();
501cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
502e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  }
503e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner  return MadeChange;
504e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner}
505e234a30a282f1aaec4aa63460fe8bba6416832a8Chris Lattner
506b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//===----------------------------------------------------------------------===//
50740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner//  Control Flow Graph Restructuring.
508b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner//
509b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner
51040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
51140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
51240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
51340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
51440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
51540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
51640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// nodes that collapse into identity values.  For example, if we have:
51740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   x = phi(1, 0, 0, 0)
51840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///   y = and x, z
51940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner///
52040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
52140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner/// recursively fold the and to 0.
5224c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainarvoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
52340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // This only adjusts blocks with PHI nodes.
52440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  if (!isa<PHINode>(BB->begin()))
52540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    return;
526a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
52740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
52840d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
52940d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  // that can be removed.
53040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  BB->removePredecessor(Pred, true);
531a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
53240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  WeakVH PhiIt = &BB->front();
53340d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
53440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
5356b980541df5846ad335c377c8803b517968daee2Chandler Carruth    Value *OldPhiIt = PhiIt;
5366ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
5374c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (!recursivelySimplifyInstruction(PN))
5386b980541df5846ad335c377c8803b517968daee2Chandler Carruth      continue;
5396ac3386e100db376895dbc4a324d56d0ecd666d2Duncan Sands
54040d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // If recursive simplification ended up deleting the next PHI node we would
54140d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
54240d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner    // of the block.
54335a939b97dba538bfc12010b7ac26bffbf5ec4cbChris Lattner    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
54440d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner  }
54540d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner}
54640d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
54740d8c28b27377199b7465ba2c5a2c59c6fd12fa9Chris Lattner
548b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
549b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
550b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// between them, moving the instructions in the predecessor into DestBB and
551b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner/// deleting the predecessor block.
552b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner///
553ebe69fe11e48d322045d5949c83283927a0d790bStephen Hinesvoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
554b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // If BB has single-entry PHI nodes, fold them.
555b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
556b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    Value *NewVal = PN->getIncomingValue(0);
557b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    // Replace self referencing PHI with undef, it must be dead.
5589e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
559b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->replaceAllUsesWith(NewVal);
560b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner    PN->eraseFromParent();
561b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  }
562a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
563b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  BasicBlock *PredBB = DestBB->getSinglePredecessor();
564b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  assert(PredBB && "Block doesn't have a single predecessor!");
565a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
56637914c8e83c43d710925263b66014159f03fa355Chris Lattner  // Zap anything that took the address of DestBB.  Not doing this will give the
56737914c8e83c43d710925263b66014159f03fa355Chris Lattner  // address an invalid value.
56837914c8e83c43d710925263b66014159f03fa355Chris Lattner  if (DestBB->hasAddressTaken()) {
56937914c8e83c43d710925263b66014159f03fa355Chris Lattner    BlockAddress *BA = BlockAddress::get(DestBB);
57037914c8e83c43d710925263b66014159f03fa355Chris Lattner    Constant *Replacement =
57137914c8e83c43d710925263b66014159f03fa355Chris Lattner      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
57237914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
57337914c8e83c43d710925263b66014159f03fa355Chris Lattner                                                     BA->getType()));
57437914c8e83c43d710925263b66014159f03fa355Chris Lattner    BA->destroyConstant();
57537914c8e83c43d710925263b66014159f03fa355Chris Lattner  }
576a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
577b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Anything that branched to PredBB now branches to DestBB.
578b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->replaceAllUsesWith(DestBB);
579a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
58095c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  // Splice all the instructions from PredBB to DestBB.
58195c3e48f9557adb6064d580684bb14cacec2f826Jay Foad  PredBB->getTerminator()->eraseFromParent();
5823e033f29239e48c190f29cdf3a02cdfbaf2fe72bBill Wendling  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
58395c3e48f9557adb6064d580684bb14cacec2f826Jay Foad
58437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // If the PredBB is the entry block of the function, move DestBB up to
58537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  // become the entry block after we erase PredBB.
58637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  if (PredBB == &DestBB->getParent()->getEntryBlock())
58737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    DestBB->moveAfter(PredBB);
58837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
589ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (DT) {
590ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
591ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DT->changeImmediateDominator(DestBB, PredBBIDom);
592ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DT->eraseNode(PredBB);
593ad80981a106c9d0ec83351e63ee3ac75ed646bf4Andreas Neustifter  }
594b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  // Nuke BB.
595b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner  PredBB->eraseFromParent();
596b29714a10af94b6daae437e48a82ae32675f79cbChris Lattner}
5974afc90dacf309999d8b7f6c2b4b0c56af346bab5Devang Patel
598c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// CanMergeValues - Return true if we can choose one of these values to use
599c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// in place of the other. Note that we will always choose the non-undef
600c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// value to keep.
601c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic bool CanMergeValues(Value *First, Value *Second) {
602c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
603c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
604c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
605dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
6061b6e10f53bec0cd261924734bd5eb58c75c8f550Mark Lacey/// almost-empty BB ending in an unconditional branch to Succ, into Succ.
607dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
608dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// Assumption: Succ is the single successor for BB.
609dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner///
610dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
611dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
612dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
613a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
614dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        << Succ->getName() << "\n");
615dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Shortcut, if there is only a single predecessor it must be BB and merging
616dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // is always safe
617dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (Succ->getSinglePredecessor()) return true;
618dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
619dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Make a list of the predecessors of BB
62088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer  SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
621dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
622dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Look at all the phi nodes in Succ, to see if they present a conflict when
623dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // merging these blocks
624dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
625dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *PN = cast<PHINode>(I);
626dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
627dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If the incoming value from BB is again a PHINode in
628dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // BB which has the same incoming value for *PI as PN does, we can
629dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // merge the phi nodes and then the blocks can still be merged
630dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
631dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    if (BBPN && BBPN->getParent() == BB) {
63288c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
63388c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
63488c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        if (BBPreds.count(IBB) &&
635c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
636c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                            PN->getIncomingValue(PI))) {
637a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
638a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak                << Succ->getName() << " is conflicting with "
639dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << BBPN->getName() << " with regard to common predecessor "
64088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << IBB->getName() << "\n");
641dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
642dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
643dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
644dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    } else {
645dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      Value* Val = PN->getIncomingValueForBlock(BB);
64688c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer      for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
647dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // See if the incoming value for the common predecessor is equal to the
648dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // one for BB, in which case this phi node will not prevent the merging
649dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        // of the block.
65088c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer        BasicBlock *IBB = PN->getIncomingBlock(PI);
651c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands        if (BBPreds.count(IBB) &&
652c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            !CanMergeValues(Val, PN->getIncomingValue(PI))) {
653a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
654dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner                << Succ->getName() << " is conflicting with regard to common "
65588c09143b6af07ed7b16381885a03c4b10886f96Benjamin Kramer                << "predecessor " << IBB->getName() << "\n");
656dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
657dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
658dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
659dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
660dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
661dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
662dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
663dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
664dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
665c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef SmallVector<BasicBlock *, 16> PredBlockVector;
666c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandstypedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
667c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
668c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Determines the value to use as the phi node input for a block.
669c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
670c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Select between \p OldVal any value that we know flows from \p BB
671c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// to a particular phi on the basis of which one (if either) is not
672c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// undef. Update IncomingValues based on the selected value.
673c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
674c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param OldVal The value we are considering selecting.
675c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block that the value flows in from.
676c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block-to-value for other phi inputs
677c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// that we have examined.
678c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
679c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \returns the selected value.
680c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
681c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                          IncomingValueMap &IncomingValues) {
682c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (!isa<UndefValue>(OldVal)) {
683c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    assert((!IncomingValues.count(BB) ||
684c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands            IncomingValues.find(BB)->second == OldVal) &&
685c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands           "Expected OldVal to match incoming value from BB!");
686c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
687c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValues.insert(std::make_pair(BB, OldVal));
688c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    return OldVal;
689c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
690c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
691c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap::const_iterator It = IncomingValues.find(BB);
692c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (It != IncomingValues.end()) return It->second;
693c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
694c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  return OldVal;
695c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
696c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
697c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Create a map from block to value for the operands of a
698c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// given phi.
699c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
700c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// Create a map from block to value for each non-undef value flowing
701c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// into \p PN.
702c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
703c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are collecting the map for.
704c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues [out] The map from block to value for this phi.
705c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void gatherIncomingValuesToPhi(PHINode *PN,
706c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                      IncomingValueMap &IncomingValues) {
707c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
708c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
709c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
710c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
711c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V))
712c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      IncomingValues.insert(std::make_pair(BB, V));
713c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
714c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
715c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
716c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace the incoming undef values to a phi with the values
717c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// from a block-to-value map.
718c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
719c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi we are replacing the undefs in.
720c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param IncomingValues A map from block to value.
721c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void replaceUndefValuesInPhi(PHINode *PN,
722c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                    const IncomingValueMap &IncomingValues) {
723c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
724c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    Value *V = PN->getIncomingValue(i);
725c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
726c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (!isa<UndefValue>(V)) continue;
727c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
728c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    BasicBlock *BB = PN->getIncomingBlock(i);
729c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    IncomingValueMap::const_iterator It = IncomingValues.find(BB);
730c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    if (It == IncomingValues.end()) continue;
731c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
732c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PN->setIncomingValue(i, It->second);
733c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
734c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
735c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
736c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \brief Replace a value flowing from a block to a phi with
737c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// potentially multiple instances of that value flowing from the
738c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// block's predecessors to the phi.
739c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands///
740c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BB The block with the value flowing into the phi.
741c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param BBPreds The predecessors of BB.
742c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands/// \param PN The phi that we are updating.
743c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sandsstatic void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
744c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                const PredBlockVector &BBPreds,
745c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                PHINode *PN) {
746c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  Value *OldVal = PN->removeIncomingValue(BB, false);
747c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  assert(OldVal && "No entry in PHI for Pred BB!");
748c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
749c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  IncomingValueMap IncomingValues;
750c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
751c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // We are merging two blocks - BB, and the block containing PN - and
752c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // as a result we need to redirect edges from the predecessors of BB
753c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // to go to the block containing PN, and update PN
754c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // accordingly. Since we allow merging blocks in the case where the
755c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // predecessor and successor blocks both share some predecessors,
756c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // and where some of those common predecessors might have undef
757c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // values flowing into PN, we want to rewrite those values to be
758c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // consistent with the non-undef values.
759c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
760c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  gatherIncomingValuesToPhi(PN, IncomingValues);
761c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
762c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // If this incoming value is one of the PHI nodes in BB, the new entries
763c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  // in the PHI node are the entries from the old PHI.
764c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
765c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    PHINode *OldValPN = cast<PHINode>(OldVal);
766c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
767c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Note that, since we are merging phi nodes and BB and Succ might
768c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // have common predecessors, we could end up with a phi node with
769c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // identical incoming branches. This will be cleaned up later (and
770c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // will trigger asserts if we try to clean it up now, without also
771c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // simplifying the corresponding conditional branch).
772c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
773c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *PredVal = OldValPN->getIncomingValue(i);
774c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
775c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
776c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
777c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
778c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
779c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
780c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
781c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  } else {
782c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
783c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // Update existing incoming values in PN for this
784c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // predecessor of BB.
785c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      BasicBlock *PredBB = BBPreds[i];
786c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
787c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands                                                    IncomingValues);
788c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
789c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // And add a new incoming value for this predecessor for the
790c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      // newly retargeted branch.
791c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      PN->addIncoming(Selected, PredBB);
792c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    }
793c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  }
794c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
795c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands  replaceUndefValuesInPhi(PN, IncomingValues);
796c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands}
797c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
798dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
799dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner/// unconditional branch, and contains no instructions other than PHI nodes,
80077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// potential side-effect free intrinsics and the branch.  If possible,
80177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// eliminate BB by rewriting all the predecessors to branch to the successor
80277a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola/// block and return true.  If we can't transform, return false.
803dce94d92df77da125a1c1256a9294db891a9db9cChris Lattnerbool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
804e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman  assert(BB != &BB->getParent()->getEntryBlock() &&
805e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
806e2c6d131d12c779a410740e0a90545def75e0f48Dan Gohman
807dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // We can't eliminate infinite loops.
808dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
809dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (BB == Succ) return false;
810a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
811dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check to see if merging these blocks would cause conflicts for any of the
812dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // phi nodes in BB or Succ. If not, we can safely merge.
813dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
814dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
815dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Check for cases where Succ has multiple predecessors and a PHI node in BB
816dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // has uses which will not disappear when the PHI nodes are merged.  It is
817dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // possible to handle such cases, but difficult: it requires checking whether
818dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // BB dominates Succ, which is non-trivial to calculate in the case where
819dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Succ has multiple predecessors.  Also, it requires checking whether
8203a19999413b18304d1a00cbdbe73fc43ea9cb75fAlexey Samsonov  // constructing the necessary self-referential PHI node doesn't introduce any
821dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // conflicts; this isn't too difficult, but the previous code for doing this
822dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // was incorrect.
823dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  //
824dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Note that if this check finds a live use, BB dominates Succ, so BB is
825dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
826dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // folding the branch isn't profitable in that case anyway.
827dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->getSinglePredecessor()) {
828dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    BasicBlock::iterator BBI = BB->begin();
829dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    while (isa<PHINode>(*BBI)) {
83036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (Use &U : BBI->uses()) {
83136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
83236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          if (PN->getIncomingBlock(U) != BB)
833dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner            return false;
834dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        } else {
835dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner          return false;
836dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner        }
837dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      }
838dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      ++BBI;
839dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
840dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
841dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
842fae7706dfd3591391c03ed1439850edaed9d291cDavid Greene  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
843a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
844dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (isa<PHINode>(Succ->begin())) {
845dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // If there is more than one pred of succ, and there are PHI nodes in
846dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // the successor, then we need to add incoming edges for the PHI nodes
847dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    //
848c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands    const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
849a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
850dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    // Loop over all of the PHI nodes in the successor of BB.
851dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
852dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PHINode *PN = cast<PHINode>(I);
853c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands
854c48b55a33dc5cd898dc9e58c0a1650b8f24c3879Duncan Sands      redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
855dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
856dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
857a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
85877a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  if (Succ->getSinglePredecessor()) {
85977a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // BB is the only predecessor of Succ, so Succ will end up with exactly
86077a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // the same predecessors BB had.
86177a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola
86277a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    // Copy over any phi, debug or lifetime instruction.
86377a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    BB->getTerminator()->eraseFromParent();
864cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
865cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                               BB->getInstList());
86677a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola  } else {
86777a2c372face15a302f4c9e5cb9acc035b8b3bd3Rafael Espindola    while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
868dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
869dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      assert(PN->use_empty() && "There shouldn't be any uses here!");
870dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner      PN->eraseFromParent();
871dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner    }
872dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  }
873a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
874dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  // Everything that jumped to BB now goes to Succ.
875dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->replaceAllUsesWith(Succ);
876dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  if (!Succ->hasName()) Succ->takeName(BB);
877dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  BB->eraseFromParent();              // Delete the old basic block.
878dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner  return true;
879dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner}
880dce94d92df77da125a1c1256a9294db891a9db9cChris Lattner
88143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
88243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// nodes in this block. This doesn't try to be clever about PHI nodes
88343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// which differ only in the order of the incoming values, but instcombine
88443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach/// orders them so it usually won't matter.
88543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach///
88643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbachbool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
88743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // This implementation doesn't currently consider undef operands
88889991d44136414c4c74eee7c6dfbdbeab287b881Nick Lewycky  // specially. Theoretically, two phis which are identical except for
88943a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // one having an undef where the other doesn't could be collapsed.
89043a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
891cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  struct PHIDenseMapInfo {
892cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    static PHINode *getEmptyKey() {
893cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return DenseMapInfo<PHINode *>::getEmptyKey();
894cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
895cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    static PHINode *getTombstoneKey() {
896cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return DenseMapInfo<PHINode *>::getTombstoneKey();
897cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
898cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    static unsigned getHashValue(PHINode *PN) {
899cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // Compute a hash value on the operands. Instcombine will likely have
900cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // sorted them, which helps expose duplicates, but we have to check all
901cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // the operands to be safe in case instcombine hasn't run.
902cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return static_cast<unsigned>(hash_combine(
903cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
904cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          hash_combine_range(PN->block_begin(), PN->block_end())));
905cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
906cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    static bool isEqual(PHINode *LHS, PHINode *RHS) {
907cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
908cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          RHS == getEmptyKey() || RHS == getTombstoneKey())
909cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        return LHS == RHS;
910cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      return LHS->isIdenticalTo(RHS);
911cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
912cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  };
91343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
914cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Set of unique PHINodes.
915cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
91643a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
91743a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  // Examine each PHI.
918cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  bool Changed = false;
919cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
920cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    auto Inserted = PHISet.insert(PN);
921cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!Inserted.second) {
922cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // A duplicate. Replace this PHI with its duplicate.
923cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      PN->replaceAllUsesWith(*Inserted.first);
924cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      PN->eraseFromParent();
925cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      Changed = true;
926cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
927cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // The RAUW can change PHIs that we already visited. Start over from the
928cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      // beginning.
929cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      PHISet.clear();
930cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      I = BB->begin();
93143a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach    }
93243a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  }
93343a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach
93443a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach  return Changed;
93543a8241b65b70ded3a87fb26852719633908a1e4Jim Grosbach}
936687140c818ba4b896329a83324714140b6580ef8Chris Lattner
937687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// enforceKnownAlignment - If the specified pointer points to an object that
938687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we control, modify the object's alignment to PrefAlign. This isn't
939687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// often possible though. If alignment is important, a more reliable approach
940687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// is to simply align all global variables and allocation instructions to
941687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// their preferred alignment from the beginning.
942687140c818ba4b896329a83324714140b6580ef8Chris Lattner///
94319282365147f498a60463d250dbed2f8e1b81861Benjamin Kramerstatic unsigned enforceKnownAlignment(Value *V, unsigned Align,
9444c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                      unsigned PrefAlign,
9454c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                      const DataLayout &DL) {
946b53c7937c5651e5500b554186657b27838137365Eli Friedman  V = V->stripPointerCasts();
947687140c818ba4b896329a83324714140b6580ef8Chris Lattner
948b53c7937c5651e5500b554186657b27838137365Eli Friedman  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
949bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // If the preferred alignment is greater than the natural stack alignment
950bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames    // then don't round up. This avoids dynamic stack realignment.
9514c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar    if (DL.exceedsNaturalStackAlignment(PrefAlign))
952bb5b3f33594cfa40e9f53bf9a71af359b080a697Lang Hames      return Align;
953687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a requested alignment and if this is an alloca, round up.
954687140c818ba4b896329a83324714140b6580ef8Chris Lattner    if (AI->getAlignment() >= PrefAlign)
955687140c818ba4b896329a83324714140b6580ef8Chris Lattner      return AI->getAlignment();
956687140c818ba4b896329a83324714140b6580ef8Chris Lattner    AI->setAlignment(PrefAlign);
957687140c818ba4b896329a83324714140b6580ef8Chris Lattner    return PrefAlign;
958687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
959687140c818ba4b896329a83324714140b6580ef8Chris Lattner
960dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (auto *GO = dyn_cast<GlobalObject>(V)) {
961687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // If there is a large requested alignment and we can, bump up the alignment
962cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // of the global.  If the memory we set aside for the global may not be the
963cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // memory used by the final program then it is impossible for us to reliably
964cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // enforce the preferred alignment.
965cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!GO->isStrongDefinitionForLinker())
966dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return Align;
967a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
968dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (GO->getAlignment() >= PrefAlign)
969dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return GO->getAlignment();
970687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // We can only increase the alignment of the global if it has no alignment
971687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // specified or if it is not assigned a section.  If it is assigned a
972687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, the global could be densely packed with other objects in the
973687140c818ba4b896329a83324714140b6580ef8Chris Lattner    // section, increasing the alignment could cause padding issues.
974dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!GO->hasSection() || GO->getAlignment() == 0)
975dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      GO->setAlignment(PrefAlign);
976dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return GO->getAlignment();
977687140c818ba4b896329a83324714140b6580ef8Chris Lattner  }
978687140c818ba4b896329a83324714140b6580ef8Chris Lattner
979687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
980687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
981687140c818ba4b896329a83324714140b6580ef8Chris Lattner
982687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
983687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
984687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// and it is more than the alignment of the ultimate object, see if we can
985687140c818ba4b896329a83324714140b6580ef8Chris Lattner/// increase the alignment of the ultimate object, making this check succeed.
986687140c818ba4b896329a83324714140b6580ef8Chris Lattnerunsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
9874c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                          const DataLayout &DL,
98837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const Instruction *CxtI,
9894c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar                                          AssumptionCache *AC,
99037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                                          const DominatorTree *DT) {
991687140c818ba4b896329a83324714140b6580ef8Chris Lattner  assert(V->getType()->isPointerTy() &&
992687140c818ba4b896329a83324714140b6580ef8Chris Lattner         "getOrEnforceKnownAlignment expects a pointer!");
9934c5e43da7792f75567b693105cc53e3f1992ad98Pirama Arumuga Nainar  unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
994186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault
995687140c818ba4b896329a83324714140b6580ef8Chris Lattner  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
996ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
997687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned TrailZ = KnownZero.countTrailingOnes();
998a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
99959a3878c525657701e83bd516d27236814e29f25Matt Arsenault  // Avoid trouble with ridiculously large TrailZ values, such as
1000687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // those computed from a null pointer.
1001687140c818ba4b896329a83324714140b6580ef8Chris Lattner  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
1002a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1003687140c818ba4b896329a83324714140b6580ef8Chris Lattner  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
1004a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1005687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // LLVM doesn't support alignments larger than this currently.
1006687140c818ba4b896329a83324714140b6580ef8Chris Lattner  Align = std::min(Align, +Value::MaximumAlignment);
1007a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1008687140c818ba4b896329a83324714140b6580ef8Chris Lattner  if (PrefAlign > Align)
1009186f8f9d41ea5dfa219144fec3cdb4bf2dd0f64aMatt Arsenault    Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
1010a18c5748989d0b2889d076a2951be17ce61d4f69Jakub Staszak
1011687140c818ba4b896329a83324714140b6580ef8Chris Lattner  // We don't need to make any adjustment.
1012687140c818ba4b896329a83324714140b6580ef8Chris Lattner  return Align;
1013687140c818ba4b896329a83324714140b6580ef8Chris Lattner}
1014687140c818ba4b896329a83324714140b6580ef8Chris Lattner
10155ee20680c7ebc765950983633e19fafab5235245Devang Patel///===---------------------------------------------------------------------===//
10165ee20680c7ebc765950983633e19fafab5235245Devang Patel///  Dbg Intrinsic utilities
10175ee20680c7ebc765950983633e19fafab5235245Devang Patel///
10185ee20680c7ebc765950983633e19fafab5235245Devang Patel
1019163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl/// See if there is a dbg.value intrinsic for DIVar before I.
10206948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainarstatic bool LdStHasDebugValue(const DILocalVariable *DIVar, Instruction *I) {
1021163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // Since we can't guarantee that the original dbg.declare instrinsic
1022163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // is removed by LowerDbgDeclare(), we need to make sure that we are
1023163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  // not inserting the same dbg.value intrinsic over and over.
1024163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  llvm::BasicBlock::InstListType::iterator PrevI(I);
1025163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (PrevI != I->getParent()->getInstList().begin()) {
1026163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    --PrevI;
1027163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1028163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl      if (DVI->getValue() == I->getOperand(0) &&
1029163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getOffset() == 0 &&
1030163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl          DVI->getVariable() == DIVar)
1031163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl        return true;
1032163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  }
1033163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  return false;
1034163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl}
1035163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
10369d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
10375ee20680c7ebc765950983633e19fafab5235245Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
10385ee20680c7ebc765950983633e19fafab5235245Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
10395ee20680c7ebc765950983633e19fafab5235245Devang Patel                                           StoreInst *SI, DIBuilder &Builder) {
10406948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIVar = DDI->getVariable();
10416948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIExpr = DDI->getExpression();
10426948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  assert(DIVar && "Missing variable");
10435ee20680c7ebc765950983633e19fafab5235245Devang Patel
1044163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, SI))
1045163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1046163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1047227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // If an argument is zero extended then use argument directly. The ZExt
1048227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  // may be zapped by an optimization pass in future.
1049dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Argument *ExtendedArg = nullptr;
1050227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1051227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1052227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1053227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1054227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  if (ExtendedArg)
10550c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr,
10560c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar                                    DDI->getDebugLoc(), SI);
1057227dfdb3c44c5cc5ec140b4be89f618bdc59a133Devang Patel  else
10580c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar    Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
10590c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar                                    DDI->getDebugLoc(), SI);
10605ee20680c7ebc765950983633e19fafab5235245Devang Patel  return true;
10615ee20680c7ebc765950983633e19fafab5235245Devang Patel}
10625ee20680c7ebc765950983633e19fafab5235245Devang Patel
10639d5d58a49b23d4145c8bdb12dd10fc88e37bb8f8Adrian Prantl/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
106436fae67831517f132255118b45b21a8cf199a012Devang Patel/// that has an associated llvm.dbg.decl intrinsic.
106536fae67831517f132255118b45b21a8cf199a012Devang Patelbool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
106636fae67831517f132255118b45b21a8cf199a012Devang Patel                                           LoadInst *LI, DIBuilder &Builder) {
10676948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIVar = DDI->getVariable();
10686948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIExpr = DDI->getExpression();
10696948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  assert(DIVar && "Missing variable");
107036fae67831517f132255118b45b21a8cf199a012Devang Patel
1071163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl  if (LdStHasDebugValue(DIVar, LI))
1072163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl    return true;
1073163da930235839d635ecae0c1c8e2f41d8018a24Adrian Prantl
1074cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // We are now tracking the loaded value instead of the address. In the
1075cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // future if multi-location support is added to the IR, it might be
1076cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // preferable to keep tracking both the loaded value and the original
1077cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // address in case the alloca can not be elided.
1078cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1079cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
1080cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  DbgValue->insertAfter(LI);
108136fae67831517f132255118b45b21a8cf199a012Devang Patel  return true;
108236fae67831517f132255118b45b21a8cf199a012Devang Patel}
108336fae67831517f132255118b45b21a8cf199a012Devang Patel
1084dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines/// Determine whether this alloca is either a VLA or an array.
1085dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hinesstatic bool isArray(AllocaInst *AI) {
1086dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return AI->isArrayAllocation() ||
1087dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    AI->getType()->getElementType()->isArrayTy();
1088dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines}
1089dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
1090813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1091813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel/// of llvm.dbg.value intrinsics.
1092813c9a0f19c0d27085a3ea81eb44033747007741Devang Patelbool llvm::LowerDbgDeclare(Function &F) {
1093ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1094813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  SmallVector<DbgDeclareInst *, 4> Dbgs;
109536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &FI : F)
1096cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (Instruction &BI : FI)
1097cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1098813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel        Dbgs.push_back(DDI);
109936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1100813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  if (Dbgs.empty())
1101813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    return false;
1102813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel
110336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (auto &I : Dbgs) {
110436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    DbgDeclareInst *DDI = I;
1105940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1106940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // If this is an alloca for a scalar variable, insert a dbg.value
1107940267e7f208751fdc48dbb7d6b5d86b6310ce7cAdrian Prantl    // at each load and store to the alloca and erase the dbg.declare.
1108dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // The dbg.values allow tracking a variable even if it is not
1109dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // stored on the stack, while the dbg.declare can only describe
1110dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // the stack slot (and at a lexical-scope granularity). Later
1111dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // passes will attempt to elide the stack slot.
1112dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (AI && !isArray(AI)) {
111336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      for (User *U : AI->users())
111436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        if (StoreInst *SI = dyn_cast<StoreInst>(U))
1115813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
111636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        else if (LoadInst *LI = dyn_cast<LoadInst>(U))
111736fae67831517f132255118b45b21a8cf199a012Devang Patel          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1118dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        else if (CallInst *CI = dyn_cast<CallInst>(U)) {
111937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // This is a call by-value or some other instruction that
112037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // takes a pointer to the variable. Insert a *value*
112137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          // intrinsic that describes the alloca.
1122cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          SmallVector<uint64_t, 1> NewDIExpr;
1123cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          auto *DIExpr = DDI->getExpression();
1124cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          NewDIExpr.push_back(dwarf::DW_OP_deref);
1125cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
11266948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar          DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
1127cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                      DIB.createExpression(NewDIExpr),
1128cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                      DDI->getDebugLoc(), CI);
112937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
1130dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      DDI->eraseFromParent();
1131813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel    }
1132813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  }
1133813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel  return true;
1134813c9a0f19c0d27085a3ea81eb44033747007741Devang Patel}
1135c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1136c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1137c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich/// alloca 'V', if any.
1138c827939046670a9800659b83e2048f1d3a79a531Cameron ZwarichDbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1139ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  if (auto *L = LocalAsMetadata::getIfExists(V))
1140ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1141ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines      for (User *U : MDV->users())
1142ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1143ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines          return DDI;
1144c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich
1145dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return nullptr;
1146c827939046670a9800659b83e2048f1d3a79a531Cameron Zwarich}
11471afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
1148cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarbool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1149cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                             Instruction *InsertBefore, DIBuilder &Builder,
1150cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                             bool Deref, int Offset) {
1151cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
11521afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  if (!DDI)
11531afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    return false;
1154ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines  DebugLoc Loc = DDI->getDebugLoc();
11556948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIVar = DDI->getVariable();
11566948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  auto *DIExpr = DDI->getExpression();
11576948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  assert(DIVar && "Missing variable");
11581afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
1159cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (Deref || Offset) {
1160ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // Create a copy of the original DIDescriptor for user variable, prepending
1161ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // "deref" operation to a list of address elements, as new llvm.dbg.declare
1162ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // will take a value storing address of the memory for variable, not
1163ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    // alloca itself.
1164ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    SmallVector<uint64_t, 4> NewDIExpr;
1165cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (Deref)
1166cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewDIExpr.push_back(dwarf::DW_OP_deref);
1167cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (Offset > 0) {
1168cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewDIExpr.push_back(dwarf::DW_OP_plus);
1169cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewDIExpr.push_back(Offset);
1170cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    } else if (Offset < 0) {
1171cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewDIExpr.push_back(dwarf::DW_OP_minus);
1172cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewDIExpr.push_back(-Offset);
1173cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
1174ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    if (DIExpr)
11750c7f116bb6950ef819323d855415b2f2b0aad987Pirama Arumuga Nainar      NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1176ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines    DIExpr = Builder.createExpression(NewDIExpr);
11771afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  }
11781afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov
1179cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Insert llvm.dbg.declare immediately after the original alloca, and remove
1180cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // old llvm.dbg.declare.
1181cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
11821afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  DDI->eraseFromParent();
11831afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov  return true;
11841afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov}
11853333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
1186cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarbool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1187cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                      DIBuilder &Builder, bool Deref, int Offset) {
1188cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1189cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                           Deref, Offset);
1190cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1191cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1192cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarvoid llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
11934f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BasicBlock *BB = I->getParent();
11944f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the successors, removing BB's entry from any PHI
11954f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // nodes.
11964f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
11974f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    (*SI)->removePredecessor(BB);
11984f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
11994f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Insert a call to llvm.trap right before this.  This turns the undefined
12004f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // behavior into a hard fail instead of falling through into random code.
12014f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  if (UseLLVMTrap) {
12024f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Function *TrapFn =
12034f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
12044f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
12054f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    CallTrap->setDebugLoc(I->getDebugLoc());
12064f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
12074f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  new UnreachableInst(I->getContext(), I);
12084f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12094f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // All instructions after this are dead.
1210cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
12114f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  while (BBI != BBE) {
12124f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (!BBI->use_empty())
12134f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
12144f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->getInstList().erase(BBI++);
12154f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  }
12164f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
12174f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12184f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// changeToCall - Convert the specified invoke into a normal call.
12194f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournestatic void changeToCall(InvokeInst *II) {
1220cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
1221cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  SmallVector<OperandBundleDef, 1> OpBundles;
1222cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  II->getOperandBundlesAsDefs(OpBundles);
1223cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1224cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                       "", II);
12254f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->takeName(II);
12264f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setCallingConv(II->getCallingConv());
12274f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setAttributes(II->getAttributes());
12284f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NewCall->setDebugLoc(II->getDebugLoc());
12294f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->replaceAllUsesWith(NewCall);
12304f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12314f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Follow the call by a branch to the normal destination.
12324f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  BranchInst::Create(II->getNormalDest(), II);
12334f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12344f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Update PHI nodes in the unwind destination
12354f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->getUnwindDest()->removePredecessor(II->getParent());
12364f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  II->eraseFromParent();
12374f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
12384f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
1239cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarstatic bool markAliveBlocks(Function &F,
124037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                            SmallPtrSetImpl<BasicBlock*> &Reachable) {
12414f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12423333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  SmallVector<BasicBlock*, 128> Worklist;
1243cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  BasicBlock *BB = &F.front();
12444f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Worklist.push_back(BB);
12454f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  Reachable.insert(BB);
12464f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  bool Changed = false;
12473333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  do {
12484f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB = Worklist.pop_back_val();
12494f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12504f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Do a quick scan of the basic block, turning any obviously unreachable
12514f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // instructions into LLVM unreachable insts.  The instruction combining pass
12524f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // canonicalizes unreachable insts into stores to null or undef.
12534f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
125437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Assumptions that are known to be false are equivalent to unreachable.
125537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // Also, if the condition is undefined, then we make the choice most
125637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      // beneficial to the optimizer, and choose that to also be unreachable.
125737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
125837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        if (II->getIntrinsicID() == Intrinsic::assume) {
125937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          bool MakeUnreachable = false;
126037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (isa<UndefValue>(II->getArgOperand(0)))
126137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = true;
126237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          else if (ConstantInt *Cond =
126337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines                   dyn_cast<ConstantInt>(II->getArgOperand(0)))
126437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            MakeUnreachable = Cond->isZero();
126537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
126637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          if (MakeUnreachable) {
126737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            // Don't insert a call to llvm.trap right before the unreachable.
1268cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            changeToUnreachable(&*BBI, false);
126937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            Changed = true;
127037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines            break;
127137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines          }
127237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        }
127337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
12744f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
12754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (CI->doesNotReturn()) {
12764f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // If we found a call to a no-return function, insert an unreachable
12774f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // instruction after it.  Make sure there isn't *already* one there
12784f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // though.
12794f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          ++BBI;
12804f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          if (!isa<UnreachableInst>(BBI)) {
12814f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            // Don't insert a call to llvm.trap right before the unreachable.
1282cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar            changeToUnreachable(&*BBI, false);
12834f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            Changed = true;
12844f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          }
12854f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
12864f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
12874f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
12884f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12894f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // Store to undef and store to null are undefined and used to signal that
12904f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // they should be changed to unreachable by passes that can't modify the
12914f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      // CFG.
12924f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
12934f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        // Don't touch volatile stores.
12944f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (SI->isVolatile()) continue;
12954f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12964f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Value *Ptr = SI->getOperand(1);
12974f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
12984f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (isa<UndefValue>(Ptr) ||
12994f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne            (isa<ConstantPointerNull>(Ptr) &&
13004f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne             SI->getPointerAddressSpace() == 0)) {
13014f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToUnreachable(SI, true);
13024f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          Changed = true;
13034f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          break;
13044f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        }
13054f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
13064f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
13074f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
13084f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    // Turn invokes that call 'nounwind' functions into ordinary calls.
13094f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
13104f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      Value *Callee = II->getCalledValue();
13114f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
13124f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        changeToUnreachable(II, true);
13134f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
1314cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
13154f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        if (II->use_empty() && II->onlyReadsMemory()) {
13164f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          // jump to the normal destination branch.
13174f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          BranchInst::Create(II->getNormalDest(), II);
13184f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->getUnwindDest()->removePredecessor(II->getParent());
13194f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          II->eraseFromParent();
13204f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        } else
13214f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne          changeToCall(II);
13224f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne        Changed = true;
13234f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne      }
13244f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    }
13254f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
13264f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    Changed |= ConstantFoldTerminator(BB, true);
13273333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
132837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      if (Reachable.insert(*SI).second)
13293333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov        Worklist.push_back(*SI);
13303333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  } while (!Worklist.empty());
13314f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  return Changed;
13324f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne}
13334f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
1334cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarvoid llvm::removeUnwindEdge(BasicBlock *BB) {
1335cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  TerminatorInst *TI = BB->getTerminator();
1336cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1337cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (auto *II = dyn_cast<InvokeInst>(TI)) {
1338cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    changeToCall(II);
1339cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return;
1340cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1341cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1342cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  TerminatorInst *NewTI;
1343cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  BasicBlock *UnwindDest;
1344cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1345cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1346cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
1347cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    UnwindDest = CRI->getUnwindDest();
1348cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1349cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    auto *NewCatchSwitch = CatchSwitchInst::Create(
1350cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
1351cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        CatchSwitch->getName(), CatchSwitch);
1352cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (BasicBlock *PadBB : CatchSwitch->handlers())
1353cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      NewCatchSwitch->addHandler(PadBB);
1354cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1355cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    NewTI = NewCatchSwitch;
1356cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    UnwindDest = CatchSwitch->getUnwindDest();
1357cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  } else {
1358cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    llvm_unreachable("Could not find unwind successor");
1359cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1360cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1361cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  NewTI->takeName(TI);
1362cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  NewTI->setDebugLoc(TI->getDebugLoc());
1363cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  UnwindDest->removePredecessor(BB);
1364cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  TI->replaceAllUsesWith(NewTI);
1365cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  TI->eraseFromParent();
1366cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1367cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
13684f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
13694f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// if they are in a dead cycle.  Return true if a change was made, false
13704f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne/// otherwise.
13714f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbournebool llvm::removeUnreachableBlocks(Function &F) {
13724f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  SmallPtrSet<BasicBlock*, 128> Reachable;
1373cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  bool Changed = markAliveBlocks(F, Reachable);
13743333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13754f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // If there are unreachable blocks in the CFG...
13763333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  if (Reachable.size() == F.size())
13774f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    return Changed;
13783333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13793333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  assert(Reachable.size() < F.size());
13804f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  NumRemoved += F.size()-Reachable.size();
13814f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne
13824f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // Loop over all of the basic blocks that are not reachable, dropping all of
13834f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  // their internal references...
13844f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1385cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (Reachable.count(&*BB))
13863333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      continue;
13873333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
1388cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    for (succ_iterator SI = succ_begin(&*BB), SE = succ_end(&*BB); SI != SE;
1389cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar         ++SI)
13903333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov      if (Reachable.count(*SI))
1391cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        (*SI)->removePredecessor(&*BB);
13924f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne    BB->dropAllReferences();
13937541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov  }
13943333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
13954f96b7e1478be0b33cda589db40635a1e3a40c11Peter Collingbourne  for (Function::iterator I = ++F.begin(); I != F.end();)
1396cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (!Reachable.count(&*I))
13977541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      I = F.getBasicBlockList().erase(I);
13987541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov    else
13997541cd36fdd1bd044e22497838faac7b8f7e48cdEvgeniy Stepanov      ++I;
14003333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov
14013333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov  return true;
14023333e668221f52f8c708df0037ee9c4bf2417929Evgeniy Stepanov}
140337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
1404cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarvoid llvm::combineMetadata(Instruction *K, const Instruction *J,
1405cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                           ArrayRef<unsigned> KnownIDs) {
140637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1407cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  K->dropUnknownNonDebugMetadata(KnownIDs);
140837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  K->getAllMetadataOtherThanDebugLoc(Metadata);
140937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
141037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    unsigned Kind = Metadata[i].first;
141137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *JMD = J->getMetadata(Kind);
141237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    MDNode *KMD = Metadata[i].second;
141337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines
141437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    switch (Kind) {
141537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      default:
141637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, nullptr); // Remove unknown metadata
141737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
141837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_dbg:
141937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
142037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_tbaa:
142137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
142237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
142337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_alias_scope:
1424ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1425ebe69fe11e48d322045d5949c83283927a0d790bStephen Hines        break;
142637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_noalias:
142737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
142837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
142937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_range:
143037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
143137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
143237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_fpmath:
143337ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
143437ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
143537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_invariant_load:
143637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !invariant.load if it is present in both instructions.
143737ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
143837ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
143937ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines      case LLVMContext::MD_nonnull:
144037ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        // Only set the !nonnull if it is present in both instructions.
144137ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        K->setMetadata(Kind, JMD);
144237ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines        break;
1443cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      case LLVMContext::MD_invariant_group:
1444cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        // Preserve !invariant.group in K.
1445cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        break;
1446cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      case LLVMContext::MD_align:
1447cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        K->setMetadata(Kind,
1448cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1449cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        break;
1450cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      case LLVMContext::MD_dereferenceable:
1451cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      case LLVMContext::MD_dereferenceable_or_null:
1452cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        K->setMetadata(Kind,
1453cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar          MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1454cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar        break;
145537ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines    }
145637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines  }
1457cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Set !invariant.group from J if J has it. If both instructions have it
1458cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // then we will just pick it from J - even when they are different.
1459cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Also make sure that K is load or store - f.e. combining bitcast with load
1460cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // could produce bitcast with invariant.group metadata, which is invalid.
1461cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // FIXME: we should try to preserve both invariant.group md if they are
1462cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // different, but right now instruction can only have one invariant.group.
1463cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
1464cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (isa<LoadInst>(K) || isa<StoreInst>(K))
1465cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      K->setMetadata(LLVMContext::MD_invariant_group, JMD);
146637ed9c199ca639565f6ce88105f9e39e898d82d0Stephen Hines}
14676948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
14686948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainarunsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
14696948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar                                        DominatorTree &DT,
14706948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar                                        const BasicBlockEdge &Root) {
14716948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  assert(From->getType() == To->getType());
14726948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar
14736948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  unsigned Count = 0;
14746948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
14756948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar       UI != UE; ) {
14766948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    Use &U = *UI++;
14776948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    if (DT.dominates(Root, U)) {
14786948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      U.set(To);
14796948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      DEBUG(dbgs() << "Replace dominated use of '"
14806948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar            << From->getName() << "' as "
14816948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar            << *To << " in " << *U << "\n");
14826948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar      ++Count;
14836948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar    }
14846948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  }
14856948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar  return Count;
14866948897e478cbd66626159776a8017b3c18579b9Pirama Arumuga Nainar}
1487cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1488cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarunsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1489cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                        DominatorTree &DT,
1490cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                                        const BasicBlock *BB) {
1491cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  assert(From->getType() == To->getType());
1492cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1493cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  unsigned Count = 0;
1494cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1495cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar       UI != UE;) {
1496cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    Use &U = *UI++;
1497cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    auto *I = cast<Instruction>(U.getUser());
1498cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    if (DT.dominates(BB, I->getParent())) {
1499cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      U.set(To);
1500cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
1501cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar                   << *To << " in " << *U << "\n");
1502cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar      ++Count;
1503cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    }
1504cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  }
1505cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return Count;
1506cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1507cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1508cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainarbool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
1509cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (isa<IntrinsicInst>(CS.getInstruction()))
1510cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // Most LLVM intrinsics are things which can never take a safepoint.
1511cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // As a result, we don't need to have the stack parsable at the
1512cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // callsite.  This is a highly useful optimization since intrinsic
1513cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    // calls are fairly prevalent, particularly in debug builds.
1514cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return true;
1515cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1516cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // Check if the function is specifically marked as a gc leaf function.
1517cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  //
1518cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  // TODO: we should be checking the attributes on the call site as well.
1519cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  if (const Function *F = CS.getCalledFunction())
1520cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar    return F->hasFnAttribute("gc-leaf-function");
1521cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar
1522cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar  return false;
1523cddc3e03e4ec99c0268c03a126195173e519ed58Pirama Arumuga Nainar}
1524