simplify code by using Value::takeName
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Peephole optimize the CFG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "simplifycfg"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include <algorithm>
25 #include <functional>
26 #include <set>
27 #include <map>
28 using namespace llvm;
29
30 /// SafeToMergeTerminators - Return true if it is safe to merge these two
31 /// terminator instructions together.
32 ///
33 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
34   if (SI1 == SI2) return false;  // Can't merge with self!
35   
36   // It is not safe to merge these two switch instructions if they have a common
37   // successor, and if that successor has a PHI node, and if *that* PHI node has
38   // conflicting incoming values from the two switch blocks.
39   BasicBlock *SI1BB = SI1->getParent();
40   BasicBlock *SI2BB = SI2->getParent();
41   std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
42   
43   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
44     if (SI1Succs.count(*I))
45       for (BasicBlock::iterator BBI = (*I)->begin();
46            isa<PHINode>(BBI); ++BBI) {
47         PHINode *PN = cast<PHINode>(BBI);
48         if (PN->getIncomingValueForBlock(SI1BB) !=
49             PN->getIncomingValueForBlock(SI2BB))
50           return false;
51       }
52         
53   return true;
54 }
55
56 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
57 /// now be entries in it from the 'NewPred' block.  The values that will be
58 /// flowing into the PHI nodes will be the same as those coming in from
59 /// ExistPred, an existing predecessor of Succ.
60 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
61                                   BasicBlock *ExistPred) {
62   assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
63          succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
64   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
65   
66   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
67     PHINode *PN = cast<PHINode>(I);
68     Value *V = PN->getIncomingValueForBlock(ExistPred);
69     PN->addIncoming(V, NewPred);
70   }
71 }
72
73 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
74 // almost-empty BB ending in an unconditional branch to Succ, into succ.
75 //
76 // Assumption: Succ is the single successor for BB.
77 //
78 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
79   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
80
81   // Check to see if one of the predecessors of BB is already a predecessor of
82   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
83   // with incompatible values coming in from the two edges!
84   //
85   if (isa<PHINode>(Succ->front())) {
86     std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
87     for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
88          PI != PE; ++PI)
89       if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
90         // Loop over all of the PHI nodes checking to see if there are
91         // incompatible values coming in.
92         for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
93           PHINode *PN = cast<PHINode>(I);
94           // Loop up the entries in the PHI node for BB and for *PI if the
95           // values coming in are non-equal, we cannot merge these two blocks
96           // (instead we should insert a conditional move or something, then
97           // merge the blocks).
98           if (PN->getIncomingValueForBlock(BB) !=
99               PN->getIncomingValueForBlock(*PI))
100             return false;  // Values are not equal...
101         }
102       }
103   }
104     
105   // Finally, if BB has PHI nodes that are used by things other than the PHIs in
106   // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
107   // fold these blocks, as we don't know whether BB dominates Succ or not to
108   // update the PHI nodes correctly.
109   if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
110
111   // If the predecessors of Succ are only BB and Succ itself, we can handle this.
112   bool IsSafe = true;
113   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
114     if (*PI != Succ && *PI != BB) {
115       IsSafe = false;
116       break;
117     }
118   if (IsSafe) return true;
119   
120   // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
121   // BB and Succ have no common predecessors.
122   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
123     PHINode *PN = cast<PHINode>(I);
124     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
125          ++UI)
126       if (cast<Instruction>(*UI)->getParent() != Succ)
127         return false;
128   }
129   
130   // Scan the predecessor sets of BB and Succ, making sure there are no common
131   // predecessors.  Common predecessors would cause us to build a phi node with
132   // differing incoming values, which is not legal.
133   std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
134   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
135     if (BBPreds.count(*PI))
136       return false;
137     
138   return true;
139 }
140
141 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
142 /// branch to Succ, and contains no instructions other than PHI nodes and the
143 /// branch.  If possible, eliminate BB.
144 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
145                                                     BasicBlock *Succ) {
146   // If our successor has PHI nodes, then we need to update them to include
147   // entries for BB's predecessors, not for BB itself.  Be careful though,
148   // if this transformation fails (returns true) then we cannot do this
149   // transformation!
150   //
151   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
152   
153   DOUT << "Killing Trivial BB: \n" << *BB;
154   
155   if (isa<PHINode>(Succ->begin())) {
156     // If there is more than one pred of succ, and there are PHI nodes in
157     // the successor, then we need to add incoming edges for the PHI nodes
158     //
159     const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
160     
161     // Loop over all of the PHI nodes in the successor of BB.
162     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
163       PHINode *PN = cast<PHINode>(I);
164       Value *OldVal = PN->removeIncomingValue(BB, false);
165       assert(OldVal && "No entry in PHI for Pred BB!");
166       
167       // If this incoming value is one of the PHI nodes in BB, the new entries
168       // in the PHI node are the entries from the old PHI.
169       if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
170         PHINode *OldValPN = cast<PHINode>(OldVal);
171         for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
172           PN->addIncoming(OldValPN->getIncomingValue(i),
173                           OldValPN->getIncomingBlock(i));
174       } else {
175         for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
176              End = BBPreds.end(); PredI != End; ++PredI) {
177           // Add an incoming value for each of the new incoming values...
178           PN->addIncoming(OldVal, *PredI);
179         }
180       }
181     }
182   }
183   
184   if (isa<PHINode>(&BB->front())) {
185     std::vector<BasicBlock*>
186     OldSuccPreds(pred_begin(Succ), pred_end(Succ));
187     
188     // Move all PHI nodes in BB to Succ if they are alive, otherwise
189     // delete them.
190     while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
191       if (PN->use_empty()) {
192         // Just remove the dead phi.  This happens if Succ's PHIs were the only
193         // users of the PHI nodes.
194         PN->eraseFromParent();
195       } else {
196         // The instruction is alive, so this means that Succ must have
197         // *ONLY* had BB as a predecessor, and the PHI node is still valid
198         // now.  Simply move it into Succ, because we know that BB
199         // strictly dominated Succ.
200         Succ->getInstList().splice(Succ->begin(),
201                                    BB->getInstList(), BB->begin());
202         
203         // We need to add new entries for the PHI node to account for
204         // predecessors of Succ that the PHI node does not take into
205         // account.  At this point, since we know that BB dominated succ,
206         // this means that we should any newly added incoming edges should
207         // use the PHI node as the value for these edges, because they are
208         // loop back edges.
209         for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
210           if (OldSuccPreds[i] != BB)
211             PN->addIncoming(PN, OldSuccPreds[i]);
212       }
213   }
214     
215   // Everything that jumped to BB now goes to Succ.
216   BB->replaceAllUsesWith(Succ);
217   if (!Succ->hasName()) Succ->takeName(BB);
218   BB->eraseFromParent();              // Delete the old basic block.
219   return true;
220 }
221
222 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
223 /// presumably PHI nodes in it), check to see if the merge at this block is due
224 /// to an "if condition".  If so, return the boolean condition that determines
225 /// which entry into BB will be taken.  Also, return by references the block
226 /// that will be entered from if the condition is true, and the block that will
227 /// be entered if the condition is false.
228 ///
229 ///
230 static Value *GetIfCondition(BasicBlock *BB,
231                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
232   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
233          "Function can only handle blocks with 2 predecessors!");
234   BasicBlock *Pred1 = *pred_begin(BB);
235   BasicBlock *Pred2 = *++pred_begin(BB);
236
237   // We can only handle branches.  Other control flow will be lowered to
238   // branches if possible anyway.
239   if (!isa<BranchInst>(Pred1->getTerminator()) ||
240       !isa<BranchInst>(Pred2->getTerminator()))
241     return 0;
242   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
243   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
244
245   // Eliminate code duplication by ensuring that Pred1Br is conditional if
246   // either are.
247   if (Pred2Br->isConditional()) {
248     // If both branches are conditional, we don't have an "if statement".  In
249     // reality, we could transform this case, but since the condition will be
250     // required anyway, we stand no chance of eliminating it, so the xform is
251     // probably not profitable.
252     if (Pred1Br->isConditional())
253       return 0;
254
255     std::swap(Pred1, Pred2);
256     std::swap(Pred1Br, Pred2Br);
257   }
258
259   if (Pred1Br->isConditional()) {
260     // If we found a conditional branch predecessor, make sure that it branches
261     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
262     if (Pred1Br->getSuccessor(0) == BB &&
263         Pred1Br->getSuccessor(1) == Pred2) {
264       IfTrue = Pred1;
265       IfFalse = Pred2;
266     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
267                Pred1Br->getSuccessor(1) == BB) {
268       IfTrue = Pred2;
269       IfFalse = Pred1;
270     } else {
271       // We know that one arm of the conditional goes to BB, so the other must
272       // go somewhere unrelated, and this must not be an "if statement".
273       return 0;
274     }
275
276     // The only thing we have to watch out for here is to make sure that Pred2
277     // doesn't have incoming edges from other blocks.  If it does, the condition
278     // doesn't dominate BB.
279     if (++pred_begin(Pred2) != pred_end(Pred2))
280       return 0;
281
282     return Pred1Br->getCondition();
283   }
284
285   // Ok, if we got here, both predecessors end with an unconditional branch to
286   // BB.  Don't panic!  If both blocks only have a single (identical)
287   // predecessor, and THAT is a conditional branch, then we're all ok!
288   if (pred_begin(Pred1) == pred_end(Pred1) ||
289       ++pred_begin(Pred1) != pred_end(Pred1) ||
290       pred_begin(Pred2) == pred_end(Pred2) ||
291       ++pred_begin(Pred2) != pred_end(Pred2) ||
292       *pred_begin(Pred1) != *pred_begin(Pred2))
293     return 0;
294
295   // Otherwise, if this is a conditional branch, then we can use it!
296   BasicBlock *CommonPred = *pred_begin(Pred1);
297   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
298     assert(BI->isConditional() && "Two successors but not conditional?");
299     if (BI->getSuccessor(0) == Pred1) {
300       IfTrue = Pred1;
301       IfFalse = Pred2;
302     } else {
303       IfTrue = Pred2;
304       IfFalse = Pred1;
305     }
306     return BI->getCondition();
307   }
308   return 0;
309 }
310
311
312 // If we have a merge point of an "if condition" as accepted above, return true
313 // if the specified value dominates the block.  We don't handle the true
314 // generality of domination here, just a special case which works well enough
315 // for us.
316 //
317 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
318 // see if V (which must be an instruction) is cheap to compute and is
319 // non-trapping.  If both are true, the instruction is inserted into the set and
320 // true is returned.
321 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
322                                 std::set<Instruction*> *AggressiveInsts) {
323   Instruction *I = dyn_cast<Instruction>(V);
324   if (!I) {
325     // Non-instructions all dominate instructions, but not all constantexprs
326     // can be executed unconditionally.
327     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
328       if (C->canTrap())
329         return false;
330     return true;
331   }
332   BasicBlock *PBB = I->getParent();
333
334   // We don't want to allow weird loops that might have the "if condition" in
335   // the bottom of this block.
336   if (PBB == BB) return false;
337
338   // If this instruction is defined in a block that contains an unconditional
339   // branch to BB, then it must be in the 'conditional' part of the "if
340   // statement".
341   if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
342     if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
343       if (!AggressiveInsts) return false;
344       // Okay, it looks like the instruction IS in the "condition".  Check to
345       // see if its a cheap instruction to unconditionally compute, and if it
346       // only uses stuff defined outside of the condition.  If so, hoist it out.
347       switch (I->getOpcode()) {
348       default: return false;  // Cannot hoist this out safely.
349       case Instruction::Load:
350         // We can hoist loads that are non-volatile and obviously cannot trap.
351         if (cast<LoadInst>(I)->isVolatile())
352           return false;
353         if (!isa<AllocaInst>(I->getOperand(0)) &&
354             !isa<Constant>(I->getOperand(0)))
355           return false;
356
357         // Finally, we have to check to make sure there are no instructions
358         // before the load in its basic block, as we are going to hoist the loop
359         // out to its predecessor.
360         if (PBB->begin() != BasicBlock::iterator(I))
361           return false;
362         break;
363       case Instruction::Add:
364       case Instruction::Sub:
365       case Instruction::And:
366       case Instruction::Or:
367       case Instruction::Xor:
368       case Instruction::Shl:
369       case Instruction::LShr:
370       case Instruction::AShr:
371       case Instruction::ICmp:
372       case Instruction::FCmp:
373         break;   // These are all cheap and non-trapping instructions.
374       }
375
376       // Okay, we can only really hoist these out if their operands are not
377       // defined in the conditional region.
378       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
379         if (!DominatesMergePoint(I->getOperand(i), BB, 0))
380           return false;
381       // Okay, it's safe to do this!  Remember this instruction.
382       AggressiveInsts->insert(I);
383     }
384
385   return true;
386 }
387
388 // GatherConstantSetEQs - Given a potentially 'or'd together collection of 
389 // icmp_eq instructions that compare a value against a constant, return the 
390 // value being compared, and stick the constant into the Values vector.
391 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
392   if (Instruction *Inst = dyn_cast<Instruction>(V))
393     if (Inst->getOpcode() == Instruction::ICmp &&
394         cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
395       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
396         Values.push_back(C);
397         return Inst->getOperand(0);
398       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
399         Values.push_back(C);
400         return Inst->getOperand(1);
401       }
402     } else if (Inst->getOpcode() == Instruction::Or) {
403       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
404         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
405           if (LHS == RHS)
406             return LHS;
407     }
408   return 0;
409 }
410
411 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
412 // setne instructions that compare a value against a constant, return the value
413 // being compared, and stick the constant into the Values vector.
414 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
415   if (Instruction *Inst = dyn_cast<Instruction>(V))
416     if (Inst->getOpcode() == Instruction::ICmp &&
417                cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
418       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
419         Values.push_back(C);
420         return Inst->getOperand(0);
421       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
422         Values.push_back(C);
423         return Inst->getOperand(1);
424       }
425     } else if (Inst->getOpcode() == Instruction::And) {
426       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
427         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
428           if (LHS == RHS)
429             return LHS;
430     }
431   return 0;
432 }
433
434
435
436 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
437 /// bunch of comparisons of one value against constants, return the value and
438 /// the constants being compared.
439 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
440                                    std::vector<ConstantInt*> &Values) {
441   if (Cond->getOpcode() == Instruction::Or) {
442     CompVal = GatherConstantSetEQs(Cond, Values);
443
444     // Return true to indicate that the condition is true if the CompVal is
445     // equal to one of the constants.
446     return true;
447   } else if (Cond->getOpcode() == Instruction::And) {
448     CompVal = GatherConstantSetNEs(Cond, Values);
449
450     // Return false to indicate that the condition is false if the CompVal is
451     // equal to one of the constants.
452     return false;
453   }
454   return false;
455 }
456
457 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
458 /// has no side effects, nuke it.  If it uses any instructions that become dead
459 /// because the instruction is now gone, nuke them too.
460 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
461   if (!isInstructionTriviallyDead(I)) return;
462   
463   std::vector<Instruction*> InstrsToInspect;
464   InstrsToInspect.push_back(I);
465
466   while (!InstrsToInspect.empty()) {
467     I = InstrsToInspect.back();
468     InstrsToInspect.pop_back();
469
470     if (!isInstructionTriviallyDead(I)) continue;
471
472     // If I is in the work list multiple times, remove previous instances.
473     for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
474       if (InstrsToInspect[i] == I) {
475         InstrsToInspect.erase(InstrsToInspect.begin()+i);
476         --i, --e;
477       }
478
479     // Add operands of dead instruction to worklist.
480     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
481       if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
482         InstrsToInspect.push_back(OpI);
483
484     // Remove dead instruction.
485     I->eraseFromParent();
486   }
487 }
488
489 // isValueEqualityComparison - Return true if the specified terminator checks to
490 // see if a value is equal to constant integer value.
491 static Value *isValueEqualityComparison(TerminatorInst *TI) {
492   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
493     // Do not permit merging of large switch instructions into their
494     // predecessors unless there is only one predecessor.
495     if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
496                                                pred_end(SI->getParent())) > 128)
497       return 0;
498
499     return SI->getCondition();
500   }
501   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
502     if (BI->isConditional() && BI->getCondition()->hasOneUse())
503       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
504         if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
505              ICI->getPredicate() == ICmpInst::ICMP_NE) &&
506             isa<ConstantInt>(ICI->getOperand(1)))
507           return ICI->getOperand(0);
508   return 0;
509 }
510
511 // Given a value comparison instruction, decode all of the 'cases' that it
512 // represents and return the 'default' block.
513 static BasicBlock *
514 GetValueEqualityComparisonCases(TerminatorInst *TI,
515                                 std::vector<std::pair<ConstantInt*,
516                                                       BasicBlock*> > &Cases) {
517   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
518     Cases.reserve(SI->getNumCases());
519     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
520       Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
521     return SI->getDefaultDest();
522   }
523
524   BranchInst *BI = cast<BranchInst>(TI);
525   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
526   Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
527                                  BI->getSuccessor(ICI->getPredicate() ==
528                                                   ICmpInst::ICMP_NE)));
529   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
530 }
531
532
533 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
534 // in the list that match the specified block.
535 static void EliminateBlockCases(BasicBlock *BB,
536                std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
537   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
538     if (Cases[i].second == BB) {
539       Cases.erase(Cases.begin()+i);
540       --i; --e;
541     }
542 }
543
544 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
545 // well.
546 static bool
547 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
548               std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
549   std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
550
551   // Make V1 be smaller than V2.
552   if (V1->size() > V2->size())
553     std::swap(V1, V2);
554
555   if (V1->size() == 0) return false;
556   if (V1->size() == 1) {
557     // Just scan V2.
558     ConstantInt *TheVal = (*V1)[0].first;
559     for (unsigned i = 0, e = V2->size(); i != e; ++i)
560       if (TheVal == (*V2)[i].first)
561         return true;
562   }
563
564   // Otherwise, just sort both lists and compare element by element.
565   std::sort(V1->begin(), V1->end());
566   std::sort(V2->begin(), V2->end());
567   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
568   while (i1 != e1 && i2 != e2) {
569     if ((*V1)[i1].first == (*V2)[i2].first)
570       return true;
571     if ((*V1)[i1].first < (*V2)[i2].first)
572       ++i1;
573     else
574       ++i2;
575   }
576   return false;
577 }
578
579 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
580 // terminator instruction and its block is known to only have a single
581 // predecessor block, check to see if that predecessor is also a value
582 // comparison with the same value, and if that comparison determines the outcome
583 // of this comparison.  If so, simplify TI.  This does a very limited form of
584 // jump threading.
585 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
586                                                           BasicBlock *Pred) {
587   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
588   if (!PredVal) return false;  // Not a value comparison in predecessor.
589
590   Value *ThisVal = isValueEqualityComparison(TI);
591   assert(ThisVal && "This isn't a value comparison!!");
592   if (ThisVal != PredVal) return false;  // Different predicates.
593
594   // Find out information about when control will move from Pred to TI's block.
595   std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
596   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
597                                                         PredCases);
598   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
599
600   // Find information about how control leaves this block.
601   std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
602   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
603   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
604
605   // If TI's block is the default block from Pred's comparison, potentially
606   // simplify TI based on this knowledge.
607   if (PredDef == TI->getParent()) {
608     // If we are here, we know that the value is none of those cases listed in
609     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
610     // can simplify TI.
611     if (ValuesOverlap(PredCases, ThisCases)) {
612       if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
613         // Okay, one of the successors of this condbr is dead.  Convert it to a
614         // uncond br.
615         assert(ThisCases.size() == 1 && "Branch can only have one case!");
616         Value *Cond = BTI->getCondition();
617         // Insert the new branch.
618         Instruction *NI = new BranchInst(ThisDef, TI);
619
620         // Remove PHI node entries for the dead edge.
621         ThisCases[0].second->removePredecessor(TI->getParent());
622
623         DOUT << "Threading pred instr: " << *Pred->getTerminator()
624              << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
625
626         TI->eraseFromParent();   // Nuke the old one.
627         // If condition is now dead, nuke it.
628         if (Instruction *CondI = dyn_cast<Instruction>(Cond))
629           ErasePossiblyDeadInstructionTree(CondI);
630         return true;
631
632       } else {
633         SwitchInst *SI = cast<SwitchInst>(TI);
634         // Okay, TI has cases that are statically dead, prune them away.
635         std::set<Constant*> DeadCases;
636         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
637           DeadCases.insert(PredCases[i].first);
638
639         DOUT << "Threading pred instr: " << *Pred->getTerminator()
640              << "Through successor TI: " << *TI;
641
642         for (unsigned i = SI->getNumCases()-1; i != 0; --i)
643           if (DeadCases.count(SI->getCaseValue(i))) {
644             SI->getSuccessor(i)->removePredecessor(TI->getParent());
645             SI->removeCase(i);
646           }
647
648         DOUT << "Leaving: " << *TI << "\n";
649         return true;
650       }
651     }
652
653   } else {
654     // Otherwise, TI's block must correspond to some matched value.  Find out
655     // which value (or set of values) this is.
656     ConstantInt *TIV = 0;
657     BasicBlock *TIBB = TI->getParent();
658     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
659       if (PredCases[i].second == TIBB)
660         if (TIV == 0)
661           TIV = PredCases[i].first;
662         else
663           return false;  // Cannot handle multiple values coming to this block.
664     assert(TIV && "No edge from pred to succ?");
665
666     // Okay, we found the one constant that our value can be if we get into TI's
667     // BB.  Find out which successor will unconditionally be branched to.
668     BasicBlock *TheRealDest = 0;
669     for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
670       if (ThisCases[i].first == TIV) {
671         TheRealDest = ThisCases[i].second;
672         break;
673       }
674
675     // If not handled by any explicit cases, it is handled by the default case.
676     if (TheRealDest == 0) TheRealDest = ThisDef;
677
678     // Remove PHI node entries for dead edges.
679     BasicBlock *CheckEdge = TheRealDest;
680     for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
681       if (*SI != CheckEdge)
682         (*SI)->removePredecessor(TIBB);
683       else
684         CheckEdge = 0;
685
686     // Insert the new branch.
687     Instruction *NI = new BranchInst(TheRealDest, TI);
688
689     DOUT << "Threading pred instr: " << *Pred->getTerminator()
690          << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
691     Instruction *Cond = 0;
692     if (BranchInst *BI = dyn_cast<BranchInst>(TI))
693       Cond = dyn_cast<Instruction>(BI->getCondition());
694     TI->eraseFromParent();   // Nuke the old one.
695
696     if (Cond) ErasePossiblyDeadInstructionTree(Cond);
697     return true;
698   }
699   return false;
700 }
701
702 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
703 // equality comparison instruction (either a switch or a branch on "X == c").
704 // See if any of the predecessors of the terminator block are value comparisons
705 // on the same value.  If so, and if safe to do so, fold them together.
706 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
707   BasicBlock *BB = TI->getParent();
708   Value *CV = isValueEqualityComparison(TI);  // CondVal
709   assert(CV && "Not a comparison?");
710   bool Changed = false;
711
712   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
713   while (!Preds.empty()) {
714     BasicBlock *Pred = Preds.back();
715     Preds.pop_back();
716
717     // See if the predecessor is a comparison with the same value.
718     TerminatorInst *PTI = Pred->getTerminator();
719     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
720
721     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
722       // Figure out which 'cases' to copy from SI to PSI.
723       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
724       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
725
726       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
727       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
728
729       // Based on whether the default edge from PTI goes to BB or not, fill in
730       // PredCases and PredDefault with the new switch cases we would like to
731       // build.
732       std::vector<BasicBlock*> NewSuccessors;
733
734       if (PredDefault == BB) {
735         // If this is the default destination from PTI, only the edges in TI
736         // that don't occur in PTI, or that branch to BB will be activated.
737         std::set<ConstantInt*> PTIHandled;
738         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
739           if (PredCases[i].second != BB)
740             PTIHandled.insert(PredCases[i].first);
741           else {
742             // The default destination is BB, we don't need explicit targets.
743             std::swap(PredCases[i], PredCases.back());
744             PredCases.pop_back();
745             --i; --e;
746           }
747
748         // Reconstruct the new switch statement we will be building.
749         if (PredDefault != BBDefault) {
750           PredDefault->removePredecessor(Pred);
751           PredDefault = BBDefault;
752           NewSuccessors.push_back(BBDefault);
753         }
754         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
755           if (!PTIHandled.count(BBCases[i].first) &&
756               BBCases[i].second != BBDefault) {
757             PredCases.push_back(BBCases[i]);
758             NewSuccessors.push_back(BBCases[i].second);
759           }
760
761       } else {
762         // If this is not the default destination from PSI, only the edges
763         // in SI that occur in PSI with a destination of BB will be
764         // activated.
765         std::set<ConstantInt*> PTIHandled;
766         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
767           if (PredCases[i].second == BB) {
768             PTIHandled.insert(PredCases[i].first);
769             std::swap(PredCases[i], PredCases.back());
770             PredCases.pop_back();
771             --i; --e;
772           }
773
774         // Okay, now we know which constants were sent to BB from the
775         // predecessor.  Figure out where they will all go now.
776         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
777           if (PTIHandled.count(BBCases[i].first)) {
778             // If this is one we are capable of getting...
779             PredCases.push_back(BBCases[i]);
780             NewSuccessors.push_back(BBCases[i].second);
781             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
782           }
783
784         // If there are any constants vectored to BB that TI doesn't handle,
785         // they must go to the default destination of TI.
786         for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
787                E = PTIHandled.end(); I != E; ++I) {
788           PredCases.push_back(std::make_pair(*I, BBDefault));
789           NewSuccessors.push_back(BBDefault);
790         }
791       }
792
793       // Okay, at this point, we know which new successor Pred will get.  Make
794       // sure we update the number of entries in the PHI nodes for these
795       // successors.
796       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
797         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
798
799       // Now that the successors are updated, create the new Switch instruction.
800       SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
801       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
802         NewSI->addCase(PredCases[i].first, PredCases[i].second);
803
804       Instruction *DeadCond = 0;
805       if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
806         // If PTI is a branch, remember the condition.
807         DeadCond = dyn_cast<Instruction>(BI->getCondition());
808       Pred->getInstList().erase(PTI);
809
810       // If the condition is dead now, remove the instruction tree.
811       if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
812
813       // Okay, last check.  If BB is still a successor of PSI, then we must
814       // have an infinite loop case.  If so, add an infinitely looping block
815       // to handle the case to preserve the behavior of the code.
816       BasicBlock *InfLoopBlock = 0;
817       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
818         if (NewSI->getSuccessor(i) == BB) {
819           if (InfLoopBlock == 0) {
820             // Insert it at the end of the loop, because it's either code,
821             // or it won't matter if it's hot. :)
822             InfLoopBlock = new BasicBlock("infloop", BB->getParent());
823             new BranchInst(InfLoopBlock, InfLoopBlock);
824           }
825           NewSI->setSuccessor(i, InfLoopBlock);
826         }
827
828       Changed = true;
829     }
830   }
831   return Changed;
832 }
833
834 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
835 /// BB2, hoist any common code in the two blocks up into the branch block.  The
836 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
837 static bool HoistThenElseCodeToIf(BranchInst *BI) {
838   // This does very trivial matching, with limited scanning, to find identical
839   // instructions in the two blocks.  In particular, we don't want to get into
840   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
841   // such, we currently just scan for obviously identical instructions in an
842   // identical order.
843   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
844   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
845
846   Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
847   if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) || 
848       isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
849     return false;
850
851   // If we get here, we can hoist at least one instruction.
852   BasicBlock *BIParent = BI->getParent();
853
854   do {
855     // If we are hoisting the terminator instruction, don't move one (making a
856     // broken BB), instead clone it, and remove BI.
857     if (isa<TerminatorInst>(I1))
858       goto HoistTerminator;
859
860     // For a normal instruction, we just move one to right before the branch,
861     // then replace all uses of the other with the first.  Finally, we remove
862     // the now redundant second instruction.
863     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
864     if (!I2->use_empty())
865       I2->replaceAllUsesWith(I1);
866     BB2->getInstList().erase(I2);
867
868     I1 = BB1->begin();
869     I2 = BB2->begin();
870   } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
871
872   return true;
873
874 HoistTerminator:
875   // Okay, it is safe to hoist the terminator.
876   Instruction *NT = I1->clone();
877   BIParent->getInstList().insert(BI, NT);
878   if (NT->getType() != Type::VoidTy) {
879     I1->replaceAllUsesWith(NT);
880     I2->replaceAllUsesWith(NT);
881     NT->takeName(I1);
882   }
883
884   // Hoisting one of the terminators from our successor is a great thing.
885   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
886   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
887   // nodes, so we insert select instruction to compute the final result.
888   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
889   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
890     PHINode *PN;
891     for (BasicBlock::iterator BBI = SI->begin();
892          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
893       Value *BB1V = PN->getIncomingValueForBlock(BB1);
894       Value *BB2V = PN->getIncomingValueForBlock(BB2);
895       if (BB1V != BB2V) {
896         // These values do not agree.  Insert a select instruction before NT
897         // that determines the right value.
898         SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
899         if (SI == 0)
900           SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
901                               BB1V->getName()+"."+BB2V->getName(), NT);
902         // Make the PHI node use the select for all incoming values for BB1/BB2
903         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
904           if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
905             PN->setIncomingValue(i, SI);
906       }
907     }
908   }
909
910   // Update any PHI nodes in our new successors.
911   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
912     AddPredecessorToBlock(*SI, BIParent, BB1);
913
914   BI->eraseFromParent();
915   return true;
916 }
917
918 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
919 /// across this block.
920 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
921   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
922   unsigned Size = 0;
923   
924   // If this basic block contains anything other than a PHI (which controls the
925   // branch) and branch itself, bail out.  FIXME: improve this in the future.
926   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
927     if (Size > 10) return false;  // Don't clone large BB's.
928     
929     // We can only support instructions that are do not define values that are
930     // live outside of the current basic block.
931     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
932          UI != E; ++UI) {
933       Instruction *U = cast<Instruction>(*UI);
934       if (U->getParent() != BB || isa<PHINode>(U)) return false;
935     }
936     
937     // Looks ok, continue checking.
938   }
939
940   return true;
941 }
942
943 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
944 /// that is defined in the same block as the branch and if any PHI entries are
945 /// constants, thread edges corresponding to that entry to be branches to their
946 /// ultimate destination.
947 static bool FoldCondBranchOnPHI(BranchInst *BI) {
948   BasicBlock *BB = BI->getParent();
949   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
950   // NOTE: we currently cannot transform this case if the PHI node is used
951   // outside of the block.
952   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
953     return false;
954   
955   // Degenerate case of a single entry PHI.
956   if (PN->getNumIncomingValues() == 1) {
957     if (PN->getIncomingValue(0) != PN)
958       PN->replaceAllUsesWith(PN->getIncomingValue(0));
959     else
960       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
961     PN->eraseFromParent();
962     return true;    
963   }
964
965   // Now we know that this block has multiple preds and two succs.
966   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
967   
968   // Okay, this is a simple enough basic block.  See if any phi values are
969   // constants.
970   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
971     ConstantInt *CB;
972     if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
973         CB->getType() == Type::Int1Ty) {
974       // Okay, we now know that all edges from PredBB should be revectored to
975       // branch to RealDest.
976       BasicBlock *PredBB = PN->getIncomingBlock(i);
977       BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
978       
979       if (RealDest == BB) continue;  // Skip self loops.
980       
981       // The dest block might have PHI nodes, other predecessors and other
982       // difficult cases.  Instead of being smart about this, just insert a new
983       // block that jumps to the destination block, effectively splitting
984       // the edge we are about to create.
985       BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
986                                           RealDest->getParent(), RealDest);
987       new BranchInst(RealDest, EdgeBB);
988       PHINode *PN;
989       for (BasicBlock::iterator BBI = RealDest->begin();
990            (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
991         Value *V = PN->getIncomingValueForBlock(BB);
992         PN->addIncoming(V, EdgeBB);
993       }
994
995       // BB may have instructions that are being threaded over.  Clone these
996       // instructions into EdgeBB.  We know that there will be no uses of the
997       // cloned instructions outside of EdgeBB.
998       BasicBlock::iterator InsertPt = EdgeBB->begin();
999       std::map<Value*, Value*> TranslateMap;  // Track translated values.
1000       for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1001         if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1002           TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1003         } else {
1004           // Clone the instruction.
1005           Instruction *N = BBI->clone();
1006           if (BBI->hasName()) N->setName(BBI->getName()+".c");
1007           
1008           // Update operands due to translation.
1009           for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1010             std::map<Value*, Value*>::iterator PI =
1011               TranslateMap.find(N->getOperand(i));
1012             if (PI != TranslateMap.end())
1013               N->setOperand(i, PI->second);
1014           }
1015           
1016           // Check for trivial simplification.
1017           if (Constant *C = ConstantFoldInstruction(N)) {
1018             TranslateMap[BBI] = C;
1019             delete N;   // Constant folded away, don't need actual inst
1020           } else {
1021             // Insert the new instruction into its new home.
1022             EdgeBB->getInstList().insert(InsertPt, N);
1023             if (!BBI->use_empty())
1024               TranslateMap[BBI] = N;
1025           }
1026         }
1027       }
1028
1029       // Loop over all of the edges from PredBB to BB, changing them to branch
1030       // to EdgeBB instead.
1031       TerminatorInst *PredBBTI = PredBB->getTerminator();
1032       for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1033         if (PredBBTI->getSuccessor(i) == BB) {
1034           BB->removePredecessor(PredBB);
1035           PredBBTI->setSuccessor(i, EdgeBB);
1036         }
1037       
1038       // Recurse, simplifying any other constants.
1039       return FoldCondBranchOnPHI(BI) | true;
1040     }
1041   }
1042
1043   return false;
1044 }
1045
1046 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1047 /// PHI node, see if we can eliminate it.
1048 static bool FoldTwoEntryPHINode(PHINode *PN) {
1049   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1050   // statement", which has a very simple dominance structure.  Basically, we
1051   // are trying to find the condition that is being branched on, which
1052   // subsequently causes this merge to happen.  We really want control
1053   // dependence information for this check, but simplifycfg can't keep it up
1054   // to date, and this catches most of the cases we care about anyway.
1055   //
1056   BasicBlock *BB = PN->getParent();
1057   BasicBlock *IfTrue, *IfFalse;
1058   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1059   if (!IfCond) return false;
1060   
1061   // Okay, we found that we can merge this two-entry phi node into a select.
1062   // Doing so would require us to fold *all* two entry phi nodes in this block.
1063   // At some point this becomes non-profitable (particularly if the target
1064   // doesn't support cmov's).  Only do this transformation if there are two or
1065   // fewer PHI nodes in this block.
1066   unsigned NumPhis = 0;
1067   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1068     if (NumPhis > 2)
1069       return false;
1070   
1071   DOUT << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1072        << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n";
1073   
1074   // Loop over the PHI's seeing if we can promote them all to select
1075   // instructions.  While we are at it, keep track of the instructions
1076   // that need to be moved to the dominating block.
1077   std::set<Instruction*> AggressiveInsts;
1078   
1079   BasicBlock::iterator AfterPHIIt = BB->begin();
1080   while (isa<PHINode>(AfterPHIIt)) {
1081     PHINode *PN = cast<PHINode>(AfterPHIIt++);
1082     if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1083       if (PN->getIncomingValue(0) != PN)
1084         PN->replaceAllUsesWith(PN->getIncomingValue(0));
1085       else
1086         PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1087     } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1088                                     &AggressiveInsts) ||
1089                !DominatesMergePoint(PN->getIncomingValue(1), BB,
1090                                     &AggressiveInsts)) {
1091       return false;
1092     }
1093   }
1094   
1095   // If we all PHI nodes are promotable, check to make sure that all
1096   // instructions in the predecessor blocks can be promoted as well.  If
1097   // not, we won't be able to get rid of the control flow, so it's not
1098   // worth promoting to select instructions.
1099   BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1100   PN = cast<PHINode>(BB->begin());
1101   BasicBlock *Pred = PN->getIncomingBlock(0);
1102   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1103     IfBlock1 = Pred;
1104     DomBlock = *pred_begin(Pred);
1105     for (BasicBlock::iterator I = Pred->begin();
1106          !isa<TerminatorInst>(I); ++I)
1107       if (!AggressiveInsts.count(I)) {
1108         // This is not an aggressive instruction that we can promote.
1109         // Because of this, we won't be able to get rid of the control
1110         // flow, so the xform is not worth it.
1111         return false;
1112       }
1113   }
1114     
1115   Pred = PN->getIncomingBlock(1);
1116   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1117     IfBlock2 = Pred;
1118     DomBlock = *pred_begin(Pred);
1119     for (BasicBlock::iterator I = Pred->begin();
1120          !isa<TerminatorInst>(I); ++I)
1121       if (!AggressiveInsts.count(I)) {
1122         // This is not an aggressive instruction that we can promote.
1123         // Because of this, we won't be able to get rid of the control
1124         // flow, so the xform is not worth it.
1125         return false;
1126       }
1127   }
1128       
1129   // If we can still promote the PHI nodes after this gauntlet of tests,
1130   // do all of the PHI's now.
1131
1132   // Move all 'aggressive' instructions, which are defined in the
1133   // conditional parts of the if's up to the dominating block.
1134   if (IfBlock1) {
1135     DomBlock->getInstList().splice(DomBlock->getTerminator(),
1136                                    IfBlock1->getInstList(),
1137                                    IfBlock1->begin(),
1138                                    IfBlock1->getTerminator());
1139   }
1140   if (IfBlock2) {
1141     DomBlock->getInstList().splice(DomBlock->getTerminator(),
1142                                    IfBlock2->getInstList(),
1143                                    IfBlock2->begin(),
1144                                    IfBlock2->getTerminator());
1145   }
1146   
1147   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1148     // Change the PHI node into a select instruction.
1149     Value *TrueVal =
1150       PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1151     Value *FalseVal =
1152       PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1153     
1154     Value *NV = new SelectInst(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
1155     PN->replaceAllUsesWith(NV);
1156     NV->takeName(PN);
1157     
1158     BB->getInstList().erase(PN);
1159   }
1160   return true;
1161 }
1162
1163 namespace {
1164   /// ConstantIntOrdering - This class implements a stable ordering of constant
1165   /// integers that does not depend on their address.  This is important for
1166   /// applications that sort ConstantInt's to ensure uniqueness.
1167   struct ConstantIntOrdering {
1168     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1169       return LHS->getZExtValue() < RHS->getZExtValue();
1170     }
1171   };
1172 }
1173
1174 // SimplifyCFG - This function is used to do simplification of a CFG.  For
1175 // example, it adjusts branches to branches to eliminate the extra hop, it
1176 // eliminates unreachable basic blocks, and does other "peephole" optimization
1177 // of the CFG.  It returns true if a modification was made.
1178 //
1179 // WARNING:  The entry node of a function may not be simplified.
1180 //
1181 bool llvm::SimplifyCFG(BasicBlock *BB) {
1182   bool Changed = false;
1183   Function *M = BB->getParent();
1184
1185   assert(BB && BB->getParent() && "Block not embedded in function!");
1186   assert(BB->getTerminator() && "Degenerate basic block encountered!");
1187   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
1188
1189   // Remove basic blocks that have no predecessors... which are unreachable.
1190   if (pred_begin(BB) == pred_end(BB) ||
1191       *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
1192     DOUT << "Removing BB: \n" << *BB;
1193
1194     // Loop through all of our successors and make sure they know that one
1195     // of their predecessors is going away.
1196     for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1197       SI->removePredecessor(BB);
1198
1199     while (!BB->empty()) {
1200       Instruction &I = BB->back();
1201       // If this instruction is used, replace uses with an arbitrary
1202       // value.  Because control flow can't get here, we don't care
1203       // what we replace the value with.  Note that since this block is
1204       // unreachable, and all values contained within it must dominate their
1205       // uses, that all uses will eventually be removed.
1206       if (!I.use_empty())
1207         // Make all users of this instruction use undef instead
1208         I.replaceAllUsesWith(UndefValue::get(I.getType()));
1209
1210       // Remove the instruction from the basic block
1211       BB->getInstList().pop_back();
1212     }
1213     M->getBasicBlockList().erase(BB);
1214     return true;
1215   }
1216
1217   // Check to see if we can constant propagate this terminator instruction
1218   // away...
1219   Changed |= ConstantFoldTerminator(BB);
1220
1221   // If this is a returning block with only PHI nodes in it, fold the return
1222   // instruction into any unconditional branch predecessors.
1223   //
1224   // If any predecessor is a conditional branch that just selects among
1225   // different return values, fold the replace the branch/return with a select
1226   // and return.
1227   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1228     BasicBlock::iterator BBI = BB->getTerminator();
1229     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1230       // Find predecessors that end with branches.
1231       std::vector<BasicBlock*> UncondBranchPreds;
1232       std::vector<BranchInst*> CondBranchPreds;
1233       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1234         TerminatorInst *PTI = (*PI)->getTerminator();
1235         if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1236           if (BI->isUnconditional())
1237             UncondBranchPreds.push_back(*PI);
1238           else
1239             CondBranchPreds.push_back(BI);
1240       }
1241
1242       // If we found some, do the transformation!
1243       if (!UncondBranchPreds.empty()) {
1244         while (!UncondBranchPreds.empty()) {
1245           BasicBlock *Pred = UncondBranchPreds.back();
1246           DOUT << "FOLDING: " << *BB
1247                << "INTO UNCOND BRANCH PRED: " << *Pred;
1248           UncondBranchPreds.pop_back();
1249           Instruction *UncondBranch = Pred->getTerminator();
1250           // Clone the return and add it to the end of the predecessor.
1251           Instruction *NewRet = RI->clone();
1252           Pred->getInstList().push_back(NewRet);
1253
1254           // If the return instruction returns a value, and if the value was a
1255           // PHI node in "BB", propagate the right value into the return.
1256           if (NewRet->getNumOperands() == 1)
1257             if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1258               if (PN->getParent() == BB)
1259                 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1260           // Update any PHI nodes in the returning block to realize that we no
1261           // longer branch to them.
1262           BB->removePredecessor(Pred);
1263           Pred->getInstList().erase(UncondBranch);
1264         }
1265
1266         // If we eliminated all predecessors of the block, delete the block now.
1267         if (pred_begin(BB) == pred_end(BB))
1268           // We know there are no successors, so just nuke the block.
1269           M->getBasicBlockList().erase(BB);
1270
1271         return true;
1272       }
1273
1274       // Check out all of the conditional branches going to this return
1275       // instruction.  If any of them just select between returns, change the
1276       // branch itself into a select/return pair.
1277       while (!CondBranchPreds.empty()) {
1278         BranchInst *BI = CondBranchPreds.back();
1279         CondBranchPreds.pop_back();
1280         BasicBlock *TrueSucc = BI->getSuccessor(0);
1281         BasicBlock *FalseSucc = BI->getSuccessor(1);
1282         BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1283
1284         // Check to see if the non-BB successor is also a return block.
1285         if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1286           // Check to see if there are only PHI instructions in this block.
1287           BasicBlock::iterator OSI = OtherSucc->getTerminator();
1288           if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1289             // Okay, we found a branch that is going to two return nodes.  If
1290             // there is no return value for this function, just change the
1291             // branch into a return.
1292             if (RI->getNumOperands() == 0) {
1293               TrueSucc->removePredecessor(BI->getParent());
1294               FalseSucc->removePredecessor(BI->getParent());
1295               new ReturnInst(0, BI);
1296               BI->getParent()->getInstList().erase(BI);
1297               return true;
1298             }
1299
1300             // Otherwise, figure out what the true and false return values are
1301             // so we can insert a new select instruction.
1302             Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1303             Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1304
1305             // Unwrap any PHI nodes in the return blocks.
1306             if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1307               if (TVPN->getParent() == TrueSucc)
1308                 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1309             if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1310               if (FVPN->getParent() == FalseSucc)
1311                 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1312
1313             // In order for this transformation to be safe, we must be able to
1314             // unconditionally execute both operands to the return.  This is
1315             // normally the case, but we could have a potentially-trapping
1316             // constant expression that prevents this transformation from being
1317             // safe.
1318             if ((!isa<ConstantExpr>(TrueValue) ||
1319                  !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1320                 (!isa<ConstantExpr>(TrueValue) ||
1321                  !cast<ConstantExpr>(TrueValue)->canTrap())) {
1322               TrueSucc->removePredecessor(BI->getParent());
1323               FalseSucc->removePredecessor(BI->getParent());
1324
1325               // Insert a new select instruction.
1326               Value *NewRetVal;
1327               Value *BrCond = BI->getCondition();
1328               if (TrueValue != FalseValue)
1329                 NewRetVal = new SelectInst(BrCond, TrueValue,
1330                                            FalseValue, "retval", BI);
1331               else
1332                 NewRetVal = TrueValue;
1333               
1334               DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1335                    << "\n  " << *BI << "Select = " << *NewRetVal
1336                    << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1337
1338               new ReturnInst(NewRetVal, BI);
1339               BI->eraseFromParent();
1340               if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1341                 if (isInstructionTriviallyDead(BrCondI))
1342                   BrCondI->eraseFromParent();
1343               return true;
1344             }
1345           }
1346         }
1347       }
1348     }
1349   } else if (isa<UnwindInst>(BB->begin())) {
1350     // Check to see if the first instruction in this block is just an unwind.
1351     // If so, replace any invoke instructions which use this as an exception
1352     // destination with call instructions, and any unconditional branch
1353     // predecessor with an unwind.
1354     //
1355     std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1356     while (!Preds.empty()) {
1357       BasicBlock *Pred = Preds.back();
1358       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1359         if (BI->isUnconditional()) {
1360           Pred->getInstList().pop_back();  // nuke uncond branch
1361           new UnwindInst(Pred);            // Use unwind.
1362           Changed = true;
1363         }
1364       } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1365         if (II->getUnwindDest() == BB) {
1366           // Insert a new branch instruction before the invoke, because this
1367           // is now a fall through...
1368           BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1369           Pred->getInstList().remove(II);   // Take out of symbol table
1370
1371           // Insert the call now...
1372           std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1373           CallInst *CI = new CallInst(II->getCalledValue(), Args,
1374                                       II->getName(), BI);
1375           CI->setCallingConv(II->getCallingConv());
1376           // If the invoke produced a value, the Call now does instead
1377           II->replaceAllUsesWith(CI);
1378           delete II;
1379           Changed = true;
1380         }
1381
1382       Preds.pop_back();
1383     }
1384
1385     // If this block is now dead, remove it.
1386     if (pred_begin(BB) == pred_end(BB)) {
1387       // We know there are no successors, so just nuke the block.
1388       M->getBasicBlockList().erase(BB);
1389       return true;
1390     }
1391
1392   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1393     if (isValueEqualityComparison(SI)) {
1394       // If we only have one predecessor, and if it is a branch on this value,
1395       // see if that predecessor totally determines the outcome of this switch.
1396       if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1397         if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1398           return SimplifyCFG(BB) || 1;
1399
1400       // If the block only contains the switch, see if we can fold the block
1401       // away into any preds.
1402       if (SI == &BB->front())
1403         if (FoldValueComparisonIntoPredecessors(SI))
1404           return SimplifyCFG(BB) || 1;
1405     }
1406   } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1407     if (BI->isUnconditional()) {
1408       BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
1409       while (isa<PHINode>(*BBI)) ++BBI;
1410
1411       BasicBlock *Succ = BI->getSuccessor(0);
1412       if (BBI->isTerminator() &&  // Terminator is the only non-phi instruction!
1413           Succ != BB)             // Don't hurt infinite loops!
1414         if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1415           return 1;
1416       
1417     } else {  // Conditional branch
1418       if (isValueEqualityComparison(BI)) {
1419         // If we only have one predecessor, and if it is a branch on this value,
1420         // see if that predecessor totally determines the outcome of this
1421         // switch.
1422         if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1423           if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1424             return SimplifyCFG(BB) || 1;
1425
1426         // This block must be empty, except for the setcond inst, if it exists.
1427         BasicBlock::iterator I = BB->begin();
1428         if (&*I == BI ||
1429             (&*I == cast<Instruction>(BI->getCondition()) &&
1430              &*++I == BI))
1431           if (FoldValueComparisonIntoPredecessors(BI))
1432             return SimplifyCFG(BB) | true;
1433       }
1434       
1435       // If this is a branch on a phi node in the current block, thread control
1436       // through this block if any PHI node entries are constants.
1437       if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1438         if (PN->getParent() == BI->getParent())
1439           if (FoldCondBranchOnPHI(BI))
1440             return SimplifyCFG(BB) | true;
1441
1442       // If this basic block is ONLY a setcc and a branch, and if a predecessor
1443       // branches to us and one of our successors, fold the setcc into the
1444       // predecessor and use logical operations to pick the right destination.
1445       BasicBlock *TrueDest  = BI->getSuccessor(0);
1446       BasicBlock *FalseDest = BI->getSuccessor(1);
1447       if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
1448         if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1449             Cond->getParent() == BB && &BB->front() == Cond &&
1450             Cond->getNext() == BI && Cond->hasOneUse() &&
1451             TrueDest != BB && FalseDest != BB)
1452           for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1453             if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1454               if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1455                 BasicBlock *PredBlock = *PI;
1456                 if (PBI->getSuccessor(0) == FalseDest ||
1457                     PBI->getSuccessor(1) == TrueDest) {
1458                   // Invert the predecessors condition test (xor it with true),
1459                   // which allows us to write this code once.
1460                   Value *NewCond =
1461                     BinaryOperator::createNot(PBI->getCondition(),
1462                                     PBI->getCondition()->getName()+".not", PBI);
1463                   PBI->setCondition(NewCond);
1464                   BasicBlock *OldTrue = PBI->getSuccessor(0);
1465                   BasicBlock *OldFalse = PBI->getSuccessor(1);
1466                   PBI->setSuccessor(0, OldFalse);
1467                   PBI->setSuccessor(1, OldTrue);
1468                 }
1469
1470                 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1471                     (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
1472                   // Clone Cond into the predecessor basic block, and or/and the
1473                   // two conditions together.
1474                   Instruction *New = Cond->clone();
1475                   PredBlock->getInstList().insert(PBI, New);
1476                   New->takeName(Cond);
1477                   Cond->setName(New->getName()+".old");
1478                   Instruction::BinaryOps Opcode =
1479                     PBI->getSuccessor(0) == TrueDest ?
1480                     Instruction::Or : Instruction::And;
1481                   Value *NewCond =
1482                     BinaryOperator::create(Opcode, PBI->getCondition(),
1483                                            New, "bothcond", PBI);
1484                   PBI->setCondition(NewCond);
1485                   if (PBI->getSuccessor(0) == BB) {
1486                     AddPredecessorToBlock(TrueDest, PredBlock, BB);
1487                     PBI->setSuccessor(0, TrueDest);
1488                   }
1489                   if (PBI->getSuccessor(1) == BB) {
1490                     AddPredecessorToBlock(FalseDest, PredBlock, BB);
1491                     PBI->setSuccessor(1, FalseDest);
1492                   }
1493                   return SimplifyCFG(BB) | 1;
1494                 }
1495               }
1496
1497       // Scan predessor blocks for conditional branchs.
1498       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1499         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1500           if (PBI != BI && PBI->isConditional()) {
1501               
1502             // If this block ends with a branch instruction, and if there is a
1503             // predecessor that ends on a branch of the same condition, make 
1504             // this conditional branch redundant.
1505             if (PBI->getCondition() == BI->getCondition() &&
1506                 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1507               // Okay, the outcome of this conditional branch is statically
1508               // knowable.  If this block had a single pred, handle specially.
1509               if (BB->getSinglePredecessor()) {
1510                 // Turn this into a branch on constant.
1511                 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1512                 BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
1513                 return SimplifyCFG(BB);  // Nuke the branch on constant.
1514               }
1515               
1516               // Otherwise, if there are multiple predecessors, insert a PHI 
1517               // that merges in the constant and simplify the block result.
1518               if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1519                 PHINode *NewPN = new PHINode(Type::Int1Ty,
1520                                             BI->getCondition()->getName()+".pr",
1521                                             BB->begin());
1522                 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1523                   if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1524                       PBI != BI && PBI->isConditional() &&
1525                       PBI->getCondition() == BI->getCondition() &&
1526                       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1527                     bool CondIsTrue = PBI->getSuccessor(0) == BB;
1528                     NewPN->addIncoming(ConstantInt::get(Type::Int1Ty, 
1529                                                         CondIsTrue), *PI);
1530                   } else {
1531                     NewPN->addIncoming(BI->getCondition(), *PI);
1532                   }
1533                 
1534                 BI->setCondition(NewPN);
1535                 // This will thread the branch.
1536                 return SimplifyCFG(BB) | true;
1537               }
1538             }
1539             
1540             // If this is a conditional branch in an empty block, and if any
1541             // predecessors is a conditional branch to one of our destinations,
1542             // fold the conditions into logical ops and one cond br.
1543             if (&BB->front() == BI) {
1544               int PBIOp, BIOp;
1545               if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1546                 PBIOp = BIOp = 0;
1547               } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1548                 PBIOp = 0; BIOp = 1;
1549               } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1550                 PBIOp = 1; BIOp = 0;
1551               } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1552                 PBIOp = BIOp = 1;
1553               } else {
1554                 PBIOp = BIOp = -1;
1555               }
1556               
1557               // Check to make sure that the other destination of this branch
1558               // isn't BB itself.  If so, this is an infinite loop that will
1559               // keep getting unwound.
1560               if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1561                 PBIOp = BIOp = -1;
1562               
1563               // Do not perform this transformation if it would require 
1564               // insertion of a large number of select instructions. For targets
1565               // without predication/cmovs, this is a big pessimization.
1566               if (PBIOp != -1) {
1567                 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1568            
1569                 unsigned NumPhis = 0;
1570                 for (BasicBlock::iterator II = CommonDest->begin();
1571                      isa<PHINode>(II); ++II, ++NumPhis) {
1572                   if (NumPhis > 2) {
1573                     // Disable this xform.
1574                     PBIOp = -1;
1575                     break;
1576                   }
1577                 }
1578               }
1579
1580               // Finally, if everything is ok, fold the branches to logical ops.
1581               if (PBIOp != -1) {
1582                 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1583                 BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
1584
1585                 // If OtherDest *is* BB, then this is a basic block with just
1586                 // a conditional branch in it, where one edge (OtherDesg) goes
1587                 // back to the block.  We know that the program doesn't get
1588                 // stuck in the infinite loop, so the condition must be such
1589                 // that OtherDest isn't branched through. Forward to CommonDest,
1590                 // and avoid an infinite loop at optimizer time.
1591                 if (OtherDest == BB)
1592                   OtherDest = CommonDest;
1593                 
1594                 DOUT << "FOLDING BRs:" << *PBI->getParent()
1595                      << "AND: " << *BI->getParent();
1596                                 
1597                 // BI may have other predecessors.  Because of this, we leave
1598                 // it alone, but modify PBI.
1599                 
1600                 // Make sure we get to CommonDest on True&True directions.
1601                 Value *PBICond = PBI->getCondition();
1602                 if (PBIOp)
1603                   PBICond = BinaryOperator::createNot(PBICond,
1604                                                       PBICond->getName()+".not",
1605                                                       PBI);
1606                 Value *BICond = BI->getCondition();
1607                 if (BIOp)
1608                   BICond = BinaryOperator::createNot(BICond,
1609                                                      BICond->getName()+".not",
1610                                                      PBI);
1611                 // Merge the conditions.
1612                 Value *Cond =
1613                   BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1614                 
1615                 // Modify PBI to branch on the new condition to the new dests.
1616                 PBI->setCondition(Cond);
1617                 PBI->setSuccessor(0, CommonDest);
1618                 PBI->setSuccessor(1, OtherDest);
1619
1620                 // OtherDest may have phi nodes.  If so, add an entry from PBI's
1621                 // block that are identical to the entries for BI's block.
1622                 PHINode *PN;
1623                 for (BasicBlock::iterator II = OtherDest->begin();
1624                      (PN = dyn_cast<PHINode>(II)); ++II) {
1625                   Value *V = PN->getIncomingValueForBlock(BB);
1626                   PN->addIncoming(V, PBI->getParent());
1627                 }
1628                 
1629                 // We know that the CommonDest already had an edge from PBI to
1630                 // it.  If it has PHIs though, the PHIs may have different
1631                 // entries for BB and PBI's BB.  If so, insert a select to make
1632                 // them agree.
1633                 for (BasicBlock::iterator II = CommonDest->begin();
1634                      (PN = dyn_cast<PHINode>(II)); ++II) {
1635                   Value * BIV = PN->getIncomingValueForBlock(BB);
1636                   unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1637                   Value *PBIV = PN->getIncomingValue(PBBIdx);
1638                   if (BIV != PBIV) {
1639                     // Insert a select in PBI to pick the right value.
1640                     Value *NV = new SelectInst(PBICond, PBIV, BIV,
1641                                                PBIV->getName()+".mux", PBI);
1642                     PN->setIncomingValue(PBBIdx, NV);
1643                   }
1644                 }
1645
1646                 DOUT << "INTO: " << *PBI->getParent();
1647
1648                 // This basic block is probably dead.  We know it has at least
1649                 // one fewer predecessor.
1650                 return SimplifyCFG(BB) | true;
1651               }
1652             }
1653           }
1654     }
1655   } else if (isa<UnreachableInst>(BB->getTerminator())) {
1656     // If there are any instructions immediately before the unreachable that can
1657     // be removed, do so.
1658     Instruction *Unreachable = BB->getTerminator();
1659     while (Unreachable != BB->begin()) {
1660       BasicBlock::iterator BBI = Unreachable;
1661       --BBI;
1662       if (isa<CallInst>(BBI)) break;
1663       // Delete this instruction
1664       BB->getInstList().erase(BBI);
1665       Changed = true;
1666     }
1667
1668     // If the unreachable instruction is the first in the block, take a gander
1669     // at all of the predecessors of this instruction, and simplify them.
1670     if (&BB->front() == Unreachable) {
1671       std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1672       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1673         TerminatorInst *TI = Preds[i]->getTerminator();
1674
1675         if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1676           if (BI->isUnconditional()) {
1677             if (BI->getSuccessor(0) == BB) {
1678               new UnreachableInst(TI);
1679               TI->eraseFromParent();
1680               Changed = true;
1681             }
1682           } else {
1683             if (BI->getSuccessor(0) == BB) {
1684               new BranchInst(BI->getSuccessor(1), BI);
1685               BI->eraseFromParent();
1686             } else if (BI->getSuccessor(1) == BB) {
1687               new BranchInst(BI->getSuccessor(0), BI);
1688               BI->eraseFromParent();
1689               Changed = true;
1690             }
1691           }
1692         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1693           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1694             if (SI->getSuccessor(i) == BB) {
1695               BB->removePredecessor(SI->getParent());
1696               SI->removeCase(i);
1697               --i; --e;
1698               Changed = true;
1699             }
1700           // If the default value is unreachable, figure out the most popular
1701           // destination and make it the default.
1702           if (SI->getSuccessor(0) == BB) {
1703             std::map<BasicBlock*, unsigned> Popularity;
1704             for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1705               Popularity[SI->getSuccessor(i)]++;
1706
1707             // Find the most popular block.
1708             unsigned MaxPop = 0;
1709             BasicBlock *MaxBlock = 0;
1710             for (std::map<BasicBlock*, unsigned>::iterator
1711                    I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1712               if (I->second > MaxPop) {
1713                 MaxPop = I->second;
1714                 MaxBlock = I->first;
1715               }
1716             }
1717             if (MaxBlock) {
1718               // Make this the new default, allowing us to delete any explicit
1719               // edges to it.
1720               SI->setSuccessor(0, MaxBlock);
1721               Changed = true;
1722
1723               // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1724               // it.
1725               if (isa<PHINode>(MaxBlock->begin()))
1726                 for (unsigned i = 0; i != MaxPop-1; ++i)
1727                   MaxBlock->removePredecessor(SI->getParent());
1728
1729               for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1730                 if (SI->getSuccessor(i) == MaxBlock) {
1731                   SI->removeCase(i);
1732                   --i; --e;
1733                 }
1734             }
1735           }
1736         } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1737           if (II->getUnwindDest() == BB) {
1738             // Convert the invoke to a call instruction.  This would be a good
1739             // place to note that the call does not throw though.
1740             BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1741             II->removeFromParent();   // Take out of symbol table
1742
1743             // Insert the call now...
1744             std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1745             CallInst *CI = new CallInst(II->getCalledValue(), Args,
1746                                         II->getName(), BI);
1747             CI->setCallingConv(II->getCallingConv());
1748             // If the invoke produced a value, the Call does now instead.
1749             II->replaceAllUsesWith(CI);
1750             delete II;
1751             Changed = true;
1752           }
1753         }
1754       }
1755
1756       // If this block is now dead, remove it.
1757       if (pred_begin(BB) == pred_end(BB)) {
1758         // We know there are no successors, so just nuke the block.
1759         M->getBasicBlockList().erase(BB);
1760         return true;
1761       }
1762     }
1763   }
1764
1765   // Merge basic blocks into their predecessor if there is only one distinct
1766   // pred, and if there is only one distinct successor of the predecessor, and
1767   // if there are no PHI nodes.
1768   //
1769   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1770   BasicBlock *OnlyPred = *PI++;
1771   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
1772     if (*PI != OnlyPred) {
1773       OnlyPred = 0;       // There are multiple different predecessors...
1774       break;
1775     }
1776
1777   BasicBlock *OnlySucc = 0;
1778   if (OnlyPred && OnlyPred != BB &&    // Don't break self loops
1779       OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1780     // Check to see if there is only one distinct successor...
1781     succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1782     OnlySucc = BB;
1783     for (; SI != SE; ++SI)
1784       if (*SI != OnlySucc) {
1785         OnlySucc = 0;     // There are multiple distinct successors!
1786         break;
1787       }
1788   }
1789
1790   if (OnlySucc) {
1791     DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
1792
1793     // Resolve any PHI nodes at the start of the block.  They are all
1794     // guaranteed to have exactly one entry if they exist, unless there are
1795     // multiple duplicate (but guaranteed to be equal) entries for the
1796     // incoming edges.  This occurs when there are multiple edges from
1797     // OnlyPred to OnlySucc.
1798     //
1799     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1800       PN->replaceAllUsesWith(PN->getIncomingValue(0));
1801       BB->getInstList().pop_front();  // Delete the phi node.
1802     }
1803
1804     // Delete the unconditional branch from the predecessor.
1805     OnlyPred->getInstList().pop_back();
1806
1807     // Move all definitions in the successor to the predecessor.
1808     OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1809
1810     // Make all PHI nodes that referred to BB now refer to Pred as their
1811     // source.
1812     BB->replaceAllUsesWith(OnlyPred);
1813
1814     // Inherit predecessors name if it exists.
1815     if (!OnlyPred->hasName())
1816       OnlyPred->takeName(BB);
1817     
1818     // Erase basic block from the function.
1819     M->getBasicBlockList().erase(BB);
1820
1821     return true;
1822   }
1823
1824   // Otherwise, if this block only has a single predecessor, and if that block
1825   // is a conditional branch, see if we can hoist any code from this block up
1826   // into our predecessor.
1827   if (OnlyPred)
1828     if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1829       if (BI->isConditional()) {
1830         // Get the other block.
1831         BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1832         PI = pred_begin(OtherBB);
1833         ++PI;
1834         if (PI == pred_end(OtherBB)) {
1835           // We have a conditional branch to two blocks that are only reachable
1836           // from the condbr.  We know that the condbr dominates the two blocks,
1837           // so see if there is any identical code in the "then" and "else"
1838           // blocks.  If so, we can hoist it up to the branching block.
1839           Changed |= HoistThenElseCodeToIf(BI);
1840         }
1841       }
1842
1843   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1844     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1845       // Change br (X == 0 | X == 1), T, F into a switch instruction.
1846       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1847         Instruction *Cond = cast<Instruction>(BI->getCondition());
1848         // If this is a bunch of seteq's or'd together, or if it's a bunch of
1849         // 'setne's and'ed together, collect them.
1850         Value *CompVal = 0;
1851         std::vector<ConstantInt*> Values;
1852         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1853         if (CompVal && CompVal->getType()->isInteger()) {
1854           // There might be duplicate constants in the list, which the switch
1855           // instruction can't handle, remove them now.
1856           std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1857           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1858
1859           // Figure out which block is which destination.
1860           BasicBlock *DefaultBB = BI->getSuccessor(1);
1861           BasicBlock *EdgeBB    = BI->getSuccessor(0);
1862           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1863
1864           // Create the new switch instruction now.
1865           SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1866
1867           // Add all of the 'cases' to the switch instruction.
1868           for (unsigned i = 0, e = Values.size(); i != e; ++i)
1869             New->addCase(Values[i], EdgeBB);
1870
1871           // We added edges from PI to the EdgeBB.  As such, if there were any
1872           // PHI nodes in EdgeBB, they need entries to be added corresponding to
1873           // the number of edges added.
1874           for (BasicBlock::iterator BBI = EdgeBB->begin();
1875                isa<PHINode>(BBI); ++BBI) {
1876             PHINode *PN = cast<PHINode>(BBI);
1877             Value *InVal = PN->getIncomingValueForBlock(*PI);
1878             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1879               PN->addIncoming(InVal, *PI);
1880           }
1881
1882           // Erase the old branch instruction.
1883           (*PI)->getInstList().erase(BI);
1884
1885           // Erase the potentially condition tree that was used to computed the
1886           // branch condition.
1887           ErasePossiblyDeadInstructionTree(Cond);
1888           return true;
1889         }
1890       }
1891
1892   // If there is a trivial two-entry PHI node in this basic block, and we can
1893   // eliminate it, do so now.
1894   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1895     if (PN->getNumIncomingValues() == 2)
1896       Changed |= FoldTwoEntryPHINode(PN); 
1897
1898   return Changed;
1899 }