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