Instcombine (X & FF00) + xx00 -> (X+xx00) & FF00, implementing and.ll:test27
[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 %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %X, 2
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 "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/ADT/Statistic.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 namespace {
59   Statistic<> NumCombined ("instcombine", "Number of insts combined");
60   Statistic<> NumConstProp("instcombine", "Number of constant folds");
61   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
63   class InstCombiner : public FunctionPass,
64                        public InstVisitor<InstCombiner, Instruction*> {
65     // Worklist of all of the instructions that need to be simplified.
66     std::vector<Instruction*> WorkList;
67     TargetData *TD;
68
69     /// AddUsersToWorkList - When an instruction is simplified, add all users of
70     /// the instruction to the work lists because they might get more simplified
71     /// now.
72     ///
73     void AddUsersToWorkList(Instruction &I) {
74       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
75            UI != UE; ++UI)
76         WorkList.push_back(cast<Instruction>(*UI));
77     }
78
79     /// AddUsesToWorkList - When an instruction is simplified, add operands to
80     /// the work lists because they might get more simplified now.
81     ///
82     void AddUsesToWorkList(Instruction &I) {
83       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85           WorkList.push_back(Op);
86     }
87
88     // removeFromWorkList - remove all instances of I from the worklist.
89     void removeFromWorkList(Instruction *I);
90   public:
91     virtual bool runOnFunction(Function &F);
92
93     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94       AU.addRequired<TargetData>();
95       AU.setPreservesCFG();
96     }
97
98     TargetData &getTargetData() const { return *TD; }
99
100     // Visitation implementation - Implement instruction combining for different
101     // instruction types.  The semantics are as follows:
102     // Return Value:
103     //    null        - No change was made
104     //     I          - Change was made, I is still valid, I may be dead though
105     //   otherwise    - Change was made, replace I with returned instruction
106     //   
107     Instruction *visitAdd(BinaryOperator &I);
108     Instruction *visitSub(BinaryOperator &I);
109     Instruction *visitMul(BinaryOperator &I);
110     Instruction *visitDiv(BinaryOperator &I);
111     Instruction *visitRem(BinaryOperator &I);
112     Instruction *visitAnd(BinaryOperator &I);
113     Instruction *visitOr (BinaryOperator &I);
114     Instruction *visitXor(BinaryOperator &I);
115     Instruction *visitSetCondInst(BinaryOperator &I);
116     Instruction *visitShiftInst(ShiftInst &I);
117     Instruction *visitCastInst(CastInst &CI);
118     Instruction *visitSelectInst(SelectInst &CI);
119     Instruction *visitCallInst(CallInst &CI);
120     Instruction *visitInvokeInst(InvokeInst &II);
121     Instruction *visitPHINode(PHINode &PN);
122     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
123     Instruction *visitAllocationInst(AllocationInst &AI);
124     Instruction *visitFreeInst(FreeInst &FI);
125     Instruction *visitLoadInst(LoadInst &LI);
126     Instruction *visitBranchInst(BranchInst &BI);
127     Instruction *visitSwitchInst(SwitchInst &SI);
128
129     // visitInstruction - Specify what to return for unhandled instructions...
130     Instruction *visitInstruction(Instruction &I) { return 0; }
131
132   private:
133     Instruction *visitCallSite(CallSite CS);
134     bool transformConstExprCastCall(CallSite CS);
135
136   public:
137     // InsertNewInstBefore - insert an instruction New before instruction Old
138     // in the program.  Add the new instruction to the worklist.
139     //
140     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
141       assert(New && New->getParent() == 0 &&
142              "New instruction already inserted into a basic block!");
143       BasicBlock *BB = Old.getParent();
144       BB->getInstList().insert(&Old, New);  // Insert inst
145       WorkList.push_back(New);              // Add to worklist
146       return New;
147     }
148
149     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150     /// This also adds the cast to the worklist.  Finally, this returns the
151     /// cast.
152     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153       if (V->getType() == Ty) return V;
154       
155       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156       WorkList.push_back(C);
157       return C;
158     }
159
160     // ReplaceInstUsesWith - This method is to be used when an instruction is
161     // found to be dead, replacable with another preexisting expression.  Here
162     // we add all uses of I to the worklist, replace all uses of I with the new
163     // value, then return I, so that the inst combiner will know that I was
164     // modified.
165     //
166     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
167       AddUsersToWorkList(I);         // Add all modified instrs to worklist
168       if (&I != V) {
169         I.replaceAllUsesWith(V);
170         return &I;
171       } else {
172         // If we are replacing the instruction with itself, this must be in a
173         // segment of unreachable code, so just clobber the instruction.
174         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175         return &I;
176       }
177     }
178
179     // EraseInstFromFunction - When dealing with an instruction that has side
180     // effects or produces a void value, we can't rely on DCE to delete the
181     // instruction.  Instead, visit methods should return the value returned by
182     // this function.
183     Instruction *EraseInstFromFunction(Instruction &I) {
184       assert(I.use_empty() && "Cannot erase instruction that is used!");
185       AddUsesToWorkList(I);
186       removeFromWorkList(&I);
187       I.getParent()->getInstList().erase(&I);
188       return 0;  // Don't do anything with FI
189     }
190
191
192   private:
193     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
195     /// casts that are known to not do anything...
196     ///
197     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198                                    Instruction *InsertBefore);
199
200     // SimplifyCommutative - This performs a few simplifications for commutative
201     // operators.
202     bool SimplifyCommutative(BinaryOperator &I);
203
204
205     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206     // PHI node as operand #0, see if we can fold the instruction into the PHI
207     // (which is only possible if all operands to the PHI are constants).
208     Instruction *FoldOpIntoPhi(Instruction &I);
209
210     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
212
213     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214                                  bool Inside, Instruction &IB);
215   };
216
217   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
218 }
219
220 // getComplexity:  Assign a complexity or rank value to LLVM Values...
221 //   0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222 static unsigned getComplexity(Value *V) {
223   if (isa<Instruction>(V)) {
224     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
225       return 2;
226     return 3;
227   }
228   if (isa<Argument>(V)) return 2;
229   return isa<Constant>(V) ? 0 : 1;
230 }
231
232 // isOnlyUse - Return true if this instruction will be deleted if we stop using
233 // it.
234 static bool isOnlyUse(Value *V) {
235   return V->hasOneUse() || isa<Constant>(V);
236 }
237
238 // getPromotedType - Return the specified type promoted as it would be to pass
239 // though a va_arg area...
240 static const Type *getPromotedType(const Type *Ty) {
241   switch (Ty->getTypeID()) {
242   case Type::SByteTyID:
243   case Type::ShortTyID:  return Type::IntTy;
244   case Type::UByteTyID:
245   case Type::UShortTyID: return Type::UIntTy;
246   case Type::FloatTyID:  return Type::DoubleTy;
247   default:               return Ty;
248   }
249 }
250
251 // SimplifyCommutative - This performs a few simplifications for commutative
252 // operators:
253 //
254 //  1. Order operands such that they are listed from right (least complex) to
255 //     left (most complex).  This puts constants before unary operators before
256 //     binary operators.
257 //
258 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
260 //
261 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
262   bool Changed = false;
263   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264     Changed = !I.swapOperands();
265   
266   if (!I.isAssociative()) return Changed;
267   Instruction::BinaryOps Opcode = I.getOpcode();
268   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270       if (isa<Constant>(I.getOperand(1))) {
271         Constant *Folded = ConstantExpr::get(I.getOpcode(),
272                                              cast<Constant>(I.getOperand(1)),
273                                              cast<Constant>(Op->getOperand(1)));
274         I.setOperand(0, Op->getOperand(0));
275         I.setOperand(1, Folded);
276         return true;
277       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279             isOnlyUse(Op) && isOnlyUse(Op1)) {
280           Constant *C1 = cast<Constant>(Op->getOperand(1));
281           Constant *C2 = cast<Constant>(Op1->getOperand(1));
282
283           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
284           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
285           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286                                                     Op1->getOperand(0),
287                                                     Op1->getName(), &I);
288           WorkList.push_back(New);
289           I.setOperand(0, New);
290           I.setOperand(1, Folded);
291           return true;
292         }      
293     }
294   return Changed;
295 }
296
297 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298 // if the LHS is a constant zero (which is the 'negate' form).
299 //
300 static inline Value *dyn_castNegVal(Value *V) {
301   if (BinaryOperator::isNeg(V))
302     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
303
304   // Constants can be considered to be negated values if they can be folded...
305   if (Constant *C = dyn_cast<Constant>(V))
306     return ConstantExpr::getNeg(C);
307   return 0;
308 }
309
310 static inline Value *dyn_castNotVal(Value *V) {
311   if (BinaryOperator::isNot(V))
312     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
313
314   // Constants can be considered to be not'ed values...
315   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
316     return ConstantExpr::getNot(C);
317   return 0;
318 }
319
320 // dyn_castFoldableMul - If this value is a multiply that can be folded into
321 // other computations (because it has a constant operand), return the
322 // non-constant operand of the multiply.
323 //
324 static inline Value *dyn_castFoldableMul(Value *V) {
325   if (V->hasOneUse() && V->getType()->isInteger())
326     if (Instruction *I = dyn_cast<Instruction>(V))
327       if (I->getOpcode() == Instruction::Mul)
328         if (isa<Constant>(I->getOperand(1)))
329           return I->getOperand(0);
330   return 0;
331 }
332
333 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
334 // power of 2.
335 static unsigned Log2(uint64_t Val) {
336   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337   unsigned Count = 0;
338   while (Val != 1) {
339     if (Val & 1) return 0;    // Multiple bits set?
340     Val >>= 1;
341     ++Count;
342   }
343   return Count;
344 }
345
346 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
347 static ConstantInt *AddOne(ConstantInt *C) {
348   return cast<ConstantInt>(ConstantExpr::getAdd(C,
349                                          ConstantInt::get(C->getType(), 1)));
350 }
351 static ConstantInt *SubOne(ConstantInt *C) {
352   return cast<ConstantInt>(ConstantExpr::getSub(C,
353                                          ConstantInt::get(C->getType(), 1)));
354 }
355
356 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
357 // true when both operands are equal...
358 //
359 static bool isTrueWhenEqual(Instruction &I) {
360   return I.getOpcode() == Instruction::SetEQ ||
361          I.getOpcode() == Instruction::SetGE ||
362          I.getOpcode() == Instruction::SetLE;
363 }
364
365 /// AssociativeOpt - Perform an optimization on an associative operator.  This
366 /// function is designed to check a chain of associative operators for a
367 /// potential to apply a certain optimization.  Since the optimization may be
368 /// applicable if the expression was reassociated, this checks the chain, then
369 /// reassociates the expression as necessary to expose the optimization
370 /// opportunity.  This makes use of a special Functor, which must define
371 /// 'shouldApply' and 'apply' methods.
372 ///
373 template<typename Functor>
374 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375   unsigned Opcode = Root.getOpcode();
376   Value *LHS = Root.getOperand(0);
377
378   // Quick check, see if the immediate LHS matches...
379   if (F.shouldApply(LHS))
380     return F.apply(Root);
381
382   // Otherwise, if the LHS is not of the same opcode as the root, return.
383   Instruction *LHSI = dyn_cast<Instruction>(LHS);
384   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
385     // Should we apply this transform to the RHS?
386     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388     // If not to the RHS, check to see if we should apply to the LHS...
389     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
391       ShouldApply = true;
392     }
393
394     // If the functor wants to apply the optimization to the RHS of LHSI,
395     // reassociate the expression from ((? op A) op B) to (? op (A op B))
396     if (ShouldApply) {
397       BasicBlock *BB = Root.getParent();
398       
399       // Now all of the instructions are in the current basic block, go ahead
400       // and perform the reassociation.
401       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
402
403       // First move the selected RHS to the LHS of the root...
404       Root.setOperand(0, LHSI->getOperand(1));
405
406       // Make what used to be the LHS of the root be the user of the root...
407       Value *ExtraOperand = TmpLHSI->getOperand(1);
408       if (&Root == TmpLHSI) {
409         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410         return 0;
411       }
412       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
413       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
414       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415       BasicBlock::iterator ARI = &Root; ++ARI;
416       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
417       ARI = Root;
418
419       // Now propagate the ExtraOperand down the chain of instructions until we
420       // get to LHSI.
421       while (TmpLHSI != LHSI) {
422         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
423         // Move the instruction to immediately before the chain we are
424         // constructing to avoid breaking dominance properties.
425         NextLHSI->getParent()->getInstList().remove(NextLHSI);
426         BB->getInstList().insert(ARI, NextLHSI);
427         ARI = NextLHSI;
428
429         Value *NextOp = NextLHSI->getOperand(1);
430         NextLHSI->setOperand(1, ExtraOperand);
431         TmpLHSI = NextLHSI;
432         ExtraOperand = NextOp;
433       }
434       
435       // Now that the instructions are reassociated, have the functor perform
436       // the transformation...
437       return F.apply(Root);
438     }
439     
440     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
441   }
442   return 0;
443 }
444
445
446 // AddRHS - Implements: X + X --> X << 1
447 struct AddRHS {
448   Value *RHS;
449   AddRHS(Value *rhs) : RHS(rhs) {}
450   bool shouldApply(Value *LHS) const { return LHS == RHS; }
451   Instruction *apply(BinaryOperator &Add) const {
452     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453                          ConstantInt::get(Type::UByteTy, 1));
454   }
455 };
456
457 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
458 //                 iff C1&C2 == 0
459 struct AddMaskingAnd {
460   Constant *C2;
461   AddMaskingAnd(Constant *c) : C2(c) {}
462   bool shouldApply(Value *LHS) const {
463     ConstantInt *C1;
464     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) && 
465            ConstantExpr::getAnd(C1, C2)->isNullValue();
466   }
467   Instruction *apply(BinaryOperator &Add) const {
468     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
469   }
470 };
471
472 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
473                                              InstCombiner *IC) {
474   // Figure out if the constant is the left or the right argument.
475   bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476   Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
477
478   if (Constant *SOC = dyn_cast<Constant>(SO)) {
479     if (ConstIsRHS)
480       return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481     return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482   }
483
484   Value *Op0 = SO, *Op1 = ConstOperand;
485   if (!ConstIsRHS)
486     std::swap(Op0, Op1);
487   Instruction *New;
488   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491     New = new ShiftInst(SI->getOpcode(), Op0, Op1);
492   else {
493     assert(0 && "Unknown binary instruction type!");
494     abort();
495   }
496   return IC->InsertNewInstBefore(New, BI);
497 }
498
499
500 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501 /// node as operand #0, see if we can fold the instruction into the PHI (which
502 /// is only possible if all operands to the PHI are constants).
503 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504   PHINode *PN = cast<PHINode>(I.getOperand(0));
505   if (!PN->hasOneUse()) return 0;
506
507   // Check to see if all of the operands of the PHI are constants.  If not, we
508   // cannot do the transformation.
509   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510     if (!isa<Constant>(PN->getIncomingValue(i)))
511       return 0;
512
513   // Okay, we can do the transformation: create the new PHI node.
514   PHINode *NewPN = new PHINode(I.getType(), I.getName());
515   I.setName("");
516   NewPN->op_reserve(PN->getNumOperands());
517   InsertNewInstBefore(NewPN, *PN);
518
519   // Next, add all of the operands to the PHI.
520   if (I.getNumOperands() == 2) {
521     Constant *C = cast<Constant>(I.getOperand(1));
522     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525                          PN->getIncomingBlock(i));
526     }
527   } else {
528     assert(isa<CastInst>(I) && "Unary op should be a cast!");
529     const Type *RetTy = I.getType();
530     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533                          PN->getIncomingBlock(i));
534     }
535   }
536   return ReplaceInstUsesWith(I, NewPN);
537 }
538
539 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540 // constant as the other operand, try to fold the binary operator into the
541 // select arguments.
542 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
543                                         InstCombiner *IC) {
544   // Don't modify shared select instructions
545   if (!SI->hasOneUse()) return 0;
546   Value *TV = SI->getOperand(1);
547   Value *FV = SI->getOperand(2);
548
549   if (isa<Constant>(TV) || isa<Constant>(FV)) {
550     Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
551     Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
552
553     return new SelectInst(SI->getCondition(), SelectTrueVal,
554                           SelectFalseVal);
555   }
556   return 0;
557 }
558
559 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
560   bool Changed = SimplifyCommutative(I);
561   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
562
563   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
564     // X + 0 --> X
565     if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
566         RHSC->isNullValue())
567       return ReplaceInstUsesWith(I, LHS);
568     
569     // X + (signbit) --> X ^ signbit
570     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571       unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572       uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573       if (Val == (1ULL << NumBits-1))
574         return BinaryOperator::createXor(LHS, RHS);
575     }
576
577     if (isa<PHINode>(LHS))
578       if (Instruction *NV = FoldOpIntoPhi(I))
579         return NV;
580   }
581
582   // X + X --> X << 1
583   if (I.getType()->isInteger()) {
584     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
585   }
586
587   // -A + B  -->  B - A
588   if (Value *V = dyn_castNegVal(LHS))
589     return BinaryOperator::createSub(RHS, V);
590
591   // A + -B  -->  A - B
592   if (!isa<Constant>(RHS))
593     if (Value *V = dyn_castNegVal(RHS))
594       return BinaryOperator::createSub(LHS, V);
595
596   // X*C + X --> X * (C+1)
597   if (dyn_castFoldableMul(LHS) == RHS) {
598     Constant *CP1 =
599       ConstantExpr::getAdd(
600                         cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601                         ConstantInt::get(I.getType(), 1));
602     return BinaryOperator::createMul(RHS, CP1);
603   }
604
605   // X + X*C --> X * (C+1)
606   if (dyn_castFoldableMul(RHS) == LHS) {
607     Constant *CP1 =
608       ConstantExpr::getAdd(
609                         cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610                         ConstantInt::get(I.getType(), 1));
611     return BinaryOperator::createMul(LHS, CP1);
612   }
613
614   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
615   ConstantInt *C2;
616   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
617     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
618
619   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
620     Value *X;
621     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
622       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623       return BinaryOperator::createSub(C, X);
624     }
625
626     // (X & FF00) + xx00  -> (X+xx00) & FF00
627     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
628       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
629       if (Anded == CRHS) {
630         // See if all bits from the first bit set in the Add RHS up are included
631         // in the mask.  First, get the rightmost bit.
632         uint64_t AddRHSV = CRHS->getRawValue();
633
634         // Form a mask of all bits from the lowest bit added through the top.
635         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
636         AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
637
638         // See if the and mask includes all of these bits.
639         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
640         
641         if (AddRHSHighBits == AddRHSHighBitsAnd) {
642           // Okay, the xform is safe.  Insert the new add pronto.
643           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
644                                                             LHS->getName()), I);
645           return BinaryOperator::createAnd(NewAdd, C2);
646         }
647       }
648     }
649
650
651     // Try to fold constant add into select arguments.
652     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
653       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
654         return R;
655   }
656
657   return Changed ? &I : 0;
658 }
659
660 // isSignBit - Return true if the value represented by the constant only has the
661 // highest order bit set.
662 static bool isSignBit(ConstantInt *CI) {
663   unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
664   return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
665 }
666
667 static unsigned getTypeSizeInBits(const Type *Ty) {
668   return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
669 }
670
671 /// RemoveNoopCast - Strip off nonconverting casts from the value.
672 ///
673 static Value *RemoveNoopCast(Value *V) {
674   if (CastInst *CI = dyn_cast<CastInst>(V)) {
675     const Type *CTy = CI->getType();
676     const Type *OpTy = CI->getOperand(0)->getType();
677     if (CTy->isInteger() && OpTy->isInteger()) {
678       if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
679         return RemoveNoopCast(CI->getOperand(0));
680     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
681       return RemoveNoopCast(CI->getOperand(0));
682   }
683   return V;
684 }
685
686 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
687   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
688
689   if (Op0 == Op1)         // sub X, X  -> 0
690     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
691
692   // If this is a 'B = x-(-A)', change to B = x+A...
693   if (Value *V = dyn_castNegVal(Op1))
694     return BinaryOperator::createAdd(Op0, V);
695
696   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
697     // Replace (-1 - A) with (~A)...
698     if (C->isAllOnesValue())
699       return BinaryOperator::createNot(Op1);
700
701     // C - ~X == X + (1+C)
702     Value *X;
703     if (match(Op1, m_Not(m_Value(X))))
704       return BinaryOperator::createAdd(X,
705                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
706     // -((uint)X >> 31) -> ((int)X >> 31)
707     // -((int)X >> 31) -> ((uint)X >> 31)
708     if (C->isNullValue()) {
709       Value *NoopCastedRHS = RemoveNoopCast(Op1);
710       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
711         if (SI->getOpcode() == Instruction::Shr)
712           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
713             const Type *NewTy;
714             if (SI->getType()->isSigned())
715               NewTy = SI->getType()->getUnsignedVersion();
716             else
717               NewTy = SI->getType()->getSignedVersion();
718             // Check to see if we are shifting out everything but the sign bit.
719             if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
720               // Ok, the transformation is safe.  Insert a cast of the incoming
721               // value, then the new shift, then the new cast.
722               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
723                                                  SI->getOperand(0)->getName());
724               Value *InV = InsertNewInstBefore(FirstCast, I);
725               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
726                                                     CU, SI->getName());
727               if (NewShift->getType() == I.getType())
728                 return NewShift;
729               else {
730                 InV = InsertNewInstBefore(NewShift, I);
731                 return new CastInst(NewShift, I.getType());
732               }
733             }
734           }
735     }
736
737     // Try to fold constant sub into select arguments.
738     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
739       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
740         return R;
741
742     if (isa<PHINode>(Op0))
743       if (Instruction *NV = FoldOpIntoPhi(I))
744         return NV;
745   }
746
747   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
748     if (Op1I->hasOneUse()) {
749       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
750       // is not used by anyone else...
751       //
752       if (Op1I->getOpcode() == Instruction::Sub &&
753           !Op1I->getType()->isFloatingPoint()) {
754         // Swap the two operands of the subexpr...
755         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
756         Op1I->setOperand(0, IIOp1);
757         Op1I->setOperand(1, IIOp0);
758         
759         // Create the new top level add instruction...
760         return BinaryOperator::createAdd(Op0, Op1);
761       }
762
763       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
764       //
765       if (Op1I->getOpcode() == Instruction::And &&
766           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
767         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
768
769         Value *NewNot =
770           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
771         return BinaryOperator::createAnd(Op0, NewNot);
772       }
773
774       // -(X sdiv C)  -> (X sdiv -C)
775       if (Op1I->getOpcode() == Instruction::Div)
776         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
777           if (CSI->getValue() == 0)
778             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
779               return BinaryOperator::createDiv(Op1I->getOperand(0), 
780                                                ConstantExpr::getNeg(DivRHS));
781
782       // X - X*C --> X * (1-C)
783       if (dyn_castFoldableMul(Op1I) == Op0) {
784         Constant *CP1 =
785           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
786                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
787         assert(CP1 && "Couldn't constant fold 1-C?");
788         return BinaryOperator::createMul(Op0, CP1);
789       }
790     }
791
792   // X*C - X --> X * (C-1)
793   if (dyn_castFoldableMul(Op0) == Op1) {
794     Constant *CP1 =
795      ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
796                         ConstantInt::get(I.getType(), 1));
797     assert(CP1 && "Couldn't constant fold C - 1?");
798     return BinaryOperator::createMul(Op1, CP1);
799   }
800
801   return 0;
802 }
803
804 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
805 /// really just returns true if the most significant (sign) bit is set.
806 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
807   if (RHS->getType()->isSigned()) {
808     // True if source is LHS < 0 or LHS <= -1
809     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
810            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
811   } else {
812     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
813     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
814     // the size of the integer type.
815     if (Opcode == Instruction::SetGE)
816       return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
817     if (Opcode == Instruction::SetGT)
818       return RHSC->getValue() ==
819         (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
820   }
821   return false;
822 }
823
824 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
825   bool Changed = SimplifyCommutative(I);
826   Value *Op0 = I.getOperand(0);
827
828   // Simplify mul instructions with a constant RHS...
829   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
830     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
831
832       // ((X << C1)*C2) == (X * (C2 << C1))
833       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
834         if (SI->getOpcode() == Instruction::Shl)
835           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
836             return BinaryOperator::createMul(SI->getOperand(0),
837                                              ConstantExpr::getShl(CI, ShOp));
838       
839       if (CI->isNullValue())
840         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
841       if (CI->equalsInt(1))                  // X * 1  == X
842         return ReplaceInstUsesWith(I, Op0);
843       if (CI->isAllOnesValue())              // X * -1 == 0 - X
844         return BinaryOperator::createNeg(Op0, I.getName());
845
846       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
847       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
848         return new ShiftInst(Instruction::Shl, Op0,
849                              ConstantUInt::get(Type::UByteTy, C));
850     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
851       if (Op1F->isNullValue())
852         return ReplaceInstUsesWith(I, Op1);
853
854       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
855       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
856       if (Op1F->getValue() == 1.0)
857         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
858     }
859
860     // Try to fold constant mul into select arguments.
861     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
862       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
863         return R;
864
865     if (isa<PHINode>(Op0))
866       if (Instruction *NV = FoldOpIntoPhi(I))
867         return NV;
868   }
869
870   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
871     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
872       return BinaryOperator::createMul(Op0v, Op1v);
873
874   // If one of the operands of the multiply is a cast from a boolean value, then
875   // we know the bool is either zero or one, so this is a 'masking' multiply.
876   // See if we can simplify things based on how the boolean was originally
877   // formed.
878   CastInst *BoolCast = 0;
879   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
880     if (CI->getOperand(0)->getType() == Type::BoolTy)
881       BoolCast = CI;
882   if (!BoolCast)
883     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
884       if (CI->getOperand(0)->getType() == Type::BoolTy)
885         BoolCast = CI;
886   if (BoolCast) {
887     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
888       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
889       const Type *SCOpTy = SCIOp0->getType();
890
891       // If the setcc is true iff the sign bit of X is set, then convert this
892       // multiply into a shift/and combination.
893       if (isa<ConstantInt>(SCIOp1) &&
894           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
895         // Shift the X value right to turn it into "all signbits".
896         Constant *Amt = ConstantUInt::get(Type::UByteTy,
897                                           SCOpTy->getPrimitiveSize()*8-1);
898         if (SCIOp0->getType()->isUnsigned()) {
899           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
900           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
901                                                     SCIOp0->getName()), I);
902         }
903
904         Value *V =
905           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
906                                             BoolCast->getOperand(0)->getName()+
907                                             ".mask"), I);
908
909         // If the multiply type is not the same as the source type, sign extend
910         // or truncate to the multiply type.
911         if (I.getType() != V->getType())
912           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
913         
914         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
915         return BinaryOperator::createAnd(V, OtherOp);
916       }
917     }
918   }
919
920   return Changed ? &I : 0;
921 }
922
923 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
924   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
925     // div X, 1 == X
926     if (RHS->equalsInt(1))
927       return ReplaceInstUsesWith(I, I.getOperand(0));
928
929     // div X, -1 == -X
930     if (RHS->isAllOnesValue())
931       return BinaryOperator::createNeg(I.getOperand(0));
932
933     if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
934       if (LHS->getOpcode() == Instruction::Div)
935         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
936           // (X / C1) / C2  -> X / (C1*C2)
937           return BinaryOperator::createDiv(LHS->getOperand(0),
938                                            ConstantExpr::getMul(RHS, LHSRHS));
939         }
940
941     // Check to see if this is an unsigned division with an exact power of 2,
942     // if so, convert to a right shift.
943     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
944       if (uint64_t Val = C->getValue())    // Don't break X / 0
945         if (uint64_t C = Log2(Val))
946           return new ShiftInst(Instruction::Shr, I.getOperand(0),
947                                ConstantUInt::get(Type::UByteTy, C));
948
949     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
950       if (Instruction *NV = FoldOpIntoPhi(I))
951         return NV;
952   }
953
954   // 0 / X == 0, we don't need to preserve faults!
955   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
956     if (LHS->equalsInt(0))
957       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
958
959   return 0;
960 }
961
962
963 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
964   if (I.getType()->isSigned())
965     if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
966       if (!isa<ConstantSInt>(RHSNeg) ||
967           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
968         // X % -Y -> X % Y
969         AddUsesToWorkList(I);
970         I.setOperand(1, RHSNeg);
971         return &I;
972       }
973
974   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
975     if (RHS->equalsInt(1))  // X % 1 == 0
976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
977
978     // Check to see if this is an unsigned remainder with an exact power of 2,
979     // if so, convert to a bitwise and.
980     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
981       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
982         if (!(Val & (Val-1)))              // Power of 2
983           return BinaryOperator::createAnd(I.getOperand(0),
984                                         ConstantUInt::get(I.getType(), Val-1));
985     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
986       if (Instruction *NV = FoldOpIntoPhi(I))
987         return NV;
988   }
989
990   // 0 % X == 0, we don't need to preserve faults!
991   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
992     if (LHS->equalsInt(0))
993       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
994
995   return 0;
996 }
997
998 // isMaxValueMinusOne - return true if this is Max-1
999 static bool isMaxValueMinusOne(const ConstantInt *C) {
1000   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1001     // Calculate -1 casted to the right type...
1002     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1003     uint64_t Val = ~0ULL;                // All ones
1004     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1005     return CU->getValue() == Val-1;
1006   }
1007
1008   const ConstantSInt *CS = cast<ConstantSInt>(C);
1009   
1010   // Calculate 0111111111..11111
1011   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1012   int64_t Val = INT64_MAX;             // All ones
1013   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1014   return CS->getValue() == Val-1;
1015 }
1016
1017 // isMinValuePlusOne - return true if this is Min+1
1018 static bool isMinValuePlusOne(const ConstantInt *C) {
1019   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1020     return CU->getValue() == 1;
1021
1022   const ConstantSInt *CS = cast<ConstantSInt>(C);
1023   
1024   // Calculate 1111111111000000000000 
1025   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1026   int64_t Val = -1;                    // All ones
1027   Val <<= TypeBits-1;                  // Shift over to the right spot
1028   return CS->getValue() == Val+1;
1029 }
1030
1031 // isOneBitSet - Return true if there is exactly one bit set in the specified
1032 // constant.
1033 static bool isOneBitSet(const ConstantInt *CI) {
1034   uint64_t V = CI->getRawValue();
1035   return V && (V & (V-1)) == 0;
1036 }
1037
1038 #if 0   // Currently unused
1039 // isLowOnes - Return true if the constant is of the form 0+1+.
1040 static bool isLowOnes(const ConstantInt *CI) {
1041   uint64_t V = CI->getRawValue();
1042
1043   // There won't be bits set in parts that the type doesn't contain.
1044   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1045
1046   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1047   return U && V && (U & V) == 0;
1048 }
1049 #endif
1050
1051 // isHighOnes - Return true if the constant is of the form 1+0+.
1052 // This is the same as lowones(~X).
1053 static bool isHighOnes(const ConstantInt *CI) {
1054   uint64_t V = ~CI->getRawValue();
1055
1056   // There won't be bits set in parts that the type doesn't contain.
1057   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1058
1059   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1060   return U && V && (U & V) == 0;
1061 }
1062
1063
1064 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1065 /// are carefully arranged to allow folding of expressions such as:
1066 ///
1067 ///      (A < B) | (A > B) --> (A != B)
1068 ///
1069 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1070 /// represents that the comparison is true if A == B, and bit value '1' is true
1071 /// if A < B.
1072 ///
1073 static unsigned getSetCondCode(const SetCondInst *SCI) {
1074   switch (SCI->getOpcode()) {
1075     // False -> 0
1076   case Instruction::SetGT: return 1;
1077   case Instruction::SetEQ: return 2;
1078   case Instruction::SetGE: return 3;
1079   case Instruction::SetLT: return 4;
1080   case Instruction::SetNE: return 5;
1081   case Instruction::SetLE: return 6;
1082     // True -> 7
1083   default:
1084     assert(0 && "Invalid SetCC opcode!");
1085     return 0;
1086   }
1087 }
1088
1089 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1090 /// opcode and two operands into either a constant true or false, or a brand new
1091 /// SetCC instruction.
1092 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1093   switch (Opcode) {
1094   case 0: return ConstantBool::False;
1095   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1096   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1097   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1098   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1099   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1100   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1101   case 7: return ConstantBool::True;
1102   default: assert(0 && "Illegal SetCCCode!"); return 0;
1103   }
1104 }
1105
1106 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1107 struct FoldSetCCLogical {
1108   InstCombiner &IC;
1109   Value *LHS, *RHS;
1110   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1111     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1112   bool shouldApply(Value *V) const {
1113     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1114       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1115               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1116     return false;
1117   }
1118   Instruction *apply(BinaryOperator &Log) const {
1119     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1120     if (SCI->getOperand(0) != LHS) {
1121       assert(SCI->getOperand(1) == LHS);
1122       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
1123     }
1124
1125     unsigned LHSCode = getSetCondCode(SCI);
1126     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1127     unsigned Code;
1128     switch (Log.getOpcode()) {
1129     case Instruction::And: Code = LHSCode & RHSCode; break;
1130     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1131     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1132     default: assert(0 && "Illegal logical opcode!"); return 0;
1133     }
1134
1135     Value *RV = getSetCCValue(Code, LHS, RHS);
1136     if (Instruction *I = dyn_cast<Instruction>(RV))
1137       return I;
1138     // Otherwise, it's a constant boolean value...
1139     return IC.ReplaceInstUsesWith(Log, RV);
1140   }
1141 };
1142
1143
1144 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1145 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1146 // guaranteed to be either a shift instruction or a binary operator.
1147 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1148                                     ConstantIntegral *OpRHS,
1149                                     ConstantIntegral *AndRHS,
1150                                     BinaryOperator &TheAnd) {
1151   Value *X = Op->getOperand(0);
1152   Constant *Together = 0;
1153   if (!isa<ShiftInst>(Op))
1154     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1155
1156   switch (Op->getOpcode()) {
1157   case Instruction::Xor:
1158     if (Together->isNullValue()) {
1159       // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1160       return BinaryOperator::createAnd(X, AndRHS);
1161     } else if (Op->hasOneUse()) {
1162       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1163       std::string OpName = Op->getName(); Op->setName("");
1164       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1165       InsertNewInstBefore(And, TheAnd);
1166       return BinaryOperator::createXor(And, Together);
1167     }
1168     break;
1169   case Instruction::Or:
1170     // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1171     if (Together->isNullValue())
1172       return BinaryOperator::createAnd(X, AndRHS);
1173     else {
1174       if (Together == AndRHS) // (X | C) & C --> C
1175         return ReplaceInstUsesWith(TheAnd, AndRHS);
1176       
1177       if (Op->hasOneUse() && Together != OpRHS) {
1178         // (X | C1) & C2 --> (X | (C1&C2)) & C2
1179         std::string Op0Name = Op->getName(); Op->setName("");
1180         Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1181         InsertNewInstBefore(Or, TheAnd);
1182         return BinaryOperator::createAnd(Or, AndRHS);
1183       }
1184     }
1185     break;
1186   case Instruction::Add:
1187     if (Op->hasOneUse()) {
1188       // Adding a one to a single bit bit-field should be turned into an XOR
1189       // of the bit.  First thing to check is to see if this AND is with a
1190       // single bit constant.
1191       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1192
1193       // Clear bits that are not part of the constant.
1194       AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1195
1196       // If there is only one bit set...
1197       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1198         // Ok, at this point, we know that we are masking the result of the
1199         // ADD down to exactly one bit.  If the constant we are adding has
1200         // no bits set below this bit, then we can eliminate the ADD.
1201         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1202             
1203         // Check to see if any bits below the one bit set in AndRHSV are set.
1204         if ((AddRHS & (AndRHSV-1)) == 0) {
1205           // If not, the only thing that can effect the output of the AND is
1206           // the bit specified by AndRHSV.  If that bit is set, the effect of
1207           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1208           // no effect.
1209           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1210             TheAnd.setOperand(0, X);
1211             return &TheAnd;
1212           } else {
1213             std::string Name = Op->getName(); Op->setName("");
1214             // Pull the XOR out of the AND.
1215             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1216             InsertNewInstBefore(NewAnd, TheAnd);
1217             return BinaryOperator::createXor(NewAnd, AndRHS);
1218           }
1219         }
1220       }
1221     }
1222     break;
1223
1224   case Instruction::Shl: {
1225     // We know that the AND will not produce any of the bits shifted in, so if
1226     // the anded constant includes them, clear them now!
1227     //
1228     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1229     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1230     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1231                                         
1232     if (CI == ShlMask) {   // Masking out bits that the shift already masks
1233       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
1234     } else if (CI != AndRHS) {                  // Reducing bits set in and.
1235       TheAnd.setOperand(1, CI);
1236       return &TheAnd;
1237     }
1238     break;
1239   } 
1240   case Instruction::Shr:
1241     // We know that the AND will not produce any of the bits shifted in, so if
1242     // the anded constant includes them, clear them now!  This only applies to
1243     // unsigned shifts, because a signed shr may bring in set bits!
1244     //
1245     if (AndRHS->getType()->isUnsigned()) {
1246       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1247       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1248       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1249
1250       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
1251         return ReplaceInstUsesWith(TheAnd, Op);
1252       } else if (CI != AndRHS) {
1253         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
1254         return &TheAnd;
1255       }
1256     } else {   // Signed shr.
1257       // See if this is shifting in some sign extension, then masking it out
1258       // with an and.
1259       if (Op->hasOneUse()) {
1260         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1261         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1262         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1263         if (CI == ShrMask) {          // Masking out bits shifted in.
1264           // Make the argument unsigned.
1265           Value *ShVal = Op->getOperand(0);
1266           ShVal = InsertCastBefore(ShVal,
1267                                    ShVal->getType()->getUnsignedVersion(),
1268                                    TheAnd);
1269           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1270                                                     OpRHS, Op->getName()),
1271                                       TheAnd);
1272           return new CastInst(ShVal, Op->getType());
1273         }
1274       }
1275     }
1276     break;
1277   }
1278   return 0;
1279 }
1280
1281
1282 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1283 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
1284 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
1285 /// insert new instructions.
1286 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1287                                            bool Inside, Instruction &IB) {
1288   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1289          "Lo is not <= Hi in range emission code!");
1290   if (Inside) {
1291     if (Lo == Hi)  // Trivially false.
1292       return new SetCondInst(Instruction::SetNE, V, V);
1293     if (cast<ConstantIntegral>(Lo)->isMinValue())
1294       return new SetCondInst(Instruction::SetLT, V, Hi);
1295     
1296     Constant *AddCST = ConstantExpr::getNeg(Lo);
1297     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1298     InsertNewInstBefore(Add, IB);
1299     // Convert to unsigned for the comparison.
1300     const Type *UnsType = Add->getType()->getUnsignedVersion();
1301     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1302     AddCST = ConstantExpr::getAdd(AddCST, Hi);
1303     AddCST = ConstantExpr::getCast(AddCST, UnsType);
1304     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1305   }
1306
1307   if (Lo == Hi)  // Trivially true.
1308     return new SetCondInst(Instruction::SetEQ, V, V);
1309
1310   Hi = SubOne(cast<ConstantInt>(Hi));
1311   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1312     return new SetCondInst(Instruction::SetGT, V, Hi);
1313
1314   // Emit X-Lo > Hi-Lo-1
1315   Constant *AddCST = ConstantExpr::getNeg(Lo);
1316   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1317   InsertNewInstBefore(Add, IB);
1318   // Convert to unsigned for the comparison.
1319   const Type *UnsType = Add->getType()->getUnsignedVersion();
1320   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1321   AddCST = ConstantExpr::getAdd(AddCST, Hi);
1322   AddCST = ConstantExpr::getCast(AddCST, UnsType);
1323   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1324 }
1325
1326
1327 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1328   bool Changed = SimplifyCommutative(I);
1329   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1330
1331   // and X, X = X   and X, 0 == 0
1332   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1333     return ReplaceInstUsesWith(I, Op1);
1334
1335   // and X, -1 == X
1336   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1337     if (RHS->isAllOnesValue())
1338       return ReplaceInstUsesWith(I, Op0);
1339
1340     // Optimize a variety of ((val OP C1) & C2) combinations...
1341     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1342       Instruction *Op0I = cast<Instruction>(Op0);
1343       Value *X = Op0I->getOperand(0);
1344       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1345         if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1346           return Res;
1347     }
1348
1349     // Try to fold constant and into select arguments.
1350     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1351       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1352         return R;
1353     if (isa<PHINode>(Op0))
1354       if (Instruction *NV = FoldOpIntoPhi(I))
1355         return NV;
1356   }
1357
1358   Value *Op0NotVal = dyn_castNotVal(Op0);
1359   Value *Op1NotVal = dyn_castNotVal(Op1);
1360
1361   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1362     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1363
1364   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1365   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1366     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1367                                                I.getName()+".demorgan");
1368     InsertNewInstBefore(Or, I);
1369     return BinaryOperator::createNot(Or);
1370   }
1371
1372   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1373     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1374     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1375       return R;
1376
1377     Value *LHSVal, *RHSVal;
1378     ConstantInt *LHSCst, *RHSCst;
1379     Instruction::BinaryOps LHSCC, RHSCC;
1380     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1381       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1382         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
1383             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1384             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1385             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1386           // Ensure that the larger constant is on the RHS.
1387           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1388           SetCondInst *LHS = cast<SetCondInst>(Op0);
1389           if (cast<ConstantBool>(Cmp)->getValue()) {
1390             std::swap(LHS, RHS);
1391             std::swap(LHSCst, RHSCst);
1392             std::swap(LHSCC, RHSCC);
1393           }
1394
1395           // At this point, we know we have have two setcc instructions
1396           // comparing a value against two constants and and'ing the result
1397           // together.  Because of the above check, we know that we only have
1398           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1399           // FoldSetCCLogical check above), that the two constants are not
1400           // equal.
1401           assert(LHSCst != RHSCst && "Compares not folded above?");
1402
1403           switch (LHSCC) {
1404           default: assert(0 && "Unknown integer condition code!");
1405           case Instruction::SetEQ:
1406             switch (RHSCC) {
1407             default: assert(0 && "Unknown integer condition code!");
1408             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
1409             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
1410               return ReplaceInstUsesWith(I, ConstantBool::False);
1411             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
1412             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
1413               return ReplaceInstUsesWith(I, LHS);
1414             }
1415           case Instruction::SetNE:
1416             switch (RHSCC) {
1417             default: assert(0 && "Unknown integer condition code!");
1418             case Instruction::SetLT:
1419               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1420                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1421               break;                        // (X != 13 & X < 15) -> no change
1422             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
1423             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
1424               return ReplaceInstUsesWith(I, RHS);
1425             case Instruction::SetNE:
1426               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1427                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1428                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1429                                                       LHSVal->getName()+".off");
1430                 InsertNewInstBefore(Add, I);
1431                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1432                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1433                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1434                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1435                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1436               }
1437               break;                        // (X != 13 & X != 15) -> no change
1438             }
1439             break;
1440           case Instruction::SetLT:
1441             switch (RHSCC) {
1442             default: assert(0 && "Unknown integer condition code!");
1443             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
1444             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
1445               return ReplaceInstUsesWith(I, ConstantBool::False);
1446             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
1447             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
1448               return ReplaceInstUsesWith(I, LHS);
1449             }
1450           case Instruction::SetGT:
1451             switch (RHSCC) {
1452             default: assert(0 && "Unknown integer condition code!");
1453             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
1454               return ReplaceInstUsesWith(I, LHS);
1455             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
1456               return ReplaceInstUsesWith(I, RHS);
1457             case Instruction::SetNE:
1458               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1459                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1460               break;                        // (X > 13 & X != 15) -> no change
1461             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
1462               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1463             }
1464           }
1465         }
1466   }
1467
1468   return Changed ? &I : 0;
1469 }
1470
1471 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1472   bool Changed = SimplifyCommutative(I);
1473   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1474
1475   // or X, X = X   or X, 0 == X
1476   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1477     return ReplaceInstUsesWith(I, Op0);
1478
1479   // or X, -1 == -1
1480   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1481     if (RHS->isAllOnesValue())
1482       return ReplaceInstUsesWith(I, Op1);
1483
1484     ConstantInt *C1; Value *X;
1485     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1486     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1487       std::string Op0Name = Op0->getName(); Op0->setName("");
1488       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1489       InsertNewInstBefore(Or, I);
1490       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1491     }
1492
1493     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1494     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1495       std::string Op0Name = Op0->getName(); Op0->setName("");
1496       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1497       InsertNewInstBefore(Or, I);
1498       return BinaryOperator::createXor(Or,
1499                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1500     }
1501
1502     // Try to fold constant and into select arguments.
1503     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1504       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1505         return R;
1506     if (isa<PHINode>(Op0))
1507       if (Instruction *NV = FoldOpIntoPhi(I))
1508         return NV;
1509   }
1510
1511   // (A & C1)|(A & C2) == A & (C1|C2)
1512   Value *A, *B; ConstantInt *C1, *C2;
1513   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1514       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1515     return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1516
1517   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
1518     if (A == Op1)   // ~A | A == -1
1519       return ReplaceInstUsesWith(I, 
1520                                 ConstantIntegral::getAllOnesValue(I.getType()));
1521   } else {
1522     A = 0;
1523   }
1524
1525   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
1526     if (Op0 == B)
1527       return ReplaceInstUsesWith(I, 
1528                                 ConstantIntegral::getAllOnesValue(I.getType()));
1529
1530     // (~A | ~B) == (~(A & B)) - De Morgan's Law
1531     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1532       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1533                                               I.getName()+".demorgan"), I);
1534       return BinaryOperator::createNot(And);
1535     }
1536   }
1537
1538   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1539   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1540     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1541       return R;
1542
1543     Value *LHSVal, *RHSVal;
1544     ConstantInt *LHSCst, *RHSCst;
1545     Instruction::BinaryOps LHSCC, RHSCC;
1546     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1547       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1548         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
1549             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1550             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1551             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1552           // Ensure that the larger constant is on the RHS.
1553           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1554           SetCondInst *LHS = cast<SetCondInst>(Op0);
1555           if (cast<ConstantBool>(Cmp)->getValue()) {
1556             std::swap(LHS, RHS);
1557             std::swap(LHSCst, RHSCst);
1558             std::swap(LHSCC, RHSCC);
1559           }
1560
1561           // At this point, we know we have have two setcc instructions
1562           // comparing a value against two constants and or'ing the result
1563           // together.  Because of the above check, we know that we only have
1564           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1565           // FoldSetCCLogical check above), that the two constants are not
1566           // equal.
1567           assert(LHSCst != RHSCst && "Compares not folded above?");
1568
1569           switch (LHSCC) {
1570           default: assert(0 && "Unknown integer condition code!");
1571           case Instruction::SetEQ:
1572             switch (RHSCC) {
1573             default: assert(0 && "Unknown integer condition code!");
1574             case Instruction::SetEQ:
1575               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1576                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1577                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1578                                                       LHSVal->getName()+".off");
1579                 InsertNewInstBefore(Add, I);
1580                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1581                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1582                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1583                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1584                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1585               }
1586               break;                  // (X == 13 | X == 15) -> no change
1587
1588             case Instruction::SetGT:
1589               if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1590                 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1591               break;                        // (X == 13 | X > 15) -> no change
1592             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
1593             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
1594               return ReplaceInstUsesWith(I, RHS);
1595             }
1596             break;
1597           case Instruction::SetNE:
1598             switch (RHSCC) {
1599             default: assert(0 && "Unknown integer condition code!");
1600             case Instruction::SetLT:        // (X != 13 | X < 15) -> X < 15
1601               return ReplaceInstUsesWith(I, RHS);
1602             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
1603             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
1604               return ReplaceInstUsesWith(I, LHS);
1605             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
1606               return ReplaceInstUsesWith(I, ConstantBool::True);
1607             }
1608             break;
1609           case Instruction::SetLT:
1610             switch (RHSCC) {
1611             default: assert(0 && "Unknown integer condition code!");
1612             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
1613               break;
1614             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
1615               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1616             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
1617             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
1618               return ReplaceInstUsesWith(I, RHS);
1619             }
1620             break;
1621           case Instruction::SetGT:
1622             switch (RHSCC) {
1623             default: assert(0 && "Unknown integer condition code!");
1624             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
1625             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
1626               return ReplaceInstUsesWith(I, LHS);
1627             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
1628             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
1629               return ReplaceInstUsesWith(I, ConstantBool::True);
1630             }
1631           }
1632         }
1633   }
1634   return Changed ? &I : 0;
1635 }
1636
1637 // XorSelf - Implements: X ^ X --> 0
1638 struct XorSelf {
1639   Value *RHS;
1640   XorSelf(Value *rhs) : RHS(rhs) {}
1641   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1642   Instruction *apply(BinaryOperator &Xor) const {
1643     return &Xor;
1644   }
1645 };
1646
1647
1648 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1649   bool Changed = SimplifyCommutative(I);
1650   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1651
1652   // xor X, X = 0, even if X is nested in a sequence of Xor's.
1653   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1654     assert(Result == &I && "AssociativeOpt didn't work?");
1655     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1656   }
1657
1658   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1659     // xor X, 0 == X
1660     if (RHS->isNullValue())
1661       return ReplaceInstUsesWith(I, Op0);
1662
1663     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1664       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1665       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1666         if (RHS == ConstantBool::True && SCI->hasOneUse())
1667           return new SetCondInst(SCI->getInverseCondition(),
1668                                  SCI->getOperand(0), SCI->getOperand(1));
1669
1670       // ~(c-X) == X-c-1 == X+(-c-1)
1671       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1672         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1673           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1674           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1675                                               ConstantInt::get(I.getType(), 1));
1676           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1677         }
1678
1679       // ~(~X & Y) --> (X | ~Y)
1680       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1681         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1682         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1683           Instruction *NotY =
1684             BinaryOperator::createNot(Op0I->getOperand(1), 
1685                                       Op0I->getOperand(1)->getName()+".not");
1686           InsertNewInstBefore(NotY, I);
1687           return BinaryOperator::createOr(Op0NotVal, NotY);
1688         }
1689       }
1690           
1691       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1692         switch (Op0I->getOpcode()) {
1693         case Instruction::Add:
1694           // ~(X-c) --> (-c-1)-X
1695           if (RHS->isAllOnesValue()) {
1696             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1697             return BinaryOperator::createSub(
1698                            ConstantExpr::getSub(NegOp0CI,
1699                                              ConstantInt::get(I.getType(), 1)),
1700                                           Op0I->getOperand(0));
1701           }
1702           break;
1703         case Instruction::And:
1704           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1705           if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1706             return BinaryOperator::createOr(Op0, RHS);
1707           break;
1708         case Instruction::Or:
1709           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1710           if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1711             return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1712           break;
1713         default: break;
1714         }
1715     }
1716
1717     // Try to fold constant and into select arguments.
1718     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1719       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1720         return R;
1721     if (isa<PHINode>(Op0))
1722       if (Instruction *NV = FoldOpIntoPhi(I))
1723         return NV;
1724   }
1725
1726   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1727     if (X == Op1)
1728       return ReplaceInstUsesWith(I,
1729                                 ConstantIntegral::getAllOnesValue(I.getType()));
1730
1731   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1732     if (X == Op0)
1733       return ReplaceInstUsesWith(I,
1734                                 ConstantIntegral::getAllOnesValue(I.getType()));
1735
1736   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1737     if (Op1I->getOpcode() == Instruction::Or) {
1738       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
1739         cast<BinaryOperator>(Op1I)->swapOperands();
1740         I.swapOperands();
1741         std::swap(Op0, Op1);
1742       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
1743         I.swapOperands();
1744         std::swap(Op0, Op1);
1745       }      
1746     } else if (Op1I->getOpcode() == Instruction::Xor) {
1747       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
1748         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1749       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
1750         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1751     }
1752
1753   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1754     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1755       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
1756         cast<BinaryOperator>(Op0I)->swapOperands();
1757       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
1758         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1759                                                      Op1->getName()+".not"), I);
1760         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1761       }
1762     } else if (Op0I->getOpcode() == Instruction::Xor) {
1763       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
1764         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1765       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
1766         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1767     }
1768
1769   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1770   Value *A, *B; ConstantInt *C1, *C2;
1771   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1772       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1773       ConstantExpr::getAnd(C1, C2)->isNullValue())
1774     return BinaryOperator::createOr(Op0, Op1);
1775
1776   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1777   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1778     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1779       return R;
1780
1781   return Changed ? &I : 0;
1782 }
1783
1784 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1785 /// overflowed for this type.
1786 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1787                             ConstantInt *In2) {
1788   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1789   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1790 }
1791
1792 static bool isPositive(ConstantInt *C) {
1793   return cast<ConstantSInt>(C)->getValue() >= 0;
1794 }
1795
1796 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1797 /// overflowed for this type.
1798 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1799                             ConstantInt *In2) {
1800   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1801
1802   if (In1->getType()->isUnsigned())
1803     return cast<ConstantUInt>(Result)->getValue() <
1804            cast<ConstantUInt>(In1)->getValue();
1805   if (isPositive(In1) != isPositive(In2))
1806     return false;
1807   if (isPositive(In1))
1808     return cast<ConstantSInt>(Result)->getValue() <
1809            cast<ConstantSInt>(In1)->getValue();
1810   return cast<ConstantSInt>(Result)->getValue() >
1811          cast<ConstantSInt>(In1)->getValue();
1812 }
1813
1814 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1815   bool Changed = SimplifyCommutative(I);
1816   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1817   const Type *Ty = Op0->getType();
1818
1819   // setcc X, X
1820   if (Op0 == Op1)
1821     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1822
1823   // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1824   if (isa<ConstantPointerNull>(Op1) && 
1825       (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1826     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1827
1828
1829   // setcc's with boolean values can always be turned into bitwise operations
1830   if (Ty == Type::BoolTy) {
1831     switch (I.getOpcode()) {
1832     default: assert(0 && "Invalid setcc instruction!");
1833     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
1834       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1835       InsertNewInstBefore(Xor, I);
1836       return BinaryOperator::createNot(Xor);
1837     }
1838     case Instruction::SetNE:
1839       return BinaryOperator::createXor(Op0, Op1);
1840
1841     case Instruction::SetGT:
1842       std::swap(Op0, Op1);                   // Change setgt -> setlt
1843       // FALL THROUGH
1844     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
1845       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1846       InsertNewInstBefore(Not, I);
1847       return BinaryOperator::createAnd(Not, Op1);
1848     }
1849     case Instruction::SetGE:
1850       std::swap(Op0, Op1);                   // Change setge -> setle
1851       // FALL THROUGH
1852     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
1853       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1854       InsertNewInstBefore(Not, I);
1855       return BinaryOperator::createOr(Not, Op1);
1856     }
1857     }
1858   }
1859
1860   // See if we are doing a comparison between a constant and an instruction that
1861   // can be folded into the comparison.
1862   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1863     // Check to see if we are comparing against the minimum or maximum value...
1864     if (CI->isMinValue()) {
1865       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
1866         return ReplaceInstUsesWith(I, ConstantBool::False);
1867       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
1868         return ReplaceInstUsesWith(I, ConstantBool::True);
1869       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
1870         return BinaryOperator::createSetEQ(Op0, Op1);
1871       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
1872         return BinaryOperator::createSetNE(Op0, Op1);
1873
1874     } else if (CI->isMaxValue()) {
1875       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
1876         return ReplaceInstUsesWith(I, ConstantBool::False);
1877       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
1878         return ReplaceInstUsesWith(I, ConstantBool::True);
1879       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
1880         return BinaryOperator::createSetEQ(Op0, Op1);
1881       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
1882         return BinaryOperator::createSetNE(Op0, Op1);
1883
1884       // Comparing against a value really close to min or max?
1885     } else if (isMinValuePlusOne(CI)) {
1886       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
1887         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1888       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
1889         return BinaryOperator::createSetNE(Op0, SubOne(CI));
1890
1891     } else if (isMaxValueMinusOne(CI)) {
1892       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
1893         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1894       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
1895         return BinaryOperator::createSetNE(Op0, AddOne(CI));
1896     }
1897
1898     // If we still have a setle or setge instruction, turn it into the
1899     // appropriate setlt or setgt instruction.  Since the border cases have
1900     // already been handled above, this requires little checking.
1901     //
1902     if (I.getOpcode() == Instruction::SetLE)
1903       return BinaryOperator::createSetLT(Op0, AddOne(CI));
1904     if (I.getOpcode() == Instruction::SetGE)
1905       return BinaryOperator::createSetGT(Op0, SubOne(CI));
1906
1907     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1908       switch (LHSI->getOpcode()) {
1909       case Instruction::PHI:
1910         if (Instruction *NV = FoldOpIntoPhi(I))
1911           return NV;
1912         break;
1913       case Instruction::And:
1914         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1915             LHSI->getOperand(0)->hasOneUse()) {
1916           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1917           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1918           // happens a LOT in code produced by the C front-end, for bitfield
1919           // access.
1920           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1921           ConstantUInt *ShAmt;
1922           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1923           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1924           const Type *Ty = LHSI->getType();
1925           
1926           // We can fold this as long as we can't shift unknown bits
1927           // into the mask.  This can only happen with signed shift
1928           // rights, as they sign-extend.
1929           if (ShAmt) {
1930             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1931                            Shift->getType()->isUnsigned();
1932             if (!CanFold) {
1933               // To test for the bad case of the signed shr, see if any
1934               // of the bits shifted in could be tested after the mask.
1935               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, 
1936                                    Ty->getPrimitiveSize()*8-ShAmt->getValue());
1937               Constant *ShVal = 
1938                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1939               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1940                 CanFold = true;
1941             }
1942             
1943             if (CanFold) {
1944               Constant *NewCst;
1945               if (Shift->getOpcode() == Instruction::Shl)
1946                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1947               else
1948                 NewCst = ConstantExpr::getShl(CI, ShAmt);
1949
1950               // Check to see if we are shifting out any of the bits being
1951               // compared.
1952               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1953                 // If we shifted bits out, the fold is not going to work out.
1954                 // As a special case, check to see if this means that the
1955                 // result is always true or false now.
1956                 if (I.getOpcode() == Instruction::SetEQ)
1957                   return ReplaceInstUsesWith(I, ConstantBool::False);
1958                 if (I.getOpcode() == Instruction::SetNE)
1959                   return ReplaceInstUsesWith(I, ConstantBool::True);
1960               } else {
1961                 I.setOperand(1, NewCst);
1962                 Constant *NewAndCST;
1963                 if (Shift->getOpcode() == Instruction::Shl)
1964                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1965                 else
1966                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1967                 LHSI->setOperand(1, NewAndCST);
1968                 LHSI->setOperand(0, Shift->getOperand(0));
1969                 WorkList.push_back(Shift); // Shift is dead.
1970                 AddUsesToWorkList(I);
1971                 return &I;
1972               }
1973             }
1974           }
1975         }
1976         break;
1977
1978       case Instruction::Cast: {       // (setcc (cast X to larger), CI)
1979         const Type *SrcTy = LHSI->getOperand(0)->getType();
1980         if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
1981           unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
1982           if (SrcTy == Type::BoolTy) SrcBits = 1;
1983           unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
1984           if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1985           if (SrcBits < DestBits) {
1986             // Check to see if the comparison is always true or false.
1987             Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1988             if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1989               Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1990               Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1991               Min = ConstantExpr::getCast(Min, LHSI->getType());
1992               Max = ConstantExpr::getCast(Max, LHSI->getType());
1993               switch (I.getOpcode()) {
1994               default: assert(0 && "unknown integer comparison");
1995               case Instruction::SetEQ:
1996                 return ReplaceInstUsesWith(I, ConstantBool::False);
1997               case Instruction::SetNE:
1998                 return ReplaceInstUsesWith(I, ConstantBool::True);
1999               case Instruction::SetLT:
2000                 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2001               case Instruction::SetGT:
2002                 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2003               }
2004             }
2005
2006             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2007                                    ConstantExpr::getCast(CI, SrcTy));
2008           }
2009         }
2010         break;
2011       }
2012       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
2013         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2014           switch (I.getOpcode()) {
2015           default: break;
2016           case Instruction::SetEQ:
2017           case Instruction::SetNE: {
2018             // If we are comparing against bits always shifted out, the
2019             // comparison cannot succeed.
2020             Constant *Comp = 
2021               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2022             if (Comp != CI) {// Comparing against a bit that we know is zero.
2023               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2024               Constant *Cst = ConstantBool::get(IsSetNE);
2025               return ReplaceInstUsesWith(I, Cst);
2026             }
2027
2028             if (LHSI->hasOneUse()) {
2029               // Otherwise strength reduce the shift into an and.
2030               unsigned ShAmtVal = ShAmt->getValue();
2031               unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2032               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2033
2034               Constant *Mask;
2035               if (CI->getType()->isUnsigned()) {
2036                 Mask = ConstantUInt::get(CI->getType(), Val);
2037               } else if (ShAmtVal != 0) {
2038                 Mask = ConstantSInt::get(CI->getType(), Val);
2039               } else {
2040                 Mask = ConstantInt::getAllOnesValue(CI->getType());
2041               }
2042               
2043               Instruction *AndI =
2044                 BinaryOperator::createAnd(LHSI->getOperand(0),
2045                                           Mask, LHSI->getName()+".mask");
2046               Value *And = InsertNewInstBefore(AndI, I);
2047               return new SetCondInst(I.getOpcode(), And,
2048                                      ConstantExpr::getUShr(CI, ShAmt));
2049             }
2050           }
2051           }
2052         }
2053         break;
2054
2055       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
2056         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2057           switch (I.getOpcode()) {
2058           default: break;
2059           case Instruction::SetEQ:
2060           case Instruction::SetNE: {
2061             // If we are comparing against bits always shifted out, the
2062             // comparison cannot succeed.
2063             Constant *Comp = 
2064               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2065             
2066             if (Comp != CI) {// Comparing against a bit that we know is zero.
2067               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2068               Constant *Cst = ConstantBool::get(IsSetNE);
2069               return ReplaceInstUsesWith(I, Cst);
2070             }
2071               
2072             if (LHSI->hasOneUse() || CI->isNullValue()) {
2073               unsigned ShAmtVal = ShAmt->getValue();
2074
2075               // Otherwise strength reduce the shift into an and.
2076               uint64_t Val = ~0ULL;          // All ones.
2077               Val <<= ShAmtVal;              // Shift over to the right spot.
2078
2079               Constant *Mask;
2080               if (CI->getType()->isUnsigned()) {
2081                 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2082                 Val &= (1ULL << TypeBits)-1;
2083                 Mask = ConstantUInt::get(CI->getType(), Val);
2084               } else {
2085                 Mask = ConstantSInt::get(CI->getType(), Val);
2086               }
2087               
2088               Instruction *AndI =
2089                 BinaryOperator::createAnd(LHSI->getOperand(0),
2090                                           Mask, LHSI->getName()+".mask");
2091               Value *And = InsertNewInstBefore(AndI, I);
2092               return new SetCondInst(I.getOpcode(), And,
2093                                      ConstantExpr::getShl(CI, ShAmt));
2094             }
2095             break;
2096           }
2097           }
2098         }
2099         break;
2100
2101       case Instruction::Div:
2102         // Fold: (div X, C1) op C2 -> range check
2103         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2104           // Fold this div into the comparison, producing a range check.
2105           // Determine, based on the divide type, what the range is being
2106           // checked.  If there is an overflow on the low or high side, remember
2107           // it, otherwise compute the range [low, hi) bounding the new value.
2108           bool LoOverflow = false, HiOverflow = 0;
2109           ConstantInt *LoBound = 0, *HiBound = 0;
2110
2111           ConstantInt *Prod;
2112           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2113
2114           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
2115           } else if (LHSI->getType()->isUnsigned()) {  // udiv
2116             LoBound = Prod;
2117             LoOverflow = ProdOV;
2118             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2119           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
2120             if (CI->isNullValue()) {       // (X / pos) op 0
2121               // Can't overflow.
2122               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2123               HiBound = DivRHS;
2124             } else if (isPositive(CI)) {   // (X / pos) op pos
2125               LoBound = Prod;
2126               LoOverflow = ProdOV;
2127               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2128             } else {                       // (X / pos) op neg
2129               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2130               LoOverflow = AddWithOverflow(LoBound, Prod,
2131                                            cast<ConstantInt>(DivRHSH));
2132               HiBound = Prod;
2133               HiOverflow = ProdOV;
2134             }
2135           } else {                                     // Divisor is < 0.
2136             if (CI->isNullValue()) {       // (X / neg) op 0
2137               LoBound = AddOne(DivRHS);
2138               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2139             } else if (isPositive(CI)) {   // (X / neg) op pos
2140               HiOverflow = LoOverflow = ProdOV;
2141               if (!LoOverflow)
2142                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2143               HiBound = AddOne(Prod);
2144             } else {                       // (X / neg) op neg
2145               LoBound = Prod;
2146               LoOverflow = HiOverflow = ProdOV;
2147               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2148             }
2149           }
2150
2151           if (LoBound) {
2152             Value *X = LHSI->getOperand(0);
2153             switch (I.getOpcode()) {
2154             default: assert(0 && "Unhandled setcc opcode!");
2155             case Instruction::SetEQ:
2156               if (LoOverflow && HiOverflow)
2157                 return ReplaceInstUsesWith(I, ConstantBool::False);
2158               else if (HiOverflow)
2159                 return new SetCondInst(Instruction::SetGE, X, LoBound);
2160               else if (LoOverflow)
2161                 return new SetCondInst(Instruction::SetLT, X, HiBound);
2162               else
2163                 return InsertRangeTest(X, LoBound, HiBound, true, I);
2164             case Instruction::SetNE:
2165               if (LoOverflow && HiOverflow)
2166                 return ReplaceInstUsesWith(I, ConstantBool::True);
2167               else if (HiOverflow)
2168                 return new SetCondInst(Instruction::SetLT, X, LoBound);
2169               else if (LoOverflow)
2170                 return new SetCondInst(Instruction::SetGE, X, HiBound);
2171               else
2172                 return InsertRangeTest(X, LoBound, HiBound, false, I);
2173             case Instruction::SetLT:
2174               if (LoOverflow)
2175                 return ReplaceInstUsesWith(I, ConstantBool::False);
2176               return new SetCondInst(Instruction::SetLT, X, LoBound);
2177             case Instruction::SetGT:
2178               if (HiOverflow)
2179                 return ReplaceInstUsesWith(I, ConstantBool::False);
2180               return new SetCondInst(Instruction::SetGE, X, HiBound);
2181             }
2182           }
2183         }
2184         break;
2185       case Instruction::Select:
2186         // If either operand of the select is a constant, we can fold the
2187         // comparison into the select arms, which will cause one to be
2188         // constant folded and the select turned into a bitwise or.
2189         Value *Op1 = 0, *Op2 = 0;
2190         if (LHSI->hasOneUse()) {
2191           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2192             // Fold the known value into the constant operand.
2193             Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2194             // Insert a new SetCC of the other select operand.
2195             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2196                                                       LHSI->getOperand(2), CI,
2197                                                       I.getName()), I);
2198           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2199             // Fold the known value into the constant operand.
2200             Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2201             // Insert a new SetCC of the other select operand.
2202             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2203                                                       LHSI->getOperand(1), CI,
2204                                                       I.getName()), I);
2205           }
2206         }
2207         
2208         if (Op1)
2209           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2210         break;
2211       }
2212     
2213     // Simplify seteq and setne instructions...
2214     if (I.getOpcode() == Instruction::SetEQ ||
2215         I.getOpcode() == Instruction::SetNE) {
2216       bool isSetNE = I.getOpcode() == Instruction::SetNE;
2217
2218       // If the first operand is (and|or|xor) with a constant, and the second
2219       // operand is a constant, simplify a bit.
2220       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2221         switch (BO->getOpcode()) {
2222         case Instruction::Rem:
2223           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2224           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2225               BO->hasOneUse() &&
2226               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2227             if (unsigned L2 =
2228                 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2229               const Type *UTy = BO->getType()->getUnsignedVersion();
2230               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2231                                                              UTy, "tmp"), I);
2232               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2233               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2234                                                     RHSCst, BO->getName()), I);
2235               return BinaryOperator::create(I.getOpcode(), NewRem,
2236                                             Constant::getNullValue(UTy));
2237             }
2238           break;          
2239
2240         case Instruction::Add:
2241           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2242           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2243             if (BO->hasOneUse())
2244               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2245                                      ConstantExpr::getSub(CI, BOp1C));
2246           } else if (CI->isNullValue()) {
2247             // Replace ((add A, B) != 0) with (A != -B) if A or B is
2248             // efficiently invertible, or if the add has just this one use.
2249             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2250             
2251             if (Value *NegVal = dyn_castNegVal(BOp1))
2252               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2253             else if (Value *NegVal = dyn_castNegVal(BOp0))
2254               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2255             else if (BO->hasOneUse()) {
2256               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2257               BO->setName("");
2258               InsertNewInstBefore(Neg, I);
2259               return new SetCondInst(I.getOpcode(), BOp0, Neg);
2260             }
2261           }
2262           break;
2263         case Instruction::Xor:
2264           // For the xor case, we can xor two constants together, eliminating
2265           // the explicit xor.
2266           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2267             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2268                                   ConstantExpr::getXor(CI, BOC));
2269
2270           // FALLTHROUGH
2271         case Instruction::Sub:
2272           // Replace (([sub|xor] A, B) != 0) with (A != B)
2273           if (CI->isNullValue())
2274             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2275                                    BO->getOperand(1));
2276           break;
2277
2278         case Instruction::Or:
2279           // If bits are being or'd in that are not present in the constant we
2280           // are comparing against, then the comparison could never succeed!
2281           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2282             Constant *NotCI = ConstantExpr::getNot(CI);
2283             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2284               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2285           }
2286           break;
2287
2288         case Instruction::And:
2289           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2290             // If bits are being compared against that are and'd out, then the
2291             // comparison can never succeed!
2292             if (!ConstantExpr::getAnd(CI,
2293                                       ConstantExpr::getNot(BOC))->isNullValue())
2294               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2295
2296             // If we have ((X & C) == C), turn it into ((X & C) != 0).
2297             if (CI == BOC && isOneBitSet(CI))
2298               return new SetCondInst(isSetNE ? Instruction::SetEQ :
2299                                      Instruction::SetNE, Op0,
2300                                      Constant::getNullValue(CI->getType()));
2301
2302             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2303             // to be a signed value as appropriate.
2304             if (isSignBit(BOC)) {
2305               Value *X = BO->getOperand(0);
2306               // If 'X' is not signed, insert a cast now...
2307               if (!BOC->getType()->isSigned()) {
2308                 const Type *DestTy = BOC->getType()->getSignedVersion();
2309                 X = InsertCastBefore(X, DestTy, I);
2310               }
2311               return new SetCondInst(isSetNE ? Instruction::SetLT :
2312                                          Instruction::SetGE, X,
2313                                      Constant::getNullValue(X->getType()));
2314             }
2315             
2316             // ((X & ~7) == 0) --> X < 8
2317             if (CI->isNullValue() && isHighOnes(BOC)) {
2318               Value *X = BO->getOperand(0);
2319               Constant *NegX = ConstantExpr::getNeg(BOC);
2320
2321               // If 'X' is signed, insert a cast now.
2322               if (NegX->getType()->isSigned()) {
2323                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2324                 X = InsertCastBefore(X, DestTy, I);
2325                 NegX = ConstantExpr::getCast(NegX, DestTy);
2326               }
2327
2328               return new SetCondInst(isSetNE ? Instruction::SetGE :
2329                                      Instruction::SetLT, X, NegX);
2330             }
2331
2332           }
2333         default: break;
2334         }
2335       }
2336     } else {  // Not a SetEQ/SetNE
2337       // If the LHS is a cast from an integral value of the same size, 
2338       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2339         Value *CastOp = Cast->getOperand(0);
2340         const Type *SrcTy = CastOp->getType();
2341         unsigned SrcTySize = SrcTy->getPrimitiveSize();
2342         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2343             SrcTySize == Cast->getType()->getPrimitiveSize()) {
2344           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) && 
2345                  "Source and destination signednesses should differ!");
2346           if (Cast->getType()->isSigned()) {
2347             // If this is a signed comparison, check for comparisons in the
2348             // vicinity of zero.
2349             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2350               // X < 0  => x > 127
2351               return BinaryOperator::createSetGT(CastOp,
2352                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2353             else if (I.getOpcode() == Instruction::SetGT &&
2354                      cast<ConstantSInt>(CI)->getValue() == -1)
2355               // X > -1  => x < 128
2356               return BinaryOperator::createSetLT(CastOp,
2357                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2358           } else {
2359             ConstantUInt *CUI = cast<ConstantUInt>(CI);
2360             if (I.getOpcode() == Instruction::SetLT &&
2361                 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2362               // X < 128 => X > -1
2363               return BinaryOperator::createSetGT(CastOp,
2364                                                  ConstantSInt::get(SrcTy, -1));
2365             else if (I.getOpcode() == Instruction::SetGT &&
2366                      CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2367               // X > 127 => X < 0
2368               return BinaryOperator::createSetLT(CastOp,
2369                                                  Constant::getNullValue(SrcTy));
2370           }
2371         }
2372       }
2373     }
2374   }
2375
2376   // Test to see if the operands of the setcc are casted versions of other
2377   // values.  If the cast can be stripped off both arguments, we do so now.
2378   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2379     Value *CastOp0 = CI->getOperand(0);
2380     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2381         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2382         (I.getOpcode() == Instruction::SetEQ ||
2383          I.getOpcode() == Instruction::SetNE)) {
2384       // We keep moving the cast from the left operand over to the right
2385       // operand, where it can often be eliminated completely.
2386       Op0 = CastOp0;
2387       
2388       // If operand #1 is a cast instruction, see if we can eliminate it as
2389       // well.
2390       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2391         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2392                                                                Op0->getType()))
2393           Op1 = CI2->getOperand(0);
2394       
2395       // If Op1 is a constant, we can fold the cast into the constant.
2396       if (Op1->getType() != Op0->getType())
2397         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2398           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2399         } else {
2400           // Otherwise, cast the RHS right before the setcc
2401           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2402           InsertNewInstBefore(cast<Instruction>(Op1), I);
2403         }
2404       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2405     }
2406
2407     // Handle the special case of: setcc (cast bool to X), <cst>
2408     // This comes up when you have code like
2409     //   int X = A < B;
2410     //   if (X) ...
2411     // For generality, we handle any zero-extension of any operand comparison
2412     // with a constant.
2413     if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2414       const Type *SrcTy = CastOp0->getType();
2415       const Type *DestTy = Op0->getType();
2416       if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2417           (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2418         // Ok, we have an expansion of operand 0 into a new type.  Get the
2419         // constant value, masink off bits which are not set in the RHS.  These
2420         // could be set if the destination value is signed.
2421         uint64_t ConstVal = ConstantRHS->getRawValue();
2422         ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2423
2424         // If the constant we are comparing it with has high bits set, which
2425         // don't exist in the original value, the values could never be equal,
2426         // because the source would be zero extended.
2427         unsigned SrcBits =
2428           SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2429         bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2430         if (ConstVal & ~((1ULL << SrcBits)-1)) {
2431           switch (I.getOpcode()) {
2432           default: assert(0 && "Unknown comparison type!");
2433           case Instruction::SetEQ:
2434             return ReplaceInstUsesWith(I, ConstantBool::False);
2435           case Instruction::SetNE:
2436             return ReplaceInstUsesWith(I, ConstantBool::True);
2437           case Instruction::SetLT:
2438           case Instruction::SetLE:
2439             if (DestTy->isSigned() && HasSignBit)
2440               return ReplaceInstUsesWith(I, ConstantBool::False);
2441             return ReplaceInstUsesWith(I, ConstantBool::True);
2442           case Instruction::SetGT:
2443           case Instruction::SetGE:
2444             if (DestTy->isSigned() && HasSignBit)
2445               return ReplaceInstUsesWith(I, ConstantBool::True);
2446             return ReplaceInstUsesWith(I, ConstantBool::False);
2447           }
2448         }
2449         
2450         // Otherwise, we can replace the setcc with a setcc of the smaller
2451         // operand value.
2452         Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2453         return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2454       }
2455     }
2456   }
2457   return Changed ? &I : 0;
2458 }
2459
2460
2461
2462 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2463   assert(I.getOperand(1)->getType() == Type::UByteTy);
2464   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2465   bool isLeftShift = I.getOpcode() == Instruction::Shl;
2466
2467   // shl X, 0 == X and shr X, 0 == X
2468   // shl 0, X == 0 and shr 0, X == 0
2469   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2470       Op0 == Constant::getNullValue(Op0->getType()))
2471     return ReplaceInstUsesWith(I, Op0);
2472
2473   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
2474   if (!isLeftShift)
2475     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2476       if (CSI->isAllOnesValue())
2477         return ReplaceInstUsesWith(I, CSI);
2478
2479   // Try to fold constant and into select arguments.
2480   if (isa<Constant>(Op0))
2481     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2482       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2483         return R;
2484
2485   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2486     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2487     // of a signed value.
2488     //
2489     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2490     if (CUI->getValue() >= TypeBits) {
2491       if (!Op0->getType()->isSigned() || isLeftShift)
2492         return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2493       else {
2494         I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2495         return &I;
2496       }
2497     }
2498
2499     // ((X*C1) << C2) == (X * (C1 << C2))
2500     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2501       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2502         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2503           return BinaryOperator::createMul(BO->getOperand(0),
2504                                            ConstantExpr::getShl(BOOp, CUI));
2505     
2506     // Try to fold constant and into select arguments.
2507     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2508       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2509         return R;
2510     if (isa<PHINode>(Op0))
2511       if (Instruction *NV = FoldOpIntoPhi(I))
2512         return NV;
2513
2514     // If the operand is an bitwise operator with a constant RHS, and the
2515     // shift is the only use, we can pull it out of the shift.
2516     if (Op0->hasOneUse())
2517       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2518         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2519           bool isValid = true;     // Valid only for And, Or, Xor
2520           bool highBitSet = false; // Transform if high bit of constant set?
2521
2522           switch (Op0BO->getOpcode()) {
2523           default: isValid = false; break;   // Do not perform transform!
2524           case Instruction::Add:
2525             isValid = isLeftShift;
2526             break;
2527           case Instruction::Or:
2528           case Instruction::Xor:
2529             highBitSet = false;
2530             break;
2531           case Instruction::And:
2532             highBitSet = true;
2533             break;
2534           }
2535
2536           // If this is a signed shift right, and the high bit is modified
2537           // by the logical operation, do not perform the transformation.
2538           // The highBitSet boolean indicates the value of the high bit of
2539           // the constant which would cause it to be modified for this
2540           // operation.
2541           //
2542           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2543             uint64_t Val = Op0C->getRawValue();
2544             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2545           }
2546
2547           if (isValid) {
2548             Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2549
2550             Instruction *NewShift =
2551               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2552                             Op0BO->getName());
2553             Op0BO->setName("");
2554             InsertNewInstBefore(NewShift, I);
2555
2556             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2557                                           NewRHS);
2558           }
2559         }
2560
2561     // If this is a shift of a shift, see if we can fold the two together...
2562     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2563       if (ConstantUInt *ShiftAmt1C =
2564                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2565         unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2566         unsigned ShiftAmt2 = CUI->getValue();
2567         
2568         // Check for (A << c1) << c2   and   (A >> c1) >> c2
2569         if (I.getOpcode() == Op0SI->getOpcode()) {
2570           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
2571           if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2572             Amt = Op0->getType()->getPrimitiveSize()*8;
2573           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2574                                ConstantUInt::get(Type::UByteTy, Amt));
2575         }
2576         
2577         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
2578         // signed types, we can only support the (A >> c1) << c2 configuration,
2579         // because it can not turn an arbitrary bit of A into a sign bit.
2580         if (I.getType()->isUnsigned() || isLeftShift) {
2581           // Calculate bitmask for what gets shifted off the edge...
2582           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2583           if (isLeftShift)
2584             C = ConstantExpr::getShl(C, ShiftAmt1C);
2585           else
2586             C = ConstantExpr::getShr(C, ShiftAmt1C);
2587           
2588           Instruction *Mask =
2589             BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2590                                       Op0SI->getOperand(0)->getName()+".mask");
2591           InsertNewInstBefore(Mask, I);
2592           
2593           // Figure out what flavor of shift we should use...
2594           if (ShiftAmt1 == ShiftAmt2)
2595             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
2596           else if (ShiftAmt1 < ShiftAmt2) {
2597             return new ShiftInst(I.getOpcode(), Mask,
2598                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2599           } else {
2600             return new ShiftInst(Op0SI->getOpcode(), Mask,
2601                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2602           }
2603         }
2604       }
2605   }
2606
2607   return 0;
2608 }
2609
2610 enum CastType {
2611   Noop     = 0,
2612   Truncate = 1,
2613   Signext  = 2,
2614   Zeroext  = 3
2615 };
2616
2617 /// getCastType - In the future, we will split the cast instruction into these
2618 /// various types.  Until then, we have to do the analysis here.
2619 static CastType getCastType(const Type *Src, const Type *Dest) {
2620   assert(Src->isIntegral() && Dest->isIntegral() &&
2621          "Only works on integral types!");
2622   unsigned SrcSize = Src->getPrimitiveSize()*8;
2623   if (Src == Type::BoolTy) SrcSize = 1;
2624   unsigned DestSize = Dest->getPrimitiveSize()*8;
2625   if (Dest == Type::BoolTy) DestSize = 1;
2626
2627   if (SrcSize == DestSize) return Noop;
2628   if (SrcSize > DestSize)  return Truncate;
2629   if (Src->isSigned()) return Signext;
2630   return Zeroext;
2631 }
2632
2633
2634 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2635 // instruction.
2636 //
2637 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2638                                           const Type *DstTy, TargetData *TD) {
2639
2640   // It is legal to eliminate the instruction if casting A->B->A if the sizes
2641   // are identical and the bits don't get reinterpreted (for example 
2642   // int->float->int would not be allowed).
2643   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2644     return true;
2645
2646   // If we are casting between pointer and integer types, treat pointers as
2647   // integers of the appropriate size for the code below.
2648   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2649   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2650   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2651
2652   // Allow free casting and conversion of sizes as long as the sign doesn't
2653   // change...
2654   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2655     CastType FirstCast = getCastType(SrcTy, MidTy);
2656     CastType SecondCast = getCastType(MidTy, DstTy);
2657
2658     // Capture the effect of these two casts.  If the result is a legal cast,
2659     // the CastType is stored here, otherwise a special code is used.
2660     static const unsigned CastResult[] = {
2661       // First cast is noop
2662       0, 1, 2, 3,
2663       // First cast is a truncate
2664       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
2665       // First cast is a sign ext
2666       2, 5, 2, 4,         // signext->zeroext never ok
2667       // First cast is a zero ext
2668       3, 5, 3, 3,
2669     };
2670
2671     unsigned Result = CastResult[FirstCast*4+SecondCast];
2672     switch (Result) {
2673     default: assert(0 && "Illegal table value!");
2674     case 0:
2675     case 1:
2676     case 2:
2677     case 3:
2678       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2679       // truncates, we could eliminate more casts.
2680       return (unsigned)getCastType(SrcTy, DstTy) == Result;
2681     case 4:
2682       return false;  // Not possible to eliminate this here.
2683     case 5:
2684       // Sign or zero extend followed by truncate is always ok if the result
2685       // is a truncate or noop.
2686       CastType ResultCast = getCastType(SrcTy, DstTy);
2687       if (ResultCast == Noop || ResultCast == Truncate)
2688         return true;
2689       // Otherwise we are still growing the value, we are only safe if the 
2690       // result will match the sign/zeroextendness of the result.
2691       return ResultCast == FirstCast;
2692     }
2693   }
2694   return false;
2695 }
2696
2697 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2698   if (V->getType() == Ty || isa<Constant>(V)) return false;
2699   if (const CastInst *CI = dyn_cast<CastInst>(V))
2700     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2701                                TD))
2702       return false;
2703   return true;
2704 }
2705
2706 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2707 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
2708 /// casts that are known to not do anything...
2709 ///
2710 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2711                                              Instruction *InsertBefore) {
2712   if (V->getType() == DestTy) return V;
2713   if (Constant *C = dyn_cast<Constant>(V))
2714     return ConstantExpr::getCast(C, DestTy);
2715
2716   CastInst *CI = new CastInst(V, DestTy, V->getName());
2717   InsertNewInstBefore(CI, *InsertBefore);
2718   return CI;
2719 }
2720
2721 // CastInst simplification
2722 //
2723 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2724   Value *Src = CI.getOperand(0);
2725
2726   // If the user is casting a value to the same type, eliminate this cast
2727   // instruction...
2728   if (CI.getType() == Src->getType())
2729     return ReplaceInstUsesWith(CI, Src);
2730
2731   // If casting the result of another cast instruction, try to eliminate this
2732   // one!
2733   //
2734   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2735     if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2736                                CSrc->getType(), CI.getType(), TD)) {
2737       // This instruction now refers directly to the cast's src operand.  This
2738       // has a good chance of making CSrc dead.
2739       CI.setOperand(0, CSrc->getOperand(0));
2740       return &CI;
2741     }
2742
2743     // If this is an A->B->A cast, and we are dealing with integral types, try
2744     // to convert this into a logical 'and' instruction.
2745     //
2746     if (CSrc->getOperand(0)->getType() == CI.getType() &&
2747         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2748         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2749         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2750       assert(CSrc->getType() != Type::ULongTy &&
2751              "Cannot have type bigger than ulong!");
2752       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2753       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2754       return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2755     }
2756   }
2757
2758   // If this is a cast to bool, turn it into the appropriate setne instruction.
2759   if (CI.getType() == Type::BoolTy)
2760     return BinaryOperator::createSetNE(CI.getOperand(0),
2761                        Constant::getNullValue(CI.getOperand(0)->getType()));
2762
2763   // If casting the result of a getelementptr instruction with no offset, turn
2764   // this into a cast of the original pointer!
2765   //
2766   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2767     bool AllZeroOperands = true;
2768     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2769       if (!isa<Constant>(GEP->getOperand(i)) ||
2770           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2771         AllZeroOperands = false;
2772         break;
2773       }
2774     if (AllZeroOperands) {
2775       CI.setOperand(0, GEP->getOperand(0));
2776       return &CI;
2777     }
2778   }
2779
2780   // If we are casting a malloc or alloca to a pointer to a type of the same
2781   // size, rewrite the allocation instruction to allocate the "right" type.
2782   //
2783   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2784     if (AI->hasOneUse() && !AI->isArrayAllocation())
2785       if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2786         // Get the type really allocated and the type casted to...
2787         const Type *AllocElTy = AI->getAllocatedType();
2788         const Type *CastElTy = PTy->getElementType();
2789         if (AllocElTy->isSized() && CastElTy->isSized()) {
2790           unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2791           unsigned CastElTySize = TD->getTypeSize(CastElTy);
2792
2793           // If the allocation is for an even multiple of the cast type size
2794           if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2795             Value *Amt = ConstantUInt::get(Type::UIntTy, 
2796                                          AllocElTySize/CastElTySize);
2797             std::string Name = AI->getName(); AI->setName("");
2798             AllocationInst *New;
2799             if (isa<MallocInst>(AI))
2800               New = new MallocInst(CastElTy, Amt, Name);
2801             else
2802               New = new AllocaInst(CastElTy, Amt, Name);
2803             InsertNewInstBefore(New, *AI);
2804             return ReplaceInstUsesWith(CI, New);
2805           }
2806         }
2807       }
2808
2809   if (isa<PHINode>(Src))
2810     if (Instruction *NV = FoldOpIntoPhi(CI))
2811       return NV;
2812
2813   // If the source value is an instruction with only this use, we can attempt to
2814   // propagate the cast into the instruction.  Also, only handle integral types
2815   // for now.
2816   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2817     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2818         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
2819       const Type *DestTy = CI.getType();
2820       unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2821       unsigned DestBitSize = getTypeSizeInBits(DestTy);
2822
2823       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2824       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2825
2826       switch (SrcI->getOpcode()) {
2827       case Instruction::Add:
2828       case Instruction::Mul:
2829       case Instruction::And:
2830       case Instruction::Or:
2831       case Instruction::Xor:
2832         // If we are discarding information, or just changing the sign, rewrite.
2833         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2834           // Don't insert two casts if they cannot be eliminated.  We allow two
2835           // casts to be inserted if the sizes are the same.  This could only be
2836           // converting signedness, which is a noop.
2837           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2838               !ValueRequiresCast(Op0, DestTy, TD)) {
2839             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2840             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2841             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2842                              ->getOpcode(), Op0c, Op1c);
2843           }
2844         }
2845         break;
2846       case Instruction::Shl:
2847         // Allow changing the sign of the source operand.  Do not allow changing
2848         // the size of the shift, UNLESS the shift amount is a constant.  We
2849         // mush not change variable sized shifts to a smaller size, because it
2850         // is undefined to shift more bits out than exist in the value.
2851         if (DestBitSize == SrcBitSize ||
2852             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2853           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2854           return new ShiftInst(Instruction::Shl, Op0c, Op1);
2855         }
2856         break;
2857       }
2858     }
2859   
2860   return 0;
2861 }
2862
2863 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2864 ///   %C = or %A, %B
2865 ///   %D = select %cond, %C, %A
2866 /// into:
2867 ///   %C = select %cond, %B, 0
2868 ///   %D = or %A, %C
2869 ///
2870 /// Assuming that the specified instruction is an operand to the select, return
2871 /// a bitmask indicating which operands of this instruction are foldable if they
2872 /// equal the other incoming value of the select.
2873 ///
2874 static unsigned GetSelectFoldableOperands(Instruction *I) {
2875   switch (I->getOpcode()) {
2876   case Instruction::Add:
2877   case Instruction::Mul:
2878   case Instruction::And:
2879   case Instruction::Or:
2880   case Instruction::Xor:
2881     return 3;              // Can fold through either operand.
2882   case Instruction::Sub:   // Can only fold on the amount subtracted.
2883   case Instruction::Shl:   // Can only fold on the shift amount.
2884   case Instruction::Shr:
2885     return 1;           
2886   default:
2887     return 0;              // Cannot fold
2888   }
2889 }
2890
2891 /// GetSelectFoldableConstant - For the same transformation as the previous
2892 /// function, return the identity constant that goes into the select.
2893 static Constant *GetSelectFoldableConstant(Instruction *I) {
2894   switch (I->getOpcode()) {
2895   default: assert(0 && "This cannot happen!"); abort();
2896   case Instruction::Add:
2897   case Instruction::Sub:
2898   case Instruction::Or:
2899   case Instruction::Xor:
2900     return Constant::getNullValue(I->getType());
2901   case Instruction::Shl:
2902   case Instruction::Shr:
2903     return Constant::getNullValue(Type::UByteTy);
2904   case Instruction::And:
2905     return ConstantInt::getAllOnesValue(I->getType());
2906   case Instruction::Mul:
2907     return ConstantInt::get(I->getType(), 1);
2908   }
2909 }
2910
2911 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2912   Value *CondVal = SI.getCondition();
2913   Value *TrueVal = SI.getTrueValue();
2914   Value *FalseVal = SI.getFalseValue();
2915
2916   // select true, X, Y  -> X
2917   // select false, X, Y -> Y
2918   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2919     if (C == ConstantBool::True)
2920       return ReplaceInstUsesWith(SI, TrueVal);
2921     else {
2922       assert(C == ConstantBool::False);
2923       return ReplaceInstUsesWith(SI, FalseVal);
2924     }
2925
2926   // select C, X, X -> X
2927   if (TrueVal == FalseVal)
2928     return ReplaceInstUsesWith(SI, TrueVal);
2929
2930   if (SI.getType() == Type::BoolTy)
2931     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2932       if (C == ConstantBool::True) {
2933         // Change: A = select B, true, C --> A = or B, C
2934         return BinaryOperator::createOr(CondVal, FalseVal);
2935       } else {
2936         // Change: A = select B, false, C --> A = and !B, C
2937         Value *NotCond =
2938           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2939                                              "not."+CondVal->getName()), SI);
2940         return BinaryOperator::createAnd(NotCond, FalseVal);
2941       }
2942     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2943       if (C == ConstantBool::False) {
2944         // Change: A = select B, C, false --> A = and B, C
2945         return BinaryOperator::createAnd(CondVal, TrueVal);
2946       } else {
2947         // Change: A = select B, C, true --> A = or !B, C
2948         Value *NotCond =
2949           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2950                                              "not."+CondVal->getName()), SI);
2951         return BinaryOperator::createOr(NotCond, TrueVal);
2952       }
2953     }
2954
2955   // Selecting between two integer constants?
2956   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2957     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2958       // select C, 1, 0 -> cast C to int
2959       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2960         return new CastInst(CondVal, SI.getType());
2961       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2962         // select C, 0, 1 -> cast !C to int
2963         Value *NotCond =
2964           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2965                                                "not."+CondVal->getName()), SI);
2966         return new CastInst(NotCond, SI.getType());
2967       }
2968
2969       // If one of the constants is zero (we know they can't both be) and we
2970       // have a setcc instruction with zero, and we have an 'and' with the
2971       // non-constant value, eliminate this whole mess.  This corresponds to
2972       // cases like this: ((X & 27) ? 27 : 0)
2973       if (TrueValC->isNullValue() || FalseValC->isNullValue())
2974         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2975           if ((IC->getOpcode() == Instruction::SetEQ ||
2976                IC->getOpcode() == Instruction::SetNE) &&
2977               isa<ConstantInt>(IC->getOperand(1)) &&
2978               cast<Constant>(IC->getOperand(1))->isNullValue())
2979             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2980               if (ICA->getOpcode() == Instruction::And &&
2981                   isa<ConstantInt>(ICA->getOperand(1)) && 
2982                   (ICA->getOperand(1) == TrueValC || 
2983                    ICA->getOperand(1) == FalseValC) && 
2984                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2985                 // Okay, now we know that everything is set up, we just don't
2986                 // know whether we have a setne or seteq and whether the true or
2987                 // false val is the zero.
2988                 bool ShouldNotVal = !TrueValC->isNullValue();
2989                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2990                 Value *V = ICA;
2991                 if (ShouldNotVal)
2992                   V = InsertNewInstBefore(BinaryOperator::create(
2993                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
2994                 return ReplaceInstUsesWith(SI, V);
2995               }
2996     }
2997
2998   // See if we are selecting two values based on a comparison of the two values.
2999   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3000     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3001       // Transform (X == Y) ? X : Y  -> Y
3002       if (SCI->getOpcode() == Instruction::SetEQ)
3003         return ReplaceInstUsesWith(SI, FalseVal);
3004       // Transform (X != Y) ? X : Y  -> X
3005       if (SCI->getOpcode() == Instruction::SetNE)
3006         return ReplaceInstUsesWith(SI, TrueVal);
3007       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3008
3009     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3010       // Transform (X == Y) ? Y : X  -> X
3011       if (SCI->getOpcode() == Instruction::SetEQ)
3012         return ReplaceInstUsesWith(SI, FalseVal);
3013       // Transform (X != Y) ? Y : X  -> Y
3014       if (SCI->getOpcode() == Instruction::SetNE)
3015         return ReplaceInstUsesWith(SI, TrueVal);
3016       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3017     }
3018   }
3019   
3020   // See if we can fold the select into one of our operands.
3021   if (SI.getType()->isInteger()) {
3022     // See the comment above GetSelectFoldableOperands for a description of the
3023     // transformation we are doing here.
3024     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3025       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3026           !isa<Constant>(FalseVal))
3027         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3028           unsigned OpToFold = 0;
3029           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3030             OpToFold = 1;
3031           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3032             OpToFold = 2;
3033           }
3034
3035           if (OpToFold) {
3036             Constant *C = GetSelectFoldableConstant(TVI);
3037             std::string Name = TVI->getName(); TVI->setName("");
3038             Instruction *NewSel =
3039               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3040                              Name);
3041             InsertNewInstBefore(NewSel, SI);
3042             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3043               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3044             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3045               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3046             else {
3047               assert(0 && "Unknown instruction!!");
3048             }
3049           }
3050         }
3051
3052     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3053       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3054           !isa<Constant>(TrueVal))
3055         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3056           unsigned OpToFold = 0;
3057           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3058             OpToFold = 1;
3059           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3060             OpToFold = 2;
3061           }
3062
3063           if (OpToFold) {
3064             Constant *C = GetSelectFoldableConstant(FVI);
3065             std::string Name = FVI->getName(); FVI->setName("");
3066             Instruction *NewSel =
3067               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3068                              Name);
3069             InsertNewInstBefore(NewSel, SI);
3070             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3071               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3072             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3073               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3074             else {
3075               assert(0 && "Unknown instruction!!");
3076             }
3077           }
3078         }
3079   }
3080   return 0;
3081 }
3082
3083
3084 // CallInst simplification
3085 //
3086 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3087   // Intrinsics cannot occur in an invoke, so handle them here instead of in
3088   // visitCallSite.
3089   if (Function *F = CI.getCalledFunction())
3090     switch (F->getIntrinsicID()) {
3091     case Intrinsic::memmove:
3092     case Intrinsic::memcpy:
3093     case Intrinsic::memset:
3094       // memmove/cpy/set of zero bytes is a noop.
3095       if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3096         if (NumBytes->isNullValue())
3097           return EraseInstFromFunction(CI);
3098       }
3099       break;
3100     default:
3101       break;
3102     }
3103
3104   return visitCallSite(&CI);
3105 }
3106
3107 // InvokeInst simplification
3108 //
3109 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3110   return visitCallSite(&II);
3111 }
3112
3113 // visitCallSite - Improvements for call and invoke instructions.
3114 //
3115 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3116   bool Changed = false;
3117
3118   // If the callee is a constexpr cast of a function, attempt to move the cast
3119   // to the arguments of the call/invoke.
3120   if (transformConstExprCastCall(CS)) return 0;
3121
3122   Value *Callee = CS.getCalledValue();
3123   const PointerType *PTy = cast<PointerType>(Callee->getType());
3124   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3125   if (FTy->isVarArg()) {
3126     // See if we can optimize any arguments passed through the varargs area of
3127     // the call.
3128     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3129            E = CS.arg_end(); I != E; ++I)
3130       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3131         // If this cast does not effect the value passed through the varargs
3132         // area, we can eliminate the use of the cast.
3133         Value *Op = CI->getOperand(0);
3134         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3135           *I = Op;
3136           Changed = true;
3137         }
3138       }
3139   }
3140   
3141   return Changed ? CS.getInstruction() : 0;
3142 }
3143
3144 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3145 // attempt to move the cast to the arguments of the call/invoke.
3146 //
3147 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3148   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3149   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3150   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3151     return false;
3152   Function *Callee = cast<Function>(CE->getOperand(0));
3153   Instruction *Caller = CS.getInstruction();
3154
3155   // Okay, this is a cast from a function to a different type.  Unless doing so
3156   // would cause a type conversion of one of our arguments, change this call to
3157   // be a direct call with arguments casted to the appropriate types.
3158   //
3159   const FunctionType *FT = Callee->getFunctionType();
3160   const Type *OldRetTy = Caller->getType();
3161
3162   // Check to see if we are changing the return type...
3163   if (OldRetTy != FT->getReturnType()) {
3164     if (Callee->isExternal() &&
3165         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3166         !Caller->use_empty())
3167       return false;   // Cannot transform this return value...
3168
3169     // If the callsite is an invoke instruction, and the return value is used by
3170     // a PHI node in a successor, we cannot change the return type of the call
3171     // because there is no place to put the cast instruction (without breaking
3172     // the critical edge).  Bail out in this case.
3173     if (!Caller->use_empty())
3174       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3175         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3176              UI != E; ++UI)
3177           if (PHINode *PN = dyn_cast<PHINode>(*UI))
3178             if (PN->getParent() == II->getNormalDest() ||
3179                 PN->getParent() == II->getUnwindDest())
3180               return false;
3181   }
3182
3183   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3184   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3185                                     
3186   CallSite::arg_iterator AI = CS.arg_begin();
3187   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3188     const Type *ParamTy = FT->getParamType(i);
3189     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3190     if (Callee->isExternal() && !isConvertible) return false;    
3191   }
3192
3193   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3194       Callee->isExternal())
3195     return false;   // Do not delete arguments unless we have a function body...
3196
3197   // Okay, we decided that this is a safe thing to do: go ahead and start
3198   // inserting cast instructions as necessary...
3199   std::vector<Value*> Args;
3200   Args.reserve(NumActualArgs);
3201
3202   AI = CS.arg_begin();
3203   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3204     const Type *ParamTy = FT->getParamType(i);
3205     if ((*AI)->getType() == ParamTy) {
3206       Args.push_back(*AI);
3207     } else {
3208       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3209                                          *Caller));
3210     }
3211   }
3212
3213   // If the function takes more arguments than the call was taking, add them
3214   // now...
3215   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3216     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3217
3218   // If we are removing arguments to the function, emit an obnoxious warning...
3219   if (FT->getNumParams() < NumActualArgs)
3220     if (!FT->isVarArg()) {
3221       std::cerr << "WARNING: While resolving call to function '"
3222                 << Callee->getName() << "' arguments were dropped!\n";
3223     } else {
3224       // Add all of the arguments in their promoted form to the arg list...
3225       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3226         const Type *PTy = getPromotedType((*AI)->getType());
3227         if (PTy != (*AI)->getType()) {
3228           // Must promote to pass through va_arg area!
3229           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3230           InsertNewInstBefore(Cast, *Caller);
3231           Args.push_back(Cast);
3232         } else {
3233           Args.push_back(*AI);
3234         }
3235       }
3236     }
3237
3238   if (FT->getReturnType() == Type::VoidTy)
3239     Caller->setName("");   // Void type should not have a name...
3240
3241   Instruction *NC;
3242   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3243     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3244                         Args, Caller->getName(), Caller);
3245   } else {
3246     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3247   }
3248
3249   // Insert a cast of the return type as necessary...
3250   Value *NV = NC;
3251   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3252     if (NV->getType() != Type::VoidTy) {
3253       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3254
3255       // If this is an invoke instruction, we should insert it after the first
3256       // non-phi, instruction in the normal successor block.
3257       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3258         BasicBlock::iterator I = II->getNormalDest()->begin();
3259         while (isa<PHINode>(I)) ++I;
3260         InsertNewInstBefore(NC, *I);
3261       } else {
3262         // Otherwise, it's a call, just insert cast right after the call instr
3263         InsertNewInstBefore(NC, *Caller);
3264       }
3265       AddUsersToWorkList(*Caller);
3266     } else {
3267       NV = Constant::getNullValue(Caller->getType());
3268     }
3269   }
3270
3271   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3272     Caller->replaceAllUsesWith(NV);
3273   Caller->getParent()->getInstList().erase(Caller);
3274   removeFromWorkList(Caller);
3275   return true;
3276 }
3277
3278
3279
3280 // PHINode simplification
3281 //
3282 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3283   if (Value *V = hasConstantValue(&PN))
3284     return ReplaceInstUsesWith(PN, V);
3285
3286   // If the only user of this instruction is a cast instruction, and all of the
3287   // incoming values are constants, change this PHI to merge together the casted
3288   // constants.
3289   if (PN.hasOneUse())
3290     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3291       if (CI->getType() != PN.getType()) {  // noop casts will be folded
3292         bool AllConstant = true;
3293         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3294           if (!isa<Constant>(PN.getIncomingValue(i))) {
3295             AllConstant = false;
3296             break;
3297           }
3298         if (AllConstant) {
3299           // Make a new PHI with all casted values.
3300           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3301           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3302             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3303             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3304                              PN.getIncomingBlock(i));
3305           }
3306
3307           // Update the cast instruction.
3308           CI->setOperand(0, New);
3309           WorkList.push_back(CI);    // revisit the cast instruction to fold.
3310           WorkList.push_back(New);   // Make sure to revisit the new Phi
3311           return &PN;                // PN is now dead!
3312         }
3313       }
3314   return 0;
3315 }
3316
3317 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3318                                       Instruction *InsertPoint,
3319                                       InstCombiner *IC) {
3320   unsigned PS = IC->getTargetData().getPointerSize();
3321   const Type *VTy = V->getType();
3322   Instruction *Cast;
3323   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3324     // We must insert a cast to ensure we sign-extend.
3325     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3326                                              V->getName()), *InsertPoint);
3327   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3328                                  *InsertPoint);
3329 }
3330
3331
3332 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3333   Value *PtrOp = GEP.getOperand(0);
3334   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
3335   // If so, eliminate the noop.
3336   if (GEP.getNumOperands() == 1)
3337     return ReplaceInstUsesWith(GEP, PtrOp);
3338
3339   bool HasZeroPointerIndex = false;
3340   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3341     HasZeroPointerIndex = C->isNullValue();
3342
3343   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3344     return ReplaceInstUsesWith(GEP, PtrOp);
3345
3346   // Eliminate unneeded casts for indices.
3347   bool MadeChange = false;
3348   gep_type_iterator GTI = gep_type_begin(GEP);
3349   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3350     if (isa<SequentialType>(*GTI)) {
3351       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3352         Value *Src = CI->getOperand(0);
3353         const Type *SrcTy = Src->getType();
3354         const Type *DestTy = CI->getType();
3355         if (Src->getType()->isInteger()) {
3356           if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3357             // We can always eliminate a cast from ulong or long to the other.
3358             // We can always eliminate a cast from uint to int or the other on
3359             // 32-bit pointer platforms.
3360             if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3361               MadeChange = true;
3362               GEP.setOperand(i, Src);
3363             }
3364           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3365                      SrcTy->getPrimitiveSize() == 4) {
3366             // We can always eliminate a cast from int to [u]long.  We can
3367             // eliminate a cast from uint to [u]long iff the target is a 32-bit
3368             // pointer target.
3369             if (SrcTy->isSigned() || 
3370                 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3371               MadeChange = true;
3372               GEP.setOperand(i, Src);
3373             }
3374           }
3375         }
3376       }
3377       // If we are using a wider index than needed for this platform, shrink it
3378       // to what we need.  If the incoming value needs a cast instruction,
3379       // insert it.  This explicit cast can make subsequent optimizations more
3380       // obvious.
3381       Value *Op = GEP.getOperand(i);
3382       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3383         if (Constant *C = dyn_cast<Constant>(Op)) {
3384           GEP.setOperand(i, ConstantExpr::getCast(C,
3385                                      TD->getIntPtrType()->getSignedVersion()));
3386           MadeChange = true;
3387         } else {
3388           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3389                                                 Op->getName()), GEP);
3390           GEP.setOperand(i, Op);
3391           MadeChange = true;
3392         }
3393
3394       // If this is a constant idx, make sure to canonicalize it to be a signed
3395       // operand, otherwise CSE and other optimizations are pessimized.
3396       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3397         GEP.setOperand(i, ConstantExpr::getCast(CUI,
3398                                           CUI->getType()->getSignedVersion()));
3399         MadeChange = true;
3400       }
3401     }
3402   if (MadeChange) return &GEP;
3403
3404   // Combine Indices - If the source pointer to this getelementptr instruction
3405   // is a getelementptr instruction, combine the indices of the two
3406   // getelementptr instructions into a single instruction.
3407   //
3408   std::vector<Value*> SrcGEPOperands;
3409   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3410     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3411   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3412     if (CE->getOpcode() == Instruction::GetElementPtr)
3413       SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3414   }
3415
3416   if (!SrcGEPOperands.empty()) {
3417     // Note that if our source is a gep chain itself that we wait for that
3418     // chain to be resolved before we perform this transformation.  This
3419     // avoids us creating a TON of code in some cases.
3420     //
3421     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3422         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3423       return 0;   // Wait until our source is folded to completion.
3424
3425     std::vector<Value *> Indices;
3426
3427     // Find out whether the last index in the source GEP is a sequential idx.
3428     bool EndsWithSequential = false;
3429     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3430            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3431       EndsWithSequential = !isa<StructType>(*I);
3432   
3433     // Can we combine the two pointer arithmetics offsets?
3434     if (EndsWithSequential) {
3435       // Replace: gep (gep %P, long B), long A, ...
3436       // With:    T = long A+B; gep %P, T, ...
3437       //
3438       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3439       if (SO1 == Constant::getNullValue(SO1->getType())) {
3440         Sum = GO1;
3441       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3442         Sum = SO1;
3443       } else {
3444         // If they aren't the same type, convert both to an integer of the
3445         // target's pointer size.
3446         if (SO1->getType() != GO1->getType()) {
3447           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3448             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3449           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3450             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3451           } else {
3452             unsigned PS = TD->getPointerSize();
3453             Instruction *Cast;
3454             if (SO1->getType()->getPrimitiveSize() == PS) {
3455               // Convert GO1 to SO1's type.
3456               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3457
3458             } else if (GO1->getType()->getPrimitiveSize() == PS) {
3459               // Convert SO1 to GO1's type.
3460               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3461             } else {
3462               const Type *PT = TD->getIntPtrType();
3463               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3464               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3465             }
3466           }
3467         }
3468         if (isa<Constant>(SO1) && isa<Constant>(GO1))
3469           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3470         else {
3471           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3472           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3473         }
3474       }
3475
3476       // Recycle the GEP we already have if possible.
3477       if (SrcGEPOperands.size() == 2) {
3478         GEP.setOperand(0, SrcGEPOperands[0]);
3479         GEP.setOperand(1, Sum);
3480         return &GEP;
3481       } else {
3482         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3483                        SrcGEPOperands.end()-1);
3484         Indices.push_back(Sum);
3485         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3486       }
3487     } else if (isa<Constant>(*GEP.idx_begin()) && 
3488                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3489                SrcGEPOperands.size() != 1) { 
3490       // Otherwise we can do the fold if the first index of the GEP is a zero
3491       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3492                      SrcGEPOperands.end());
3493       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3494     }
3495
3496     if (!Indices.empty())
3497       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3498
3499   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3500     // GEP of global variable.  If all of the indices for this GEP are
3501     // constants, we can promote this to a constexpr instead of an instruction.
3502
3503     // Scan for nonconstants...
3504     std::vector<Constant*> Indices;
3505     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3506     for (; I != E && isa<Constant>(*I); ++I)
3507       Indices.push_back(cast<Constant>(*I));
3508
3509     if (I == E) {  // If they are all constants...
3510       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3511
3512       // Replace all uses of the GEP with the new constexpr...
3513       return ReplaceInstUsesWith(GEP, CE);
3514     }
3515   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3516     if (CE->getOpcode() == Instruction::Cast) {
3517       if (HasZeroPointerIndex) {
3518         // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3519         // into     : GEP [10 x ubyte]* X, long 0, ...
3520         //
3521         // This occurs when the program declares an array extern like "int X[];"
3522         //
3523         Constant *X = CE->getOperand(0);
3524         const PointerType *CPTy = cast<PointerType>(CE->getType());
3525         if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3526           if (const ArrayType *XATy =
3527               dyn_cast<ArrayType>(XTy->getElementType()))
3528             if (const ArrayType *CATy =
3529                 dyn_cast<ArrayType>(CPTy->getElementType()))
3530               if (CATy->getElementType() == XATy->getElementType()) {
3531                 // At this point, we know that the cast source type is a pointer
3532                 // to an array of the same type as the destination pointer
3533                 // array.  Because the array type is never stepped over (there
3534                 // is a leading zero) we can fold the cast into this GEP.
3535                 GEP.setOperand(0, X);
3536                 return &GEP;
3537               }
3538       }
3539     }
3540   }
3541
3542   return 0;
3543 }
3544
3545 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3546   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3547   if (AI.isArrayAllocation())    // Check C != 1
3548     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3549       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3550       AllocationInst *New = 0;
3551
3552       // Create and insert the replacement instruction...
3553       if (isa<MallocInst>(AI))
3554         New = new MallocInst(NewTy, 0, AI.getName());
3555       else {
3556         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3557         New = new AllocaInst(NewTy, 0, AI.getName());
3558       }
3559
3560       InsertNewInstBefore(New, AI);
3561       
3562       // Scan to the end of the allocation instructions, to skip over a block of
3563       // allocas if possible...
3564       //
3565       BasicBlock::iterator It = New;
3566       while (isa<AllocationInst>(*It)) ++It;
3567
3568       // Now that I is pointing to the first non-allocation-inst in the block,
3569       // insert our getelementptr instruction...
3570       //
3571       std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3572       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3573
3574       // Now make everything use the getelementptr instead of the original
3575       // allocation.
3576       return ReplaceInstUsesWith(AI, V);
3577     }
3578
3579   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3580   // Note that we only do this for alloca's, because malloc should allocate and
3581   // return a unique pointer, even for a zero byte allocation.
3582   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() && 
3583       TD->getTypeSize(AI.getAllocatedType()) == 0)
3584     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3585
3586   return 0;
3587 }
3588
3589 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3590   Value *Op = FI.getOperand(0);
3591
3592   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3593   if (CastInst *CI = dyn_cast<CastInst>(Op))
3594     if (isa<PointerType>(CI->getOperand(0)->getType())) {
3595       FI.setOperand(0, CI->getOperand(0));
3596       return &FI;
3597     }
3598
3599   // If we have 'free null' delete the instruction.  This can happen in stl code
3600   // when lots of inlining happens.
3601   if (isa<ConstantPointerNull>(Op))
3602     return EraseInstFromFunction(FI);
3603
3604   return 0;
3605 }
3606
3607
3608 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3609 /// constantexpr, return the constant value being addressed by the constant
3610 /// expression, or null if something is funny.
3611 ///
3612 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3613   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3614     return 0;  // Do not allow stepping over the value!
3615
3616   // Loop over all of the operands, tracking down which value we are
3617   // addressing...
3618   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3619   for (++I; I != E; ++I)
3620     if (const StructType *STy = dyn_cast<StructType>(*I)) {
3621       ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3622       assert(CU->getValue() < STy->getNumElements() &&
3623              "Struct index out of range!");
3624       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3625         C = CS->getOperand(CU->getValue());
3626       } else if (isa<ConstantAggregateZero>(C)) {
3627         C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3628       } else {
3629         return 0;
3630       }
3631     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3632       const ArrayType *ATy = cast<ArrayType>(*I);
3633       if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3634       if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3635         C = CA->getOperand(CI->getRawValue());
3636       else if (isa<ConstantAggregateZero>(C))
3637         C = Constant::getNullValue(ATy->getElementType());
3638       else
3639         return 0;
3640     } else {
3641       return 0;
3642     }
3643   return C;
3644 }
3645
3646 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3647   User *CI = cast<User>(LI.getOperand(0));
3648
3649   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3650   if (const PointerType *SrcTy =
3651       dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3652     const Type *SrcPTy = SrcTy->getElementType();
3653     if (SrcPTy->isSized() && DestPTy->isSized() &&
3654         IC.getTargetData().getTypeSize(SrcPTy) == 
3655             IC.getTargetData().getTypeSize(DestPTy) &&
3656         (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3657         (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3658       // Okay, we are casting from one integer or pointer type to another of
3659       // the same size.  Instead of casting the pointer before the load, cast
3660       // the result of the loaded value.
3661       Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3662                                                            CI->getName(),
3663                                                            LI.isVolatile()),LI);
3664       // Now cast the result of the load.
3665       return new CastInst(NewLoad, LI.getType());
3666     }
3667   }
3668   return 0;
3669 }
3670
3671 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3672 /// from this value cannot trap.  If it is not obviously safe to load from the
3673 /// specified pointer, we do a quick local scan of the basic block containing
3674 /// ScanFrom, to determine if the address is already accessed.
3675 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3676   // If it is an alloca or global variable, it is always safe to load from.
3677   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3678
3679   // Otherwise, be a little bit agressive by scanning the local block where we
3680   // want to check to see if the pointer is already being loaded or stored
3681   // from/to.  If so, the previous load or store would have already trapped,
3682   // so there is no harm doing an extra load (also, CSE will later eliminate
3683   // the load entirely).
3684   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3685
3686   while (BBI != E) {
3687     --BBI;
3688
3689     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3690       if (LI->getOperand(0) == V) return true;
3691     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3692       if (SI->getOperand(1) == V) return true;
3693     
3694   }
3695   return false;
3696 }
3697
3698 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3699   Value *Op = LI.getOperand(0);
3700
3701   if (Constant *C = dyn_cast<Constant>(Op))
3702     if (C->isNullValue() && !LI.isVolatile())  // load null -> 0
3703       return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
3704
3705   // Instcombine load (constant global) into the value loaded...
3706   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3707     if (GV->isConstant() && !GV->isExternal())
3708       return ReplaceInstUsesWith(LI, GV->getInitializer());
3709
3710   // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3711   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3712     if (CE->getOpcode() == Instruction::GetElementPtr) {
3713       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3714         if (GV->isConstant() && !GV->isExternal())
3715           if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3716             return ReplaceInstUsesWith(LI, V);
3717     } else if (CE->getOpcode() == Instruction::Cast) {
3718       if (Instruction *Res = InstCombineLoadCast(*this, LI))
3719         return Res;
3720     }
3721
3722   // load (cast X) --> cast (load X) iff safe
3723   if (CastInst *CI = dyn_cast<CastInst>(Op))
3724     if (Instruction *Res = InstCombineLoadCast(*this, LI))
3725       return Res;
3726
3727   if (!LI.isVolatile() && Op->hasOneUse()) {
3728     // Change select and PHI nodes to select values instead of addresses: this
3729     // helps alias analysis out a lot, allows many others simplifications, and
3730     // exposes redundancy in the code.
3731     //
3732     // Note that we cannot do the transformation unless we know that the
3733     // introduced loads cannot trap!  Something like this is valid as long as
3734     // the condition is always false: load (select bool %C, int* null, int* %G),
3735     // but it would not be valid if we transformed it to load from null
3736     // unconditionally.
3737     //
3738     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3739       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
3740       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3741           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
3742         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
3743                                      SI->getOperand(1)->getName()+".val"), LI);
3744         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
3745                                      SI->getOperand(2)->getName()+".val"), LI);
3746         return new SelectInst(SI->getCondition(), V1, V2);
3747       }
3748
3749       // load (select (cond, null, P)) -> load P
3750       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3751         if (C->isNullValue()) {
3752           LI.setOperand(0, SI->getOperand(2));
3753           return &LI;
3754         }
3755
3756       // load (select (cond, P, null)) -> load P
3757       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3758         if (C->isNullValue()) {
3759           LI.setOperand(0, SI->getOperand(1));
3760           return &LI;
3761         }
3762
3763     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3764       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
3765       bool Safe = PN->getParent() == LI.getParent();
3766
3767       // Scan all of the instructions between the PHI and the load to make
3768       // sure there are no instructions that might possibly alter the value
3769       // loaded from the PHI.
3770       if (Safe) {
3771         BasicBlock::iterator I = &LI;
3772         for (--I; !isa<PHINode>(I); --I)
3773           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3774             Safe = false;
3775             break;
3776           }
3777       }
3778
3779       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
3780         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
3781                                     PN->getIncomingBlock(i)->getTerminator()))
3782           Safe = false;
3783
3784       if (Safe) {
3785         // Create the PHI.
3786         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3787         InsertNewInstBefore(NewPN, *PN);
3788         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
3789
3790         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3791           BasicBlock *BB = PN->getIncomingBlock(i);
3792           Value *&TheLoad = LoadMap[BB];
3793           if (TheLoad == 0) {
3794             Value *InVal = PN->getIncomingValue(i);
3795             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3796                                                        InVal->getName()+".val"),
3797                                           *BB->getTerminator());
3798           }
3799           NewPN->addIncoming(TheLoad, BB);
3800         }
3801         return ReplaceInstUsesWith(LI, NewPN);
3802       }
3803     }
3804   }
3805   return 0;
3806 }
3807
3808
3809 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3810   // Change br (not X), label True, label False to: br X, label False, True
3811   Value *X;
3812   BasicBlock *TrueDest;
3813   BasicBlock *FalseDest;
3814   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3815       !isa<Constant>(X)) {
3816     // Swap Destinations and condition...
3817     BI.setCondition(X);
3818     BI.setSuccessor(0, FalseDest);
3819     BI.setSuccessor(1, TrueDest);
3820     return &BI;
3821   }
3822
3823   // Cannonicalize setne -> seteq
3824   Instruction::BinaryOps Op; Value *Y;
3825   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3826                       TrueDest, FalseDest)))
3827     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3828          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3829       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3830       std::string Name = I->getName(); I->setName("");
3831       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3832       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
3833       // Swap Destinations and condition...
3834       BI.setCondition(NewSCC);
3835       BI.setSuccessor(0, FalseDest);
3836       BI.setSuccessor(1, TrueDest);
3837       removeFromWorkList(I);
3838       I->getParent()->getInstList().erase(I);
3839       WorkList.push_back(cast<Instruction>(NewSCC));
3840       return &BI;
3841     }
3842   
3843   return 0;
3844 }
3845
3846 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3847   Value *Cond = SI.getCondition();
3848   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3849     if (I->getOpcode() == Instruction::Add)
3850       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3851         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3852         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3853           SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3854                                                 AddRHS));
3855         SI.setOperand(0, I->getOperand(0));
3856         WorkList.push_back(I);
3857         return &SI;
3858       }
3859   }
3860   return 0;
3861 }
3862
3863
3864 void InstCombiner::removeFromWorkList(Instruction *I) {
3865   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3866                  WorkList.end());
3867 }
3868
3869 bool InstCombiner::runOnFunction(Function &F) {
3870   bool Changed = false;
3871   TD = &getAnalysis<TargetData>();
3872
3873   for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3874     WorkList.push_back(&*i);
3875
3876
3877   while (!WorkList.empty()) {
3878     Instruction *I = WorkList.back();  // Get an instruction from the worklist
3879     WorkList.pop_back();
3880
3881     // Check to see if we can DCE or ConstantPropagate the instruction...
3882     // Check to see if we can DIE the instruction...
3883     if (isInstructionTriviallyDead(I)) {
3884       // Add operands to the worklist...
3885       if (I->getNumOperands() < 4)
3886         AddUsesToWorkList(*I);
3887       ++NumDeadInst;
3888
3889       I->getParent()->getInstList().erase(I);
3890       removeFromWorkList(I);
3891       continue;
3892     }
3893
3894     // Instruction isn't dead, see if we can constant propagate it...
3895     if (Constant *C = ConstantFoldInstruction(I)) {
3896       // Add operands to the worklist...
3897       AddUsesToWorkList(*I);
3898       ReplaceInstUsesWith(*I, C);
3899
3900       ++NumConstProp;
3901       I->getParent()->getInstList().erase(I);
3902       removeFromWorkList(I);
3903       continue;
3904     }
3905
3906     // Now that we have an instruction, try combining it to simplify it...
3907     if (Instruction *Result = visit(*I)) {
3908       ++NumCombined;
3909       // Should we replace the old instruction with a new one?
3910       if (Result != I) {
3911         DEBUG(std::cerr << "IC: Old = " << *I
3912                         << "    New = " << *Result);
3913
3914         // Everything uses the new instruction now.
3915         I->replaceAllUsesWith(Result);
3916
3917         // Push the new instruction and any users onto the worklist.
3918         WorkList.push_back(Result);
3919         AddUsersToWorkList(*Result);
3920
3921         // Move the name to the new instruction first...
3922         std::string OldName = I->getName(); I->setName("");
3923         Result->setName(OldName);
3924
3925         // Insert the new instruction into the basic block...
3926         BasicBlock *InstParent = I->getParent();
3927         InstParent->getInstList().insert(I, Result);
3928
3929         // Make sure that we reprocess all operands now that we reduced their
3930         // use counts.
3931         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3932           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3933             WorkList.push_back(OpI);
3934
3935         // Instructions can end up on the worklist more than once.  Make sure
3936         // we do not process an instruction that has been deleted.
3937         removeFromWorkList(I);
3938
3939         // Erase the old instruction.
3940         InstParent->getInstList().erase(I);
3941       } else {
3942         DEBUG(std::cerr << "IC: MOD = " << *I);
3943
3944         // If the instruction was modified, it's possible that it is now dead.
3945         // if so, remove it.
3946         if (isInstructionTriviallyDead(I)) {
3947           // Make sure we process all operands now that we are reducing their
3948           // use counts.
3949           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3950             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3951               WorkList.push_back(OpI);
3952           
3953           // Instructions may end up in the worklist more than once.  Erase all
3954           // occurrances of this instruction.
3955           removeFromWorkList(I);
3956           I->getParent()->getInstList().erase(I);
3957         } else {
3958           WorkList.push_back(Result);
3959           AddUsersToWorkList(*Result);
3960         }
3961       }
3962       Changed = true;
3963     }
3964   }
3965
3966   return Changed;
3967 }
3968
3969 FunctionPass *llvm::createInstructionCombiningPass() {
3970   return new InstCombiner();
3971 }
3972