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