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