Local.cpp revision 1a4021a2be4a59e9f9010776cb6f72107241aeb5
1//===-- Local.cpp - Functions to perform local transformations ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
16#include "llvm/Constants.h"
17#include "llvm/GlobalAlias.h"
18#include "llvm/GlobalVariable.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/IntrinsicInst.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/InstructionSimplify.h"
28#include "llvm/Analysis/ProfileInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
30#include "llvm/Target/TargetData.h"
31#include "llvm/Support/CFG.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/GetElementPtrTypeIterator.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Support/ValueHandle.h"
36#include "llvm/Support/raw_ostream.h"
37using namespace llvm;
38
39//===----------------------------------------------------------------------===//
40//  Local constant propagation.
41//
42
43// ConstantFoldTerminator - If a terminator instruction is predicated on a
44// constant value, convert it into an unconditional branch to the constant
45// destination.
46//
47bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
48  TerminatorInst *T = BB->getTerminator();
49
50  // Branch - See if we are conditional jumping on constant
51  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
52    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
53    BasicBlock *Dest1 = BI->getSuccessor(0);
54    BasicBlock *Dest2 = BI->getSuccessor(1);
55
56    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
57      // Are we branching on constant?
58      // YES.  Change to unconditional branch...
59      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
60      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
61
62      //cerr << "Function: " << T->getParent()->getParent()
63      //     << "\nRemoving branch from " << T->getParent()
64      //     << "\n\nTo: " << OldDest << endl;
65
66      // Let the basic block know that we are letting go of it.  Based on this,
67      // it will adjust it's PHI nodes.
68      assert(BI->getParent() && "Terminator not inserted in block!");
69      OldDest->removePredecessor(BI->getParent());
70
71      // Replace the conditional branch with an unconditional one.
72      BranchInst::Create(Destination, BI);
73      BI->eraseFromParent();
74      return true;
75    }
76
77    if (Dest2 == Dest1) {       // Conditional branch to same location?
78      // This branch matches something like this:
79      //     br bool %cond, label %Dest, label %Dest
80      // and changes it into:  br label %Dest
81
82      // Let the basic block know that we are letting go of one copy of it.
83      assert(BI->getParent() && "Terminator not inserted in block!");
84      Dest1->removePredecessor(BI->getParent());
85
86      // Replace the conditional branch with an unconditional one.
87      BranchInst::Create(Dest1, BI);
88      BI->eraseFromParent();
89      return true;
90    }
91    return false;
92  }
93
94  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
95    // If we are switching on a constant, we can convert the switch into a
96    // single branch instruction!
97    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
98    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
99    BasicBlock *DefaultDest = TheOnlyDest;
100    assert(TheOnlyDest == SI->getDefaultDest() &&
101           "Default destination is not successor #0?");
102
103    // Figure out which case it goes to.
104    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
105      // Found case matching a constant operand?
106      if (SI->getSuccessorValue(i) == CI) {
107        TheOnlyDest = SI->getSuccessor(i);
108        break;
109      }
110
111      // Check to see if this branch is going to the same place as the default
112      // dest.  If so, eliminate it as an explicit compare.
113      if (SI->getSuccessor(i) == DefaultDest) {
114        // Remove this entry.
115        DefaultDest->removePredecessor(SI->getParent());
116        SI->removeCase(i);
117        --i; --e;  // Don't skip an entry...
118        continue;
119      }
120
121      // Otherwise, check to see if the switch only branches to one destination.
122      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
123      // destinations.
124      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
125    }
126
127    if (CI && !TheOnlyDest) {
128      // Branching on a constant, but not any of the cases, go to the default
129      // successor.
130      TheOnlyDest = SI->getDefaultDest();
131    }
132
133    // If we found a single destination that we can fold the switch into, do so
134    // now.
135    if (TheOnlyDest) {
136      // Insert the new branch.
137      BranchInst::Create(TheOnlyDest, SI);
138      BasicBlock *BB = SI->getParent();
139
140      // Remove entries from PHI nodes which we no longer branch to...
141      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
142        // Found case matching a constant operand?
143        BasicBlock *Succ = SI->getSuccessor(i);
144        if (Succ == TheOnlyDest)
145          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
146        else
147          Succ->removePredecessor(BB);
148      }
149
150      // Delete the old switch.
151      BB->getInstList().erase(SI);
152      return true;
153    }
154
155    if (SI->getNumSuccessors() == 2) {
156      // Otherwise, we can fold this switch into a conditional branch
157      // instruction if it has only one non-default destination.
158      Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
159                                 SI->getSuccessorValue(1), "cond");
160      // Insert the new branch.
161      BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
162
163      // Delete the old switch.
164      SI->eraseFromParent();
165      return true;
166    }
167    return false;
168  }
169
170  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
171    // indirectbr blockaddress(@F, @BB) -> br label @BB
172    if (BlockAddress *BA =
173          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
174      BasicBlock *TheOnlyDest = BA->getBasicBlock();
175      // Insert the new branch.
176      BranchInst::Create(TheOnlyDest, IBI);
177
178      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
179        if (IBI->getDestination(i) == TheOnlyDest)
180          TheOnlyDest = 0;
181        else
182          IBI->getDestination(i)->removePredecessor(IBI->getParent());
183      }
184      IBI->eraseFromParent();
185
186      // If we didn't find our destination in the IBI successor list, then we
187      // have undefined behavior.  Replace the unconditional branch with an
188      // 'unreachable' instruction.
189      if (TheOnlyDest) {
190        BB->getTerminator()->eraseFromParent();
191        new UnreachableInst(BB->getContext(), BB);
192      }
193
194      return true;
195    }
196  }
197
198  return false;
199}
200
201
202//===----------------------------------------------------------------------===//
203//  Local dead code elimination.
204//
205
206/// isInstructionTriviallyDead - Return true if the result produced by the
207/// instruction is not used, and the instruction has no side effects.
208///
209bool llvm::isInstructionTriviallyDead(Instruction *I) {
210  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
211
212  // We don't want debug info removed by anything this general.
213  if (isa<DbgInfoIntrinsic>(I)) return false;
214
215  if (!I->mayHaveSideEffects()) return true;
216
217  // Special case intrinsics that "may have side effects" but can be deleted
218  // when dead.
219  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
220    // Safe to delete llvm.stacksave if dead.
221    if (II->getIntrinsicID() == Intrinsic::stacksave)
222      return true;
223  return false;
224}
225
226/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
227/// trivially dead instruction, delete it.  If that makes any of its operands
228/// trivially dead, delete them too, recursively.  Return true if any
229/// instructions were deleted.
230bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
231  Instruction *I = dyn_cast<Instruction>(V);
232  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
233    return false;
234
235  SmallVector<Instruction*, 16> DeadInsts;
236  DeadInsts.push_back(I);
237
238  do {
239    I = DeadInsts.pop_back_val();
240
241    // Null out all of the instruction's operands to see if any operand becomes
242    // dead as we go.
243    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
244      Value *OpV = I->getOperand(i);
245      I->setOperand(i, 0);
246
247      if (!OpV->use_empty()) continue;
248
249      // If the operand is an instruction that became dead as we nulled out the
250      // operand, and if it is 'trivially' dead, delete it in a future loop
251      // iteration.
252      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
253        if (isInstructionTriviallyDead(OpI))
254          DeadInsts.push_back(OpI);
255    }
256
257    I->eraseFromParent();
258  } while (!DeadInsts.empty());
259
260  return true;
261}
262
263/// areAllUsesEqual - Check whether the uses of a value are all the same.
264/// This is similar to Instruction::hasOneUse() except this will also return
265/// true when there are multiple uses that all refer to the same value.
266static bool areAllUsesEqual(Instruction *I) {
267  Value::use_iterator UI = I->use_begin();
268  Value::use_iterator UE = I->use_end();
269  if (UI == UE)
270    return false;
271
272  User *TheUse = *UI;
273  for (++UI; UI != UE; ++UI) {
274    if (*UI != TheUse)
275      return false;
276  }
277  return true;
278}
279
280/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
281/// dead PHI node, due to being a def-use chain of single-use nodes that
282/// either forms a cycle or is terminated by a trivially dead instruction,
283/// delete it.  If that makes any of its operands trivially dead, delete them
284/// too, recursively.  Return true if the PHI node is actually deleted.
285bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
286  // We can remove a PHI if it is on a cycle in the def-use graph
287  // where each node in the cycle has degree one, i.e. only one use,
288  // and is an instruction with no side effects.
289  if (!areAllUsesEqual(PN))
290    return false;
291
292  bool Changed = false;
293  SmallPtrSet<PHINode *, 4> PHIs;
294  PHIs.insert(PN);
295  for (Instruction *J = cast<Instruction>(*PN->use_begin());
296       areAllUsesEqual(J) && !J->mayHaveSideEffects();
297       J = cast<Instruction>(*J->use_begin()))
298    // If we find a PHI more than once, we're on a cycle that
299    // won't prove fruitful.
300    if (PHINode *JP = dyn_cast<PHINode>(J))
301      if (!PHIs.insert(JP)) {
302        // Break the cycle and delete the PHI and its operands.
303        JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
304        (void)RecursivelyDeleteTriviallyDeadInstructions(JP);
305        Changed = true;
306        break;
307      }
308  return Changed;
309}
310
311/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
312/// simplify any instructions in it and recursively delete dead instructions.
313///
314/// This returns true if it changed the code, note that it can delete
315/// instructions in other blocks as well in this block.
316bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
317  bool MadeChange = false;
318  for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
319    Instruction *Inst = BI++;
320
321    if (Value *V = SimplifyInstruction(Inst, TD)) {
322      WeakVH BIHandle(BI);
323      ReplaceAndSimplifyAllUses(Inst, V, TD);
324      MadeChange = true;
325      if (BIHandle != BI)
326        BI = BB->begin();
327      continue;
328    }
329
330    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
331  }
332  return MadeChange;
333}
334
335//===----------------------------------------------------------------------===//
336//  Control Flow Graph Restructuring.
337//
338
339
340/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
341/// method is called when we're about to delete Pred as a predecessor of BB.  If
342/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
343///
344/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
345/// nodes that collapse into identity values.  For example, if we have:
346///   x = phi(1, 0, 0, 0)
347///   y = and x, z
348///
349/// .. and delete the predecessor corresponding to the '1', this will attempt to
350/// recursively fold the and to 0.
351void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
352                                        TargetData *TD) {
353  // This only adjusts blocks with PHI nodes.
354  if (!isa<PHINode>(BB->begin()))
355    return;
356
357  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
358  // them down.  This will leave us with single entry phi nodes and other phis
359  // that can be removed.
360  BB->removePredecessor(Pred, true);
361
362  WeakVH PhiIt = &BB->front();
363  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
364    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
365
366    Value *PNV = SimplifyInstruction(PN, TD);
367    if (PNV == 0) continue;
368
369    // If we're able to simplify the phi to a single value, substitute the new
370    // value into all of its uses.
371    assert(PNV != PN && "SimplifyInstruction broken!");
372
373    Value *OldPhiIt = PhiIt;
374    ReplaceAndSimplifyAllUses(PN, PNV, TD);
375
376    // If recursive simplification ended up deleting the next PHI node we would
377    // iterate to, then our iterator is invalid, restart scanning from the top
378    // of the block.
379    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
380  }
381}
382
383
384/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
385/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
386/// between them, moving the instructions in the predecessor into DestBB and
387/// deleting the predecessor block.
388///
389void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
390  // If BB has single-entry PHI nodes, fold them.
391  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
392    Value *NewVal = PN->getIncomingValue(0);
393    // Replace self referencing PHI with undef, it must be dead.
394    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
395    PN->replaceAllUsesWith(NewVal);
396    PN->eraseFromParent();
397  }
398
399  BasicBlock *PredBB = DestBB->getSinglePredecessor();
400  assert(PredBB && "Block doesn't have a single predecessor!");
401
402  // Splice all the instructions from PredBB to DestBB.
403  PredBB->getTerminator()->eraseFromParent();
404  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
405
406  // Zap anything that took the address of DestBB.  Not doing this will give the
407  // address an invalid value.
408  if (DestBB->hasAddressTaken()) {
409    BlockAddress *BA = BlockAddress::get(DestBB);
410    Constant *Replacement =
411      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
412    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
413                                                     BA->getType()));
414    BA->destroyConstant();
415  }
416
417  // Anything that branched to PredBB now branches to DestBB.
418  PredBB->replaceAllUsesWith(DestBB);
419
420  if (P) {
421    DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
422    if (DT) {
423      BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
424      DT->changeImmediateDominator(DestBB, PredBBIDom);
425      DT->eraseNode(PredBB);
426    }
427    ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
428    if (PI) {
429      PI->replaceAllUses(PredBB, DestBB);
430      PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
431    }
432  }
433  // Nuke BB.
434  PredBB->eraseFromParent();
435}
436
437/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
438/// almost-empty BB ending in an unconditional branch to Succ, into succ.
439///
440/// Assumption: Succ is the single successor for BB.
441///
442static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
443  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
444
445  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
446        << Succ->getName() << "\n");
447  // Shortcut, if there is only a single predecessor it must be BB and merging
448  // is always safe
449  if (Succ->getSinglePredecessor()) return true;
450
451  // Make a list of the predecessors of BB
452  typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
453  BlockSet BBPreds(pred_begin(BB), pred_end(BB));
454
455  // Use that list to make another list of common predecessors of BB and Succ
456  BlockSet CommonPreds;
457  for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
458       PI != PE; ++PI) {
459    BasicBlock *P = *PI;
460    if (BBPreds.count(P))
461      CommonPreds.insert(P);
462  }
463
464  // Shortcut, if there are no common predecessors, merging is always safe
465  if (CommonPreds.empty())
466    return true;
467
468  // Look at all the phi nodes in Succ, to see if they present a conflict when
469  // merging these blocks
470  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
471    PHINode *PN = cast<PHINode>(I);
472
473    // If the incoming value from BB is again a PHINode in
474    // BB which has the same incoming value for *PI as PN does, we can
475    // merge the phi nodes and then the blocks can still be merged
476    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
477    if (BBPN && BBPN->getParent() == BB) {
478      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
479            PI != PE; PI++) {
480        if (BBPN->getIncomingValueForBlock(*PI)
481              != PN->getIncomingValueForBlock(*PI)) {
482          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
483                << Succ->getName() << " is conflicting with "
484                << BBPN->getName() << " with regard to common predecessor "
485                << (*PI)->getName() << "\n");
486          return false;
487        }
488      }
489    } else {
490      Value* Val = PN->getIncomingValueForBlock(BB);
491      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
492            PI != PE; PI++) {
493        // See if the incoming value for the common predecessor is equal to the
494        // one for BB, in which case this phi node will not prevent the merging
495        // of the block.
496        if (Val != PN->getIncomingValueForBlock(*PI)) {
497          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
498                << Succ->getName() << " is conflicting with regard to common "
499                << "predecessor " << (*PI)->getName() << "\n");
500          return false;
501        }
502      }
503    }
504  }
505
506  return true;
507}
508
509/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
510/// unconditional branch, and contains no instructions other than PHI nodes,
511/// potential debug intrinsics and the branch.  If possible, eliminate BB by
512/// rewriting all the predecessors to branch to the successor block and return
513/// true.  If we can't transform, return false.
514bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
515  assert(BB != &BB->getParent()->getEntryBlock() &&
516         "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
517
518  // We can't eliminate infinite loops.
519  BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
520  if (BB == Succ) return false;
521
522  // Check to see if merging these blocks would cause conflicts for any of the
523  // phi nodes in BB or Succ. If not, we can safely merge.
524  if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
525
526  // Check for cases where Succ has multiple predecessors and a PHI node in BB
527  // has uses which will not disappear when the PHI nodes are merged.  It is
528  // possible to handle such cases, but difficult: it requires checking whether
529  // BB dominates Succ, which is non-trivial to calculate in the case where
530  // Succ has multiple predecessors.  Also, it requires checking whether
531  // constructing the necessary self-referential PHI node doesn't intoduce any
532  // conflicts; this isn't too difficult, but the previous code for doing this
533  // was incorrect.
534  //
535  // Note that if this check finds a live use, BB dominates Succ, so BB is
536  // something like a loop pre-header (or rarely, a part of an irreducible CFG);
537  // folding the branch isn't profitable in that case anyway.
538  if (!Succ->getSinglePredecessor()) {
539    BasicBlock::iterator BBI = BB->begin();
540    while (isa<PHINode>(*BBI)) {
541      for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
542           UI != E; ++UI) {
543        if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
544          if (PN->getIncomingBlock(UI) != BB)
545            return false;
546        } else {
547          return false;
548        }
549      }
550      ++BBI;
551    }
552  }
553
554  DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
555
556  if (isa<PHINode>(Succ->begin())) {
557    // If there is more than one pred of succ, and there are PHI nodes in
558    // the successor, then we need to add incoming edges for the PHI nodes
559    //
560    const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
561
562    // Loop over all of the PHI nodes in the successor of BB.
563    for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
564      PHINode *PN = cast<PHINode>(I);
565      Value *OldVal = PN->removeIncomingValue(BB, false);
566      assert(OldVal && "No entry in PHI for Pred BB!");
567
568      // If this incoming value is one of the PHI nodes in BB, the new entries
569      // in the PHI node are the entries from the old PHI.
570      if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
571        PHINode *OldValPN = cast<PHINode>(OldVal);
572        for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
573          // Note that, since we are merging phi nodes and BB and Succ might
574          // have common predecessors, we could end up with a phi node with
575          // identical incoming branches. This will be cleaned up later (and
576          // will trigger asserts if we try to clean it up now, without also
577          // simplifying the corresponding conditional branch).
578          PN->addIncoming(OldValPN->getIncomingValue(i),
579                          OldValPN->getIncomingBlock(i));
580      } else {
581        // Add an incoming value for each of the new incoming values.
582        for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
583          PN->addIncoming(OldVal, BBPreds[i]);
584      }
585    }
586  }
587
588  while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
589    if (Succ->getSinglePredecessor()) {
590      // BB is the only predecessor of Succ, so Succ will end up with exactly
591      // the same predecessors BB had.
592      Succ->getInstList().splice(Succ->begin(),
593                                 BB->getInstList(), BB->begin());
594    } else {
595      // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
596      assert(PN->use_empty() && "There shouldn't be any uses here!");
597      PN->eraseFromParent();
598    }
599  }
600
601  // Everything that jumped to BB now goes to Succ.
602  BB->replaceAllUsesWith(Succ);
603  if (!Succ->hasName()) Succ->takeName(BB);
604  BB->eraseFromParent();              // Delete the old basic block.
605  return true;
606}
607
608/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
609/// nodes in this block. This doesn't try to be clever about PHI nodes
610/// which differ only in the order of the incoming values, but instcombine
611/// orders them so it usually won't matter.
612///
613bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
614  bool Changed = false;
615
616  // This implementation doesn't currently consider undef operands
617  // specially. Theroetically, two phis which are identical except for
618  // one having an undef where the other doesn't could be collapsed.
619
620  // Map from PHI hash values to PHI nodes. If multiple PHIs have
621  // the same hash value, the element is the first PHI in the
622  // linked list in CollisionMap.
623  DenseMap<uintptr_t, PHINode *> HashMap;
624
625  // Maintain linked lists of PHI nodes with common hash values.
626  DenseMap<PHINode *, PHINode *> CollisionMap;
627
628  // Examine each PHI.
629  for (BasicBlock::iterator I = BB->begin();
630       PHINode *PN = dyn_cast<PHINode>(I++); ) {
631    // Compute a hash value on the operands. Instcombine will likely have sorted
632    // them, which helps expose duplicates, but we have to check all the
633    // operands to be safe in case instcombine hasn't run.
634    uintptr_t Hash = 0;
635    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
636      // This hash algorithm is quite weak as hash functions go, but it seems
637      // to do a good enough job for this particular purpose, and is very quick.
638      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
639      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
640    }
641    // If we've never seen this hash value before, it's a unique PHI.
642    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
643      HashMap.insert(std::make_pair(Hash, PN));
644    if (Pair.second) continue;
645    // Otherwise it's either a duplicate or a hash collision.
646    for (PHINode *OtherPN = Pair.first->second; ; ) {
647      if (OtherPN->isIdenticalTo(PN)) {
648        // A duplicate. Replace this PHI with its duplicate.
649        PN->replaceAllUsesWith(OtherPN);
650        PN->eraseFromParent();
651        Changed = true;
652        break;
653      }
654      // A non-duplicate hash collision.
655      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
656      if (I == CollisionMap.end()) {
657        // Set this PHI to be the head of the linked list of colliding PHIs.
658        PHINode *Old = Pair.first->second;
659        Pair.first->second = PN;
660        CollisionMap[PN] = Old;
661        break;
662      }
663      // Procede to the next PHI in the list.
664      OtherPN = I->second;
665    }
666  }
667
668  return Changed;
669}
670
671/// enforceKnownAlignment - If the specified pointer points to an object that
672/// we control, modify the object's alignment to PrefAlign. This isn't
673/// often possible though. If alignment is important, a more reliable approach
674/// is to simply align all global variables and allocation instructions to
675/// their preferred alignment from the beginning.
676///
677static unsigned enforceKnownAlignment(Value *V, unsigned Align,
678                                      unsigned PrefAlign) {
679
680  User *U = dyn_cast<User>(V);
681  if (!U) return Align;
682
683  switch (Operator::getOpcode(U)) {
684  default: break;
685  case Instruction::BitCast:
686    return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
687  case Instruction::GetElementPtr: {
688    // If all indexes are zero, it is just the alignment of the base pointer.
689    bool AllZeroOperands = true;
690    for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
691      if (!isa<Constant>(*i) ||
692          !cast<Constant>(*i)->isNullValue()) {
693        AllZeroOperands = false;
694        break;
695      }
696
697    if (AllZeroOperands) {
698      // Treat this like a bitcast.
699      return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
700    }
701    return Align;
702  }
703  case Instruction::Alloca: {
704    AllocaInst *AI = cast<AllocaInst>(V);
705    // If there is a requested alignment and if this is an alloca, round up.
706    if (AI->getAlignment() >= PrefAlign)
707      return AI->getAlignment();
708    AI->setAlignment(PrefAlign);
709    return PrefAlign;
710  }
711  }
712
713  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
714    // If there is a large requested alignment and we can, bump up the alignment
715    // of the global.
716    if (GV->isDeclaration()) return Align;
717
718    if (GV->getAlignment() >= PrefAlign)
719      return GV->getAlignment();
720    // We can only increase the alignment of the global if it has no alignment
721    // specified or if it is not assigned a section.  If it is assigned a
722    // section, the global could be densely packed with other objects in the
723    // section, increasing the alignment could cause padding issues.
724    if (!GV->hasSection() || GV->getAlignment() == 0)
725      GV->setAlignment(PrefAlign);
726    return GV->getAlignment();
727  }
728
729  return Align;
730}
731
732/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
733/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
734/// and it is more than the alignment of the ultimate object, see if we can
735/// increase the alignment of the ultimate object, making this check succeed.
736unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
737                                          const TargetData *TD) {
738  assert(V->getType()->isPointerTy() &&
739         "getOrEnforceKnownAlignment expects a pointer!");
740  unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
741  APInt Mask = APInt::getAllOnesValue(BitWidth);
742  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
743  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
744  unsigned TrailZ = KnownZero.countTrailingOnes();
745
746  // Avoid trouble with rediculously large TrailZ values, such as
747  // those computed from a null pointer.
748  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
749
750  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
751
752  // LLVM doesn't support alignments larger than this currently.
753  Align = std::min(Align, +Value::MaximumAlignment);
754
755  if (PrefAlign > Align)
756    Align = enforceKnownAlignment(V, Align, PrefAlign);
757
758  // We don't need to make any adjustment.
759  return Align;
760}
761
762