Local.cpp revision c827939046670a9800659b83e2048f1d3a79a531
1c779e96158cbac4c62df8e2053ab6a933eba5868Chandler Carruth//===-- Local.cpp - Functions to perform local transformations ------------===//
25a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//
35a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//                     The LLVM Compiler Infrastructure
45a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//
55a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif// This file is distributed under the University of Illinois Open Source
65a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif// License. See LICENSE.TXT for details.
75a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//
85a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//===----------------------------------------------------------------------===//
95a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif//
100b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth// This family of functions perform various local transformations to the
115a88dda4be791426ab4d20a6a6c9c65d66614a27Chandler Carruth// program.
125a88dda4be791426ab4d20a6a6c9c65d66614a27Chandler Carruth//
130b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth//===----------------------------------------------------------------------===//
140b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth
150b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/Transforms/Utils/Local.h"
160b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/Constants.h"
1736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/GlobalAlias.h"
180b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/GlobalVariable.h"
190b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/DerivedTypes.h"
200b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/Instructions.h"
2136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/Intrinsics.h"
220b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IntrinsicInst.h"
235a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Metadata.h"
2436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/Operator.h"
255a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/ADT/DenseMap.h"
265a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/ADT/SmallPtrSet.h"
275a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Analysis/DebugInfo.h"
285a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Analysis/DIBuilder.h"
29138acfe353ed8b895de093a4c118b01093b6fbfbGabor Greif#include "llvm/Analysis/Dominators.h"
305a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Analysis/ConstantFolding.h"
315a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Analysis/InstructionSimplify.h"
32138acfe353ed8b895de093a4c118b01093b6fbfbGabor Greif#include "llvm/Analysis/ProfileInfo.h"
335a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif#include "llvm/Analysis/ValueTracking.h"
34d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif#include "llvm/Target/TargetData.h"
35138acfe353ed8b895de093a4c118b01093b6fbfbGabor Greif#include "llvm/Support/CFG.h"
3622385eb8527f6bf8083ee85f85dc51e4d4928aaaGabor Greif#include "llvm/Support/Debug.h"
37db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner#include "llvm/Support/GetElementPtrTypeIterator.h"
3822385eb8527f6bf8083ee85f85dc51e4d4928aaaGabor Greif#include "llvm/Support/IRBuilder.h"
3922385eb8527f6bf8083ee85f85dc51e4d4928aaaGabor Greif#include "llvm/Support/MathExtras.h"
40f5ec9b55e871d326b8917f203711529273e7fa54John McCall#include "llvm/Support/ValueHandle.h"
4122385eb8527f6bf8083ee85f85dc51e4d4928aaaGabor Greif#include "llvm/Support/raw_ostream.h"
42f5ec9b55e871d326b8917f203711529273e7fa54John McCallusing namespace llvm;
43f5ec9b55e871d326b8917f203711529273e7fa54John McCall
44f5ec9b55e871d326b8917f203711529273e7fa54John McCall//===----------------------------------------------------------------------===//
4522385eb8527f6bf8083ee85f85dc51e4d4928aaaGabor Greif//  Local constant propagation.
46f5ec9b55e871d326b8917f203711529273e7fa54John McCall//
47642c066906488715220dd87c5b976c67bb8a303dGabor Greif
48642c066906488715220dd87c5b976c67bb8a303dGabor Greif/// ConstantFoldTerminator - If a terminator instruction is predicated on a
49642c066906488715220dd87c5b976c67bb8a303dGabor Greif/// constant value, convert it into an unconditional branch to the constant
50642c066906488715220dd87c5b976c67bb8a303dGabor Greif/// destination.  This is a nontrivial operation because the successors of this
515a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif/// basic block must have their PHI nodes updated.
525a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
5336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// conditions and indirectbr addresses this might make dead if
5436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines/// DeleteDeadConditions is true.
5536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesbool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions) {
5636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  TerminatorInst *T = BB->getTerminator();
5736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  IRBuilder<> Builder(T);
5836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
5936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Branch - See if we are conditional jumping on constant
6036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
6236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    BasicBlock *Dest1 = BI->getSuccessor(0);
6336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    BasicBlock *Dest2 = BI->getSuccessor(1);
6436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
6536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
6636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Are we branching on constant?
6736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // YES.  Change to unconditional branch...
6836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
6936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
7036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
7136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      //cerr << "Function: " << T->getParent()->getParent()
7236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      //     << "\nRemoving branch from " << T->getParent()
7336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      //     << "\n\nTo: " << OldDest << endl;
7436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
7536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Let the basic block know that we are letting go of it.  Based on this,
7636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // it will adjust it's PHI nodes.
7736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      OldDest->removePredecessor(BB);
7836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
7936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Replace the conditional branch with an unconditional one.
8036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Builder.CreateBr(Destination);
8136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      BI->eraseFromParent();
8236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return true;
8336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
8436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
8536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (Dest2 == Dest1) {       // Conditional branch to same location?
8636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // This branch matches something like this:
8736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      //     br bool %cond, label %Dest, label %Dest
8836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // and changes it into:  br label %Dest
8936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
9036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Let the basic block know that we are letting go of one copy of it.
9136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      assert(BI->getParent() && "Terminator not inserted in block!");
9236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Dest1->removePredecessor(BI->getParent());
9336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
9436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // Replace the conditional branch with an unconditional one.
9536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Builder.CreateBr(Dest1);
9636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Value *Cond = BI->getCondition();
9736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      BI->eraseFromParent();
9836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (DeleteDeadConditions)
9936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        RecursivelyDeleteTriviallyDeadInstructions(Cond);
10036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      return true;
10136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
10236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    return false;
10336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
10436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
105d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
106d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    // If we are switching on a constant, we can convert the switch into a
107d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    // single branch instruction!
108d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
109d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
110d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    BasicBlock *DefaultDest = TheOnlyDest;
111d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    assert(TheOnlyDest == SI->getDefaultDest() &&
112d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif           "Default destination is not successor #0?");
113d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
114d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    // Figure out which case it goes to.
115abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
116abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif      // Found case matching a constant operand?
117f5ec9b55e871d326b8917f203711529273e7fa54John McCall      if (SI->getSuccessorValue(i) == CI) {
118abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif        TheOnlyDest = SI->getSuccessor(i);
119d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        break;
120f5ec9b55e871d326b8917f203711529273e7fa54John McCall      }
121d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
122d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // Check to see if this branch is going to the same place as the default
12336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // dest.  If so, eliminate it as an explicit compare.
124abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif      if (SI->getSuccessor(i) == DefaultDest) {
12536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        // Remove this entry.
126d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        DefaultDest->removePredecessor(SI->getParent());
127db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner        SI->removeCase(i);
128d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        --i; --e;  // Don't skip an entry...
129d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        continue;
130d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      }
131d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
132d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // Otherwise, check to see if the switch only branches to one destination.
133abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
134abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif      // destinations.
135f5ec9b55e871d326b8917f203711529273e7fa54John McCall      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
136abf657f7e6dbce1bf8e02fce2d602f33d5fc5c2aGabor Greif    }
137d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
138f5ec9b55e871d326b8917f203711529273e7fa54John McCall    if (CI && !TheOnlyDest) {
139d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // Branching on a constant, but not any of the cases, go to the default
140d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // successor.
141d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      TheOnlyDest = SI->getDefaultDest();
142d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    }
143d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
144f5ec9b55e871d326b8917f203711529273e7fa54John McCall    // If we found a single destination that we can fold the switch into, do so
145f5ec9b55e871d326b8917f203711529273e7fa54John McCall    // now.
146f5ec9b55e871d326b8917f203711529273e7fa54John McCall    if (TheOnlyDest) {
147d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // Insert the new branch.
148d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      Builder.CreateBr(TheOnlyDest);
149d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      BasicBlock *BB = SI->getParent();
150f5ec9b55e871d326b8917f203711529273e7fa54John McCall
151f5ec9b55e871d326b8917f203711529273e7fa54John McCall      // Remove entries from PHI nodes which we no longer branch to...
152f5ec9b55e871d326b8917f203711529273e7fa54John McCall      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
153d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        // Found case matching a constant operand?
154d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        BasicBlock *Succ = SI->getSuccessor(i);
155d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        if (Succ == TheOnlyDest)
156f5ec9b55e871d326b8917f203711529273e7fa54John McCall          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
157f5ec9b55e871d326b8917f203711529273e7fa54John McCall        else
158f5ec9b55e871d326b8917f203711529273e7fa54John McCall          Succ->removePredecessor(BB);
159d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      }
160d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
161f5ec9b55e871d326b8917f203711529273e7fa54John McCall      // Delete the old switch.
162d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      Value *Cond = SI->getCondition();
163d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      SI->eraseFromParent();
164d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      if (DeleteDeadConditions)
165d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif        RecursivelyDeleteTriviallyDeadInstructions(Cond);
166d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      return true;
167d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    }
168d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif
169d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif    if (SI->getNumSuccessors() == 2) {
170d165e1a71193ebff49ede9663d1ed70050f04699Gabor Greif      // Otherwise, we can fold this switch into a conditional branch
171607946533d4eb781713b363605c4a241503dbe0eDuncan Sands      // instruction if it has only one non-default destination.
172607946533d4eb781713b363605c4a241503dbe0eDuncan Sands      Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
173607946533d4eb781713b363605c4a241503dbe0eDuncan Sands                                         SI->getSuccessorValue(1), "cond");
174f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
175f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      // Insert the new branch.
176f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      Builder.CreateCondBr(Cond, SI->getSuccessor(1), SI->getSuccessor(0));
177f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
178f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      // Delete the old switch.
179f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      SI->eraseFromParent();
180f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      return true;
181f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    }
182f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    return false;
183f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  }
184f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
185f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
186f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    // indirectbr blockaddress(@F, @BB) -> br label @BB
187f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    if (BlockAddress *BA =
188f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
189f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      BasicBlock *TheOnlyDest = BA->getBasicBlock();
190f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      // Insert the new branch.
191f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      Builder.CreateBr(TheOnlyDest);
192f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
193f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
194f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault        if (IBI->getDestination(i) == TheOnlyDest)
195f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault          TheOnlyDest = 0;
196f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault        else
197f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault          IBI->getDestination(i)->removePredecessor(IBI->getParent());
198f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      }
199f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      Value *Address = IBI->getAddress();
200f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      IBI->eraseFromParent();
201f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      if (DeleteDeadConditions)
202f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault        RecursivelyDeleteTriviallyDeadInstructions(Address);
20336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
204607946533d4eb781713b363605c4a241503dbe0eDuncan Sands      // If we didn't find our destination in the IBI successor list, then we
205117feba971a020653fef3d6d61a16345355b83fdDuncan Sands      // have undefined behavior.  Replace the unconditional branch with an
206117feba971a020653fef3d6d61a16345355b83fdDuncan Sands      // 'unreachable' instruction.
207117feba971a020653fef3d6d61a16345355b83fdDuncan Sands      if (TheOnlyDest) {
20859d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault        BB->getTerminator()->eraseFromParent();
20959d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault        new UnreachableInst(BB->getContext(), BB);
210485c7fd76b32a69c46782a715682ed8831b0873bMatt Arsenault      }
211485c7fd76b32a69c46782a715682ed8831b0873bMatt Arsenault
212485c7fd76b32a69c46782a715682ed8831b0873bMatt Arsenault      return true;
213485c7fd76b32a69c46782a715682ed8831b0873bMatt Arsenault    }
214485c7fd76b32a69c46782a715682ed8831b0873bMatt Arsenault  }
215f5ec9b55e871d326b8917f203711529273e7fa54John McCall
216f5ec9b55e871d326b8917f203711529273e7fa54John McCall  return false;
2171608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem}
218f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
219f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
220f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault//===----------------------------------------------------------------------===//
221f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault//  Local dead code elimination.
222f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault//
223f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
224f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// isInstructionTriviallyDead - Return true if the result produced by the
225f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// instruction is not used, and the instruction has no side effects.
226f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault///
227f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenaultbool llvm::isInstructionTriviallyDead(Instruction *I) {
228f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
229f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
23059d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault  // We don't want debug info removed by anything this general, unless
23159d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault  // debug info is empty.
23259d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
23359d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault    if (DDI->getAddress())
234f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      return false;
235f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    return true;
236f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  }
237f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
238f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    if (DVI->getValue())
239f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      return false;
240f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    return true;
241f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  }
242f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
243f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (!I->mayHaveSideEffects()) return true;
244f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
245f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  // Special case intrinsics that "may have side effects" but can be deleted
246f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  // when dead.
247f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
248f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    // Safe to delete llvm.stacksave if dead.
249f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    if (II->getIntrinsicID() == Intrinsic::stacksave)
250f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault      return true;
251f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  return false;
252f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault}
253f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault
254f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
255f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// trivially dead instruction, delete it.  If that makes any of its operands
256f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// trivially dead, delete them too, recursively.  Return true if any
257f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault/// instructions were deleted.
258f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenaultbool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
259f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  Instruction *I = dyn_cast<Instruction>(V);
260f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
261f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault    return false;
2621bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault
2631bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault  SmallVector<Instruction*, 16> DeadInsts;
26436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  DeadInsts.push_back(I);
26536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
26636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  do {
26736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    I = DeadInsts.pop_back_val();
26836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
26936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // Null out all of the instruction's operands to see if any operand becomes
27036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    // dead as we go.
27136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
27236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Value *OpV = I->getOperand(i);
27336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      I->setOperand(i, 0);
27436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
27536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (!OpV->use_empty()) continue;
27636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
27736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // If the operand is an instruction that became dead as we nulled out the
27836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      // operand, and if it is 'trivially' dead, delete it in a future loop
2791bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault      // iteration.
2801bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
2811bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault        if (isInstructionTriviallyDead(OpI))
2821bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault          DeadInsts.push_back(OpI);
2831bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault    }
2841bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault
2851bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault    I->eraseFromParent();
2861bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault  } while (!DeadInsts.empty());
2871bf0ec4e1642a532c0121de8ccc0878d6403c9d3Matt Arsenault
288f34dc428fa577d6d5d71ab3a1f9765b4e5da5a4fMatt Arsenault  return true;
2891608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem}
2901608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
2911608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// areAllUsesEqual - Check whether the uses of a value are all the same.
2921608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// This is similar to Instruction::hasOneUse() except this will also return
2931608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// true when there are no uses or multiple uses that all refer to the same
2941608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// value.
29576bf61fe0754500c5c9d01fc440ff36c76ff61f5Matt Arsenaultstatic bool areAllUsesEqual(Instruction *I) {
2961608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  Value::use_iterator UI = I->use_begin();
2971608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  Value::use_iterator UE = I->use_end();
2981608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  if (UI == UE)
2991608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    return true;
3001608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3011608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  User *TheUse = *UI;
3021608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  for (++UI; UI != UE; ++UI) {
3031608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    if (*UI != TheUse)
3041608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      return false;
3051608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  }
3061608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  return true;
3071608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem}
3081608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3091608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
3101608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// dead PHI node, due to being a def-use chain of single-use nodes that
3111608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// either forms a cycle or is terminated by a trivially dead instruction,
3121608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// delete it.  If that makes any of its operands trivially dead, delete them
3131608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// too, recursively.  Return true if a change was made.
3141608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotembool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
3151608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  SmallPtrSet<Instruction*, 4> Visited;
3164802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
3174802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov       I = cast<Instruction>(*I->use_begin())) {
3184802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov    if (I->use_empty())
3194802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov      return RecursivelyDeleteTriviallyDeadInstructions(I);
3204802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov
3211608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    // If we find an instruction more than once, we're on a cycle that
3221608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    // won't prove fruitful.
3231608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    if (!Visited.insert(I)) {
3241608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      // Break the cycle and delete the instruction and its operands.
3251608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      I->replaceAllUsesWith(UndefValue::get(I->getType()));
3261608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      (void)RecursivelyDeleteTriviallyDeadInstructions(I);
3271608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      return true;
3281608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    }
3291608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  }
3301608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  return false;
3311608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem}
3321608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3331608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
3341608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// simplify any instructions in it and recursively delete dead instructions.
3351608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem///
3361608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// This returns true if it changed the code, note that it can delete
3371608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// instructions in other blocks as well in this block.
3381608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotembool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
3391608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  bool MadeChange = false;
3401608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
3411608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    Instruction *Inst = BI++;
342791cfc211a9801002bfda6b3eb4de7e041f04f53Micah Villmow
34336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    if (Value *V = SimplifyInstruction(Inst, TD)) {
3441608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      WeakVH BIHandle(BI);
3451608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      ReplaceAndSimplifyAllUses(Inst, V, TD);
346a070d2a0355c4993240b5206ebc1d517c151331dDan Gohman      MadeChange = true;
347a070d2a0355c4993240b5206ebc1d517c151331dDan Gohman      if (BIHandle != BI)
348a070d2a0355c4993240b5206ebc1d517c151331dDan Gohman        BI = BB->begin();
349a070d2a0355c4993240b5206ebc1d517c151331dDan Gohman      continue;
3501608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    }
3511608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3521608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    if (Inst->isTerminator())
3531608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      break;
3541608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3551608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    WeakVH BIHandle(BI);
3561608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
3571608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem    if (BIHandle != BI)
3581608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem      BI = BB->begin();
3591608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  }
3601608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  return MadeChange;
3611608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem}
3621608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3631608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem//===----------------------------------------------------------------------===//
3641608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem//  Control Flow Graph Restructuring.
3651608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem//
3661608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3671608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3681608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
3691608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// method is called when we're about to delete Pred as a predecessor of BB.  If
3701608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
3711608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem///
3721608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
3731608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// nodes that collapse into identity values.  For example, if we have:
3741608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem///   x = phi(1, 0, 0, 0)
3751608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem///   y = and x, z
3761608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem///
3771608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// .. and delete the predecessor corresponding to the '1', this will attempt to
3781608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem/// recursively fold the and to 0.
3791608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotemvoid llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
3801608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem                                        TargetData *TD) {
3811608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  // This only adjusts blocks with PHI nodes.
3824802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov  if (!isa<PHINode>(BB->begin()))
3834802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov    return;
3844802b9d6dc7443985066f0381c0a2468f72f9b81Evgeniy Stepanov
3851608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
3861608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  // them down.  This will leave us with single entry phi nodes and other phis
3871608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  // that can be removed.
3881608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  BB->removePredecessor(Pred, true);
3891608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem
3901608769abeb1430dc34f31ffac0d9850f99ae36aNadav Rotem  WeakVH PhiIt = &BB->front();
3918883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
3928883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
3938883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands
3948883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    Value *PNV = SimplifyInstruction(PN, TD);
3958883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    if (PNV == 0) continue;
3968883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands
3978883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    // If we're able to simplify the phi to a single value, substitute the new
3988883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    // value into all of its uses.
3998883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    assert(PNV != PN && "SimplifyInstruction broken!");
4008883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands
4018883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    Value *OldPhiIt = PhiIt;
4028883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    ReplaceAndSimplifyAllUses(PN, PNV, TD);
4038883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands
4048883c43ddc13e5f92ba8dfe00f2116a153a570d5Duncan Sands    // If recursive simplification ended up deleting the next PHI node we would
405446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    // iterate to, then our iterator is invalid, restart scanning from the top
406446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    // of the block.
407446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
408446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  }
4093181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault}
410446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands
411446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands
412446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
413446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
414446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands/// between them, moving the instructions in the predecessor into DestBB and
415446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands/// deleting the predecessor block.
416446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands///
417446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sandsvoid llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
418c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines  // If BB has single-entry PHI nodes, fold them.
419446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
420446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    Value *NewVal = PN->getIncomingValue(0);
4213181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    // Replace self referencing PHI with undef, it must be dead.
4223181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
423446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    PN->replaceAllUsesWith(NewVal);
424446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    PN->eraseFromParent();
425446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  }
426c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines
4273181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  BasicBlock *PredBB = DestBB->getSinglePredecessor();
4283181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  assert(PredBB && "Block doesn't have a single predecessor!");
4293181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault
4303181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // Splice all the instructions from PredBB to DestBB.
4313181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  PredBB->getTerminator()->eraseFromParent();
4323181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
4333181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault
434c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines  // Zap anything that took the address of DestBB.  Not doing this will give the
435446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  // address an invalid value.
436446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  if (DestBB->hasAddressTaken()) {
437446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    BlockAddress *BA = BlockAddress::get(DestBB);
438446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    Constant *Replacement =
439446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
440446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
441c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines                                                     BA->getType()));
442446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    BA->destroyConstant();
443446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  }
444446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands
445446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  // Anything that branched to PredBB now branches to DestBB.
446446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  PredBB->replaceAllUsesWith(DestBB);
447446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands
448c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines  if (P) {
449446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands    DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
4503181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    if (DT) {
4513181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault      BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
4523181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault      DT->changeImmediateDominator(DestBB, PredBBIDom);
4533181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault      DT->eraseNode(PredBB);
4543181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    }
45536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
4563181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    if (PI) {
4573181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault      PI->replaceAllUses(PredBB, DestBB);
4583181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault      PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
4593181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault    }
4603181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  }
4613181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // Nuke BB.
4623181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  PredBB->eraseFromParent();
46359d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault}
4643181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault
46559d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
4663181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault/// almost-empty BB ending in an unconditional branch to Succ, into succ.
467c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines///
4683181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault/// Assumption: Succ is the single successor for BB.
4693181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault///
47059d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenaultstatic bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
47159d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
47259d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault
47359d3ae6cdc4316ad338cd848251f33a236ccb36cMatt Arsenault  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
474c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines        << Succ->getName() << "\n");
4753181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // Shortcut, if there is only a single predecessor it must be BB and merging
4763181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // is always safe
4773181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  if (Succ->getSinglePredecessor()) return true;
4783181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault
4793181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // Make a list of the predecessors of BB
4803181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
481c6a4f5e819217e1e12c458aed8e7b122e23a3a58Stephen Hines  BlockSet BBPreds(pred_begin(BB), pred_end(BB));
4823181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault
4833181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault  // Use that list to make another list of common predecessors of BB and Succ
484446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  BlockSet CommonPreds;
485446cf94cdbbc1f8e22452fc46664ac73d810c6a2Duncan Sands  for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
486dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines       PI != PE; ++PI) {
487dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    BasicBlock *P = *PI;
488dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (BBPreds.count(P))
489dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      CommonPreds.insert(P);
490dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  }
491dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
492dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // Shortcut, if there are no common predecessors, merging is always safe
493dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (CommonPreds.empty())
494dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return true;
495dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
496dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // Look at all the phi nodes in Succ, to see if they present a conflict when
497dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  // merging these blocks
498dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
499dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    PHINode *PN = cast<PHINode>(I);
500dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
501dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // If the incoming value from BB is again a PHINode in
502dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // BB which has the same incoming value for *PI as PN does, we can
503dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    // merge the phi nodes and then the blocks can still be merged
504dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
505dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (BBPN && BBPN->getParent() == BB) {
506dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
507dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines            PI != PE; PI++) {
508dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        if (BBPN->getIncomingValueForBlock(*PI)
509dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines              != PN->getIncomingValueForBlock(*PI)) {
510dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
511dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                << Succ->getName() << " is conflicting with "
512dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                << BBPN->getName() << " with regard to common predecessor "
513dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines                << (*PI)->getName() << "\n");
514dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines          return false;
515dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        }
516dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      }
517dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    } else {
518dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      Value* Val = PN->getIncomingValueForBlock(BB);
5195a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
5205a7069a80fee26490b201cb3d88eb124585bd6c8Gabor Greif            PI != PE; PI++) {
5213181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault        // See if the incoming value for the common predecessor is equal to the
5223181f5900ff5d9800c38284c7d3427cb6e306c9aMatt Arsenault        // one for BB, in which case this phi node will not prevent the merging
523        // of the block.
524        if (Val != PN->getIncomingValueForBlock(*PI)) {
525          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
526                << Succ->getName() << " is conflicting with regard to common "
527                << "predecessor " << (*PI)->getName() << "\n");
528          return false;
529        }
530      }
531    }
532  }
533
534  return true;
535}
536
537/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
538/// unconditional branch, and contains no instructions other than PHI nodes,
539/// potential debug intrinsics and the branch.  If possible, eliminate BB by
540/// rewriting all the predecessors to branch to the successor block and return
541/// true.  If we can't transform, return false.
542bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
543  assert(BB != &BB->getParent()->getEntryBlock() &&
544         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
545
546  // We can't eliminate infinite loops.
547  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
548  if (BB == Succ) return false;
549
550  // Check to see if merging these blocks would cause conflicts for any of the
551  // phi nodes in BB or Succ. If not, we can safely merge.
552  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
553
554  // Check for cases where Succ has multiple predecessors and a PHI node in BB
555  // has uses which will not disappear when the PHI nodes are merged.  It is
556  // possible to handle such cases, but difficult: it requires checking whether
557  // BB dominates Succ, which is non-trivial to calculate in the case where
558  // Succ has multiple predecessors.  Also, it requires checking whether
559  // constructing the necessary self-referential PHI node doesn't intoduce any
560  // conflicts; this isn't too difficult, but the previous code for doing this
561  // was incorrect.
562  //
563  // Note that if this check finds a live use, BB dominates Succ, so BB is
564  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
565  // folding the branch isn't profitable in that case anyway.
566  if (!Succ->getSinglePredecessor()) {
567    BasicBlock::iterator BBI = BB->begin();
568    while (isa<PHINode>(*BBI)) {
569      for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
570           UI != E; ++UI) {
571        if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
572          if (PN->getIncomingBlock(UI) != BB)
573            return false;
574        } else {
575          return false;
576        }
577      }
578      ++BBI;
579    }
580  }
581
582  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
583
584  if (isa<PHINode>(Succ->begin())) {
585    // If there is more than one pred of succ, and there are PHI nodes in
586    // the successor, then we need to add incoming edges for the PHI nodes
587    //
588    const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
589
590    // Loop over all of the PHI nodes in the successor of BB.
591    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
592      PHINode *PN = cast<PHINode>(I);
593      Value *OldVal = PN->removeIncomingValue(BB, false);
594      assert(OldVal && "No entry in PHI for Pred BB!");
595
596      // If this incoming value is one of the PHI nodes in BB, the new entries
597      // in the PHI node are the entries from the old PHI.
598      if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
599        PHINode *OldValPN = cast<PHINode>(OldVal);
600        for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
601          // Note that, since we are merging phi nodes and BB and Succ might
602          // have common predecessors, we could end up with a phi node with
603          // identical incoming branches. This will be cleaned up later (and
604          // will trigger asserts if we try to clean it up now, without also
605          // simplifying the corresponding conditional branch).
606          PN->addIncoming(OldValPN->getIncomingValue(i),
607                          OldValPN->getIncomingBlock(i));
608      } else {
609        // Add an incoming value for each of the new incoming values.
610        for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
611          PN->addIncoming(OldVal, BBPreds[i]);
612      }
613    }
614  }
615
616  while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
617    if (Succ->getSinglePredecessor()) {
618      // BB is the only predecessor of Succ, so Succ will end up with exactly
619      // the same predecessors BB had.
620      Succ->getInstList().splice(Succ->begin(),
621                                 BB->getInstList(), BB->begin());
622    } else {
623      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
624      assert(PN->use_empty() && "There shouldn't be any uses here!");
625      PN->eraseFromParent();
626    }
627  }
628
629  // Everything that jumped to BB now goes to Succ.
630  BB->replaceAllUsesWith(Succ);
631  if (!Succ->hasName()) Succ->takeName(BB);
632  BB->eraseFromParent();              // Delete the old basic block.
633  return true;
634}
635
636/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
637/// nodes in this block. This doesn't try to be clever about PHI nodes
638/// which differ only in the order of the incoming values, but instcombine
639/// orders them so it usually won't matter.
640///
641bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
642  bool Changed = false;
643
644  // This implementation doesn't currently consider undef operands
645  // specially. Theroetically, two phis which are identical except for
646  // one having an undef where the other doesn't could be collapsed.
647
648  // Map from PHI hash values to PHI nodes. If multiple PHIs have
649  // the same hash value, the element is the first PHI in the
650  // linked list in CollisionMap.
651  DenseMap<uintptr_t, PHINode *> HashMap;
652
653  // Maintain linked lists of PHI nodes with common hash values.
654  DenseMap<PHINode *, PHINode *> CollisionMap;
655
656  // Examine each PHI.
657  for (BasicBlock::iterator I = BB->begin();
658       PHINode *PN = dyn_cast<PHINode>(I++); ) {
659    // Compute a hash value on the operands. Instcombine will likely have sorted
660    // them, which helps expose duplicates, but we have to check all the
661    // operands to be safe in case instcombine hasn't run.
662    uintptr_t Hash = 0;
663    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
664      // This hash algorithm is quite weak as hash functions go, but it seems
665      // to do a good enough job for this particular purpose, and is very quick.
666      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
667      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
668    }
669    // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
670    Hash >>= 1;
671    // If we've never seen this hash value before, it's a unique PHI.
672    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
673      HashMap.insert(std::make_pair(Hash, PN));
674    if (Pair.second) continue;
675    // Otherwise it's either a duplicate or a hash collision.
676    for (PHINode *OtherPN = Pair.first->second; ; ) {
677      if (OtherPN->isIdenticalTo(PN)) {
678        // A duplicate. Replace this PHI with its duplicate.
679        PN->replaceAllUsesWith(OtherPN);
680        PN->eraseFromParent();
681        Changed = true;
682        break;
683      }
684      // A non-duplicate hash collision.
685      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
686      if (I == CollisionMap.end()) {
687        // Set this PHI to be the head of the linked list of colliding PHIs.
688        PHINode *Old = Pair.first->second;
689        Pair.first->second = PN;
690        CollisionMap[PN] = Old;
691        break;
692      }
693      // Procede to the next PHI in the list.
694      OtherPN = I->second;
695    }
696  }
697
698  return Changed;
699}
700
701/// enforceKnownAlignment - If the specified pointer points to an object that
702/// we control, modify the object's alignment to PrefAlign. This isn't
703/// often possible though. If alignment is important, a more reliable approach
704/// is to simply align all global variables and allocation instructions to
705/// their preferred alignment from the beginning.
706///
707static unsigned enforceKnownAlignment(Value *V, unsigned Align,
708                                      unsigned PrefAlign) {
709
710  User *U = dyn_cast<User>(V);
711  if (!U) return Align;
712
713  switch (Operator::getOpcode(U)) {
714  default: break;
715  case Instruction::BitCast:
716    return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
717  case Instruction::GetElementPtr: {
718    // If all indexes are zero, it is just the alignment of the base pointer.
719    bool AllZeroOperands = true;
720    for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
721      if (!isa<Constant>(*i) ||
722          !cast<Constant>(*i)->isNullValue()) {
723        AllZeroOperands = false;
724        break;
725      }
726
727    if (AllZeroOperands) {
728      // Treat this like a bitcast.
729      return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
730    }
731    return Align;
732  }
733  case Instruction::Alloca: {
734    AllocaInst *AI = cast<AllocaInst>(V);
735    // If there is a requested alignment and if this is an alloca, round up.
736    if (AI->getAlignment() >= PrefAlign)
737      return AI->getAlignment();
738    AI->setAlignment(PrefAlign);
739    return PrefAlign;
740  }
741  }
742
743  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
744    // If there is a large requested alignment and we can, bump up the alignment
745    // of the global.
746    if (GV->isDeclaration()) return Align;
747
748    if (GV->getAlignment() >= PrefAlign)
749      return GV->getAlignment();
750    // We can only increase the alignment of the global if it has no alignment
751    // specified or if it is not assigned a section.  If it is assigned a
752    // section, the global could be densely packed with other objects in the
753    // section, increasing the alignment could cause padding issues.
754    if (!GV->hasSection() || GV->getAlignment() == 0)
755      GV->setAlignment(PrefAlign);
756    return GV->getAlignment();
757  }
758
759  return Align;
760}
761
762/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
763/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
764/// and it is more than the alignment of the ultimate object, see if we can
765/// increase the alignment of the ultimate object, making this check succeed.
766unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
767                                          const TargetData *TD) {
768  assert(V->getType()->isPointerTy() &&
769         "getOrEnforceKnownAlignment expects a pointer!");
770  unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
771  APInt Mask = APInt::getAllOnesValue(BitWidth);
772  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
774  unsigned TrailZ = KnownZero.countTrailingOnes();
775
776  // Avoid trouble with rediculously large TrailZ values, such as
777  // those computed from a null pointer.
778  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
779
780  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
781
782  // LLVM doesn't support alignments larger than this currently.
783  Align = std::min(Align, +Value::MaximumAlignment);
784
785  if (PrefAlign > Align)
786    Align = enforceKnownAlignment(V, Align, PrefAlign);
787
788  // We don't need to make any adjustment.
789  return Align;
790}
791
792///===---------------------------------------------------------------------===//
793///  Dbg Intrinsic utilities
794///
795
796/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
797/// that has an associated llvm.dbg.decl intrinsic.
798bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
799                                           StoreInst *SI, DIBuilder &Builder) {
800  DIVariable DIVar(DDI->getVariable());
801  if (!DIVar.Verify())
802    return false;
803
804  Instruction *DbgVal = NULL;
805  // If an argument is zero extended then use argument directly. The ZExt
806  // may be zapped by an optimization pass in future.
807  Argument *ExtendedArg = NULL;
808  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
809    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
810  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
811    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
812  if (ExtendedArg)
813    DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
814  else
815    DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
816
817  // Propagate any debug metadata from the store onto the dbg.value.
818  DebugLoc SIDL = SI->getDebugLoc();
819  if (!SIDL.isUnknown())
820    DbgVal->setDebugLoc(SIDL);
821  // Otherwise propagate debug metadata from dbg.declare.
822  else
823    DbgVal->setDebugLoc(DDI->getDebugLoc());
824  return true;
825}
826
827/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
828/// that has an associated llvm.dbg.decl intrinsic.
829bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
830                                           LoadInst *LI, DIBuilder &Builder) {
831  DIVariable DIVar(DDI->getVariable());
832  if (!DIVar.Verify())
833    return false;
834
835  Instruction *DbgVal =
836    Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
837                                    DIVar, LI);
838
839  // Propagate any debug metadata from the store onto the dbg.value.
840  DebugLoc LIDL = LI->getDebugLoc();
841  if (!LIDL.isUnknown())
842    DbgVal->setDebugLoc(LIDL);
843  // Otherwise propagate debug metadata from dbg.declare.
844  else
845    DbgVal->setDebugLoc(DDI->getDebugLoc());
846  return true;
847}
848
849/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
850/// of llvm.dbg.value intrinsics.
851bool llvm::LowerDbgDeclare(Function &F) {
852  DIBuilder DIB(*F.getParent());
853  SmallVector<DbgDeclareInst *, 4> Dbgs;
854  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
855    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
856      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
857        Dbgs.push_back(DDI);
858    }
859  if (Dbgs.empty())
860    return false;
861
862  for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
863         E = Dbgs.end(); I != E; ++I) {
864    DbgDeclareInst *DDI = *I;
865    if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
866      bool RemoveDDI = true;
867      for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
868           UI != E; ++UI)
869        if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
870          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
871        else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
872          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
873        else
874          RemoveDDI = false;
875      if (RemoveDDI)
876        DDI->eraseFromParent();
877    }
878  }
879  return true;
880}
881
882/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
883/// alloca 'V', if any.
884DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
885  if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
886    for (Value::use_iterator UI = DebugNode->use_begin(),
887         E = DebugNode->use_end(); UI != E; ++UI)
888      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
889        return DDI;
890
891  return 0;
892}
893