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