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