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