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