Implement select.ll:test12*
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int 1, %X
16 //    %Z = add int 1, %Y
17 // into:
18 //    %Z = add int 2, %X
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All SetCC instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //    N. This list is incomplete
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Intrinsics.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Constants.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "Support/Debug.h"
52 #include "Support/Statistic.h"
53 #include <algorithm>
54 using namespace llvm;
55
56 namespace {
57   Statistic<> NumCombined ("instcombine", "Number of insts combined");
58   Statistic<> NumConstProp("instcombine", "Number of constant folds");
59   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
61   class InstCombiner : public FunctionPass,
62                        public InstVisitor<InstCombiner, Instruction*> {
63     // Worklist of all of the instructions that need to be simplified.
64     std::vector<Instruction*> WorkList;
65     TargetData *TD;
66
67     /// AddUsersToWorkList - When an instruction is simplified, add all users of
68     /// the instruction to the work lists because they might get more simplified
69     /// now.
70     ///
71     void AddUsersToWorkList(Instruction &I) {
72       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
73            UI != UE; ++UI)
74         WorkList.push_back(cast<Instruction>(*UI));
75     }
76
77     /// AddUsesToWorkList - When an instruction is simplified, add operands to
78     /// the work lists because they might get more simplified now.
79     ///
80     void AddUsesToWorkList(Instruction &I) {
81       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83           WorkList.push_back(Op);
84     }
85
86     // removeFromWorkList - remove all instances of I from the worklist.
87     void removeFromWorkList(Instruction *I);
88   public:
89     virtual bool runOnFunction(Function &F);
90
91     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92       AU.addRequired<TargetData>();
93       AU.setPreservesCFG();
94     }
95
96     TargetData &getTargetData() const { return *TD; }
97
98     // Visitation implementation - Implement instruction combining for different
99     // instruction types.  The semantics are as follows:
100     // Return Value:
101     //    null        - No change was made
102     //     I          - Change was made, I is still valid, I may be dead though
103     //   otherwise    - Change was made, replace I with returned instruction
104     //   
105     Instruction *visitAdd(BinaryOperator &I);
106     Instruction *visitSub(BinaryOperator &I);
107     Instruction *visitMul(BinaryOperator &I);
108     Instruction *visitDiv(BinaryOperator &I);
109     Instruction *visitRem(BinaryOperator &I);
110     Instruction *visitAnd(BinaryOperator &I);
111     Instruction *visitOr (BinaryOperator &I);
112     Instruction *visitXor(BinaryOperator &I);
113     Instruction *visitSetCondInst(BinaryOperator &I);
114     Instruction *visitShiftInst(ShiftInst &I);
115     Instruction *visitCastInst(CastInst &CI);
116     Instruction *visitSelectInst(SelectInst &CI);
117     Instruction *visitCallInst(CallInst &CI);
118     Instruction *visitInvokeInst(InvokeInst &II);
119     Instruction *visitPHINode(PHINode &PN);
120     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
121     Instruction *visitAllocationInst(AllocationInst &AI);
122     Instruction *visitFreeInst(FreeInst &FI);
123     Instruction *visitLoadInst(LoadInst &LI);
124     Instruction *visitBranchInst(BranchInst &BI);
125
126     // visitInstruction - Specify what to return for unhandled instructions...
127     Instruction *visitInstruction(Instruction &I) { return 0; }
128
129   private:
130     Instruction *visitCallSite(CallSite CS);
131     bool transformConstExprCastCall(CallSite CS);
132
133   public:
134     // InsertNewInstBefore - insert an instruction New before instruction Old
135     // in the program.  Add the new instruction to the worklist.
136     //
137     Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
138       assert(New && New->getParent() == 0 &&
139              "New instruction already inserted into a basic block!");
140       BasicBlock *BB = Old.getParent();
141       BB->getInstList().insert(&Old, New);  // Insert inst
142       WorkList.push_back(New);              // Add to worklist
143       return New;
144     }
145
146     // ReplaceInstUsesWith - This method is to be used when an instruction is
147     // found to be dead, replacable with another preexisting expression.  Here
148     // we add all uses of I to the worklist, replace all uses of I with the new
149     // value, then return I, so that the inst combiner will know that I was
150     // modified.
151     //
152     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
153       AddUsersToWorkList(I);         // Add all modified instrs to worklist
154       if (&I != V) {
155         I.replaceAllUsesWith(V);
156         return &I;
157       } else {
158         // If we are replacing the instruction with itself, this must be in a
159         // segment of unreachable code, so just clobber the instruction.
160         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
161         return &I;
162       }
163     }
164
165     // EraseInstFromFunction - When dealing with an instruction that has side
166     // effects or produces a void value, we can't rely on DCE to delete the
167     // instruction.  Instead, visit methods should return the value returned by
168     // this function.
169     Instruction *EraseInstFromFunction(Instruction &I) {
170       assert(I.use_empty() && "Cannot erase instruction that is used!");
171       AddUsesToWorkList(I);
172       removeFromWorkList(&I);
173       I.getParent()->getInstList().erase(&I);
174       return 0;  // Don't do anything with FI
175     }
176
177
178   private:
179     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
180     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
181     /// casts that are known to not do anything...
182     ///
183     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
184                                    Instruction *InsertBefore);
185
186     // SimplifyCommutative - This performs a few simplifications for commutative
187     // operators...
188     bool SimplifyCommutative(BinaryOperator &I);
189
190     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
191                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
192   };
193
194   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
195 }
196
197 // getComplexity:  Assign a complexity or rank value to LLVM Values...
198 //   0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
199 static unsigned getComplexity(Value *V) {
200   if (isa<Instruction>(V)) {
201     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
202       return 2;
203     return 3;
204   }
205   if (isa<Argument>(V)) return 2;
206   return isa<Constant>(V) ? 0 : 1;
207 }
208
209 // isOnlyUse - Return true if this instruction will be deleted if we stop using
210 // it.
211 static bool isOnlyUse(Value *V) {
212   return V->hasOneUse() || isa<Constant>(V);
213 }
214
215 // getSignedIntegralType - Given an unsigned integral type, return the signed
216 // version of it that has the same size.
217 static const Type *getSignedIntegralType(const Type *Ty) {
218   switch (Ty->getPrimitiveID()) {
219   default: assert(0 && "Invalid unsigned integer type!"); abort();
220   case Type::UByteTyID:  return Type::SByteTy;
221   case Type::UShortTyID: return Type::ShortTy;
222   case Type::UIntTyID:   return Type::IntTy;
223   case Type::ULongTyID:  return Type::LongTy;
224   }
225 }
226
227 // getUnsignedIntegralType - Given an signed integral type, return the unsigned
228 // version of it that has the same size.
229 static const Type *getUnsignedIntegralType(const Type *Ty) {
230   switch (Ty->getPrimitiveID()) {
231   default: assert(0 && "Invalid signed integer type!"); abort();
232   case Type::SByteTyID: return Type::UByteTy;
233   case Type::ShortTyID: return Type::UShortTy;
234   case Type::IntTyID:   return Type::UIntTy;
235   case Type::LongTyID:  return Type::ULongTy;
236   }
237 }
238
239 // getPromotedType - Return the specified type promoted as it would be to pass
240 // though a va_arg area...
241 static const Type *getPromotedType(const Type *Ty) {
242   switch (Ty->getPrimitiveID()) {
243   case Type::SByteTyID:
244   case Type::ShortTyID:  return Type::IntTy;
245   case Type::UByteTyID:
246   case Type::UShortTyID: return Type::UIntTy;
247   case Type::FloatTyID:  return Type::DoubleTy;
248   default:               return Ty;
249   }
250 }
251
252 // SimplifyCommutative - This performs a few simplifications for commutative
253 // operators:
254 //
255 //  1. Order operands such that they are listed from right (least complex) to
256 //     left (most complex).  This puts constants before unary operators before
257 //     binary operators.
258 //
259 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
260 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
261 //
262 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
263   bool Changed = false;
264   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
265     Changed = !I.swapOperands();
266   
267   if (!I.isAssociative()) return Changed;
268   Instruction::BinaryOps Opcode = I.getOpcode();
269   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
270     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
271       if (isa<Constant>(I.getOperand(1))) {
272         Constant *Folded = ConstantExpr::get(I.getOpcode(),
273                                              cast<Constant>(I.getOperand(1)),
274                                              cast<Constant>(Op->getOperand(1)));
275         I.setOperand(0, Op->getOperand(0));
276         I.setOperand(1, Folded);
277         return true;
278       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
279         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
280             isOnlyUse(Op) && isOnlyUse(Op1)) {
281           Constant *C1 = cast<Constant>(Op->getOperand(1));
282           Constant *C2 = cast<Constant>(Op1->getOperand(1));
283
284           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
285           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
286           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
287                                                     Op1->getOperand(0),
288                                                     Op1->getName(), &I);
289           WorkList.push_back(New);
290           I.setOperand(0, New);
291           I.setOperand(1, Folded);
292           return true;
293         }      
294     }
295   return Changed;
296 }
297
298 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
299 // if the LHS is a constant zero (which is the 'negate' form).
300 //
301 static inline Value *dyn_castNegVal(Value *V) {
302   if (BinaryOperator::isNeg(V))
303     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
304
305   // Constants can be considered to be negated values if they can be folded...
306   if (Constant *C = dyn_cast<Constant>(V))
307     return ConstantExpr::get(Instruction::Sub,
308                              Constant::getNullValue(V->getType()), C);
309   return 0;
310 }
311
312 static Constant *NotConstant(Constant *C) {
313   return ConstantExpr::get(Instruction::Xor, C,
314                            ConstantIntegral::getAllOnesValue(C->getType()));
315 }
316
317 static inline Value *dyn_castNotVal(Value *V) {
318   if (BinaryOperator::isNot(V))
319     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
320
321   // Constants can be considered to be not'ed values...
322   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
323     return NotConstant(C);
324   return 0;
325 }
326
327 // dyn_castFoldableMul - If this value is a multiply that can be folded into
328 // other computations (because it has a constant operand), return the
329 // non-constant operand of the multiply.
330 //
331 static inline Value *dyn_castFoldableMul(Value *V) {
332   if (V->hasOneUse() && V->getType()->isInteger())
333     if (Instruction *I = dyn_cast<Instruction>(V))
334       if (I->getOpcode() == Instruction::Mul)
335         if (isa<Constant>(I->getOperand(1)))
336           return I->getOperand(0);
337   return 0;
338 }
339
340 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
341 // a constant, return the constant being anded with.
342 //
343 template<class ValueType>
344 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
345   if (Instruction *I = dyn_cast<Instruction>(V))
346     if (I->getOpcode() == Instruction::And)
347       return dyn_cast<Constant>(I->getOperand(1));
348
349   // If this is a constant, it acts just like we were masking with it.
350   return dyn_cast<Constant>(V);
351 }
352
353 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
354 // power of 2.
355 static unsigned Log2(uint64_t Val) {
356   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
357   unsigned Count = 0;
358   while (Val != 1) {
359     if (Val & 1) return 0;    // Multiple bits set?
360     Val >>= 1;
361     ++Count;
362   }
363   return Count;
364 }
365
366
367 /// AssociativeOpt - Perform an optimization on an associative operator.  This
368 /// function is designed to check a chain of associative operators for a
369 /// potential to apply a certain optimization.  Since the optimization may be
370 /// applicable if the expression was reassociated, this checks the chain, then
371 /// reassociates the expression as necessary to expose the optimization
372 /// opportunity.  This makes use of a special Functor, which must define
373 /// 'shouldApply' and 'apply' methods.
374 ///
375 template<typename Functor>
376 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
377   unsigned Opcode = Root.getOpcode();
378   Value *LHS = Root.getOperand(0);
379
380   // Quick check, see if the immediate LHS matches...
381   if (F.shouldApply(LHS))
382     return F.apply(Root);
383
384   // Otherwise, if the LHS is not of the same opcode as the root, return.
385   Instruction *LHSI = dyn_cast<Instruction>(LHS);
386   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
387     // Should we apply this transform to the RHS?
388     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
389
390     // If not to the RHS, check to see if we should apply to the LHS...
391     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
392       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
393       ShouldApply = true;
394     }
395
396     // If the functor wants to apply the optimization to the RHS of LHSI,
397     // reassociate the expression from ((? op A) op B) to (? op (A op B))
398     if (ShouldApply) {
399       BasicBlock *BB = Root.getParent();
400       // All of the instructions have a single use and have no side-effects,
401       // because of this, we can pull them all into the current basic block.
402       if (LHSI->getParent() != BB) {
403         // Move all of the instructions from root to LHSI into the current
404         // block.
405         Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
406         Instruction *LastUse = &Root;
407         while (TmpLHSI->getParent() == BB) {
408           LastUse = TmpLHSI;
409           TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
410         }
411         
412         // Loop over all of the instructions in other blocks, moving them into
413         // the current one.
414         Value *TmpLHS = TmpLHSI;
415         do {
416           TmpLHSI = cast<Instruction>(TmpLHS);
417           // Remove from current block...
418           TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
419           // Insert before the last instruction...
420           BB->getInstList().insert(LastUse, TmpLHSI);
421           TmpLHS = TmpLHSI->getOperand(0);
422         } while (TmpLHSI != LHSI);
423       }
424       
425       // Now all of the instructions are in the current basic block, go ahead
426       // and perform the reassociation.
427       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
428
429       // First move the selected RHS to the LHS of the root...
430       Root.setOperand(0, LHSI->getOperand(1));
431
432       // Make what used to be the LHS of the root be the user of the root...
433       Value *ExtraOperand = TmpLHSI->getOperand(1);
434       if (&Root != TmpLHSI)
435         Root.replaceAllUsesWith(TmpLHSI);        // Users now use TmpLHSI
436       else {
437         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
438         return 0;
439       }
440       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
441       BB->getInstList().remove(&Root);           // Remove root from the BB
442       BB->getInstList().insert(TmpLHSI, &Root);  // Insert root before TmpLHSI
443
444       // Now propagate the ExtraOperand down the chain of instructions until we
445       // get to LHSI.
446       while (TmpLHSI != LHSI) {
447         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
448         Value *NextOp = NextLHSI->getOperand(1);
449         NextLHSI->setOperand(1, ExtraOperand);
450         TmpLHSI = NextLHSI;
451         ExtraOperand = NextOp;
452       }
453       
454       // Now that the instructions are reassociated, have the functor perform
455       // the transformation...
456       return F.apply(Root);
457     }
458     
459     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
460   }
461   return 0;
462 }
463
464
465 // AddRHS - Implements: X + X --> X << 1
466 struct AddRHS {
467   Value *RHS;
468   AddRHS(Value *rhs) : RHS(rhs) {}
469   bool shouldApply(Value *LHS) const { return LHS == RHS; }
470   Instruction *apply(BinaryOperator &Add) const {
471     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
472                          ConstantInt::get(Type::UByteTy, 1));
473   }
474 };
475
476 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
477 //                 iff C1&C2 == 0
478 struct AddMaskingAnd {
479   Constant *C2;
480   AddMaskingAnd(Constant *c) : C2(c) {}
481   bool shouldApply(Value *LHS) const {
482     if (Constant *C1 = dyn_castMaskingAnd(LHS))
483       return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
484     return false;
485   }
486   Instruction *apply(BinaryOperator &Add) const {
487     return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
488                                   Add.getOperand(1));
489   }
490 };
491
492 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
493                                              InstCombiner *IC) {
494   // Figure out if the constant is the left or the right argument.
495   bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
496   Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
497
498   if (Constant *SOC = dyn_cast<Constant>(SO)) {
499     if (ConstIsRHS)
500       return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
501     return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
502   }
503
504   Value *Op0 = SO, *Op1 = ConstOperand;
505   if (!ConstIsRHS)
506     std::swap(Op0, Op1);
507   Instruction *New;
508   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
509     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
510   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
511     New = new ShiftInst(SI->getOpcode(), Op0, Op1);
512   else
513     assert(0 && "Unknown binary instruction type!");
514   return IC->InsertNewInstBefore(New, BI);
515 }
516
517 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
518 // constant as the other operand, try to fold the binary operator into the
519 // select arguments.
520 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
521                                         InstCombiner *IC) {
522   // Don't modify shared select instructions
523   if (!SI->hasOneUse()) return 0;
524   Value *TV = SI->getOperand(1);
525   Value *FV = SI->getOperand(2);
526
527   if (isa<Constant>(TV) || isa<Constant>(FV)) {
528     Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
529     Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
530
531     return new SelectInst(SI->getCondition(), SelectTrueVal,
532                           SelectFalseVal);
533   }
534   return 0;
535 }
536
537 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
538   bool Changed = SimplifyCommutative(I);
539   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
540
541   // X + 0 --> X
542   if (!I.getType()->isFloatingPoint() &&    // -0 + +0 = +0, so it's not a noop
543       RHS == Constant::getNullValue(I.getType()))
544     return ReplaceInstUsesWith(I, LHS);
545
546   // X + X --> X << 1
547   if (I.getType()->isInteger())
548     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
549
550   // -A + B  -->  B - A
551   if (Value *V = dyn_castNegVal(LHS))
552     return BinaryOperator::create(Instruction::Sub, RHS, V);
553
554   // A + -B  -->  A - B
555   if (!isa<Constant>(RHS))
556     if (Value *V = dyn_castNegVal(RHS))
557       return BinaryOperator::create(Instruction::Sub, LHS, V);
558
559   // X*C + X --> X * (C+1)
560   if (dyn_castFoldableMul(LHS) == RHS) {
561     Constant *CP1 =
562       ConstantExpr::get(Instruction::Add, 
563                         cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
564                         ConstantInt::get(I.getType(), 1));
565     return BinaryOperator::create(Instruction::Mul, RHS, CP1);
566   }
567
568   // X + X*C --> X * (C+1)
569   if (dyn_castFoldableMul(RHS) == LHS) {
570     Constant *CP1 =
571       ConstantExpr::get(Instruction::Add,
572                         cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
573                         ConstantInt::get(I.getType(), 1));
574     return BinaryOperator::create(Instruction::Mul, LHS, CP1);
575   }
576
577   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
578   if (Constant *C2 = dyn_castMaskingAnd(RHS))
579     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
580
581   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
582     if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
583       switch (ILHS->getOpcode()) {
584       case Instruction::Xor:
585         // ~X + C --> (C-1) - X
586         if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
587           if (XorRHS->isAllOnesValue())
588             return BinaryOperator::create(Instruction::Sub,
589                                           ConstantExpr::get(Instruction::Sub,
590                                     CRHS, ConstantInt::get(I.getType(), 1)),
591                                           ILHS->getOperand(0));
592         break;
593       case Instruction::Select:
594         // Try to fold constant add into select arguments.
595         if (Instruction *R = FoldBinOpIntoSelect(I,cast<SelectInst>(ILHS),this))
596           return R;
597
598       default: break;
599       }
600     }
601   }
602
603   return Changed ? &I : 0;
604 }
605
606 // isSignBit - Return true if the value represented by the constant only has the
607 // highest order bit set.
608 static bool isSignBit(ConstantInt *CI) {
609   unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
610   return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
611 }
612
613 static unsigned getTypeSizeInBits(const Type *Ty) {
614   return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
615 }
616
617 /// RemoveNoopCast - Strip off nonconverting casts from the value.
618 ///
619 static Value *RemoveNoopCast(Value *V) {
620   if (CastInst *CI = dyn_cast<CastInst>(V)) {
621     const Type *CTy = CI->getType();
622     const Type *OpTy = CI->getOperand(0)->getType();
623     if (CTy->isInteger() && OpTy->isInteger()) {
624       if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
625         return RemoveNoopCast(CI->getOperand(0));
626     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
627       return RemoveNoopCast(CI->getOperand(0));
628   }
629   return V;
630 }
631
632 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
633   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
634
635   if (Op0 == Op1)         // sub X, X  -> 0
636     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
637
638   // If this is a 'B = x-(-A)', change to B = x+A...
639   if (Value *V = dyn_castNegVal(Op1))
640     return BinaryOperator::create(Instruction::Add, Op0, V);
641
642   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
643     // Replace (-1 - A) with (~A)...
644     if (C->isAllOnesValue())
645       return BinaryOperator::createNot(Op1);
646
647     // C - ~X == X + (1+C)
648     if (BinaryOperator::isNot(Op1))
649       return BinaryOperator::create(Instruction::Add,
650                BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
651                     ConstantExpr::get(Instruction::Add, C,
652                                       ConstantInt::get(I.getType(), 1)));
653     // -((uint)X >> 31) -> ((int)X >> 31)
654     // -((int)X >> 31) -> ((uint)X >> 31)
655     if (C->isNullValue()) {
656       Value *NoopCastedRHS = RemoveNoopCast(Op1);
657       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
658         if (SI->getOpcode() == Instruction::Shr)
659           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
660             const Type *NewTy;
661             if (SI->getType()->isSigned())
662               NewTy = getUnsignedIntegralType(SI->getType());
663             else
664               NewTy = getSignedIntegralType(SI->getType());
665             // Check to see if we are shifting out everything but the sign bit.
666             if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
667               // Ok, the transformation is safe.  Insert a cast of the incoming
668               // value, then the new shift, then the new cast.
669               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
670                                                  SI->getOperand(0)->getName());
671               Value *InV = InsertNewInstBefore(FirstCast, I);
672               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
673                                                     CU, SI->getName());
674               if (NewShift->getType() == I.getType())
675                 return NewShift;
676               else {
677                 InV = InsertNewInstBefore(NewShift, I);
678                 return new CastInst(NewShift, I.getType());
679               }
680             }
681           }
682     }
683
684     // Try to fold constant sub into select arguments.
685     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
686       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
687         return R;
688   }
689
690   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
691     if (Op1I->hasOneUse()) {
692       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
693       // is not used by anyone else...
694       //
695       if (Op1I->getOpcode() == Instruction::Sub &&
696           !Op1I->getType()->isFloatingPoint()) {
697         // Swap the two operands of the subexpr...
698         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
699         Op1I->setOperand(0, IIOp1);
700         Op1I->setOperand(1, IIOp0);
701         
702         // Create the new top level add instruction...
703         return BinaryOperator::create(Instruction::Add, Op0, Op1);
704       }
705
706       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
707       //
708       if (Op1I->getOpcode() == Instruction::And &&
709           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
710         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
711
712         Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
713         return BinaryOperator::create(Instruction::And, Op0, NewNot);
714       }
715
716       // X - X*C --> X * (1-C)
717       if (dyn_castFoldableMul(Op1I) == Op0) {
718         Constant *CP1 =
719           ConstantExpr::get(Instruction::Sub,
720                             ConstantInt::get(I.getType(), 1),
721                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
722         assert(CP1 && "Couldn't constant fold 1-C?");
723         return BinaryOperator::create(Instruction::Mul, Op0, CP1);
724       }
725     }
726
727   // X*C - X --> X * (C-1)
728   if (dyn_castFoldableMul(Op0) == Op1) {
729     Constant *CP1 =
730       ConstantExpr::get(Instruction::Sub,
731                         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
732                         ConstantInt::get(I.getType(), 1));
733     assert(CP1 && "Couldn't constant fold C - 1?");
734     return BinaryOperator::create(Instruction::Mul, Op1, CP1);
735   }
736
737   return 0;
738 }
739
740 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
741 /// really just returns true if the most significant (sign) bit is set.
742 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
743   if (RHS->getType()->isSigned()) {
744     // True if source is LHS < 0 or LHS <= -1
745     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
746            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
747   } else {
748     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
749     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
750     // the size of the integer type.
751     if (Opcode == Instruction::SetGE)
752       return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
753     if (Opcode == Instruction::SetGT)
754       return RHSC->getValue() ==
755         (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
756   }
757   return false;
758 }
759
760 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
761   bool Changed = SimplifyCommutative(I);
762   Value *Op0 = I.getOperand(0);
763
764   // Simplify mul instructions with a constant RHS...
765   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
766     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
767
768       // ((X << C1)*C2) == (X * (C2 << C1))
769       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
770         if (SI->getOpcode() == Instruction::Shl)
771           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
772             return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
773                                  ConstantExpr::get(Instruction::Shl, CI, ShOp));
774       
775       if (CI->isNullValue())
776         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
777       if (CI->equalsInt(1))                  // X * 1  == X
778         return ReplaceInstUsesWith(I, Op0);
779       if (CI->isAllOnesValue())              // X * -1 == 0 - X
780         return BinaryOperator::createNeg(Op0, I.getName());
781
782       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
783       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
784         return new ShiftInst(Instruction::Shl, Op0,
785                              ConstantUInt::get(Type::UByteTy, C));
786     } else {
787       ConstantFP *Op1F = cast<ConstantFP>(Op1);
788       if (Op1F->isNullValue())
789         return ReplaceInstUsesWith(I, Op1);
790
791       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
792       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
793       if (Op1F->getValue() == 1.0)
794         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
795     }
796
797     // Try to fold constant mul into select arguments.
798     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
799       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
800         return R;
801   }
802
803   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
804     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
805       return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
806
807   // If one of the operands of the multiply is a cast from a boolean value, then
808   // we know the bool is either zero or one, so this is a 'masking' multiply.
809   // See if we can simplify things based on how the boolean was originally
810   // formed.
811   CastInst *BoolCast = 0;
812   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
813     if (CI->getOperand(0)->getType() == Type::BoolTy)
814       BoolCast = CI;
815   if (!BoolCast)
816     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
817       if (CI->getOperand(0)->getType() == Type::BoolTy)
818         BoolCast = CI;
819   if (BoolCast) {
820     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
821       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
822       const Type *SCOpTy = SCIOp0->getType();
823
824       // If the setcc is true iff the sign bit of X is set, then convert this
825       // multiply into a shift/and combination.
826       if (isa<ConstantInt>(SCIOp1) &&
827           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
828         // Shift the X value right to turn it into "all signbits".
829         Constant *Amt = ConstantUInt::get(Type::UByteTy,
830                                           SCOpTy->getPrimitiveSize()*8-1);
831         if (SCIOp0->getType()->isUnsigned()) {
832           const Type *NewTy = getSignedIntegralType(SCIOp0->getType());
833           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
834                                                     SCIOp0->getName()), I);
835         }
836
837         Value *V =
838           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
839                                             BoolCast->getOperand(0)->getName()+
840                                             ".mask"), I);
841
842         // If the multiply type is not the same as the source type, sign extend
843         // or truncate to the multiply type.
844         if (I.getType() != V->getType())
845           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
846         
847         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
848         return BinaryOperator::create(Instruction::And, V, OtherOp);
849       }
850     }
851   }
852
853   return Changed ? &I : 0;
854 }
855
856 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
857   // div X, 1 == X
858   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
859     if (RHS->equalsInt(1))
860       return ReplaceInstUsesWith(I, I.getOperand(0));
861
862     // Check to see if this is an unsigned division with an exact power of 2,
863     // if so, convert to a right shift.
864     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
865       if (uint64_t Val = C->getValue())    // Don't break X / 0
866         if (uint64_t C = Log2(Val))
867           return new ShiftInst(Instruction::Shr, I.getOperand(0),
868                                ConstantUInt::get(Type::UByteTy, C));
869   }
870
871   // 0 / X == 0, we don't need to preserve faults!
872   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
873     if (LHS->equalsInt(0))
874       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
875
876   return 0;
877 }
878
879
880 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
881   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
882     if (RHS->equalsInt(1))  // X % 1 == 0
883       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
884     if (RHS->isAllOnesValue())  // X % -1 == 0
885       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
886
887     // Check to see if this is an unsigned remainder with an exact power of 2,
888     // if so, convert to a bitwise and.
889     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
890       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
891         if (Log2(Val))
892           return BinaryOperator::create(Instruction::And, I.getOperand(0),
893                                         ConstantUInt::get(I.getType(), Val-1));
894   }
895
896   // 0 % X == 0, we don't need to preserve faults!
897   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
898     if (LHS->equalsInt(0))
899       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
900
901   return 0;
902 }
903
904 // isMaxValueMinusOne - return true if this is Max-1
905 static bool isMaxValueMinusOne(const ConstantInt *C) {
906   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
907     // Calculate -1 casted to the right type...
908     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
909     uint64_t Val = ~0ULL;                // All ones
910     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
911     return CU->getValue() == Val-1;
912   }
913
914   const ConstantSInt *CS = cast<ConstantSInt>(C);
915   
916   // Calculate 0111111111..11111
917   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
918   int64_t Val = INT64_MAX;             // All ones
919   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
920   return CS->getValue() == Val-1;
921 }
922
923 // isMinValuePlusOne - return true if this is Min+1
924 static bool isMinValuePlusOne(const ConstantInt *C) {
925   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
926     return CU->getValue() == 1;
927
928   const ConstantSInt *CS = cast<ConstantSInt>(C);
929   
930   // Calculate 1111111111000000000000 
931   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
932   int64_t Val = -1;                    // All ones
933   Val <<= TypeBits-1;                  // Shift over to the right spot
934   return CS->getValue() == Val+1;
935 }
936
937 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
938 /// are carefully arranged to allow folding of expressions such as:
939 ///
940 ///      (A < B) | (A > B) --> (A != B)
941 ///
942 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
943 /// represents that the comparison is true if A == B, and bit value '1' is true
944 /// if A < B.
945 ///
946 static unsigned getSetCondCode(const SetCondInst *SCI) {
947   switch (SCI->getOpcode()) {
948     // False -> 0
949   case Instruction::SetGT: return 1;
950   case Instruction::SetEQ: return 2;
951   case Instruction::SetGE: return 3;
952   case Instruction::SetLT: return 4;
953   case Instruction::SetNE: return 5;
954   case Instruction::SetLE: return 6;
955     // True -> 7
956   default:
957     assert(0 && "Invalid SetCC opcode!");
958     return 0;
959   }
960 }
961
962 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
963 /// opcode and two operands into either a constant true or false, or a brand new
964 /// SetCC instruction.
965 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
966   switch (Opcode) {
967   case 0: return ConstantBool::False;
968   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
969   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
970   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
971   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
972   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
973   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
974   case 7: return ConstantBool::True;
975   default: assert(0 && "Illegal SetCCCode!"); return 0;
976   }
977 }
978
979 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
980 struct FoldSetCCLogical {
981   InstCombiner &IC;
982   Value *LHS, *RHS;
983   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
984     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
985   bool shouldApply(Value *V) const {
986     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
987       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
988               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
989     return false;
990   }
991   Instruction *apply(BinaryOperator &Log) const {
992     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
993     if (SCI->getOperand(0) != LHS) {
994       assert(SCI->getOperand(1) == LHS);
995       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
996     }
997
998     unsigned LHSCode = getSetCondCode(SCI);
999     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1000     unsigned Code;
1001     switch (Log.getOpcode()) {
1002     case Instruction::And: Code = LHSCode & RHSCode; break;
1003     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1004     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1005     default: assert(0 && "Illegal logical opcode!"); return 0;
1006     }
1007
1008     Value *RV = getSetCCValue(Code, LHS, RHS);
1009     if (Instruction *I = dyn_cast<Instruction>(RV))
1010       return I;
1011     // Otherwise, it's a constant boolean value...
1012     return IC.ReplaceInstUsesWith(Log, RV);
1013   }
1014 };
1015
1016
1017 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1018 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1019 // guaranteed to be either a shift instruction or a binary operator.
1020 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1021                                     ConstantIntegral *OpRHS,
1022                                     ConstantIntegral *AndRHS,
1023                                     BinaryOperator &TheAnd) {
1024   Value *X = Op->getOperand(0);
1025   Constant *Together = 0;
1026   if (!isa<ShiftInst>(Op))
1027     Together = ConstantExpr::get(Instruction::And, AndRHS, OpRHS);
1028
1029   switch (Op->getOpcode()) {
1030   case Instruction::Xor:
1031     if (Together->isNullValue()) {
1032       // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1033       return BinaryOperator::create(Instruction::And, X, AndRHS);
1034     } else if (Op->hasOneUse()) {
1035       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1036       std::string OpName = Op->getName(); Op->setName("");
1037       Instruction *And = BinaryOperator::create(Instruction::And,
1038                                                 X, AndRHS, OpName);
1039       InsertNewInstBefore(And, TheAnd);
1040       return BinaryOperator::create(Instruction::Xor, And, Together);
1041     }
1042     break;
1043   case Instruction::Or:
1044     // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1045     if (Together->isNullValue())
1046       return BinaryOperator::create(Instruction::And, X, AndRHS);
1047     else {
1048       if (Together == AndRHS) // (X | C) & C --> C
1049         return ReplaceInstUsesWith(TheAnd, AndRHS);
1050       
1051       if (Op->hasOneUse() && Together != OpRHS) {
1052         // (X | C1) & C2 --> (X | (C1&C2)) & C2
1053         std::string Op0Name = Op->getName(); Op->setName("");
1054         Instruction *Or = BinaryOperator::create(Instruction::Or, X,
1055                                                  Together, Op0Name);
1056         InsertNewInstBefore(Or, TheAnd);
1057         return BinaryOperator::create(Instruction::And, Or, AndRHS);
1058       }
1059     }
1060     break;
1061   case Instruction::Add:
1062     if (Op->hasOneUse()) {
1063       // Adding a one to a single bit bit-field should be turned into an XOR
1064       // of the bit.  First thing to check is to see if this AND is with a
1065       // single bit constant.
1066       unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1067
1068       // Clear bits that are not part of the constant.
1069       AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1070
1071       // If there is only one bit set...
1072       if ((AndRHSV & (AndRHSV-1)) == 0) {
1073         // Ok, at this point, we know that we are masking the result of the
1074         // ADD down to exactly one bit.  If the constant we are adding has
1075         // no bits set below this bit, then we can eliminate the ADD.
1076         unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1077             
1078         // Check to see if any bits below the one bit set in AndRHSV are set.
1079         if ((AddRHS & (AndRHSV-1)) == 0) {
1080           // If not, the only thing that can effect the output of the AND is
1081           // the bit specified by AndRHSV.  If that bit is set, the effect of
1082           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1083           // no effect.
1084           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1085             TheAnd.setOperand(0, X);
1086             return &TheAnd;
1087           } else {
1088             std::string Name = Op->getName(); Op->setName("");
1089             // Pull the XOR out of the AND.
1090             Instruction *NewAnd =
1091               BinaryOperator::create(Instruction::And, X, AndRHS, Name);
1092             InsertNewInstBefore(NewAnd, TheAnd);
1093             return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
1094           }
1095         }
1096       }
1097     }
1098     break;
1099
1100   case Instruction::Shl: {
1101     // We know that the AND will not produce any of the bits shifted in, so if
1102     // the anded constant includes them, clear them now!
1103     //
1104     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1105     Constant *CI = ConstantExpr::get(Instruction::And, AndRHS,
1106                             ConstantExpr::get(Instruction::Shl, AllOne, OpRHS));
1107     if (CI != AndRHS) {
1108       TheAnd.setOperand(1, CI);
1109       return &TheAnd;
1110     }
1111     break;
1112   } 
1113   case Instruction::Shr:
1114     // We know that the AND will not produce any of the bits shifted in, so if
1115     // the anded constant includes them, clear them now!  This only applies to
1116     // unsigned shifts, because a signed shr may bring in set bits!
1117     //
1118     if (AndRHS->getType()->isUnsigned()) {
1119       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1120       Constant *CI = ConstantExpr::get(Instruction::And, AndRHS,
1121                             ConstantExpr::get(Instruction::Shr, AllOne, OpRHS));
1122       if (CI != AndRHS) {
1123         TheAnd.setOperand(1, CI);
1124         return &TheAnd;
1125       }
1126     }
1127     break;
1128   }
1129   return 0;
1130 }
1131
1132
1133 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1134   bool Changed = SimplifyCommutative(I);
1135   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1136
1137   // and X, X = X   and X, 0 == 0
1138   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1139     return ReplaceInstUsesWith(I, Op1);
1140
1141   // and X, -1 == X
1142   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1143     if (RHS->isAllOnesValue())
1144       return ReplaceInstUsesWith(I, Op0);
1145
1146     // Optimize a variety of ((val OP C1) & C2) combinations...
1147     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1148       Instruction *Op0I = cast<Instruction>(Op0);
1149       Value *X = Op0I->getOperand(0);
1150       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1151         if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1152           return Res;
1153     }
1154
1155     // Try to fold constant and into select arguments.
1156     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1157       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1158         return R;
1159   }
1160
1161   Value *Op0NotVal = dyn_castNotVal(Op0);
1162   Value *Op1NotVal = dyn_castNotVal(Op1);
1163
1164   // (~A & ~B) == (~(A | B)) - Demorgan's Law
1165   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1166     Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
1167                                              Op1NotVal,I.getName()+".demorgan");
1168     InsertNewInstBefore(Or, I);
1169     return BinaryOperator::createNot(Or);
1170   }
1171
1172   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1173     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1174
1175   // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1176   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1177     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1178       return R;
1179
1180   return Changed ? &I : 0;
1181 }
1182
1183
1184
1185 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1186   bool Changed = SimplifyCommutative(I);
1187   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1188
1189   // or X, X = X   or X, 0 == X
1190   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1191     return ReplaceInstUsesWith(I, Op0);
1192
1193   // or X, -1 == -1
1194   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1195     if (RHS->isAllOnesValue())
1196       return ReplaceInstUsesWith(I, Op1);
1197
1198     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1199       // (X & C1) | C2 --> (X | C2) & (C1|C2)
1200       if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1201         if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1202           std::string Op0Name = Op0I->getName(); Op0I->setName("");
1203           Instruction *Or = BinaryOperator::create(Instruction::Or,
1204                                                    Op0I->getOperand(0), RHS,
1205                                                    Op0Name);
1206           InsertNewInstBefore(Or, I);
1207           return BinaryOperator::create(Instruction::And, Or,
1208                              ConstantExpr::get(Instruction::Or, RHS, Op0CI));
1209         }
1210
1211       // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1212       if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1213         if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1214           std::string Op0Name = Op0I->getName(); Op0I->setName("");
1215           Instruction *Or = BinaryOperator::create(Instruction::Or,
1216                                                    Op0I->getOperand(0), RHS,
1217                                                    Op0Name);
1218           InsertNewInstBefore(Or, I);
1219           return BinaryOperator::create(Instruction::Xor, Or,
1220                             ConstantExpr::get(Instruction::And, Op0CI,
1221                                               NotConstant(RHS)));
1222         }
1223     }
1224
1225     // Try to fold constant and into select arguments.
1226     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1227       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1228         return R;
1229   }
1230
1231   // (A & C1)|(A & C2) == A & (C1|C2)
1232   if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1233     if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1234       if (LHS->getOperand(0) == RHS->getOperand(0))
1235         if (Constant *C0 = dyn_castMaskingAnd(LHS))
1236           if (Constant *C1 = dyn_castMaskingAnd(RHS))
1237             return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
1238                                     ConstantExpr::get(Instruction::Or, C0, C1));
1239
1240   Value *Op0NotVal = dyn_castNotVal(Op0);
1241   Value *Op1NotVal = dyn_castNotVal(Op1);
1242
1243   if (Op1 == Op0NotVal)   // ~A | A == -1
1244     return ReplaceInstUsesWith(I, 
1245                                ConstantIntegral::getAllOnesValue(I.getType()));
1246
1247   if (Op0 == Op1NotVal)   // A | ~A == -1
1248     return ReplaceInstUsesWith(I, 
1249                                ConstantIntegral::getAllOnesValue(I.getType()));
1250
1251   // (~A | ~B) == (~(A & B)) - Demorgan's Law
1252   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1253     Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
1254                                               Op1NotVal,I.getName()+".demorgan",
1255                                               &I);
1256     WorkList.push_back(And);
1257     return BinaryOperator::createNot(And);
1258   }
1259
1260   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1261   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1262     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1263       return R;
1264
1265   return Changed ? &I : 0;
1266 }
1267
1268 // XorSelf - Implements: X ^ X --> 0
1269 struct XorSelf {
1270   Value *RHS;
1271   XorSelf(Value *rhs) : RHS(rhs) {}
1272   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1273   Instruction *apply(BinaryOperator &Xor) const {
1274     return &Xor;
1275   }
1276 };
1277
1278
1279 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1280   bool Changed = SimplifyCommutative(I);
1281   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1282
1283   // xor X, X = 0, even if X is nested in a sequence of Xor's.
1284   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1285     assert(Result == &I && "AssociativeOpt didn't work?");
1286     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1287   }
1288
1289   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1290     // xor X, 0 == X
1291     if (RHS->isNullValue())
1292       return ReplaceInstUsesWith(I, Op0);
1293
1294     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1295       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1296       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1297         if (RHS == ConstantBool::True && SCI->hasOneUse())
1298           return new SetCondInst(SCI->getInverseCondition(),
1299                                  SCI->getOperand(0), SCI->getOperand(1));
1300
1301       // ~(c-X) == X-c-1 == X+(-c-1)
1302       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1303         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1304           Constant *NegOp0I0C = ConstantExpr::get(Instruction::Sub,
1305                              Constant::getNullValue(Op0I0C->getType()), Op0I0C);
1306           Constant *ConstantRHS = ConstantExpr::get(Instruction::Sub, NegOp0I0C,
1307                                               ConstantInt::get(I.getType(), 1));
1308           return BinaryOperator::create(Instruction::Add, Op0I->getOperand(1),
1309                                         ConstantRHS);
1310         }
1311           
1312       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1313         switch (Op0I->getOpcode()) {
1314         case Instruction::Add:
1315           // ~(X-c) --> (-c-1)-X
1316           if (RHS->isAllOnesValue()) {
1317             Constant *NegOp0CI = ConstantExpr::get(Instruction::Sub,
1318                                Constant::getNullValue(Op0CI->getType()), Op0CI);
1319             return BinaryOperator::create(Instruction::Sub,
1320                            ConstantExpr::get(Instruction::Sub, NegOp0CI,
1321                                              ConstantInt::get(I.getType(), 1)),
1322                                           Op0I->getOperand(0));
1323           }
1324           break;
1325         case Instruction::And:
1326           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1327           if (ConstantExpr::get(Instruction::And, RHS, Op0CI)->isNullValue())
1328             return BinaryOperator::create(Instruction::Or, Op0, RHS);
1329           break;
1330         case Instruction::Or:
1331           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1332           if (ConstantExpr::get(Instruction::And, RHS, Op0CI) == RHS)
1333             return BinaryOperator::create(Instruction::And, Op0,
1334                                           NotConstant(RHS));
1335           break;
1336         default: break;
1337         }
1338     }
1339
1340     // Try to fold constant and into select arguments.
1341     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1342       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1343         return R;
1344   }
1345
1346   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1347     if (X == Op1)
1348       return ReplaceInstUsesWith(I,
1349                                 ConstantIntegral::getAllOnesValue(I.getType()));
1350
1351   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1352     if (X == Op0)
1353       return ReplaceInstUsesWith(I,
1354                                 ConstantIntegral::getAllOnesValue(I.getType()));
1355
1356   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1357     if (Op1I->getOpcode() == Instruction::Or) {
1358       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
1359         cast<BinaryOperator>(Op1I)->swapOperands();
1360         I.swapOperands();
1361         std::swap(Op0, Op1);
1362       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
1363         I.swapOperands();
1364         std::swap(Op0, Op1);
1365       }      
1366     } else if (Op1I->getOpcode() == Instruction::Xor) {
1367       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
1368         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1369       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
1370         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1371     }
1372
1373   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1374     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1375       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
1376         cast<BinaryOperator>(Op0I)->swapOperands();
1377       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
1378         Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1379         WorkList.push_back(cast<Instruction>(NotB));
1380         return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1381                                       NotB);
1382       }
1383     } else if (Op0I->getOpcode() == Instruction::Xor) {
1384       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
1385         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1386       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
1387         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1388     }
1389
1390   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1391   if (Constant *C1 = dyn_castMaskingAnd(Op0))
1392     if (Constant *C2 = dyn_castMaskingAnd(Op1))
1393       if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1394         return BinaryOperator::create(Instruction::Or, Op0, Op1);
1395
1396   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1397   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1398     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1399       return R;
1400
1401   return Changed ? &I : 0;
1402 }
1403
1404 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1405 static Constant *AddOne(ConstantInt *C) {
1406   Constant *Result = ConstantExpr::get(Instruction::Add, C,
1407                                        ConstantInt::get(C->getType(), 1));
1408   assert(Result && "Constant folding integer addition failed!");
1409   return Result;
1410 }
1411 static Constant *SubOne(ConstantInt *C) {
1412   Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1413                                        ConstantInt::get(C->getType(), 1));
1414   assert(Result && "Constant folding integer addition failed!");
1415   return Result;
1416 }
1417
1418 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1419 // true when both operands are equal...
1420 //
1421 static bool isTrueWhenEqual(Instruction &I) {
1422   return I.getOpcode() == Instruction::SetEQ ||
1423          I.getOpcode() == Instruction::SetGE ||
1424          I.getOpcode() == Instruction::SetLE;
1425 }
1426
1427 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1428   bool Changed = SimplifyCommutative(I);
1429   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1430   const Type *Ty = Op0->getType();
1431
1432   // setcc X, X
1433   if (Op0 == Op1)
1434     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1435
1436   // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1437   if (isa<ConstantPointerNull>(Op1) && 
1438       (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1439     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1440
1441
1442   // setcc's with boolean values can always be turned into bitwise operations
1443   if (Ty == Type::BoolTy) {
1444     // If this is <, >, or !=, we can change this into a simple xor instruction
1445     if (!isTrueWhenEqual(I))
1446       return BinaryOperator::create(Instruction::Xor, Op0, Op1);
1447
1448     // Otherwise we need to make a temporary intermediate instruction and insert
1449     // it into the instruction stream.  This is what we are after:
1450     //
1451     //  seteq bool %A, %B -> ~(A^B)
1452     //  setle bool %A, %B -> ~A | B
1453     //  setge bool %A, %B -> A | ~B
1454     //
1455     if (I.getOpcode() == Instruction::SetEQ) {  // seteq case
1456       Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1457                                                 I.getName()+"tmp");
1458       InsertNewInstBefore(Xor, I);
1459       return BinaryOperator::createNot(Xor);
1460     }
1461
1462     // Handle the setXe cases...
1463     assert(I.getOpcode() == Instruction::SetGE ||
1464            I.getOpcode() == Instruction::SetLE);
1465
1466     if (I.getOpcode() == Instruction::SetGE)
1467       std::swap(Op0, Op1);                   // Change setge -> setle
1468
1469     // Now we just have the SetLE case.
1470     Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1471     InsertNewInstBefore(Not, I);
1472     return BinaryOperator::create(Instruction::Or, Not, Op1);
1473   }
1474
1475   // Check to see if we are doing one of many comparisons against constant
1476   // integers at the end of their ranges...
1477   //
1478   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1479     // Simplify seteq and setne instructions...
1480     if (I.getOpcode() == Instruction::SetEQ ||
1481         I.getOpcode() == Instruction::SetNE) {
1482       bool isSetNE = I.getOpcode() == Instruction::SetNE;
1483
1484       // If the first operand is (and|or|xor) with a constant, and the second
1485       // operand is a constant, simplify a bit.
1486       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1487         switch (BO->getOpcode()) {
1488         case Instruction::Add:
1489           if (CI->isNullValue()) {
1490             // Replace ((add A, B) != 0) with (A != -B) if A or B is
1491             // efficiently invertible, or if the add has just this one use.
1492             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1493             if (Value *NegVal = dyn_castNegVal(BOp1))
1494               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1495             else if (Value *NegVal = dyn_castNegVal(BOp0))
1496               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1497             else if (BO->hasOneUse()) {
1498               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1499               BO->setName("");
1500               InsertNewInstBefore(Neg, I);
1501               return new SetCondInst(I.getOpcode(), BOp0, Neg);
1502             }
1503           }
1504           break;
1505         case Instruction::Xor:
1506           // For the xor case, we can xor two constants together, eliminating
1507           // the explicit xor.
1508           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1509             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1510                                   ConstantExpr::get(Instruction::Xor, CI, BOC));
1511
1512           // FALLTHROUGH
1513         case Instruction::Sub:
1514           // Replace (([sub|xor] A, B) != 0) with (A != B)
1515           if (CI->isNullValue())
1516             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1517                                    BO->getOperand(1));
1518           break;
1519
1520         case Instruction::Or:
1521           // If bits are being or'd in that are not present in the constant we
1522           // are comparing against, then the comparison could never succeed!
1523           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1524             Constant *NotCI = NotConstant(CI);
1525             if (!ConstantExpr::get(Instruction::And, BOC, NotCI)->isNullValue())
1526               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1527           }
1528           break;
1529
1530         case Instruction::And:
1531           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1532             // If bits are being compared against that are and'd out, then the
1533             // comparison can never succeed!
1534             if (!ConstantExpr::get(Instruction::And, CI,
1535                                    NotConstant(BOC))->isNullValue())
1536               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1537
1538             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1539             // to be a signed value as appropriate.
1540             if (isSignBit(BOC)) {
1541               Value *X = BO->getOperand(0);
1542               // If 'X' is not signed, insert a cast now...
1543               if (!BOC->getType()->isSigned()) {
1544                 const Type *DestTy = getSignedIntegralType(BOC->getType());
1545                 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1546                 InsertNewInstBefore(NewCI, I);
1547                 X = NewCI;
1548               }
1549               return new SetCondInst(isSetNE ? Instruction::SetLT :
1550                                          Instruction::SetGE, X,
1551                                      Constant::getNullValue(X->getType()));
1552             }
1553           }
1554         default: break;
1555         }
1556       }
1557     } else {  // Not a SetEQ/SetNE
1558       // If the LHS is a cast from an integral value of the same size, 
1559       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1560         Value *CastOp = Cast->getOperand(0);
1561         const Type *SrcTy = CastOp->getType();
1562         unsigned SrcTySize = SrcTy->getPrimitiveSize();
1563         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1564             SrcTySize == Cast->getType()->getPrimitiveSize()) {
1565           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) && 
1566                  "Source and destination signednesses should differ!");
1567           if (Cast->getType()->isSigned()) {
1568             // If this is a signed comparison, check for comparisons in the
1569             // vicinity of zero.
1570             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1571               // X < 0  => x > 127
1572               return BinaryOperator::create(Instruction::SetGT, CastOp,
1573                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1574             else if (I.getOpcode() == Instruction::SetGT &&
1575                      cast<ConstantSInt>(CI)->getValue() == -1)
1576               // X > -1  => x < 128
1577               return BinaryOperator::create(Instruction::SetLT, CastOp,
1578                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1579           } else {
1580             ConstantUInt *CUI = cast<ConstantUInt>(CI);
1581             if (I.getOpcode() == Instruction::SetLT &&
1582                 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1583               // X < 128 => X > -1
1584               return BinaryOperator::create(Instruction::SetGT, CastOp,
1585                                             ConstantSInt::get(SrcTy, -1));
1586             else if (I.getOpcode() == Instruction::SetGT &&
1587                      CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1588               // X > 127 => X < 0
1589               return BinaryOperator::create(Instruction::SetLT, CastOp,
1590                                             Constant::getNullValue(SrcTy));
1591           }
1592         }
1593       }
1594     }
1595
1596     // Check to see if we are comparing against the minimum or maximum value...
1597     if (CI->isMinValue()) {
1598       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
1599         return ReplaceInstUsesWith(I, ConstantBool::False);
1600       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
1601         return ReplaceInstUsesWith(I, ConstantBool::True);
1602       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
1603         return BinaryOperator::create(Instruction::SetEQ, Op0, Op1);
1604       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
1605         return BinaryOperator::create(Instruction::SetNE, Op0, Op1);
1606
1607     } else if (CI->isMaxValue()) {
1608       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
1609         return ReplaceInstUsesWith(I, ConstantBool::False);
1610       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
1611         return ReplaceInstUsesWith(I, ConstantBool::True);
1612       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
1613         return BinaryOperator::create(Instruction::SetEQ, Op0, Op1);
1614       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
1615         return BinaryOperator::create(Instruction::SetNE, Op0, Op1);
1616
1617       // Comparing against a value really close to min or max?
1618     } else if (isMinValuePlusOne(CI)) {
1619       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
1620         return BinaryOperator::create(Instruction::SetEQ, Op0, SubOne(CI));
1621       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
1622         return BinaryOperator::create(Instruction::SetNE, Op0, SubOne(CI));
1623
1624     } else if (isMaxValueMinusOne(CI)) {
1625       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
1626         return BinaryOperator::create(Instruction::SetEQ, Op0, AddOne(CI));
1627       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
1628         return BinaryOperator::create(Instruction::SetNE, Op0, AddOne(CI));
1629     }
1630
1631     // If we still have a setle or setge instruction, turn it into the
1632     // appropriate setlt or setgt instruction.  Since the border cases have
1633     // already been handled above, this requires little checking.
1634     //
1635     if (I.getOpcode() == Instruction::SetLE)
1636       return BinaryOperator::create(Instruction::SetLT, Op0, AddOne(CI));
1637     if (I.getOpcode() == Instruction::SetGE)
1638       return BinaryOperator::create(Instruction::SetGT, Op0, SubOne(CI));
1639   }
1640
1641   // Test to see if the operands of the setcc are casted versions of other
1642   // values.  If the cast can be stripped off both arguments, we do so now.
1643   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1644     Value *CastOp0 = CI->getOperand(0);
1645     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
1646         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
1647         (I.getOpcode() == Instruction::SetEQ ||
1648          I.getOpcode() == Instruction::SetNE)) {
1649       // We keep moving the cast from the left operand over to the right
1650       // operand, where it can often be eliminated completely.
1651       Op0 = CastOp0;
1652       
1653       // If operand #1 is a cast instruction, see if we can eliminate it as
1654       // well.
1655       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1656         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
1657                                                                Op0->getType()))
1658           Op1 = CI2->getOperand(0);
1659       
1660       // If Op1 is a constant, we can fold the cast into the constant.
1661       if (Op1->getType() != Op0->getType())
1662         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1663           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1664         } else {
1665           // Otherwise, cast the RHS right before the setcc
1666           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1667           InsertNewInstBefore(cast<Instruction>(Op1), I);
1668         }
1669       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1670     }
1671
1672     // Handle the special case of: setcc (cast bool to X), <cst>
1673     // This comes up when you have code like
1674     //   int X = A < B;
1675     //   if (X) ...
1676     // For generality, we handle any zero-extension of any operand comparison
1677     // with a constant.
1678     if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1679       const Type *SrcTy = CastOp0->getType();
1680       const Type *DestTy = Op0->getType();
1681       if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1682           (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1683         // Ok, we have an expansion of operand 0 into a new type.  Get the
1684         // constant value, masink off bits which are not set in the RHS.  These
1685         // could be set if the destination value is signed.
1686         uint64_t ConstVal = ConstantRHS->getRawValue();
1687         ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1688
1689         // If the constant we are comparing it with has high bits set, which
1690         // don't exist in the original value, the values could never be equal,
1691         // because the source would be zero extended.
1692         unsigned SrcBits =
1693           SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
1694         bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1695         if (ConstVal & ~((1ULL << SrcBits)-1)) {
1696           switch (I.getOpcode()) {
1697           default: assert(0 && "Unknown comparison type!");
1698           case Instruction::SetEQ:
1699             return ReplaceInstUsesWith(I, ConstantBool::False);
1700           case Instruction::SetNE:
1701             return ReplaceInstUsesWith(I, ConstantBool::True);
1702           case Instruction::SetLT:
1703           case Instruction::SetLE:
1704             if (DestTy->isSigned() && HasSignBit)
1705               return ReplaceInstUsesWith(I, ConstantBool::False);
1706             return ReplaceInstUsesWith(I, ConstantBool::True);
1707           case Instruction::SetGT:
1708           case Instruction::SetGE:
1709             if (DestTy->isSigned() && HasSignBit)
1710               return ReplaceInstUsesWith(I, ConstantBool::True);
1711             return ReplaceInstUsesWith(I, ConstantBool::False);
1712           }
1713         }
1714         
1715         // Otherwise, we can replace the setcc with a setcc of the smaller
1716         // operand value.
1717         Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1718         return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1719       }
1720     }
1721   }
1722   return Changed ? &I : 0;
1723 }
1724
1725
1726
1727 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1728   assert(I.getOperand(1)->getType() == Type::UByteTy);
1729   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1730   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1731
1732   // shl X, 0 == X and shr X, 0 == X
1733   // shl 0, X == 0 and shr 0, X == 0
1734   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1735       Op0 == Constant::getNullValue(Op0->getType()))
1736     return ReplaceInstUsesWith(I, Op0);
1737
1738   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
1739   if (!isLeftShift)
1740     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1741       if (CSI->isAllOnesValue())
1742         return ReplaceInstUsesWith(I, CSI);
1743
1744   // Try to fold constant and into select arguments.
1745   if (isa<Constant>(Op0))
1746     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1747       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1748         return R;
1749
1750   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1751     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1752     // of a signed value.
1753     //
1754     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1755     if (CUI->getValue() >= TypeBits) {
1756       if (!Op0->getType()->isSigned() || isLeftShift)
1757         return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1758       else {
1759         I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1760         return &I;
1761       }
1762     }
1763
1764     // ((X*C1) << C2) == (X * (C1 << C2))
1765     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1766       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1767         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1768           return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1769                                 ConstantExpr::get(Instruction::Shl, BOOp, CUI));
1770     
1771     // Try to fold constant and into select arguments.
1772     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1773       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1774         return R;
1775
1776     // If the operand is an bitwise operator with a constant RHS, and the
1777     // shift is the only use, we can pull it out of the shift.
1778     if (Op0->hasOneUse())
1779       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1780         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1781           bool isValid = true;     // Valid only for And, Or, Xor
1782           bool highBitSet = false; // Transform if high bit of constant set?
1783
1784           switch (Op0BO->getOpcode()) {
1785           default: isValid = false; break;   // Do not perform transform!
1786           case Instruction::Or:
1787           case Instruction::Xor:
1788             highBitSet = false;
1789             break;
1790           case Instruction::And:
1791             highBitSet = true;
1792             break;
1793           }
1794
1795           // If this is a signed shift right, and the high bit is modified
1796           // by the logical operation, do not perform the transformation.
1797           // The highBitSet boolean indicates the value of the high bit of
1798           // the constant which would cause it to be modified for this
1799           // operation.
1800           //
1801           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1802             uint64_t Val = Op0C->getRawValue();
1803             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1804           }
1805
1806           if (isValid) {
1807             Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
1808
1809             Instruction *NewShift =
1810               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1811                             Op0BO->getName());
1812             Op0BO->setName("");
1813             InsertNewInstBefore(NewShift, I);
1814
1815             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1816                                           NewRHS);
1817           }
1818         }
1819
1820     // If this is a shift of a shift, see if we can fold the two together...
1821     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1822       if (ConstantUInt *ShiftAmt1C =
1823                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1824         unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1825         unsigned ShiftAmt2 = CUI->getValue();
1826         
1827         // Check for (A << c1) << c2   and   (A >> c1) >> c2
1828         if (I.getOpcode() == Op0SI->getOpcode()) {
1829           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
1830           if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1831             Amt = Op0->getType()->getPrimitiveSize()*8;
1832           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1833                                ConstantUInt::get(Type::UByteTy, Amt));
1834         }
1835         
1836         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
1837         // signed types, we can only support the (A >> c1) << c2 configuration,
1838         // because it can not turn an arbitrary bit of A into a sign bit.
1839         if (I.getType()->isUnsigned() || isLeftShift) {
1840           // Calculate bitmask for what gets shifted off the edge...
1841           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1842           if (isLeftShift)
1843             C = ConstantExpr::get(Instruction::Shl, C, ShiftAmt1C);
1844           else
1845             C = ConstantExpr::get(Instruction::Shr, C, ShiftAmt1C);
1846           
1847           Instruction *Mask =
1848             BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1849                                    C, Op0SI->getOperand(0)->getName()+".mask");
1850           InsertNewInstBefore(Mask, I);
1851           
1852           // Figure out what flavor of shift we should use...
1853           if (ShiftAmt1 == ShiftAmt2)
1854             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
1855           else if (ShiftAmt1 < ShiftAmt2) {
1856             return new ShiftInst(I.getOpcode(), Mask,
1857                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1858           } else {
1859             return new ShiftInst(Op0SI->getOpcode(), Mask,
1860                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1861           }
1862         }
1863       }
1864   }
1865
1866   return 0;
1867 }
1868
1869
1870 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1871 // instruction.
1872 //
1873 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1874                                           const Type *DstTy) {
1875
1876   // It is legal to eliminate the instruction if casting A->B->A if the sizes
1877   // are identical and the bits don't get reinterpreted (for example 
1878   // int->float->int would not be allowed)
1879   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1880     return true;
1881
1882   // Allow free casting and conversion of sizes as long as the sign doesn't
1883   // change...
1884   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1885     unsigned SrcSize = SrcTy->getPrimitiveSize();
1886     unsigned MidSize = MidTy->getPrimitiveSize();
1887     unsigned DstSize = DstTy->getPrimitiveSize();
1888
1889     // Cases where we are monotonically decreasing the size of the type are
1890     // always ok, regardless of what sign changes are going on.
1891     //
1892     if (SrcSize >= MidSize && MidSize >= DstSize)
1893       return true;
1894
1895     // Cases where the source and destination type are the same, but the middle
1896     // type is bigger are noops.
1897     //
1898     if (SrcSize == DstSize && MidSize > SrcSize)
1899       return true;
1900
1901     // If we are monotonically growing, things are more complex.
1902     //
1903     if (SrcSize <= MidSize && MidSize <= DstSize) {
1904       // We have eight combinations of signedness to worry about. Here's the
1905       // table:
1906       static const int SignTable[8] = {
1907         // CODE, SrcSigned, MidSigned, DstSigned, Comment
1908         1,     //   U          U          U       Always ok
1909         1,     //   U          U          S       Always ok
1910         3,     //   U          S          U       Ok iff SrcSize != MidSize
1911         3,     //   U          S          S       Ok iff SrcSize != MidSize
1912         0,     //   S          U          U       Never ok
1913         2,     //   S          U          S       Ok iff MidSize == DstSize
1914         1,     //   S          S          U       Always ok
1915         1,     //   S          S          S       Always ok
1916       };
1917
1918       // Choose an action based on the current entry of the signtable that this
1919       // cast of cast refers to...
1920       unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1921       switch (SignTable[Row]) {
1922       case 0: return false;              // Never ok
1923       case 1: return true;               // Always ok
1924       case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1925       case 3:                            // Ok iff SrcSize != MidSize
1926         return SrcSize != MidSize || SrcTy == Type::BoolTy;
1927       default: assert(0 && "Bad entry in sign table!");
1928       }
1929     }
1930   }
1931
1932   // Otherwise, we cannot succeed.  Specifically we do not want to allow things
1933   // like:  short -> ushort -> uint, because this can create wrong results if
1934   // the input short is negative!
1935   //
1936   return false;
1937 }
1938
1939 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1940   if (V->getType() == Ty || isa<Constant>(V)) return false;
1941   if (const CastInst *CI = dyn_cast<CastInst>(V))
1942     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1943       return false;
1944   return true;
1945 }
1946
1947 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1948 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
1949 /// casts that are known to not do anything...
1950 ///
1951 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1952                                              Instruction *InsertBefore) {
1953   if (V->getType() == DestTy) return V;
1954   if (Constant *C = dyn_cast<Constant>(V))
1955     return ConstantExpr::getCast(C, DestTy);
1956
1957   CastInst *CI = new CastInst(V, DestTy, V->getName());
1958   InsertNewInstBefore(CI, *InsertBefore);
1959   return CI;
1960 }
1961
1962 // CastInst simplification
1963 //
1964 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1965   Value *Src = CI.getOperand(0);
1966
1967   // If the user is casting a value to the same type, eliminate this cast
1968   // instruction...
1969   if (CI.getType() == Src->getType())
1970     return ReplaceInstUsesWith(CI, Src);
1971
1972   // If casting the result of another cast instruction, try to eliminate this
1973   // one!
1974   //
1975   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1976     if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1977                                CSrc->getType(), CI.getType())) {
1978       // This instruction now refers directly to the cast's src operand.  This
1979       // has a good chance of making CSrc dead.
1980       CI.setOperand(0, CSrc->getOperand(0));
1981       return &CI;
1982     }
1983
1984     // If this is an A->B->A cast, and we are dealing with integral types, try
1985     // to convert this into a logical 'and' instruction.
1986     //
1987     if (CSrc->getOperand(0)->getType() == CI.getType() &&
1988         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1989         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1990         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1991       assert(CSrc->getType() != Type::ULongTy &&
1992              "Cannot have type bigger than ulong!");
1993       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1994       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1995       return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1996                                     AndOp);
1997     }
1998   }
1999
2000   // If casting the result of a getelementptr instruction with no offset, turn
2001   // this into a cast of the original pointer!
2002   //
2003   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2004     bool AllZeroOperands = true;
2005     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2006       if (!isa<Constant>(GEP->getOperand(i)) ||
2007           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2008         AllZeroOperands = false;
2009         break;
2010       }
2011     if (AllZeroOperands) {
2012       CI.setOperand(0, GEP->getOperand(0));
2013       return &CI;
2014     }
2015   }
2016
2017   // If we are casting a malloc or alloca to a pointer to a type of the same
2018   // size, rewrite the allocation instruction to allocate the "right" type.
2019   //
2020   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2021     if (AI->hasOneUse() && !AI->isArrayAllocation())
2022       if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2023         // Get the type really allocated and the type casted to...
2024         const Type *AllocElTy = AI->getAllocatedType();
2025         unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2026         const Type *CastElTy = PTy->getElementType();
2027         unsigned CastElTySize = TD->getTypeSize(CastElTy);
2028
2029         // If the allocation is for an even multiple of the cast type size
2030         if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2031           Value *Amt = ConstantUInt::get(Type::UIntTy, 
2032                                          AllocElTySize/CastElTySize);
2033           std::string Name = AI->getName(); AI->setName("");
2034           AllocationInst *New;
2035           if (isa<MallocInst>(AI))
2036             New = new MallocInst(CastElTy, Amt, Name);
2037           else
2038             New = new AllocaInst(CastElTy, Amt, Name);
2039           InsertNewInstBefore(New, CI);
2040           return ReplaceInstUsesWith(CI, New);
2041         }
2042       }
2043
2044   // If the source value is an instruction with only this use, we can attempt to
2045   // propagate the cast into the instruction.  Also, only handle integral types
2046   // for now.
2047   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2048     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2049         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
2050       const Type *DestTy = CI.getType();
2051       unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2052       unsigned DestBitSize = getTypeSizeInBits(DestTy);
2053
2054       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2055       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2056
2057       switch (SrcI->getOpcode()) {
2058       case Instruction::Add:
2059       case Instruction::Mul:
2060       case Instruction::And:
2061       case Instruction::Or:
2062       case Instruction::Xor:
2063         // If we are discarding information, or just changing the sign, rewrite.
2064         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2065           // Don't insert two casts if they cannot be eliminated.  We allow two
2066           // casts to be inserted if the sizes are the same.  This could only be
2067           // converting signedness, which is a noop.
2068           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
2069               !ValueRequiresCast(Op0, DestTy)) {
2070             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2071             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2072             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2073                              ->getOpcode(), Op0c, Op1c);
2074           }
2075         }
2076         break;
2077       case Instruction::Shl:
2078         // Allow changing the sign of the source operand.  Do not allow changing
2079         // the size of the shift, UNLESS the shift amount is a constant.  We
2080         // mush not change variable sized shifts to a smaller size, because it
2081         // is undefined to shift more bits out than exist in the value.
2082         if (DestBitSize == SrcBitSize ||
2083             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2084           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2085           return new ShiftInst(Instruction::Shl, Op0c, Op1);
2086         }
2087         break;
2088       }
2089     }
2090   
2091   return 0;
2092 }
2093
2094 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2095 ///   %C = or %A, %B
2096 ///   %D = select %cond, %C, %A
2097 /// into:
2098 ///   %C = select %cond, %B, 0
2099 ///   %D = or %A, %C
2100 ///
2101 /// Assuming that the specified instruction is an operand to the select, return
2102 /// a bitmask indicating which operands of this instruction are foldable if they
2103 /// equal the other incoming value of the select.
2104 ///
2105 static unsigned GetSelectFoldableOperands(Instruction *I) {
2106   switch (I->getOpcode()) {
2107   case Instruction::Add:
2108   case Instruction::Mul:
2109   case Instruction::And:
2110   case Instruction::Or:
2111   case Instruction::Xor:
2112     return 3;              // Can fold through either operand.
2113   case Instruction::Sub:   // Can only fold on the amount subtracted.
2114   case Instruction::Shl:   // Can only fold on the shift amount.
2115   case Instruction::Shr:
2116     return 1;           
2117   default:
2118     return 0;              // Cannot fold
2119   }
2120 }
2121
2122 /// GetSelectFoldableConstant - For the same transformation as the previous
2123 /// function, return the identity constant that goes into the select.
2124 static Constant *GetSelectFoldableConstant(Instruction *I) {
2125   switch (I->getOpcode()) {
2126   default: assert(0 && "This cannot happen!"); abort();
2127   case Instruction::Add:
2128   case Instruction::Sub:
2129   case Instruction::Or:
2130   case Instruction::Xor:
2131     return Constant::getNullValue(I->getType());
2132   case Instruction::Shl:
2133   case Instruction::Shr:
2134     return Constant::getNullValue(Type::UByteTy);
2135   case Instruction::And:
2136     return ConstantInt::getAllOnesValue(I->getType());
2137   case Instruction::Mul:
2138     return ConstantInt::get(I->getType(), 1);
2139   }
2140 }
2141
2142 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2143   Value *CondVal = SI.getCondition();
2144   Value *TrueVal = SI.getTrueValue();
2145   Value *FalseVal = SI.getFalseValue();
2146
2147   // select true, X, Y  -> X
2148   // select false, X, Y -> Y
2149   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2150     if (C == ConstantBool::True)
2151       return ReplaceInstUsesWith(SI, TrueVal);
2152     else {
2153       assert(C == ConstantBool::False);
2154       return ReplaceInstUsesWith(SI, FalseVal);
2155     }
2156
2157   // select C, X, X -> X
2158   if (TrueVal == FalseVal)
2159     return ReplaceInstUsesWith(SI, TrueVal);
2160
2161   if (SI.getType() == Type::BoolTy)
2162     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2163       if (C == ConstantBool::True) {
2164         // Change: A = select B, true, C --> A = or B, C
2165         return BinaryOperator::create(Instruction::Or, CondVal, FalseVal);
2166       } else {
2167         // Change: A = select B, false, C --> A = and !B, C
2168         Value *NotCond =
2169           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2170                                              "not."+CondVal->getName()), SI);
2171         return BinaryOperator::create(Instruction::And, NotCond, FalseVal);
2172       }
2173     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2174       if (C == ConstantBool::False) {
2175         // Change: A = select B, C, false --> A = and B, C
2176         return BinaryOperator::create(Instruction::And, CondVal, TrueVal);
2177       } else {
2178         // Change: A = select B, C, true --> A = or !B, C
2179         Value *NotCond =
2180           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2181                                              "not."+CondVal->getName()), SI);
2182         return BinaryOperator::create(Instruction::Or, NotCond, TrueVal);
2183       }
2184     }
2185
2186   // Selecting between two integer constants?
2187   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2188     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2189       // select C, 1, 0 -> cast C to int
2190       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2191         return new CastInst(CondVal, SI.getType());
2192       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2193         // select C, 0, 1 -> cast !C to int
2194         Value *NotCond =
2195           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2196                                                "not."+CondVal->getName()), SI);
2197         return new CastInst(NotCond, SI.getType());
2198       }
2199     }
2200   
2201   // See if we can fold the select into one of our operands.
2202   if (SI.getType()->isInteger()) {
2203     // See the comment above GetSelectFoldableOperands for a description of the
2204     // transformation we are doing here.
2205     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2206       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2207           !isa<Constant>(FalseVal))
2208         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2209           unsigned OpToFold = 0;
2210           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2211             OpToFold = 1;
2212           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2213             OpToFold = 2;
2214           }
2215
2216           if (OpToFold) {
2217             Constant *C = GetSelectFoldableConstant(TVI);
2218             std::string Name = TVI->getName(); TVI->setName("");
2219             Instruction *NewSel =
2220               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2221                              Name);
2222             InsertNewInstBefore(NewSel, SI);
2223             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2224               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2225             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2226               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2227             else {
2228               assert(0 && "Unknown instruction!!");
2229             }
2230           }
2231         }
2232     
2233     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2234       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2235           !isa<Constant>(TrueVal))
2236         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2237           unsigned OpToFold = 0;
2238           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2239             OpToFold = 1;
2240           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2241             OpToFold = 2;
2242           }
2243
2244           if (OpToFold) {
2245             Constant *C = GetSelectFoldableConstant(FVI);
2246             std::string Name = FVI->getName(); FVI->setName("");
2247             Instruction *NewSel =
2248               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2249                              Name);
2250             InsertNewInstBefore(NewSel, SI);
2251             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2252               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2253             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2254               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2255             else {
2256               assert(0 && "Unknown instruction!!");
2257             }
2258           }
2259         }
2260   }
2261   return 0;
2262 }
2263
2264
2265 // CallInst simplification
2266 //
2267 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
2268   // Intrinsics cannot occur in an invoke, so handle them here instead of in
2269   // visitCallSite.
2270   if (Function *F = CI.getCalledFunction())
2271     switch (F->getIntrinsicID()) {
2272     case Intrinsic::memmove:
2273     case Intrinsic::memcpy:
2274     case Intrinsic::memset:
2275       // memmove/cpy/set of zero bytes is a noop.
2276       if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2277         if (NumBytes->isNullValue())
2278           return EraseInstFromFunction(CI);
2279       }
2280       break;
2281     default:
2282       break;
2283     }
2284
2285   return visitCallSite(&CI);
2286 }
2287
2288 // InvokeInst simplification
2289 //
2290 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2291   return visitCallSite(&II);
2292 }
2293
2294 // visitCallSite - Improvements for call and invoke instructions.
2295 //
2296 Instruction *InstCombiner::visitCallSite(CallSite CS) {
2297   bool Changed = false;
2298
2299   // If the callee is a constexpr cast of a function, attempt to move the cast
2300   // to the arguments of the call/invoke.
2301   if (transformConstExprCastCall(CS)) return 0;
2302
2303   Value *Callee = CS.getCalledValue();
2304   const PointerType *PTy = cast<PointerType>(Callee->getType());
2305   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2306   if (FTy->isVarArg()) {
2307     // See if we can optimize any arguments passed through the varargs area of
2308     // the call.
2309     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2310            E = CS.arg_end(); I != E; ++I)
2311       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2312         // If this cast does not effect the value passed through the varargs
2313         // area, we can eliminate the use of the cast.
2314         Value *Op = CI->getOperand(0);
2315         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2316           *I = Op;
2317           Changed = true;
2318         }
2319       }
2320   }
2321   
2322   return Changed ? CS.getInstruction() : 0;
2323 }
2324
2325 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
2326 // attempt to move the cast to the arguments of the call/invoke.
2327 //
2328 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2329   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2330   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2331   if (CE->getOpcode() != Instruction::Cast ||
2332       !isa<ConstantPointerRef>(CE->getOperand(0)))
2333     return false;
2334   ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2335   if (!isa<Function>(CPR->getValue())) return false;
2336   Function *Callee = cast<Function>(CPR->getValue());
2337   Instruction *Caller = CS.getInstruction();
2338
2339   // Okay, this is a cast from a function to a different type.  Unless doing so
2340   // would cause a type conversion of one of our arguments, change this call to
2341   // be a direct call with arguments casted to the appropriate types.
2342   //
2343   const FunctionType *FT = Callee->getFunctionType();
2344   const Type *OldRetTy = Caller->getType();
2345
2346   // Check to see if we are changing the return type...
2347   if (OldRetTy != FT->getReturnType()) {
2348     if (Callee->isExternal() &&
2349         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2350         !Caller->use_empty())
2351       return false;   // Cannot transform this return value...
2352
2353     // If the callsite is an invoke instruction, and the return value is used by
2354     // a PHI node in a successor, we cannot change the return type of the call
2355     // because there is no place to put the cast instruction (without breaking
2356     // the critical edge).  Bail out in this case.
2357     if (!Caller->use_empty())
2358       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2359         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2360              UI != E; ++UI)
2361           if (PHINode *PN = dyn_cast<PHINode>(*UI))
2362             if (PN->getParent() == II->getNormalDest() ||
2363                 PN->getParent() == II->getUnwindDest())
2364               return false;
2365   }
2366
2367   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2368   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2369                                     
2370   CallSite::arg_iterator AI = CS.arg_begin();
2371   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2372     const Type *ParamTy = FT->getParamType(i);
2373     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2374     if (Callee->isExternal() && !isConvertible) return false;    
2375   }
2376
2377   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2378       Callee->isExternal())
2379     return false;   // Do not delete arguments unless we have a function body...
2380
2381   // Okay, we decided that this is a safe thing to do: go ahead and start
2382   // inserting cast instructions as necessary...
2383   std::vector<Value*> Args;
2384   Args.reserve(NumActualArgs);
2385
2386   AI = CS.arg_begin();
2387   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2388     const Type *ParamTy = FT->getParamType(i);
2389     if ((*AI)->getType() == ParamTy) {
2390       Args.push_back(*AI);
2391     } else {
2392       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2393                                          *Caller));
2394     }
2395   }
2396
2397   // If the function takes more arguments than the call was taking, add them
2398   // now...
2399   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2400     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2401
2402   // If we are removing arguments to the function, emit an obnoxious warning...
2403   if (FT->getNumParams() < NumActualArgs)
2404     if (!FT->isVarArg()) {
2405       std::cerr << "WARNING: While resolving call to function '"
2406                 << Callee->getName() << "' arguments were dropped!\n";
2407     } else {
2408       // Add all of the arguments in their promoted form to the arg list...
2409       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2410         const Type *PTy = getPromotedType((*AI)->getType());
2411         if (PTy != (*AI)->getType()) {
2412           // Must promote to pass through va_arg area!
2413           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2414           InsertNewInstBefore(Cast, *Caller);
2415           Args.push_back(Cast);
2416         } else {
2417           Args.push_back(*AI);
2418         }
2419       }
2420     }
2421
2422   if (FT->getReturnType() == Type::VoidTy)
2423     Caller->setName("");   // Void type should not have a name...
2424
2425   Instruction *NC;
2426   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2427     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
2428                         Args, Caller->getName(), Caller);
2429   } else {
2430     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2431   }
2432
2433   // Insert a cast of the return type as necessary...
2434   Value *NV = NC;
2435   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2436     if (NV->getType() != Type::VoidTy) {
2437       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
2438
2439       // If this is an invoke instruction, we should insert it after the first
2440       // non-phi, instruction in the normal successor block.
2441       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2442         BasicBlock::iterator I = II->getNormalDest()->begin();
2443         while (isa<PHINode>(I)) ++I;
2444         InsertNewInstBefore(NC, *I);
2445       } else {
2446         // Otherwise, it's a call, just insert cast right after the call instr
2447         InsertNewInstBefore(NC, *Caller);
2448       }
2449       AddUsersToWorkList(*Caller);
2450     } else {
2451       NV = Constant::getNullValue(Caller->getType());
2452     }
2453   }
2454
2455   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2456     Caller->replaceAllUsesWith(NV);
2457   Caller->getParent()->getInstList().erase(Caller);
2458   removeFromWorkList(Caller);
2459   return true;
2460 }
2461
2462
2463
2464 // PHINode simplification
2465 //
2466 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
2467   if (Value *V = hasConstantValue(&PN))
2468     return ReplaceInstUsesWith(PN, V);
2469
2470   // If the only user of this instruction is a cast instruction, and all of the
2471   // incoming values are constants, change this PHI to merge together the casted
2472   // constants.
2473   if (PN.hasOneUse())
2474     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2475       if (CI->getType() != PN.getType()) {  // noop casts will be folded
2476         bool AllConstant = true;
2477         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2478           if (!isa<Constant>(PN.getIncomingValue(i))) {
2479             AllConstant = false;
2480             break;
2481           }
2482         if (AllConstant) {
2483           // Make a new PHI with all casted values.
2484           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2485           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2486             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2487             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2488                              PN.getIncomingBlock(i));
2489           }
2490
2491           // Update the cast instruction.
2492           CI->setOperand(0, New);
2493           WorkList.push_back(CI);    // revisit the cast instruction to fold.
2494           WorkList.push_back(New);   // Make sure to revisit the new Phi
2495           return &PN;                // PN is now dead!
2496         }
2497       }
2498   return 0;
2499 }
2500
2501 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2502                                       Instruction *InsertPoint,
2503                                       InstCombiner *IC) {
2504   unsigned PS = IC->getTargetData().getPointerSize();
2505   const Type *VTy = V->getType();
2506   Instruction *Cast;
2507   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2508     // We must insert a cast to ensure we sign-extend.
2509     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2510                                              V->getName()), *InsertPoint);
2511   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2512                                  *InsertPoint);
2513 }
2514
2515
2516 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2517   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
2518   // If so, eliminate the noop.
2519   if (GEP.getNumOperands() == 1)
2520     return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
2521
2522   bool HasZeroPointerIndex = false;
2523   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2524     HasZeroPointerIndex = C->isNullValue();
2525
2526   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
2527     return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
2528
2529   // Eliminate unneeded casts for indices.
2530   bool MadeChange = false;
2531   gep_type_iterator GTI = gep_type_begin(GEP);
2532   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2533     if (isa<SequentialType>(*GTI)) {
2534       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2535         Value *Src = CI->getOperand(0);
2536         const Type *SrcTy = Src->getType();
2537         const Type *DestTy = CI->getType();
2538         if (Src->getType()->isInteger()) {
2539           if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2540             // We can always eliminate a cast from ulong or long to the other.
2541             // We can always eliminate a cast from uint to int or the other on
2542             // 32-bit pointer platforms.
2543             if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2544               MadeChange = true;
2545               GEP.setOperand(i, Src);
2546             }
2547           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2548                      SrcTy->getPrimitiveSize() == 4) {
2549             // We can always eliminate a cast from int to [u]long.  We can
2550             // eliminate a cast from uint to [u]long iff the target is a 32-bit
2551             // pointer target.
2552             if (SrcTy->isSigned() || 
2553                 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2554               MadeChange = true;
2555               GEP.setOperand(i, Src);
2556             }
2557           }
2558         }
2559       }
2560       // If we are using a wider index than needed for this platform, shrink it
2561       // to what we need.  If the incoming value needs a cast instruction,
2562       // insert it.  This explicit cast can make subsequent optimizations more
2563       // obvious.
2564       Value *Op = GEP.getOperand(i);
2565       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
2566         if (!isa<Constant>(Op)) {
2567           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2568                                                 Op->getName()), GEP);
2569           GEP.setOperand(i, Op);
2570           MadeChange = true;
2571         }
2572     }
2573   if (MadeChange) return &GEP;
2574
2575   // Combine Indices - If the source pointer to this getelementptr instruction
2576   // is a getelementptr instruction, combine the indices of the two
2577   // getelementptr instructions into a single instruction.
2578   //
2579   std::vector<Value*> SrcGEPOperands;
2580   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
2581     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
2582   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP.getOperand(0))) {
2583     if (CE->getOpcode() == Instruction::GetElementPtr)
2584       SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2585   }
2586
2587   if (!SrcGEPOperands.empty()) {
2588     std::vector<Value *> Indices;
2589   
2590     // Can we combine the two pointer arithmetics offsets?
2591     if (SrcGEPOperands.size() == 2 && isa<Constant>(SrcGEPOperands[1]) &&
2592         isa<Constant>(GEP.getOperand(1))) {
2593       Constant *SGC = cast<Constant>(SrcGEPOperands[1]);
2594       Constant *GC  = cast<Constant>(GEP.getOperand(1));
2595       if (SGC->getType() != GC->getType()) {
2596         SGC = ConstantExpr::getSignExtend(SGC, Type::LongTy);
2597         GC = ConstantExpr::getSignExtend(GC, Type::LongTy);
2598       }
2599       
2600       // Replace: gep (gep %P, long C1), long C2, ...
2601       // With:    gep %P, long (C1+C2), ...
2602       GEP.setOperand(0, SrcGEPOperands[0]);
2603       GEP.setOperand(1, ConstantExpr::getAdd(SGC, GC));
2604       if (Instruction *I = dyn_cast<Instruction>(GEP.getOperand(0)))
2605         AddUsersToWorkList(*I);   // Reduce use count of Src
2606       return &GEP;
2607     } else if (SrcGEPOperands.size() == 2) {
2608       // Replace: gep (gep %P, long B), long A, ...
2609       // With:    T = long A+B; gep %P, T, ...
2610       //
2611       // Note that if our source is a gep chain itself that we wait for that
2612       // chain to be resolved before we perform this transformation.  This
2613       // avoids us creating a TON of code in some cases.
2614       //
2615       if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2616           cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2617         return 0;   // Wait until our source is folded to completion.
2618
2619       Value *Sum, *SO1 = SrcGEPOperands[1], *GO1 = GEP.getOperand(1);
2620       if (SO1 == Constant::getNullValue(SO1->getType())) {
2621         Sum = GO1;
2622       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2623         Sum = SO1;
2624       } else {
2625         // If they aren't the same type, convert both to an integer of the
2626         // target's pointer size.
2627         if (SO1->getType() != GO1->getType()) {
2628           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2629             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2630           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2631             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2632           } else {
2633             unsigned PS = TD->getPointerSize();
2634             Instruction *Cast;
2635             if (SO1->getType()->getPrimitiveSize() == PS) {
2636               // Convert GO1 to SO1's type.
2637               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2638
2639             } else if (GO1->getType()->getPrimitiveSize() == PS) {
2640               // Convert SO1 to GO1's type.
2641               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2642             } else {
2643               const Type *PT = TD->getIntPtrType();
2644               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2645               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2646             }
2647           }
2648         }
2649         Sum = BinaryOperator::create(Instruction::Add, SO1, GO1,
2650                                      GEP.getOperand(0)->getName()+".sum", &GEP);
2651         WorkList.push_back(cast<Instruction>(Sum));
2652       }
2653       GEP.setOperand(0, SrcGEPOperands[0]);
2654       GEP.setOperand(1, Sum);
2655       return &GEP;
2656     } else if (isa<Constant>(*GEP.idx_begin()) && 
2657                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2658                SrcGEPOperands.size() != 1) { 
2659       // Otherwise we can do the fold if the first index of the GEP is a zero
2660       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2661                      SrcGEPOperands.end());
2662       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2663     } else if (SrcGEPOperands.back() ==
2664                Constant::getNullValue(SrcGEPOperands.back()->getType())) {
2665       // We have to check to make sure this really is an ARRAY index we are
2666       // ending up with, not a struct index.
2667       generic_gep_type_iterator<std::vector<Value*>::iterator>
2668         GTI = gep_type_begin(SrcGEPOperands[0]->getType(),
2669                              SrcGEPOperands.begin()+1, SrcGEPOperands.end());
2670       std::advance(GTI, SrcGEPOperands.size()-2);
2671       if (isa<SequentialType>(*GTI)) {
2672         // If the src gep ends with a constant array index, merge this get into
2673         // it, even if we have a non-zero array index.
2674         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2675                        SrcGEPOperands.end()-1);
2676         Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
2677       }
2678     }
2679
2680     if (!Indices.empty())
2681       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
2682
2683   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
2684     // GEP of global variable.  If all of the indices for this GEP are
2685     // constants, we can promote this to a constexpr instead of an instruction.
2686
2687     // Scan for nonconstants...
2688     std::vector<Constant*> Indices;
2689     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2690     for (; I != E && isa<Constant>(*I); ++I)
2691       Indices.push_back(cast<Constant>(*I));
2692
2693     if (I == E) {  // If they are all constants...
2694       Constant *CE =
2695         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2696
2697       // Replace all uses of the GEP with the new constexpr...
2698       return ReplaceInstUsesWith(GEP, CE);
2699     }
2700   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP.getOperand(0))) {
2701     if (CE->getOpcode() == Instruction::Cast) {
2702       if (HasZeroPointerIndex) {
2703         // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2704         // into     : GEP [10 x ubyte]* X, long 0, ...
2705         //
2706         // This occurs when the program declares an array extern like "int X[];"
2707         //
2708         Constant *X = CE->getOperand(0);
2709         const PointerType *CPTy = cast<PointerType>(CE->getType());
2710         if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2711           if (const ArrayType *XATy =
2712               dyn_cast<ArrayType>(XTy->getElementType()))
2713             if (const ArrayType *CATy =
2714                 dyn_cast<ArrayType>(CPTy->getElementType()))
2715               if (CATy->getElementType() == XATy->getElementType()) {
2716                 // At this point, we know that the cast source type is a pointer
2717                 // to an array of the same type as the destination pointer
2718                 // array.  Because the array type is never stepped over (there
2719                 // is a leading zero) we can fold the cast into this GEP.
2720                 GEP.setOperand(0, X);
2721                 return &GEP;
2722               }
2723       }
2724     }
2725   }
2726
2727   return 0;
2728 }
2729
2730 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2731   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2732   if (AI.isArrayAllocation())    // Check C != 1
2733     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2734       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
2735       AllocationInst *New = 0;
2736
2737       // Create and insert the replacement instruction...
2738       if (isa<MallocInst>(AI))
2739         New = new MallocInst(NewTy, 0, AI.getName());
2740       else {
2741         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
2742         New = new AllocaInst(NewTy, 0, AI.getName());
2743       }
2744
2745       InsertNewInstBefore(New, AI);
2746       
2747       // Scan to the end of the allocation instructions, to skip over a block of
2748       // allocas if possible...
2749       //
2750       BasicBlock::iterator It = New;
2751       while (isa<AllocationInst>(*It)) ++It;
2752
2753       // Now that I is pointing to the first non-allocation-inst in the block,
2754       // insert our getelementptr instruction...
2755       //
2756       std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
2757       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2758
2759       // Now make everything use the getelementptr instead of the original
2760       // allocation.
2761       return ReplaceInstUsesWith(AI, V);
2762     }
2763
2764   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2765   // Note that we only do this for alloca's, because malloc should allocate and
2766   // return a unique pointer, even for a zero byte allocation.
2767   if (isa<AllocaInst>(AI) && TD->getTypeSize(AI.getAllocatedType()) == 0)
2768     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2769
2770   return 0;
2771 }
2772
2773 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2774   Value *Op = FI.getOperand(0);
2775
2776   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2777   if (CastInst *CI = dyn_cast<CastInst>(Op))
2778     if (isa<PointerType>(CI->getOperand(0)->getType())) {
2779       FI.setOperand(0, CI->getOperand(0));
2780       return &FI;
2781     }
2782
2783   // If we have 'free null' delete the instruction.  This can happen in stl code
2784   // when lots of inlining happens.
2785   if (isa<ConstantPointerNull>(Op))
2786     return EraseInstFromFunction(FI);
2787
2788   return 0;
2789 }
2790
2791
2792 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2793 /// constantexpr, return the constant value being addressed by the constant
2794 /// expression, or null if something is funny.
2795 ///
2796 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
2797   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
2798     return 0;  // Do not allow stepping over the value!
2799
2800   // Loop over all of the operands, tracking down which value we are
2801   // addressing...
2802   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
2803     if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
2804       ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
2805       if (CS == 0) return 0;
2806       if (CU->getValue() >= CS->getValues().size()) return 0;
2807       C = cast<Constant>(CS->getValues()[CU->getValue()]);
2808     } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
2809       ConstantArray *CA = dyn_cast<ConstantArray>(C);
2810       if (CA == 0) return 0;
2811       if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
2812       C = cast<Constant>(CA->getValues()[CS->getValue()]);
2813     } else 
2814       return 0;
2815   return C;
2816 }
2817
2818 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2819   Value *Op = LI.getOperand(0);
2820   if (LI.isVolatile()) return 0;
2821
2822   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
2823     Op = CPR->getValue();
2824
2825   // Instcombine load (constant global) into the value loaded...
2826   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
2827     if (GV->isConstant() && !GV->isExternal())
2828       return ReplaceInstUsesWith(LI, GV->getInitializer());
2829
2830   // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2831   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2832     if (CE->getOpcode() == Instruction::GetElementPtr)
2833       if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2834         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
2835           if (GV->isConstant() && !GV->isExternal())
2836             if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2837               return ReplaceInstUsesWith(LI, V);
2838
2839   // load (cast X) --> cast (load X) iff safe
2840   if (CastInst *CI = dyn_cast<CastInst>(Op)) {
2841     const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2842     if (const PointerType *SrcTy =
2843         dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2844       const Type *SrcPTy = SrcTy->getElementType();
2845       if (TD->getTypeSize(SrcPTy) == TD->getTypeSize(DestPTy) &&
2846           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2847           (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2848         // Okay, we are casting from one integer or pointer type to another of
2849         // the same size.  Instead of casting the pointer before the load, cast
2850         // the result of the loaded value.
2851         Value *NewLoad = InsertNewInstBefore(new LoadInst(CI->getOperand(0),
2852                                                           CI->getName()), LI);
2853         // Now cast the result of the load.
2854         return new CastInst(NewLoad, LI.getType());
2855       }
2856     }
2857   }
2858
2859   return 0;
2860 }
2861
2862
2863 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2864   // Change br (not X), label True, label False to: br X, label False, True
2865   if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
2866     if (Value *V = dyn_castNotVal(BI.getCondition())) {
2867       BasicBlock *TrueDest = BI.getSuccessor(0);
2868       BasicBlock *FalseDest = BI.getSuccessor(1);
2869       // Swap Destinations and condition...
2870       BI.setCondition(V);
2871       BI.setSuccessor(0, FalseDest);
2872       BI.setSuccessor(1, TrueDest);
2873       return &BI;
2874     } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
2875       // Cannonicalize setne -> seteq
2876       if ((I->getOpcode() == Instruction::SetNE ||
2877            I->getOpcode() == Instruction::SetLE ||
2878            I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
2879         std::string Name = I->getName(); I->setName("");
2880         Instruction::BinaryOps NewOpcode =
2881           SetCondInst::getInverseCondition(I->getOpcode());
2882         Value *NewSCC =  BinaryOperator::create(NewOpcode, I->getOperand(0),
2883                                                 I->getOperand(1), Name, I);
2884         BasicBlock *TrueDest = BI.getSuccessor(0);
2885         BasicBlock *FalseDest = BI.getSuccessor(1);
2886         // Swap Destinations and condition...
2887         BI.setCondition(NewSCC);
2888         BI.setSuccessor(0, FalseDest);
2889         BI.setSuccessor(1, TrueDest);
2890         removeFromWorkList(I);
2891         I->getParent()->getInstList().erase(I);
2892         WorkList.push_back(cast<Instruction>(NewSCC));
2893         return &BI;
2894       }
2895     }
2896   }
2897   return 0;
2898 }
2899
2900
2901 void InstCombiner::removeFromWorkList(Instruction *I) {
2902   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
2903                  WorkList.end());
2904 }
2905
2906 bool InstCombiner::runOnFunction(Function &F) {
2907   bool Changed = false;
2908   TD = &getAnalysis<TargetData>();
2909
2910   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
2911
2912   while (!WorkList.empty()) {
2913     Instruction *I = WorkList.back();  // Get an instruction from the worklist
2914     WorkList.pop_back();
2915
2916     // Check to see if we can DCE or ConstantPropagate the instruction...
2917     // Check to see if we can DIE the instruction...
2918     if (isInstructionTriviallyDead(I)) {
2919       // Add operands to the worklist...
2920       if (I->getNumOperands() < 4)
2921         AddUsesToWorkList(*I);
2922       ++NumDeadInst;
2923
2924       I->getParent()->getInstList().erase(I);
2925       removeFromWorkList(I);
2926       continue;
2927     }
2928
2929     // Instruction isn't dead, see if we can constant propagate it...
2930     if (Constant *C = ConstantFoldInstruction(I)) {
2931       // Add operands to the worklist...
2932       AddUsesToWorkList(*I);
2933       ReplaceInstUsesWith(*I, C);
2934
2935       ++NumConstProp;
2936       I->getParent()->getInstList().erase(I);
2937       removeFromWorkList(I);
2938       continue;
2939     }
2940
2941     // Check to see if any of the operands of this instruction are a
2942     // ConstantPointerRef.  Since they sneak in all over the place and inhibit
2943     // optimization, we want to strip them out unconditionally!
2944     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
2945       if (ConstantPointerRef *CPR =
2946           dyn_cast<ConstantPointerRef>(I->getOperand(i))) {
2947         I->setOperand(i, CPR->getValue());
2948         Changed = true;
2949       }
2950
2951     // Now that we have an instruction, try combining it to simplify it...
2952     if (Instruction *Result = visit(*I)) {
2953       ++NumCombined;
2954       // Should we replace the old instruction with a new one?
2955       if (Result != I) {
2956         DEBUG(std::cerr << "IC: Old = " << *I
2957                         << "    New = " << *Result);
2958
2959         // Instructions can end up on the worklist more than once.  Make sure
2960         // we do not process an instruction that has been deleted.
2961         removeFromWorkList(I);
2962
2963         // Move the name to the new instruction first...
2964         std::string OldName = I->getName(); I->setName("");
2965         Result->setName(OldName);
2966
2967         // Insert the new instruction into the basic block...
2968         BasicBlock *InstParent = I->getParent();
2969         InstParent->getInstList().insert(I, Result);
2970
2971         // Everything uses the new instruction now...
2972         I->replaceAllUsesWith(Result);
2973
2974         // Erase the old instruction.
2975         InstParent->getInstList().erase(I);
2976       } else {
2977         DEBUG(std::cerr << "IC: MOD = " << *I);
2978
2979         BasicBlock::iterator II = I;
2980
2981         // If the instruction was modified, it's possible that it is now dead.
2982         // if so, remove it.
2983         if (dceInstruction(II)) {
2984           // Instructions may end up in the worklist more than once.  Erase them
2985           // all.
2986           removeFromWorkList(I);
2987           Result = 0;
2988         }
2989       }
2990
2991       if (Result) {
2992         WorkList.push_back(Result);
2993         AddUsersToWorkList(*Result);
2994       }
2995       Changed = true;
2996     }
2997   }
2998
2999   return Changed;
3000 }
3001
3002 Pass *llvm::createInstructionCombiningPass() {
3003   return new InstCombiner();
3004 }
3005