Minor cleanups.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions.  This pass does not modify the CFG This pass is where algebraic
5 // simplification happens.
6 //
7 // This pass combines things like:
8 //    %Y = add int 1, %X
9 //    %Z = add int 1, %Y
10 // into:
11 //    %Z = add int 2, %X
12 //
13 // This is a simple worklist driven algorithm.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 #include "llvm/Transforms/Utils/Local.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "Support/Statistic.h"
27 #include <algorithm>
28
29 namespace {
30   Statistic<> NumCombined ("instcombine", "Number of insts combined");
31   Statistic<> NumConstProp("instcombine", "Number of constant folds");
32   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
33
34   class InstCombiner : public FunctionPass,
35                        public InstVisitor<InstCombiner, Instruction*> {
36     // Worklist of all of the instructions that need to be simplified.
37     std::vector<Instruction*> WorkList;
38
39     void AddUsesToWorkList(Instruction &I) {
40       // The instruction was simplified, add all users of the instruction to
41       // the work lists because they might get more simplified now...
42       //
43       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
44            UI != UE; ++UI)
45         WorkList.push_back(cast<Instruction>(*UI));
46     }
47
48     // removeFromWorkList - remove all instances of I from the worklist.
49     void removeFromWorkList(Instruction *I);
50   public:
51     virtual bool runOnFunction(Function &F);
52
53     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54       AU.setPreservesCFG();
55     }
56
57     // Visitation implementation - Implement instruction combining for different
58     // instruction types.  The semantics are as follows:
59     // Return Value:
60     //    null        - No change was made
61     //     I          - Change was made, I is still valid, I may be dead though
62     //   otherwise    - Change was made, replace I with returned instruction
63     //   
64     Instruction *visitAdd(BinaryOperator &I);
65     Instruction *visitSub(BinaryOperator &I);
66     Instruction *visitMul(BinaryOperator &I);
67     Instruction *visitDiv(BinaryOperator &I);
68     Instruction *visitRem(BinaryOperator &I);
69     Instruction *visitAnd(BinaryOperator &I);
70     Instruction *visitOr (BinaryOperator &I);
71     Instruction *visitXor(BinaryOperator &I);
72     Instruction *visitSetCondInst(BinaryOperator &I);
73     Instruction *visitShiftInst(ShiftInst &I);
74     Instruction *visitCastInst(CastInst &CI);
75     Instruction *visitPHINode(PHINode &PN);
76     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
77     Instruction *visitAllocationInst(AllocationInst &AI);
78
79     // visitInstruction - Specify what to return for unhandled instructions...
80     Instruction *visitInstruction(Instruction &I) { return 0; }
81
82     // InsertNewInstBefore - insert an instruction New before instruction Old
83     // in the program.  Add the new instruction to the worklist.
84     //
85     void InsertNewInstBefore(Instruction *New, Instruction &Old) {
86       assert(New && New->getParent() == 0 &&
87              "New instruction already inserted into a basic block!");
88       BasicBlock *BB = Old.getParent();
89       BB->getInstList().insert(&Old, New);  // Insert inst
90       WorkList.push_back(New);              // Add to worklist
91     }
92
93     // ReplaceInstUsesWith - This method is to be used when an instruction is
94     // found to be dead, replacable with another preexisting expression.  Here
95     // we add all uses of I to the worklist, replace all uses of I with the new
96     // value, then return I, so that the inst combiner will know that I was
97     // modified.
98     //
99     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
100       AddUsesToWorkList(I);         // Add all modified instrs to worklist
101       I.replaceAllUsesWith(V);
102       return &I;
103     }
104
105     // SimplifyCommutative - This performs a few simplifications for commutative
106     // operators...
107     bool SimplifyCommutative(BinaryOperator &I);
108
109   };
110
111   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
112 }
113
114 // getComplexity:  Assign a complexity or rank value to LLVM Values...
115 //   0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
116 static unsigned getComplexity(Value *V) {
117   if (isa<Instruction>(V)) {
118     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
119       return 2;
120     return 3;
121   }
122   if (isa<Argument>(V)) return 2;
123   return isa<Constant>(V) ? 0 : 1;
124 }
125
126 // isOnlyUse - Return true if this instruction will be deleted if we stop using
127 // it.
128 static bool isOnlyUse(Value *V) {
129   return V->use_size() == 1 || isa<Constant>(V);
130 }
131
132 // SimplifyCommutative - This performs a few simplifications for commutative
133 // operators:
134 //
135 //  1. Order operands such that they are listed from right (least complex) to
136 //     left (most complex).  This puts constants before unary operators before
137 //     binary operators.
138 //
139 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
140 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
141 //
142 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
143   bool Changed = false;
144   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
145     Changed = !I.swapOperands();
146   
147   if (!I.isAssociative()) return Changed;
148   Instruction::BinaryOps Opcode = I.getOpcode();
149   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
150     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
151       if (isa<Constant>(I.getOperand(1))) {
152         Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),
153             cast<Constant>(I.getOperand(1)), cast<Constant>(Op->getOperand(1)));
154         assert(Folded && "Couldn't constant fold commutative operand?");
155         I.setOperand(0, Op->getOperand(0));
156         I.setOperand(1, Folded);
157         return true;
158       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
159         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
160             isOnlyUse(Op) && isOnlyUse(Op1)) {
161           Constant *C1 = cast<Constant>(Op->getOperand(1));
162           Constant *C2 = cast<Constant>(Op1->getOperand(1));
163
164           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
165           Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),C1,C2);
166           assert(Folded && "Couldn't constant fold commutative operand?");
167           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
168                                                     Op1->getOperand(0),
169                                                     Op1->getName(), &I);
170           WorkList.push_back(New);
171           I.setOperand(0, New);
172           I.setOperand(1, Folded);
173           return true;
174         }      
175     }
176   return Changed;
177 }
178
179 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
180 // if the LHS is a constant zero (which is the 'negate' form).
181 //
182 static inline Value *dyn_castNegVal(Value *V) {
183   if (BinaryOperator::isNeg(V))
184     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
185
186   // Constants can be considered to be negated values if they can be folded...
187   if (Constant *C = dyn_cast<Constant>(V))
188     return *Constant::getNullValue(V->getType()) - *C;
189   return 0;
190 }
191
192 static inline Value *dyn_castNotVal(Value *V) {
193   if (BinaryOperator::isNot(V))
194     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
195
196   // Constants can be considered to be not'ed values...
197   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
198     return *ConstantIntegral::getAllOnesValue(C->getType()) ^ *C;
199   return 0;
200 }
201
202 // dyn_castFoldableMul - If this value is a multiply that can be folded into
203 // other computations (because it has a constant operand), return the
204 // non-constant operand of the multiply.
205 //
206 static inline Value *dyn_castFoldableMul(Value *V) {
207   if (V->use_size() == 1 && V->getType()->isInteger())
208     if (Instruction *I = dyn_cast<Instruction>(V))
209       if (I->getOpcode() == Instruction::Mul)
210         if (isa<Constant>(I->getOperand(1)))
211           return I->getOperand(0);
212   return 0;
213 }
214
215 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
216 // a constant, return the constant being anded with.
217 //
218 static inline Constant *dyn_castMaskingAnd(Value *V) {
219   if (Instruction *I = dyn_cast<Instruction>(V))
220     if (I->getOpcode() == Instruction::And)
221       return dyn_cast<Constant>(I->getOperand(1));
222
223   // If this is a constant, it acts just like we were masking with it.
224   return dyn_cast<Constant>(V);
225 }
226
227 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
228 // power of 2.
229 static unsigned Log2(uint64_t Val) {
230   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
231   unsigned Count = 0;
232   while (Val != 1) {
233     if (Val & 1) return 0;    // Multiple bits set?
234     Val >>= 1;
235     ++Count;
236   }
237   return Count;
238 }
239
240 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
241   bool Changed = SimplifyCommutative(I);
242   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
243
244   // Eliminate 'add int %X, 0'
245   if (RHS == Constant::getNullValue(I.getType()))
246     return ReplaceInstUsesWith(I, LHS);
247
248   // -A + B  -->  B - A
249   if (Value *V = dyn_castNegVal(LHS))
250     return BinaryOperator::create(Instruction::Sub, RHS, V);
251
252   // A + -B  -->  A - B
253   if (!isa<Constant>(RHS))
254     if (Value *V = dyn_castNegVal(RHS))
255       return BinaryOperator::create(Instruction::Sub, LHS, V);
256
257   // X*C + X --> X * (C+1)
258   if (dyn_castFoldableMul(LHS) == RHS) {
259     Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
260                     *ConstantInt::get(I.getType(), 1);
261     assert(CP1 && "Couldn't constant fold C + 1?");
262     return BinaryOperator::create(Instruction::Mul, RHS, CP1);
263   }
264
265   // X + X*C --> X * (C+1)
266   if (dyn_castFoldableMul(RHS) == LHS) {
267     Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
268                     *ConstantInt::get(I.getType(), 1);
269     assert(CP1 && "Couldn't constant fold C + 1?");
270     return BinaryOperator::create(Instruction::Mul, LHS, CP1);
271   }
272
273   // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
274   if (Constant *C1 = dyn_castMaskingAnd(LHS))
275     if (Constant *C2 = dyn_castMaskingAnd(RHS))
276       if ((*C1 & *C2)->isNullValue())
277         return BinaryOperator::create(Instruction::Or, LHS, RHS);
278
279   return Changed ? &I : 0;
280 }
281
282 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
283   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
284
285   if (Op0 == Op1)         // sub X, X  -> 0
286     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
287
288   // If this is a 'B = x-(-A)', change to B = x+A...
289   if (Value *V = dyn_castNegVal(Op1))
290     return BinaryOperator::create(Instruction::Add, Op0, V);
291
292   // Replace (-1 - A) with (~A)...
293   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
294     if (C->isAllOnesValue())
295       return BinaryOperator::createNot(Op1);
296
297   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
298     if (Op1I->use_size() == 1) {
299       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
300       // is not used by anyone else...
301       //
302       if (Op1I->getOpcode() == Instruction::Sub) {
303         // Swap the two operands of the subexpr...
304         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
305         Op1I->setOperand(0, IIOp1);
306         Op1I->setOperand(1, IIOp0);
307         
308         // Create the new top level add instruction...
309         return BinaryOperator::create(Instruction::Add, Op0, Op1);
310       }
311
312       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
313       //
314       if (Op1I->getOpcode() == Instruction::And &&
315           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
316         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
317
318         Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
319         return BinaryOperator::create(Instruction::And, Op0, NewNot);
320       }
321
322       // X - X*C --> X * (1-C)
323       if (dyn_castFoldableMul(Op1I) == Op0) {
324         Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
325                         *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
326         assert(CP1 && "Couldn't constant fold 1-C?");
327         return BinaryOperator::create(Instruction::Mul, Op0, CP1);
328       }
329     }
330
331   // X*C - X --> X * (C-1)
332   if (dyn_castFoldableMul(Op0) == Op1) {
333     Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
334                     *ConstantInt::get(I.getType(), 1);
335     assert(CP1 && "Couldn't constant fold C - 1?");
336     return BinaryOperator::create(Instruction::Mul, Op1, CP1);
337   }
338
339   return 0;
340 }
341
342 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
343   bool Changed = SimplifyCommutative(I);
344   Value *Op0 = I.getOperand(0);
345
346   // Simplify mul instructions with a constant RHS...
347   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
348     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
349       const Type *Ty = CI->getType();
350       uint64_t Val = Ty->isSigned() ?
351                           (uint64_t)cast<ConstantSInt>(CI)->getValue() : 
352                                     cast<ConstantUInt>(CI)->getValue();
353       switch (Val) {
354       case 0:
355         return ReplaceInstUsesWith(I, Op1);  // Eliminate 'mul double %X, 0'
356       case 1:
357         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul int %X, 1'
358       case 2:                     // Convert 'mul int %X, 2' to 'add int %X, %X'
359         return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
360       }
361
362       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
363         return new ShiftInst(Instruction::Shl, Op0,
364                              ConstantUInt::get(Type::UByteTy, C));
365     } else {
366       ConstantFP *Op1F = cast<ConstantFP>(Op1);
367       if (Op1F->isNullValue())
368         return ReplaceInstUsesWith(I, Op1);
369
370       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
371       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
372       if (Op1F->getValue() == 1.0)
373         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
374     }
375   }
376
377   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
378     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
379       return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
380
381   return Changed ? &I : 0;
382 }
383
384 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
385   // div X, 1 == X
386   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
387     if (RHS->equalsInt(1))
388       return ReplaceInstUsesWith(I, I.getOperand(0));
389
390     // Check to see if this is an unsigned division with an exact power of 2,
391     // if so, convert to a right shift.
392     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
393       if (uint64_t Val = C->getValue())    // Don't break X / 0
394         if (uint64_t C = Log2(Val))
395           return new ShiftInst(Instruction::Shr, I.getOperand(0),
396                                ConstantUInt::get(Type::UByteTy, C));
397   }
398
399   // 0 / X == 0, we don't need to preserve faults!
400   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
401     if (LHS->equalsInt(0))
402       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
403
404   return 0;
405 }
406
407
408 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
409   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
410     if (RHS->equalsInt(1))  // X % 1 == 0
411       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
412
413     // Check to see if this is an unsigned remainder with an exact power of 2,
414     // if so, convert to a bitwise and.
415     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
416       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
417         if (Log2(Val))
418           return BinaryOperator::create(Instruction::And, I.getOperand(0),
419                                         ConstantUInt::get(I.getType(), Val-1));
420   }
421
422   // 0 % X == 0, we don't need to preserve faults!
423   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
424     if (LHS->equalsInt(0))
425       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
426
427   return 0;
428 }
429
430 // isMaxValueMinusOne - return true if this is Max-1
431 static bool isMaxValueMinusOne(const ConstantInt *C) {
432   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
433     // Calculate -1 casted to the right type...
434     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
435     uint64_t Val = ~0ULL;                // All ones
436     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
437     return CU->getValue() == Val-1;
438   }
439
440   const ConstantSInt *CS = cast<ConstantSInt>(C);
441   
442   // Calculate 0111111111..11111
443   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
444   int64_t Val = INT64_MAX;             // All ones
445   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
446   return CS->getValue() == Val-1;
447 }
448
449 // isMinValuePlusOne - return true if this is Min+1
450 static bool isMinValuePlusOne(const ConstantInt *C) {
451   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
452     return CU->getValue() == 1;
453
454   const ConstantSInt *CS = cast<ConstantSInt>(C);
455   
456   // Calculate 1111111111000000000000 
457   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
458   int64_t Val = -1;                    // All ones
459   Val <<= TypeBits-1;                  // Shift over to the right spot
460   return CS->getValue() == Val+1;
461 }
462
463
464 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
465   bool Changed = SimplifyCommutative(I);
466   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
467
468   // and X, X = X   and X, 0 == 0
469   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
470     return ReplaceInstUsesWith(I, Op1);
471
472   // and X, -1 == X
473   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
474     if (RHS->isAllOnesValue())
475       return ReplaceInstUsesWith(I, Op0);
476
477   Value *Op0NotVal = dyn_castNotVal(Op0);
478   Value *Op1NotVal = dyn_castNotVal(Op1);
479
480   // (~A & ~B) == (~(A | B)) - Demorgan's Law
481   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
482     Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
483                                              Op1NotVal,I.getName()+".demorgan",
484                                              &I);
485     WorkList.push_back(Or);
486     return BinaryOperator::createNot(Or);
487   }
488
489   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
490     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
491
492   return Changed ? &I : 0;
493 }
494
495
496
497 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
498   bool Changed = SimplifyCommutative(I);
499   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
500
501   // or X, X = X   or X, 0 == X
502   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
503     return ReplaceInstUsesWith(I, Op0);
504
505   // or X, -1 == -1
506   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
507     if (RHS->isAllOnesValue())
508       return ReplaceInstUsesWith(I, Op1);
509
510   Value *Op0NotVal = dyn_castNotVal(Op0);
511   Value *Op1NotVal = dyn_castNotVal(Op1);
512
513   if (Op1 == Op0NotVal)   // ~A | A == -1
514     return ReplaceInstUsesWith(I, 
515                                ConstantIntegral::getAllOnesValue(I.getType()));
516
517   if (Op0 == Op1NotVal)   // A | ~A == -1
518     return ReplaceInstUsesWith(I, 
519                                ConstantIntegral::getAllOnesValue(I.getType()));
520
521   // (~A | ~B) == (~(A & B)) - Demorgan's Law
522   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
523     Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
524                                               Op1NotVal,I.getName()+".demorgan",
525                                               &I);
526     WorkList.push_back(And);
527     return BinaryOperator::createNot(And);
528   }
529
530   return Changed ? &I : 0;
531 }
532
533
534
535 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
536   bool Changed = SimplifyCommutative(I);
537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
538
539   // xor X, X = 0
540   if (Op0 == Op1)
541     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
542
543   if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
544     // xor X, 0 == X
545     if (Op1C->isNullValue())
546       return ReplaceInstUsesWith(I, Op0);
547
548     // Is this a "NOT" instruction?
549     if (Op1C->isAllOnesValue()) {
550       // xor (xor X, -1), -1 = not (not X) = X
551       if (Value *X = dyn_castNotVal(Op0))
552         return ReplaceInstUsesWith(I, X);
553
554       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
555       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
556         if (SCI->use_size() == 1)
557           return new SetCondInst(SCI->getInverseCondition(),
558                                  SCI->getOperand(0), SCI->getOperand(1));
559     }
560   }
561
562   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
563     if (X == Op1)
564       return ReplaceInstUsesWith(I,
565                                 ConstantIntegral::getAllOnesValue(I.getType()));
566
567   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
568     if (X == Op0)
569       return ReplaceInstUsesWith(I,
570                                 ConstantIntegral::getAllOnesValue(I.getType()));
571
572   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
573     if (Op1I->getOpcode() == Instruction::Or)
574       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
575         cast<BinaryOperator>(Op1I)->swapOperands();
576         I.swapOperands();
577         std::swap(Op0, Op1);
578       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
579         I.swapOperands();
580         std::swap(Op0, Op1);
581       }
582
583   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
584     if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
585       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
586         cast<BinaryOperator>(Op0I)->swapOperands();
587       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
588         Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
589         WorkList.push_back(cast<Instruction>(NotB));
590         return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
591                                       NotB);
592       }
593     }
594
595   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
596   if (Constant *C1 = dyn_castMaskingAnd(Op0))
597     if (Constant *C2 = dyn_castMaskingAnd(Op1))
598       if ((*C1 & *C2)->isNullValue())
599         return BinaryOperator::create(Instruction::Or, Op0, Op1);
600
601   return Changed ? &I : 0;
602 }
603
604 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
605 static Constant *AddOne(ConstantInt *C) {
606   Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
607   assert(Result && "Constant folding integer addition failed!");
608   return Result;
609 }
610 static Constant *SubOne(ConstantInt *C) {
611   Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
612   assert(Result && "Constant folding integer addition failed!");
613   return Result;
614 }
615
616 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
617 // true when both operands are equal...
618 //
619 static bool isTrueWhenEqual(Instruction &I) {
620   return I.getOpcode() == Instruction::SetEQ ||
621          I.getOpcode() == Instruction::SetGE ||
622          I.getOpcode() == Instruction::SetLE;
623 }
624
625 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
626   bool Changed = SimplifyCommutative(I);
627   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
628   const Type *Ty = Op0->getType();
629
630   // setcc X, X
631   if (Op0 == Op1)
632     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
633
634   // setcc <global*>, 0 - Global value addresses are never null!
635   if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
636     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
637
638   // setcc's with boolean values can always be turned into bitwise operations
639   if (Ty == Type::BoolTy) {
640     // If this is <, >, or !=, we can change this into a simple xor instruction
641     if (!isTrueWhenEqual(I))
642       return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
643
644     // Otherwise we need to make a temporary intermediate instruction and insert
645     // it into the instruction stream.  This is what we are after:
646     //
647     //  seteq bool %A, %B -> ~(A^B)
648     //  setle bool %A, %B -> ~A | B
649     //  setge bool %A, %B -> A | ~B
650     //
651     if (I.getOpcode() == Instruction::SetEQ) {  // seteq case
652       Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
653                                                 I.getName()+"tmp");
654       InsertNewInstBefore(Xor, I);
655       return BinaryOperator::createNot(Xor, I.getName());
656     }
657
658     // Handle the setXe cases...
659     assert(I.getOpcode() == Instruction::SetGE ||
660            I.getOpcode() == Instruction::SetLE);
661
662     if (I.getOpcode() == Instruction::SetGE)
663       std::swap(Op0, Op1);                   // Change setge -> setle
664
665     // Now we just have the SetLE case.
666     Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
667     InsertNewInstBefore(Not, I);
668     return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
669   }
670
671   // Check to see if we are doing one of many comparisons against constant
672   // integers at the end of their ranges...
673   //
674   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
675     // Check to see if we are comparing against the minimum or maximum value...
676     if (CI->isMinValue()) {
677       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
678         return ReplaceInstUsesWith(I, ConstantBool::False);
679       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
680         return ReplaceInstUsesWith(I, ConstantBool::True);
681       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
682         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
683       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
684         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
685
686     } else if (CI->isMaxValue()) {
687       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
688         return ReplaceInstUsesWith(I, ConstantBool::False);
689       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
690         return ReplaceInstUsesWith(I, ConstantBool::True);
691       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
692         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
693       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
694         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
695
696       // Comparing against a value really close to min or max?
697     } else if (isMinValuePlusOne(CI)) {
698       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
699         return BinaryOperator::create(Instruction::SetEQ, Op0,
700                                       SubOne(CI), I.getName());
701       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
702         return BinaryOperator::create(Instruction::SetNE, Op0,
703                                       SubOne(CI), I.getName());
704
705     } else if (isMaxValueMinusOne(CI)) {
706       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
707         return BinaryOperator::create(Instruction::SetEQ, Op0,
708                                       AddOne(CI), I.getName());
709       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
710         return BinaryOperator::create(Instruction::SetNE, Op0,
711                                       AddOne(CI), I.getName());
712     }
713   }
714
715   return Changed ? &I : 0;
716 }
717
718
719
720 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
721   assert(I.getOperand(1)->getType() == Type::UByteTy);
722   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
723
724   // shl X, 0 == X and shr X, 0 == X
725   // shl 0, X == 0 and shr 0, X == 0
726   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
727       Op0 == Constant::getNullValue(Op0->getType()))
728     return ReplaceInstUsesWith(I, Op0);
729
730   // If this is a shift of a shift, see if we can fold the two together...
731   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
732     if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
733       ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
734       unsigned ShiftAmt1 = ShiftAmt1C->getValue();
735       unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
736
737       // Check for (A << c1) << c2   and   (A >> c1) >> c2
738       if (I.getOpcode() == Op0SI->getOpcode()) {
739         unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
740         return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
741                              ConstantUInt::get(Type::UByteTy, Amt));
742       }
743
744       if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
745         // Calculate bitmask for what gets shifted off the edge...
746         Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
747         if (I.getOpcode() == Instruction::Shr)
748           C = *C >> *ShiftAmt1C;
749         else
750           C = *C << *ShiftAmt1C;
751         assert(C && "Couldn't constant fold shift expression?");
752           
753         Instruction *Mask =
754           BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
755                                  C, Op0SI->getOperand(0)->getName()+".mask",&I);
756         WorkList.push_back(Mask);
757           
758         // Figure out what flavor of shift we should use...
759         if (ShiftAmt1 == ShiftAmt2)
760           return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
761         else if (ShiftAmt1 < ShiftAmt2) {
762           return new ShiftInst(I.getOpcode(), Mask,
763                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
764         } else {
765           return new ShiftInst(Op0SI->getOpcode(), Mask,
766                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
767         }
768       }
769     }
770   }
771
772   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
773   // a signed value.
774   //
775   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
776     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
777     if (CUI->getValue() >= TypeBits &&
778         (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
779       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
780
781     // Check to see if we are shifting left by 1.  If so, turn it into an add
782     // instruction.
783     if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
784       // Convert 'shl int %X, 1' to 'add int %X, %X'
785       return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
786
787   }
788
789   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
790   if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
791     if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
792       return ReplaceInstUsesWith(I, CSI);
793   
794   return 0;
795 }
796
797
798 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
799 // instruction.
800 //
801 static inline bool isEliminableCastOfCast(const CastInst &CI,
802                                           const CastInst *CSrc) {
803   assert(CI.getOperand(0) == CSrc);
804   const Type *SrcTy = CSrc->getOperand(0)->getType();
805   const Type *MidTy = CSrc->getType();
806   const Type *DstTy = CI.getType();
807
808   // It is legal to eliminate the instruction if casting A->B->A if the sizes
809   // are identical and the bits don't get reinterpreted (for example 
810   // int->float->int would not be allowed)
811   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
812     return true;
813
814   // Allow free casting and conversion of sizes as long as the sign doesn't
815   // change...
816   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
817     unsigned SrcSize = SrcTy->getPrimitiveSize();
818     unsigned MidSize = MidTy->getPrimitiveSize();
819     unsigned DstSize = DstTy->getPrimitiveSize();
820
821     // Cases where we are monotonically decreasing the size of the type are
822     // always ok, regardless of what sign changes are going on.
823     //
824     if (SrcSize >= MidSize && MidSize >= DstSize)
825       return true;
826
827     // Cases where the source and destination type are the same, but the middle
828     // type is bigger are noops.
829     //
830     if (SrcSize == DstSize && MidSize > SrcSize)
831       return true;
832
833     // If we are monotonically growing, things are more complex.
834     //
835     if (SrcSize <= MidSize && MidSize <= DstSize) {
836       // We have eight combinations of signedness to worry about. Here's the
837       // table:
838       static const int SignTable[8] = {
839         // CODE, SrcSigned, MidSigned, DstSigned, Comment
840         1,     //   U          U          U       Always ok
841         1,     //   U          U          S       Always ok
842         3,     //   U          S          U       Ok iff SrcSize != MidSize
843         3,     //   U          S          S       Ok iff SrcSize != MidSize
844         0,     //   S          U          U       Never ok
845         2,     //   S          U          S       Ok iff MidSize == DstSize
846         1,     //   S          S          U       Always ok
847         1,     //   S          S          S       Always ok
848       };
849
850       // Choose an action based on the current entry of the signtable that this
851       // cast of cast refers to...
852       unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
853       switch (SignTable[Row]) {
854       case 0: return false;              // Never ok
855       case 1: return true;               // Always ok
856       case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
857       case 3:                            // Ok iff SrcSize != MidSize
858         return SrcSize != MidSize || SrcTy == Type::BoolTy;
859       default: assert(0 && "Bad entry in sign table!");
860       }
861     }
862   }
863
864   // Otherwise, we cannot succeed.  Specifically we do not want to allow things
865   // like:  short -> ushort -> uint, because this can create wrong results if
866   // the input short is negative!
867   //
868   return false;
869 }
870
871
872 // CastInst simplification
873 //
874 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
875   // If the user is casting a value to the same type, eliminate this cast
876   // instruction...
877   if (CI.getType() == CI.getOperand(0)->getType())
878     return ReplaceInstUsesWith(CI, CI.getOperand(0));
879
880   // If casting the result of another cast instruction, try to eliminate this
881   // one!
882   //
883   if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
884     if (isEliminableCastOfCast(CI, CSrc)) {
885       // This instruction now refers directly to the cast's src operand.  This
886       // has a good chance of making CSrc dead.
887       CI.setOperand(0, CSrc->getOperand(0));
888       return &CI;
889     }
890
891     // If this is an A->B->A cast, and we are dealing with integral types, try
892     // to convert this into a logical 'and' instruction.
893     //
894     if (CSrc->getOperand(0)->getType() == CI.getType() &&
895         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
896         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
897         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
898       assert(CSrc->getType() != Type::ULongTy &&
899              "Cannot have type bigger than ulong!");
900       unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
901       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
902       return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
903                                     AndOp);
904     }
905   }
906
907   return 0;
908 }
909
910
911 // PHINode simplification
912 //
913 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
914   // If the PHI node only has one incoming value, eliminate the PHI node...
915   if (PN.getNumIncomingValues() == 1)
916     return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
917   
918   // Otherwise if all of the incoming values are the same for the PHI, replace
919   // the PHI node with the incoming value.
920   //
921   Value *InVal = 0;
922   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
923     if (PN.getIncomingValue(i) != &PN)  // Not the PHI node itself...
924       if (InVal && PN.getIncomingValue(i) != InVal)
925         return 0;  // Not the same, bail out.
926       else
927         InVal = PN.getIncomingValue(i);
928
929   // The only case that could cause InVal to be null is if we have a PHI node
930   // that only has entries for itself.  In this case, there is no entry into the
931   // loop, so kill the PHI.
932   //
933   if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
934
935   // All of the incoming values are the same, replace the PHI node now.
936   return ReplaceInstUsesWith(PN, InVal);
937 }
938
939
940 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
941   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
942   // If so, eliminate the noop.
943   if ((GEP.getNumOperands() == 2 &&
944        GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
945       GEP.getNumOperands() == 1)
946     return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
947
948   // Combine Indices - If the source pointer to this getelementptr instruction
949   // is a getelementptr instruction, combine the indices of the two
950   // getelementptr instructions into a single instruction.
951   //
952   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
953     std::vector<Value *> Indices;
954   
955     // Can we combine the two pointer arithmetics offsets?
956     if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
957         isa<Constant>(GEP.getOperand(1))) {
958       // Replace: gep (gep %P, long C1), long C2, ...
959       // With:    gep %P, long (C1+C2), ...
960       Value *Sum = *cast<Constant>(Src->getOperand(1)) +
961                    *cast<Constant>(GEP.getOperand(1));
962       assert(Sum && "Constant folding of longs failed!?");
963       GEP.setOperand(0, Src->getOperand(0));
964       GEP.setOperand(1, Sum);
965       AddUsesToWorkList(*Src);   // Reduce use count of Src
966       return &GEP;
967     } else if (Src->getNumOperands() == 2) {
968       // Replace: gep (gep %P, long B), long A, ...
969       // With:    T = long A+B; gep %P, T, ...
970       //
971       Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
972                                           GEP.getOperand(1),
973                                           Src->getName()+".sum", &GEP);
974       GEP.setOperand(0, Src->getOperand(0));
975       GEP.setOperand(1, Sum);
976       WorkList.push_back(cast<Instruction>(Sum));
977       return &GEP;
978     } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
979                Src->getNumOperands() != 1) { 
980       // Otherwise we can do the fold if the first index of the GEP is a zero
981       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
982       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
983     } else if (Src->getOperand(Src->getNumOperands()-1) == 
984                Constant::getNullValue(Type::LongTy)) {
985       // If the src gep ends with a constant array index, merge this get into
986       // it, even if we have a non-zero array index.
987       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
988       Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
989     }
990
991     if (!Indices.empty())
992       return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
993
994   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
995     // GEP of global variable.  If all of the indices for this GEP are
996     // constants, we can promote this to a constexpr instead of an instruction.
997
998     // Scan for nonconstants...
999     std::vector<Constant*> Indices;
1000     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1001     for (; I != E && isa<Constant>(*I); ++I)
1002       Indices.push_back(cast<Constant>(*I));
1003
1004     if (I == E) {  // If they are all constants...
1005       Constant *CE =
1006         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1007
1008       // Replace all uses of the GEP with the new constexpr...
1009       return ReplaceInstUsesWith(GEP, CE);
1010     }
1011   }
1012
1013   return 0;
1014 }
1015
1016 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1017   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1018   if (AI.isArrayAllocation())    // Check C != 1
1019     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1020       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1021       AllocationInst *New = 0;
1022
1023       // Create and insert the replacement instruction...
1024       if (isa<MallocInst>(AI))
1025         New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1026       else {
1027         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1028         New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1029       }
1030       
1031       // Scan to the end of the allocation instructions, to skip over a block of
1032       // allocas if possible...
1033       //
1034       BasicBlock::iterator It = New;
1035       while (isa<AllocationInst>(*It)) ++It;
1036
1037       // Now that I is pointing to the first non-allocation-inst in the block,
1038       // insert our getelementptr instruction...
1039       //
1040       std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1041       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1042
1043       // Now make everything use the getelementptr instead of the original
1044       // allocation.
1045       ReplaceInstUsesWith(AI, V);
1046       return &AI;
1047     }
1048   return 0;
1049 }
1050
1051
1052
1053 void InstCombiner::removeFromWorkList(Instruction *I) {
1054   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1055                  WorkList.end());
1056 }
1057
1058 bool InstCombiner::runOnFunction(Function &F) {
1059   bool Changed = false;
1060
1061   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1062
1063   while (!WorkList.empty()) {
1064     Instruction *I = WorkList.back();  // Get an instruction from the worklist
1065     WorkList.pop_back();
1066
1067     // Check to see if we can DCE or ConstantPropagate the instruction...
1068     // Check to see if we can DIE the instruction...
1069     if (isInstructionTriviallyDead(I)) {
1070       // Add operands to the worklist...
1071       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1072         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1073           WorkList.push_back(Op);
1074
1075       ++NumDeadInst;
1076       BasicBlock::iterator BBI = I;
1077       if (dceInstruction(BBI)) {
1078         removeFromWorkList(I);
1079         continue;
1080       }
1081     } 
1082
1083     // Instruction isn't dead, see if we can constant propagate it...
1084     if (Constant *C = ConstantFoldInstruction(I)) {
1085       // Add operands to the worklist...
1086       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1087         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1088           WorkList.push_back(Op);
1089       ReplaceInstUsesWith(*I, C);
1090
1091       ++NumConstProp;
1092       BasicBlock::iterator BBI = I;
1093       if (dceInstruction(BBI)) {
1094         removeFromWorkList(I);
1095         continue;
1096       }
1097     }
1098     
1099     // Now that we have an instruction, try combining it to simplify it...
1100     if (Instruction *Result = visit(*I)) {
1101       ++NumCombined;
1102       // Should we replace the old instruction with a new one?
1103       if (Result != I) {
1104         // Instructions can end up on the worklist more than once.  Make sure
1105         // we do not process an instruction that has been deleted.
1106         removeFromWorkList(I);
1107         ReplaceInstWithInst(I, Result);
1108       } else {
1109         BasicBlock::iterator II = I;
1110
1111         // If the instruction was modified, it's possible that it is now dead.
1112         // if so, remove it.
1113         if (dceInstruction(II)) {
1114           // Instructions may end up in the worklist more than once.  Erase them
1115           // all.
1116           removeFromWorkList(I);
1117           Result = 0;
1118         }
1119       }
1120
1121       if (Result) {
1122         WorkList.push_back(Result);
1123         AddUsesToWorkList(*Result);
1124       }
1125       Changed = true;
1126     }
1127   }
1128
1129   return Changed;
1130 }
1131
1132 Pass *createInstructionCombiningPass() {
1133   return new InstCombiner();
1134 }