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