Local.cpp revision cd35e09a4a3c640b9da0b1dfe3548a605c929ae5
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/Metadata.h"
24#include "llvm/Operator.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/Analysis/DebugInfo.h"
28#include "llvm/Analysis/DIBuilder.h"
29#include "llvm/Analysis/Dominators.h"
30#include "llvm/Analysis/ConstantFolding.h"
31#include "llvm/Analysis/InstructionSimplify.h"
32#include "llvm/Analysis/ProfileInfo.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/Target/TargetData.h"
35#include "llvm/Support/CFG.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/GetElementPtrTypeIterator.h"
38#include "llvm/Support/IRBuilder.h"
39#include "llvm/Support/MathExtras.h"
40#include "llvm/Support/ValueHandle.h"
41#include "llvm/Support/raw_ostream.h"
42using namespace llvm;
43
44//===----------------------------------------------------------------------===//
45//  Local constant propagation.
46//
47
48/// ConstantFoldTerminator - If a terminator instruction is predicated on a
49/// constant value, convert it into an unconditional branch to the constant
50/// destination.  This is a nontrivial operation because the successors of this
51/// basic block must have their PHI nodes updated.
52/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
53/// conditions and indirectbr addresses this might make dead if
54/// DeleteDeadConditions is true.
55bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions) {
56  TerminatorInst *T = BB->getTerminator();
57  IRBuilder<> Builder(T);
58
59  // Branch - See if we are conditional jumping on constant
60  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
61    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
62    BasicBlock *Dest1 = BI->getSuccessor(0);
63    BasicBlock *Dest2 = BI->getSuccessor(1);
64
65    if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
66      // Are we branching on constant?
67      // YES.  Change to unconditional branch...
68      BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
69      BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
70
71      //cerr << "Function: " << T->getParent()->getParent()
72      //     << "\nRemoving branch from " << T->getParent()
73      //     << "\n\nTo: " << OldDest << endl;
74
75      // Let the basic block know that we are letting go of it.  Based on this,
76      // it will adjust it's PHI nodes.
77      OldDest->removePredecessor(BB);
78
79      // Replace the conditional branch with an unconditional one.
80      Builder.CreateBr(Destination);
81      BI->eraseFromParent();
82      return true;
83    }
84
85    if (Dest2 == Dest1) {       // Conditional branch to same location?
86      // This branch matches something like this:
87      //     br bool %cond, label %Dest, label %Dest
88      // and changes it into:  br label %Dest
89
90      // Let the basic block know that we are letting go of one copy of it.
91      assert(BI->getParent() && "Terminator not inserted in block!");
92      Dest1->removePredecessor(BI->getParent());
93
94      // Replace the conditional branch with an unconditional one.
95      Builder.CreateBr(Dest1);
96      Value *Cond = BI->getCondition();
97      BI->eraseFromParent();
98      if (DeleteDeadConditions)
99        RecursivelyDeleteTriviallyDeadInstructions(Cond);
100      return true;
101    }
102    return false;
103  }
104
105  if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
106    // If we are switching on a constant, we can convert the switch into a
107    // single branch instruction!
108    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
109    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
110    BasicBlock *DefaultDest = TheOnlyDest;
111    assert(TheOnlyDest == SI->getDefaultDest() &&
112           "Default destination is not successor #0?");
113
114    // Figure out which case it goes to.
115    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
116      // Found case matching a constant operand?
117      if (SI->getSuccessorValue(i) == CI) {
118        TheOnlyDest = SI->getSuccessor(i);
119        break;
120      }
121
122      // Check to see if this branch is going to the same place as the default
123      // dest.  If so, eliminate it as an explicit compare.
124      if (SI->getSuccessor(i) == DefaultDest) {
125        // Remove this entry.
126        DefaultDest->removePredecessor(SI->getParent());
127        SI->removeCase(i);
128        --i; --e;  // Don't skip an entry...
129        continue;
130      }
131
132      // Otherwise, check to see if the switch only branches to one destination.
133      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
134      // destinations.
135      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
136    }
137
138    if (CI && !TheOnlyDest) {
139      // Branching on a constant, but not any of the cases, go to the default
140      // successor.
141      TheOnlyDest = SI->getDefaultDest();
142    }
143
144    // If we found a single destination that we can fold the switch into, do so
145    // now.
146    if (TheOnlyDest) {
147      // Insert the new branch.
148      Builder.CreateBr(TheOnlyDest);
149      BasicBlock *BB = SI->getParent();
150
151      // Remove entries from PHI nodes which we no longer branch to...
152      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
153        // Found case matching a constant operand?
154        BasicBlock *Succ = SI->getSuccessor(i);
155        if (Succ == TheOnlyDest)
156          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
157        else
158          Succ->removePredecessor(BB);
159      }
160
161      // Delete the old switch.
162      Value *Cond = SI->getCondition();
163      SI->eraseFromParent();
164      if (DeleteDeadConditions)
165        RecursivelyDeleteTriviallyDeadInstructions(Cond);
166      return true;
167    }
168
169    if (SI->getNumSuccessors() == 2) {
170      // Otherwise, we can fold this switch into a conditional branch
171      // instruction if it has only one non-default destination.
172      Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
173                                         SI->getSuccessorValue(1), "cond");
174
175      // Insert the new branch.
176      Builder.CreateCondBr(Cond, SI->getSuccessor(1), SI->getSuccessor(0));
177
178      // Delete the old switch.
179      SI->eraseFromParent();
180      return true;
181    }
182    return false;
183  }
184
185  if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
186    // indirectbr blockaddress(@F, @BB) -> br label @BB
187    if (BlockAddress *BA =
188          dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
189      BasicBlock *TheOnlyDest = BA->getBasicBlock();
190      // Insert the new branch.
191      Builder.CreateBr(TheOnlyDest);
192
193      for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
194        if (IBI->getDestination(i) == TheOnlyDest)
195          TheOnlyDest = 0;
196        else
197          IBI->getDestination(i)->removePredecessor(IBI->getParent());
198      }
199      Value *Address = IBI->getAddress();
200      IBI->eraseFromParent();
201      if (DeleteDeadConditions)
202        RecursivelyDeleteTriviallyDeadInstructions(Address);
203
204      // If we didn't find our destination in the IBI successor list, then we
205      // have undefined behavior.  Replace the unconditional branch with an
206      // 'unreachable' instruction.
207      if (TheOnlyDest) {
208        BB->getTerminator()->eraseFromParent();
209        new UnreachableInst(BB->getContext(), BB);
210      }
211
212      return true;
213    }
214  }
215
216  return false;
217}
218
219
220//===----------------------------------------------------------------------===//
221//  Local dead code elimination.
222//
223
224/// isInstructionTriviallyDead - Return true if the result produced by the
225/// instruction is not used, and the instruction has no side effects.
226///
227bool llvm::isInstructionTriviallyDead(Instruction *I) {
228  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
229
230  // We don't want debug info removed by anything this general, unless
231  // debug info is empty.
232  if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
233    if (DDI->getAddress())
234      return false;
235    return true;
236  }
237  if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
238    if (DVI->getValue())
239      return false;
240    return true;
241  }
242
243  if (!I->mayHaveSideEffects()) return true;
244
245  // Special case intrinsics that "may have side effects" but can be deleted
246  // when dead.
247  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
248    // Safe to delete llvm.stacksave if dead.
249    if (II->getIntrinsicID() == Intrinsic::stacksave)
250      return true;
251  return false;
252}
253
254/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
255/// trivially dead instruction, delete it.  If that makes any of its operands
256/// trivially dead, delete them too, recursively.  Return true if any
257/// instructions were deleted.
258bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
259  Instruction *I = dyn_cast<Instruction>(V);
260  if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
261    return false;
262
263  SmallVector<Instruction*, 16> DeadInsts;
264  DeadInsts.push_back(I);
265
266  do {
267    I = DeadInsts.pop_back_val();
268
269    // Null out all of the instruction's operands to see if any operand becomes
270    // dead as we go.
271    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
272      Value *OpV = I->getOperand(i);
273      I->setOperand(i, 0);
274
275      if (!OpV->use_empty()) continue;
276
277      // If the operand is an instruction that became dead as we nulled out the
278      // operand, and if it is 'trivially' dead, delete it in a future loop
279      // iteration.
280      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
281        if (isInstructionTriviallyDead(OpI))
282          DeadInsts.push_back(OpI);
283    }
284
285    I->eraseFromParent();
286  } while (!DeadInsts.empty());
287
288  return true;
289}
290
291/// areAllUsesEqual - Check whether the uses of a value are all the same.
292/// This is similar to Instruction::hasOneUse() except this will also return
293/// true when there are no uses or multiple uses that all refer to the same
294/// value.
295static bool areAllUsesEqual(Instruction *I) {
296  Value::use_iterator UI = I->use_begin();
297  Value::use_iterator UE = I->use_end();
298  if (UI == UE)
299    return true;
300
301  User *TheUse = *UI;
302  for (++UI; UI != UE; ++UI) {
303    if (*UI != TheUse)
304      return false;
305  }
306  return true;
307}
308
309/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
310/// dead PHI node, due to being a def-use chain of single-use nodes that
311/// either forms a cycle or is terminated by a trivially dead instruction,
312/// delete it.  If that makes any of its operands trivially dead, delete them
313/// too, recursively.  Return true if a change was made.
314bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
315  SmallPtrSet<Instruction*, 4> Visited;
316  for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
317       I = cast<Instruction>(*I->use_begin())) {
318    if (I->use_empty())
319      return RecursivelyDeleteTriviallyDeadInstructions(I);
320
321    // If we find an instruction more than once, we're on a cycle that
322    // won't prove fruitful.
323    if (!Visited.insert(I)) {
324      // Break the cycle and delete the instruction and its operands.
325      I->replaceAllUsesWith(UndefValue::get(I->getType()));
326      (void)RecursivelyDeleteTriviallyDeadInstructions(I);
327      return true;
328    }
329  }
330  return false;
331}
332
333/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
334/// simplify any instructions in it and recursively delete dead instructions.
335///
336/// This returns true if it changed the code, note that it can delete
337/// instructions in other blocks as well in this block.
338bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
339  bool MadeChange = false;
340  for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
341    Instruction *Inst = BI++;
342
343    if (Value *V = SimplifyInstruction(Inst, TD)) {
344      WeakVH BIHandle(BI);
345      ReplaceAndSimplifyAllUses(Inst, V, TD);
346      MadeChange = true;
347      if (BIHandle != BI)
348        BI = BB->begin();
349      continue;
350    }
351
352    if (Inst->isTerminator())
353      break;
354
355    WeakVH BIHandle(BI);
356    MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
357    if (BIHandle != BI)
358      BI = BB->begin();
359  }
360  return MadeChange;
361}
362
363//===----------------------------------------------------------------------===//
364//  Control Flow Graph Restructuring.
365//
366
367
368/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
369/// method is called when we're about to delete Pred as a predecessor of BB.  If
370/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
371///
372/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
373/// nodes that collapse into identity values.  For example, if we have:
374///   x = phi(1, 0, 0, 0)
375///   y = and x, z
376///
377/// .. and delete the predecessor corresponding to the '1', this will attempt to
378/// recursively fold the and to 0.
379void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
380                                        TargetData *TD) {
381  // This only adjusts blocks with PHI nodes.
382  if (!isa<PHINode>(BB->begin()))
383    return;
384
385  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
386  // them down.  This will leave us with single entry phi nodes and other phis
387  // that can be removed.
388  BB->removePredecessor(Pred, true);
389
390  WeakVH PhiIt = &BB->front();
391  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
392    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
393
394    Value *PNV = SimplifyInstruction(PN, TD);
395    if (PNV == 0) continue;
396
397    // If we're able to simplify the phi to a single value, substitute the new
398    // value into all of its uses.
399    assert(PNV != PN && "SimplifyInstruction broken!");
400
401    Value *OldPhiIt = PhiIt;
402    ReplaceAndSimplifyAllUses(PN, PNV, TD);
403
404    // If recursive simplification ended up deleting the next PHI node we would
405    // iterate to, then our iterator is invalid, restart scanning from the top
406    // of the block.
407    if (PhiIt != OldPhiIt) PhiIt = &BB->front();
408  }
409}
410
411
412/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
413/// predecessor is known to have one successor (DestBB!).  Eliminate the edge
414/// between them, moving the instructions in the predecessor into DestBB and
415/// deleting the predecessor block.
416///
417void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
418  // If BB has single-entry PHI nodes, fold them.
419  while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
420    Value *NewVal = PN->getIncomingValue(0);
421    // Replace self referencing PHI with undef, it must be dead.
422    if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
423    PN->replaceAllUsesWith(NewVal);
424    PN->eraseFromParent();
425  }
426
427  BasicBlock *PredBB = DestBB->getSinglePredecessor();
428  assert(PredBB && "Block doesn't have a single predecessor!");
429
430  // Zap anything that took the address of DestBB.  Not doing this will give the
431  // address an invalid value.
432  if (DestBB->hasAddressTaken()) {
433    BlockAddress *BA = BlockAddress::get(DestBB);
434    Constant *Replacement =
435      ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
436    BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
437                                                     BA->getType()));
438    BA->destroyConstant();
439  }
440
441  // Anything that branched to PredBB now branches to DestBB.
442  PredBB->replaceAllUsesWith(DestBB);
443
444  // Splice all the instructions from PredBB to DestBB.
445  PredBB->getTerminator()->eraseFromParent();
446  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
447
448  if (P) {
449    DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
450    if (DT) {
451      BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
452      DT->changeImmediateDominator(DestBB, PredBBIDom);
453      DT->eraseNode(PredBB);
454    }
455    ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
456    if (PI) {
457      PI->replaceAllUses(PredBB, DestBB);
458      PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
459    }
460  }
461  // Nuke BB.
462  PredBB->eraseFromParent();
463}
464
465/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
466/// almost-empty BB ending in an unconditional branch to Succ, into succ.
467///
468/// Assumption: Succ is the single successor for BB.
469///
470static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
471  assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
472
473  DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
474        << Succ->getName() << "\n");
475  // Shortcut, if there is only a single predecessor it must be BB and merging
476  // is always safe
477  if (Succ->getSinglePredecessor()) return true;
478
479  // Make a list of the predecessors of BB
480  typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
481  BlockSet BBPreds(pred_begin(BB), pred_end(BB));
482
483  // Use that list to make another list of common predecessors of BB and Succ
484  BlockSet CommonPreds;
485  for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
486       PI != PE; ++PI) {
487    BasicBlock *P = *PI;
488    if (BBPreds.count(P))
489      CommonPreds.insert(P);
490  }
491
492  // Shortcut, if there are no common predecessors, merging is always safe
493  if (CommonPreds.empty())
494    return true;
495
496  // Look at all the phi nodes in Succ, to see if they present a conflict when
497  // merging these blocks
498  for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
499    PHINode *PN = cast<PHINode>(I);
500
501    // If the incoming value from BB is again a PHINode in
502    // BB which has the same incoming value for *PI as PN does, we can
503    // merge the phi nodes and then the blocks can still be merged
504    PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
505    if (BBPN && BBPN->getParent() == BB) {
506      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
507            PI != PE; PI++) {
508        if (BBPN->getIncomingValueForBlock(*PI)
509              != PN->getIncomingValueForBlock(*PI)) {
510          DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
511                << Succ->getName() << " is conflicting with "
512                << BBPN->getName() << " with regard to common predecessor "
513                << (*PI)->getName() << "\n");
514          return false;
515        }
516      }
517    } else {
518      Value* Val = PN->getIncomingValueForBlock(BB);
519      for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
520            PI != PE; PI++) {
521        // See if the incoming value for the common predecessor is equal to the
522        // 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    // This hash algorithm is quite weak as hash functions go, but it seems
664    // to do a good enough job for this particular purpose, and is very quick.
665    for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
666      Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
667      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
668    }
669    for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
670         I != E; ++I) {
671      Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
672      Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
673    }
674    // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
675    Hash >>= 1;
676    // If we've never seen this hash value before, it's a unique PHI.
677    std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
678      HashMap.insert(std::make_pair(Hash, PN));
679    if (Pair.second) continue;
680    // Otherwise it's either a duplicate or a hash collision.
681    for (PHINode *OtherPN = Pair.first->second; ; ) {
682      if (OtherPN->isIdenticalTo(PN)) {
683        // A duplicate. Replace this PHI with its duplicate.
684        PN->replaceAllUsesWith(OtherPN);
685        PN->eraseFromParent();
686        Changed = true;
687        break;
688      }
689      // A non-duplicate hash collision.
690      DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
691      if (I == CollisionMap.end()) {
692        // Set this PHI to be the head of the linked list of colliding PHIs.
693        PHINode *Old = Pair.first->second;
694        Pair.first->second = PN;
695        CollisionMap[PN] = Old;
696        break;
697      }
698      // Procede to the next PHI in the list.
699      OtherPN = I->second;
700    }
701  }
702
703  return Changed;
704}
705
706/// enforceKnownAlignment - If the specified pointer points to an object that
707/// we control, modify the object's alignment to PrefAlign. This isn't
708/// often possible though. If alignment is important, a more reliable approach
709/// is to simply align all global variables and allocation instructions to
710/// their preferred alignment from the beginning.
711///
712static unsigned enforceKnownAlignment(Value *V, unsigned Align,
713                                      unsigned PrefAlign) {
714  V = V->stripPointerCasts();
715
716  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
717    // If there is a requested alignment and if this is an alloca, round up.
718    if (AI->getAlignment() >= PrefAlign)
719      return AI->getAlignment();
720    AI->setAlignment(PrefAlign);
721    return PrefAlign;
722  }
723
724  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
725    // If there is a large requested alignment and we can, bump up the alignment
726    // of the global.
727    if (GV->isDeclaration()) return Align;
728
729    if (GV->getAlignment() >= PrefAlign)
730      return GV->getAlignment();
731    // We can only increase the alignment of the global if it has no alignment
732    // specified or if it is not assigned a section.  If it is assigned a
733    // section, the global could be densely packed with other objects in the
734    // section, increasing the alignment could cause padding issues.
735    if (!GV->hasSection() || GV->getAlignment() == 0)
736      GV->setAlignment(PrefAlign);
737    return GV->getAlignment();
738  }
739
740  return Align;
741}
742
743/// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
744/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
745/// and it is more than the alignment of the ultimate object, see if we can
746/// increase the alignment of the ultimate object, making this check succeed.
747unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
748                                          const TargetData *TD) {
749  assert(V->getType()->isPointerTy() &&
750         "getOrEnforceKnownAlignment expects a pointer!");
751  unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
752  APInt Mask = APInt::getAllOnesValue(BitWidth);
753  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
754  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
755  unsigned TrailZ = KnownZero.countTrailingOnes();
756
757  // Avoid trouble with rediculously large TrailZ values, such as
758  // those computed from a null pointer.
759  TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
760
761  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
762
763  // LLVM doesn't support alignments larger than this currently.
764  Align = std::min(Align, +Value::MaximumAlignment);
765
766  if (PrefAlign > Align)
767    Align = enforceKnownAlignment(V, Align, PrefAlign);
768
769  // We don't need to make any adjustment.
770  return Align;
771}
772
773///===---------------------------------------------------------------------===//
774///  Dbg Intrinsic utilities
775///
776
777/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
778/// that has an associated llvm.dbg.decl intrinsic.
779bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
780                                           StoreInst *SI, DIBuilder &Builder) {
781  DIVariable DIVar(DDI->getVariable());
782  if (!DIVar.Verify())
783    return false;
784
785  Instruction *DbgVal = NULL;
786  // If an argument is zero extended then use argument directly. The ZExt
787  // may be zapped by an optimization pass in future.
788  Argument *ExtendedArg = NULL;
789  if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
790    ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
791  if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
792    ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
793  if (ExtendedArg)
794    DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
795  else
796    DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
797
798  // Propagate any debug metadata from the store onto the dbg.value.
799  DebugLoc SIDL = SI->getDebugLoc();
800  if (!SIDL.isUnknown())
801    DbgVal->setDebugLoc(SIDL);
802  // Otherwise propagate debug metadata from dbg.declare.
803  else
804    DbgVal->setDebugLoc(DDI->getDebugLoc());
805  return true;
806}
807
808/// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
809/// that has an associated llvm.dbg.decl intrinsic.
810bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
811                                           LoadInst *LI, DIBuilder &Builder) {
812  DIVariable DIVar(DDI->getVariable());
813  if (!DIVar.Verify())
814    return false;
815
816  Instruction *DbgVal =
817    Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
818                                    DIVar, LI);
819
820  // Propagate any debug metadata from the store onto the dbg.value.
821  DebugLoc LIDL = LI->getDebugLoc();
822  if (!LIDL.isUnknown())
823    DbgVal->setDebugLoc(LIDL);
824  // Otherwise propagate debug metadata from dbg.declare.
825  else
826    DbgVal->setDebugLoc(DDI->getDebugLoc());
827  return true;
828}
829
830/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
831/// of llvm.dbg.value intrinsics.
832bool llvm::LowerDbgDeclare(Function &F) {
833  DIBuilder DIB(*F.getParent());
834  SmallVector<DbgDeclareInst *, 4> Dbgs;
835  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
836    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
837      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
838        Dbgs.push_back(DDI);
839    }
840  if (Dbgs.empty())
841    return false;
842
843  for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
844         E = Dbgs.end(); I != E; ++I) {
845    DbgDeclareInst *DDI = *I;
846    if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
847      bool RemoveDDI = true;
848      for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
849           UI != E; ++UI)
850        if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
851          ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
852        else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
853          ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
854        else
855          RemoveDDI = false;
856      if (RemoveDDI)
857        DDI->eraseFromParent();
858    }
859  }
860  return true;
861}
862
863/// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
864/// alloca 'V', if any.
865DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
866  if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
867    for (Value::use_iterator UI = DebugNode->use_begin(),
868         E = DebugNode->use_end(); UI != E; ++UI)
869      if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
870        return DDI;
871
872  return 0;
873}
874