Removed #include <iostream> and replaced with llvm_* streams.
[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 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.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   Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
63   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
64
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitSetCondInst(SetCondInst &I);
147     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
148
149     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150                               Instruction::BinaryOps Cond, Instruction &I);
151     Instruction *visitShiftInst(ShiftInst &I);
152     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
153                                      ShiftInst &I);
154     Instruction *visitCastInst(CastInst &CI);
155     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
156                                 Instruction *FI);
157     Instruction *visitSelectInst(SelectInst &CI);
158     Instruction *visitCallInst(CallInst &CI);
159     Instruction *visitInvokeInst(InvokeInst &II);
160     Instruction *visitPHINode(PHINode &PN);
161     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
162     Instruction *visitAllocationInst(AllocationInst &AI);
163     Instruction *visitFreeInst(FreeInst &FI);
164     Instruction *visitLoadInst(LoadInst &LI);
165     Instruction *visitStoreInst(StoreInst &SI);
166     Instruction *visitBranchInst(BranchInst &BI);
167     Instruction *visitSwitchInst(SwitchInst &SI);
168     Instruction *visitInsertElementInst(InsertElementInst &IE);
169     Instruction *visitExtractElementInst(ExtractElementInst &EI);
170     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
171
172     // visitInstruction - Specify what to return for unhandled instructions...
173     Instruction *visitInstruction(Instruction &I) { return 0; }
174
175   private:
176     Instruction *visitCallSite(CallSite CS);
177     bool transformConstExprCastCall(CallSite CS);
178
179   public:
180     // InsertNewInstBefore - insert an instruction New before instruction Old
181     // in the program.  Add the new instruction to the worklist.
182     //
183     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
184       assert(New && New->getParent() == 0 &&
185              "New instruction already inserted into a basic block!");
186       BasicBlock *BB = Old.getParent();
187       BB->getInstList().insert(&Old, New);  // Insert inst
188       WorkList.push_back(New);              // Add to worklist
189       return New;
190     }
191
192     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
193     /// This also adds the cast to the worklist.  Finally, this returns the
194     /// cast.
195     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
196       if (V->getType() == Ty) return V;
197
198       if (Constant *CV = dyn_cast<Constant>(V))
199         return ConstantExpr::getCast(CV, Ty);
200       
201       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
202       WorkList.push_back(C);
203       return C;
204     }
205
206     // ReplaceInstUsesWith - This method is to be used when an instruction is
207     // found to be dead, replacable with another preexisting expression.  Here
208     // we add all uses of I to the worklist, replace all uses of I with the new
209     // value, then return I, so that the inst combiner will know that I was
210     // modified.
211     //
212     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
213       AddUsersToWorkList(I);         // Add all modified instrs to worklist
214       if (&I != V) {
215         I.replaceAllUsesWith(V);
216         return &I;
217       } else {
218         // If we are replacing the instruction with itself, this must be in a
219         // segment of unreachable code, so just clobber the instruction.
220         I.replaceAllUsesWith(UndefValue::get(I.getType()));
221         return &I;
222       }
223     }
224
225     // UpdateValueUsesWith - This method is to be used when an value is
226     // found to be replacable with another preexisting expression or was
227     // updated.  Here we add all uses of I to the worklist, replace all uses of
228     // I with the new value (unless the instruction was just updated), then
229     // return true, so that the inst combiner will know that I was modified.
230     //
231     bool UpdateValueUsesWith(Value *Old, Value *New) {
232       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
233       if (Old != New)
234         Old->replaceAllUsesWith(New);
235       if (Instruction *I = dyn_cast<Instruction>(Old))
236         WorkList.push_back(I);
237       if (Instruction *I = dyn_cast<Instruction>(New))
238         WorkList.push_back(I);
239       return true;
240     }
241     
242     // EraseInstFromFunction - When dealing with an instruction that has side
243     // effects or produces a void value, we can't rely on DCE to delete the
244     // instruction.  Instead, visit methods should return the value returned by
245     // this function.
246     Instruction *EraseInstFromFunction(Instruction &I) {
247       assert(I.use_empty() && "Cannot erase instruction that is used!");
248       AddUsesToWorkList(I);
249       removeFromWorkList(&I);
250       I.eraseFromParent();
251       return 0;  // Don't do anything with FI
252     }
253
254   private:
255     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
256     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
257     /// casts that are known to not do anything...
258     ///
259     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
260                                    Instruction *InsertBefore);
261
262     // SimplifyCommutative - This performs a few simplifications for commutative
263     // operators.
264     bool SimplifyCommutative(BinaryOperator &I);
265
266     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
267                               uint64_t &KnownZero, uint64_t &KnownOne,
268                               unsigned Depth = 0);
269
270     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
271                                       uint64_t &UndefElts, unsigned Depth = 0);
272       
273     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
274     // PHI node as operand #0, see if we can fold the instruction into the PHI
275     // (which is only possible if all operands to the PHI are constants).
276     Instruction *FoldOpIntoPhi(Instruction &I);
277
278     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
279     // operator and they all are only used by the PHI, PHI together their
280     // inputs, and do the operation once, to the result of the PHI.
281     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
282     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
283     
284     
285     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
286                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
287     
288     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
289                               bool isSub, Instruction &I);
290     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
291                                  bool Inside, Instruction &IB);
292     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
293     Instruction *MatchBSwap(BinaryOperator &I);
294
295     Value *EvaluateInDifferentType(Value *V, const Type *Ty);
296   };
297
298   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
299 }
300
301 // getComplexity:  Assign a complexity or rank value to LLVM Values...
302 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
303 static unsigned getComplexity(Value *V) {
304   if (isa<Instruction>(V)) {
305     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
306       return 3;
307     return 4;
308   }
309   if (isa<Argument>(V)) return 3;
310   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
311 }
312
313 // isOnlyUse - Return true if this instruction will be deleted if we stop using
314 // it.
315 static bool isOnlyUse(Value *V) {
316   return V->hasOneUse() || isa<Constant>(V);
317 }
318
319 // getPromotedType - Return the specified type promoted as it would be to pass
320 // though a va_arg area...
321 static const Type *getPromotedType(const Type *Ty) {
322   switch (Ty->getTypeID()) {
323   case Type::SByteTyID:
324   case Type::ShortTyID:  return Type::IntTy;
325   case Type::UByteTyID:
326   case Type::UShortTyID: return Type::UIntTy;
327   case Type::FloatTyID:  return Type::DoubleTy;
328   default:               return Ty;
329   }
330 }
331
332 /// isCast - If the specified operand is a CastInst or a constant expr cast,
333 /// return the operand value, otherwise return null.
334 static Value *isCast(Value *V) {
335   if (CastInst *I = dyn_cast<CastInst>(V))
336     return I->getOperand(0);
337   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
338     if (CE->getOpcode() == Instruction::Cast)
339       return CE->getOperand(0);
340   return 0;
341 }
342
343 enum CastType {
344   Noop     = 0,
345   Truncate = 1,
346   Signext  = 2,
347   Zeroext  = 3
348 };
349
350 /// getCastType - In the future, we will split the cast instruction into these
351 /// various types.  Until then, we have to do the analysis here.
352 static CastType getCastType(const Type *Src, const Type *Dest) {
353   assert(Src->isIntegral() && Dest->isIntegral() &&
354          "Only works on integral types!");
355   unsigned SrcSize = Src->getPrimitiveSizeInBits();
356   unsigned DestSize = Dest->getPrimitiveSizeInBits();
357   
358   if (SrcSize == DestSize) return Noop;
359   if (SrcSize > DestSize)  return Truncate;
360   if (Src->isSigned()) return Signext;
361   return Zeroext;
362 }
363
364
365 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
366 // instruction.
367 //
368 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
369                                    const Type *DstTy, TargetData *TD) {
370   
371   // It is legal to eliminate the instruction if casting A->B->A if the sizes
372   // are identical and the bits don't get reinterpreted (for example
373   // int->float->int would not be allowed).
374   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
375     return true;
376   
377   // If we are casting between pointer and integer types, treat pointers as
378   // integers of the appropriate size for the code below.
379   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
380   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
381   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
382   
383   // Allow free casting and conversion of sizes as long as the sign doesn't
384   // change...
385   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
386     CastType FirstCast = getCastType(SrcTy, MidTy);
387     CastType SecondCast = getCastType(MidTy, DstTy);
388     
389     // Capture the effect of these two casts.  If the result is a legal cast,
390     // the CastType is stored here, otherwise a special code is used.
391     static const unsigned CastResult[] = {
392       // First cast is noop
393       0, 1, 2, 3,
394       // First cast is a truncate
395       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
396                           // First cast is a sign ext
397       2, 5, 2, 4,         // signext->zeroext never ok
398                           // First cast is a zero ext
399       3, 5, 3, 3,
400     };
401     
402     unsigned Result = CastResult[FirstCast*4+SecondCast];
403     switch (Result) {
404     default: assert(0 && "Illegal table value!");
405     case 0:
406     case 1:
407     case 2:
408     case 3:
409       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
410       // truncates, we could eliminate more casts.
411       return (unsigned)getCastType(SrcTy, DstTy) == Result;
412     case 4:
413       return false;  // Not possible to eliminate this here.
414     case 5:
415       // Sign or zero extend followed by truncate is always ok if the result
416       // is a truncate or noop.
417       CastType ResultCast = getCastType(SrcTy, DstTy);
418       if (ResultCast == Noop || ResultCast == Truncate)
419         return true;
420         // Otherwise we are still growing the value, we are only safe if the
421         // result will match the sign/zeroextendness of the result.
422         return ResultCast == FirstCast;
423     }
424   }
425   
426   // If this is a cast from 'float -> double -> integer', cast from
427   // 'float -> integer' directly, as the value isn't changed by the 
428   // float->double conversion.
429   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
430       DstTy->isIntegral() && 
431       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
432     return true;
433   
434   // Packed type conversions don't modify bits.
435   if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
436     return true;
437   
438   return false;
439 }
440
441 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442 /// in any code being generated.  It does not require codegen if V is simple
443 /// enough or if the cast can be folded into other casts.
444 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
445   if (V->getType() == Ty || isa<Constant>(V)) return false;
446   
447   // If this is a noop cast, it isn't real codegen.
448   if (V->getType()->isLosslesslyConvertibleTo(Ty))
449     return false;
450
451   // If this is another cast that can be eliminated, it isn't codegen either.
452   if (const CastInst *CI = dyn_cast<CastInst>(V))
453     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
454                                TD))
455       return false;
456   return true;
457 }
458
459 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
460 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
461 /// casts that are known to not do anything...
462 ///
463 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
464                                              Instruction *InsertBefore) {
465   if (V->getType() == DestTy) return V;
466   if (Constant *C = dyn_cast<Constant>(V))
467     return ConstantExpr::getCast(C, DestTy);
468   
469   return InsertCastBefore(V, DestTy, *InsertBefore);
470 }
471
472 // SimplifyCommutative - This performs a few simplifications for commutative
473 // operators:
474 //
475 //  1. Order operands such that they are listed from right (least complex) to
476 //     left (most complex).  This puts constants before unary operators before
477 //     binary operators.
478 //
479 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
480 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
481 //
482 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
483   bool Changed = false;
484   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
485     Changed = !I.swapOperands();
486
487   if (!I.isAssociative()) return Changed;
488   Instruction::BinaryOps Opcode = I.getOpcode();
489   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
490     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
491       if (isa<Constant>(I.getOperand(1))) {
492         Constant *Folded = ConstantExpr::get(I.getOpcode(),
493                                              cast<Constant>(I.getOperand(1)),
494                                              cast<Constant>(Op->getOperand(1)));
495         I.setOperand(0, Op->getOperand(0));
496         I.setOperand(1, Folded);
497         return true;
498       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
499         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
500             isOnlyUse(Op) && isOnlyUse(Op1)) {
501           Constant *C1 = cast<Constant>(Op->getOperand(1));
502           Constant *C2 = cast<Constant>(Op1->getOperand(1));
503
504           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
506           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
507                                                     Op1->getOperand(0),
508                                                     Op1->getName(), &I);
509           WorkList.push_back(New);
510           I.setOperand(0, New);
511           I.setOperand(1, Folded);
512           return true;
513         }
514     }
515   return Changed;
516 }
517
518 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
519 // if the LHS is a constant zero (which is the 'negate' form).
520 //
521 static inline Value *dyn_castNegVal(Value *V) {
522   if (BinaryOperator::isNeg(V))
523     return BinaryOperator::getNegArgument(V);
524
525   // Constants can be considered to be negated values if they can be folded.
526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527     return ConstantExpr::getNeg(C);
528   return 0;
529 }
530
531 static inline Value *dyn_castNotVal(Value *V) {
532   if (BinaryOperator::isNot(V))
533     return BinaryOperator::getNotArgument(V);
534
535   // Constants can be considered to be not'ed values...
536   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
537     return ConstantExpr::getNot(C);
538   return 0;
539 }
540
541 // dyn_castFoldableMul - If this value is a multiply that can be folded into
542 // other computations (because it has a constant operand), return the
543 // non-constant operand of the multiply, and set CST to point to the multiplier.
544 // Otherwise, return null.
545 //
546 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
547   if (V->hasOneUse() && V->getType()->isInteger())
548     if (Instruction *I = dyn_cast<Instruction>(V)) {
549       if (I->getOpcode() == Instruction::Mul)
550         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
551           return I->getOperand(0);
552       if (I->getOpcode() == Instruction::Shl)
553         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
554           // The multiplier is really 1 << CST.
555           Constant *One = ConstantInt::get(V->getType(), 1);
556           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
557           return I->getOperand(0);
558         }
559     }
560   return 0;
561 }
562
563 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
564 /// expression, return it.
565 static User *dyn_castGetElementPtr(Value *V) {
566   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
567   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
568     if (CE->getOpcode() == Instruction::GetElementPtr)
569       return cast<User>(V);
570   return false;
571 }
572
573 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
574 static ConstantInt *AddOne(ConstantInt *C) {
575   return cast<ConstantInt>(ConstantExpr::getAdd(C,
576                                          ConstantInt::get(C->getType(), 1)));
577 }
578 static ConstantInt *SubOne(ConstantInt *C) {
579   return cast<ConstantInt>(ConstantExpr::getSub(C,
580                                          ConstantInt::get(C->getType(), 1)));
581 }
582
583 /// GetConstantInType - Return a ConstantInt with the specified type and value.
584 ///
585 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
586   if (Ty->isUnsigned()) 
587     return ConstantInt::get(Ty, Val);
588   else if (Ty->getTypeID() == Type::BoolTyID)
589     return ConstantBool::get(Val);
590   int64_t SVal = Val;
591   SVal <<= 64-Ty->getPrimitiveSizeInBits();
592   SVal >>= 64-Ty->getPrimitiveSizeInBits();
593   return ConstantInt::get(Ty, SVal);
594 }
595
596
597 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
598 /// known to be either zero or one and return them in the KnownZero/KnownOne
599 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
600 /// processing.
601 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
602                               uint64_t &KnownOne, unsigned Depth = 0) {
603   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
604   // we cannot optimize based on the assumption that it is zero without changing
605   // it to be an explicit zero.  If we don't change it to zero, other code could
606   // optimized based on the contradictory assumption that it is non-zero.
607   // Because instcombine aggressively folds operations with undef args anyway,
608   // this won't lose us code quality.
609   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
610     // We know all of the bits for a constant!
611     KnownOne = CI->getZExtValue() & Mask;
612     KnownZero = ~KnownOne & Mask;
613     return;
614   }
615
616   KnownZero = KnownOne = 0;   // Don't know anything.
617   if (Depth == 6 || Mask == 0)
618     return;  // Limit search depth.
619
620   uint64_t KnownZero2, KnownOne2;
621   Instruction *I = dyn_cast<Instruction>(V);
622   if (!I) return;
623
624   Mask &= V->getType()->getIntegralTypeMask();
625   
626   switch (I->getOpcode()) {
627   case Instruction::And:
628     // If either the LHS or the RHS are Zero, the result is zero.
629     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
630     Mask &= ~KnownZero;
631     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
632     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
633     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
634     
635     // Output known-1 bits are only known if set in both the LHS & RHS.
636     KnownOne &= KnownOne2;
637     // Output known-0 are known to be clear if zero in either the LHS | RHS.
638     KnownZero |= KnownZero2;
639     return;
640   case Instruction::Or:
641     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
642     Mask &= ~KnownOne;
643     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
644     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
645     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
646     
647     // Output known-0 bits are only known if clear in both the LHS & RHS.
648     KnownZero &= KnownZero2;
649     // Output known-1 are known to be set if set in either the LHS | RHS.
650     KnownOne |= KnownOne2;
651     return;
652   case Instruction::Xor: {
653     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
654     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
655     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
656     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
657     
658     // Output known-0 bits are known if clear or set in both the LHS & RHS.
659     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
660     // Output known-1 are known to be set if set in only one of the LHS, RHS.
661     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
662     KnownZero = KnownZeroOut;
663     return;
664   }
665   case Instruction::Select:
666     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
667     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
668     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
669     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
670
671     // Only known if known in both the LHS and RHS.
672     KnownOne &= KnownOne2;
673     KnownZero &= KnownZero2;
674     return;
675   case Instruction::Cast: {
676     const Type *SrcTy = I->getOperand(0)->getType();
677     if (!SrcTy->isIntegral()) return;
678     
679     // If this is an integer truncate or noop, just look in the input.
680     if (SrcTy->getPrimitiveSizeInBits() >= 
681            I->getType()->getPrimitiveSizeInBits()) {
682       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
683       return;
684     }
685
686     // Sign or Zero extension.  Compute the bits in the result that are not
687     // present in the input.
688     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
689     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
690       
691     // Handle zero extension.
692     if (!SrcTy->isSigned()) {
693       Mask &= SrcTy->getIntegralTypeMask();
694       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
696       // The top bits are known to be zero.
697       KnownZero |= NewBits;
698     } else {
699       // Sign extension.
700       Mask &= SrcTy->getIntegralTypeMask();
701       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
702       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
703
704       // If the sign bit of the input is known set or clear, then we know the
705       // top bits of the result.
706       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
707       if (KnownZero & InSignBit) {          // Input sign bit known zero
708         KnownZero |= NewBits;
709         KnownOne &= ~NewBits;
710       } else if (KnownOne & InSignBit) {    // Input sign bit known set
711         KnownOne |= NewBits;
712         KnownZero &= ~NewBits;
713       } else {                              // Input sign bit unknown
714         KnownZero &= ~NewBits;
715         KnownOne &= ~NewBits;
716       }
717     }
718     return;
719   }
720   case Instruction::Shl:
721     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
722     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
723       uint64_t ShiftAmt = SA->getZExtValue();
724       Mask >>= ShiftAmt;
725       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
726       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
727       KnownZero <<= ShiftAmt;
728       KnownOne  <<= ShiftAmt;
729       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
730       return;
731     }
732     break;
733   case Instruction::LShr:
734     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
735     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
736       // Compute the new bits that are at the top now.
737       uint64_t ShiftAmt = SA->getZExtValue();
738       uint64_t HighBits = (1ULL << ShiftAmt)-1;
739       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
740       
741       // Unsigned shift right.
742       Mask <<= ShiftAmt;
743       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
744       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
745       KnownZero >>= ShiftAmt;
746       KnownOne  >>= ShiftAmt;
747       KnownZero |= HighBits;  // high bits known zero.
748       return;
749     }
750     break;
751   case Instruction::AShr:
752     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
753     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
754       // Compute the new bits that are at the top now.
755       uint64_t ShiftAmt = SA->getZExtValue();
756       uint64_t HighBits = (1ULL << ShiftAmt)-1;
757       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
758       
759       // Signed shift right.
760       Mask <<= ShiftAmt;
761       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
762       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
763       KnownZero >>= ShiftAmt;
764       KnownOne  >>= ShiftAmt;
765         
766       // Handle the sign bits.
767       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
768       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
769         
770       if (KnownZero & SignBit) {       // New bits are known zero.
771         KnownZero |= HighBits;
772       } else if (KnownOne & SignBit) { // New bits are known one.
773         KnownOne |= HighBits;
774       }
775       return;
776     }
777     break;
778   }
779 }
780
781 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
782 /// this predicate to simplify operations downstream.  Mask is known to be zero
783 /// for bits that V cannot have.
784 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
785   uint64_t KnownZero, KnownOne;
786   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
787   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
788   return (KnownZero & Mask) == Mask;
789 }
790
791 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
792 /// specified instruction is a constant integer.  If so, check to see if there
793 /// are any bits set in the constant that are not demanded.  If so, shrink the
794 /// constant and return true.
795 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
796                                    uint64_t Demanded) {
797   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
798   if (!OpC) return false;
799
800   // If there are no bits set that aren't demanded, nothing to do.
801   if ((~Demanded & OpC->getZExtValue()) == 0)
802     return false;
803
804   // This is producing any bits that are not needed, shrink the RHS.
805   uint64_t Val = Demanded & OpC->getZExtValue();
806   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
807   return true;
808 }
809
810 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
811 // set of known zero and one bits, compute the maximum and minimum values that
812 // could have the specified known zero and known one bits, returning them in
813 // min/max.
814 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
815                                                    uint64_t KnownZero,
816                                                    uint64_t KnownOne,
817                                                    int64_t &Min, int64_t &Max) {
818   uint64_t TypeBits = Ty->getIntegralTypeMask();
819   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
820
821   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
822   
823   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
824   // bit if it is unknown.
825   Min = KnownOne;
826   Max = KnownOne|UnknownBits;
827   
828   if (SignBit & UnknownBits) { // Sign bit is unknown
829     Min |= SignBit;
830     Max &= ~SignBit;
831   }
832   
833   // Sign extend the min/max values.
834   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
835   Min = (Min << ShAmt) >> ShAmt;
836   Max = (Max << ShAmt) >> ShAmt;
837 }
838
839 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
840 // a set of known zero and one bits, compute the maximum and minimum values that
841 // could have the specified known zero and known one bits, returning them in
842 // min/max.
843 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
844                                                      uint64_t KnownZero,
845                                                      uint64_t KnownOne,
846                                                      uint64_t &Min,
847                                                      uint64_t &Max) {
848   uint64_t TypeBits = Ty->getIntegralTypeMask();
849   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
850   
851   // The minimum value is when the unknown bits are all zeros.
852   Min = KnownOne;
853   // The maximum value is when the unknown bits are all ones.
854   Max = KnownOne|UnknownBits;
855 }
856
857
858 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
859 /// DemandedMask bits of the result of V are ever used downstream.  If we can
860 /// use this information to simplify V, do so and return true.  Otherwise,
861 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
862 /// the expression (used to simplify the caller).  The KnownZero/One bits may
863 /// only be accurate for those bits in the DemandedMask.
864 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
865                                         uint64_t &KnownZero, uint64_t &KnownOne,
866                                         unsigned Depth) {
867   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
868     // We know all of the bits for a constant!
869     KnownOne = CI->getZExtValue() & DemandedMask;
870     KnownZero = ~KnownOne & DemandedMask;
871     return false;
872   }
873   
874   KnownZero = KnownOne = 0;
875   if (!V->hasOneUse()) {    // Other users may use these bits.
876     if (Depth != 0) {       // Not at the root.
877       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
878       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
879       return false;
880     }
881     // If this is the root being simplified, allow it to have multiple uses,
882     // just set the DemandedMask to all bits.
883     DemandedMask = V->getType()->getIntegralTypeMask();
884   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
885     if (V != UndefValue::get(V->getType()))
886       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
887     return false;
888   } else if (Depth == 6) {        // Limit search depth.
889     return false;
890   }
891   
892   Instruction *I = dyn_cast<Instruction>(V);
893   if (!I) return false;        // Only analyze instructions.
894
895   DemandedMask &= V->getType()->getIntegralTypeMask();
896   
897   uint64_t KnownZero2, KnownOne2;
898   switch (I->getOpcode()) {
899   default: break;
900   case Instruction::And:
901     // If either the LHS or the RHS are Zero, the result is zero.
902     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
903                              KnownZero, KnownOne, Depth+1))
904       return true;
905     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
906
907     // If something is known zero on the RHS, the bits aren't demanded on the
908     // LHS.
909     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
910                              KnownZero2, KnownOne2, Depth+1))
911       return true;
912     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
913
914     // If all of the demanded bits are known one on one side, return the other.
915     // These bits cannot contribute to the result of the 'and'.
916     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
917       return UpdateValueUsesWith(I, I->getOperand(0));
918     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
919       return UpdateValueUsesWith(I, I->getOperand(1));
920     
921     // If all of the demanded bits in the inputs are known zeros, return zero.
922     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
923       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
924       
925     // If the RHS is a constant, see if we can simplify it.
926     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
927       return UpdateValueUsesWith(I, I);
928       
929     // Output known-1 bits are only known if set in both the LHS & RHS.
930     KnownOne &= KnownOne2;
931     // Output known-0 are known to be clear if zero in either the LHS | RHS.
932     KnownZero |= KnownZero2;
933     break;
934   case Instruction::Or:
935     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
936                              KnownZero, KnownOne, Depth+1))
937       return true;
938     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
939     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
940                              KnownZero2, KnownOne2, Depth+1))
941       return true;
942     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
943     
944     // If all of the demanded bits are known zero on one side, return the other.
945     // These bits cannot contribute to the result of the 'or'.
946     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
947       return UpdateValueUsesWith(I, I->getOperand(0));
948     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
949       return UpdateValueUsesWith(I, I->getOperand(1));
950
951     // If all of the potentially set bits on one side are known to be set on
952     // the other side, just use the 'other' side.
953     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
954         (DemandedMask & (~KnownZero)))
955       return UpdateValueUsesWith(I, I->getOperand(0));
956     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
957         (DemandedMask & (~KnownZero2)))
958       return UpdateValueUsesWith(I, I->getOperand(1));
959         
960     // If the RHS is a constant, see if we can simplify it.
961     if (ShrinkDemandedConstant(I, 1, DemandedMask))
962       return UpdateValueUsesWith(I, I);
963           
964     // Output known-0 bits are only known if clear in both the LHS & RHS.
965     KnownZero &= KnownZero2;
966     // Output known-1 are known to be set if set in either the LHS | RHS.
967     KnownOne |= KnownOne2;
968     break;
969   case Instruction::Xor: {
970     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
971                              KnownZero, KnownOne, Depth+1))
972       return true;
973     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
974     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
975                              KnownZero2, KnownOne2, Depth+1))
976       return true;
977     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
978     
979     // If all of the demanded bits are known zero on one side, return the other.
980     // These bits cannot contribute to the result of the 'xor'.
981     if ((DemandedMask & KnownZero) == DemandedMask)
982       return UpdateValueUsesWith(I, I->getOperand(0));
983     if ((DemandedMask & KnownZero2) == DemandedMask)
984       return UpdateValueUsesWith(I, I->getOperand(1));
985     
986     // Output known-0 bits are known if clear or set in both the LHS & RHS.
987     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
988     // Output known-1 are known to be set if set in only one of the LHS, RHS.
989     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
990     
991     // If all of the unknown bits are known to be zero on one side or the other
992     // (but not both) turn this into an *inclusive* or.
993     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
994     if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
995       if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
996         Instruction *Or =
997           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
998                                    I->getName());
999         InsertNewInstBefore(Or, *I);
1000         return UpdateValueUsesWith(I, Or);
1001       }
1002     }
1003     
1004     // If all of the demanded bits on one side are known, and all of the set
1005     // bits on that side are also known to be set on the other side, turn this
1006     // into an AND, as we know the bits will be cleared.
1007     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1008     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1009       if ((KnownOne & KnownOne2) == KnownOne) {
1010         Constant *AndC = GetConstantInType(I->getType(), 
1011                                            ~KnownOne & DemandedMask);
1012         Instruction *And = 
1013           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1014         InsertNewInstBefore(And, *I);
1015         return UpdateValueUsesWith(I, And);
1016       }
1017     }
1018     
1019     // If the RHS is a constant, see if we can simplify it.
1020     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1021     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1022       return UpdateValueUsesWith(I, I);
1023     
1024     KnownZero = KnownZeroOut;
1025     KnownOne  = KnownOneOut;
1026     break;
1027   }
1028   case Instruction::Select:
1029     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1030                              KnownZero, KnownOne, Depth+1))
1031       return true;
1032     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1033                              KnownZero2, KnownOne2, Depth+1))
1034       return true;
1035     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1036     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1037     
1038     // If the operands are constants, see if we can simplify them.
1039     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1040       return UpdateValueUsesWith(I, I);
1041     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1042       return UpdateValueUsesWith(I, I);
1043     
1044     // Only known if known in both the LHS and RHS.
1045     KnownOne &= KnownOne2;
1046     KnownZero &= KnownZero2;
1047     break;
1048   case Instruction::Cast: {
1049     const Type *SrcTy = I->getOperand(0)->getType();
1050     if (!SrcTy->isIntegral()) return false;
1051     
1052     // If this is an integer truncate or noop, just look in the input.
1053     if (SrcTy->getPrimitiveSizeInBits() >= 
1054         I->getType()->getPrimitiveSizeInBits()) {
1055       // Cast to bool is a comparison against 0, which demands all bits.  We
1056       // can't propagate anything useful up.
1057       if (I->getType() == Type::BoolTy)
1058         break;
1059       
1060       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1061                                KnownZero, KnownOne, Depth+1))
1062         return true;
1063       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1064       break;
1065     }
1066     
1067     // Sign or Zero extension.  Compute the bits in the result that are not
1068     // present in the input.
1069     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1070     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1071     
1072     // Handle zero extension.
1073     if (!SrcTy->isSigned()) {
1074       DemandedMask &= SrcTy->getIntegralTypeMask();
1075       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1076                                KnownZero, KnownOne, Depth+1))
1077         return true;
1078       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1079       // The top bits are known to be zero.
1080       KnownZero |= NewBits;
1081     } else {
1082       // Sign extension.
1083       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1084       int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1085
1086       // If any of the sign extended bits are demanded, we know that the sign
1087       // bit is demanded.
1088       if (NewBits & DemandedMask)
1089         InputDemandedBits |= InSignBit;
1090       
1091       if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1092                                KnownZero, KnownOne, Depth+1))
1093         return true;
1094       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1095       
1096       // If the sign bit of the input is known set or clear, then we know the
1097       // top bits of the result.
1098
1099       // If the input sign bit is known zero, or if the NewBits are not demanded
1100       // convert this into a zero extension.
1101       if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1102         // Convert to unsigned first.
1103         Value *NewVal = 
1104           InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
1105         // Then cast that to the destination type.
1106         NewVal = new CastInst(NewVal, I->getType(), I->getName());
1107         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1108         return UpdateValueUsesWith(I, NewVal);
1109       } else if (KnownOne & InSignBit) {    // Input sign bit known set
1110         KnownOne |= NewBits;
1111         KnownZero &= ~NewBits;
1112       } else {                              // Input sign bit unknown
1113         KnownZero &= ~NewBits;
1114         KnownOne &= ~NewBits;
1115       }
1116     }
1117     break;
1118   }
1119   case Instruction::Add:
1120     // If there is a constant on the RHS, there are a variety of xformations
1121     // we can do.
1122     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1123       // If null, this should be simplified elsewhere.  Some of the xforms here
1124       // won't work if the RHS is zero.
1125       if (RHS->isNullValue())
1126         break;
1127       
1128       // Figure out what the input bits are.  If the top bits of the and result
1129       // are not demanded, then the add doesn't demand them from its input
1130       // either.
1131       
1132       // Shift the demanded mask up so that it's at the top of the uint64_t.
1133       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1134       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1135       
1136       // If the top bit of the output is demanded, demand everything from the
1137       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1138       uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1139
1140       // Find information about known zero/one bits in the input.
1141       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1142                                KnownZero2, KnownOne2, Depth+1))
1143         return true;
1144
1145       // If the RHS of the add has bits set that can't affect the input, reduce
1146       // the constant.
1147       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1148         return UpdateValueUsesWith(I, I);
1149       
1150       // Avoid excess work.
1151       if (KnownZero2 == 0 && KnownOne2 == 0)
1152         break;
1153       
1154       // Turn it into OR if input bits are zero.
1155       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1156         Instruction *Or =
1157           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1158                                    I->getName());
1159         InsertNewInstBefore(Or, *I);
1160         return UpdateValueUsesWith(I, Or);
1161       }
1162       
1163       // We can say something about the output known-zero and known-one bits,
1164       // depending on potential carries from the input constant and the
1165       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1166       // bits set and the RHS constant is 0x01001, then we know we have a known
1167       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1168       
1169       // To compute this, we first compute the potential carry bits.  These are
1170       // the bits which may be modified.  I'm not aware of a better way to do
1171       // this scan.
1172       uint64_t RHSVal = RHS->getZExtValue();
1173       
1174       bool CarryIn = false;
1175       uint64_t CarryBits = 0;
1176       uint64_t CurBit = 1;
1177       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1178         // Record the current carry in.
1179         if (CarryIn) CarryBits |= CurBit;
1180         
1181         bool CarryOut;
1182         
1183         // This bit has a carry out unless it is "zero + zero" or
1184         // "zero + anything" with no carry in.
1185         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1186           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1187         } else if (!CarryIn &&
1188                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1189           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1190         } else {
1191           // Otherwise, we have to assume we have a carry out.
1192           CarryOut = true;
1193         }
1194         
1195         // This stage's carry out becomes the next stage's carry-in.
1196         CarryIn = CarryOut;
1197       }
1198       
1199       // Now that we know which bits have carries, compute the known-1/0 sets.
1200       
1201       // Bits are known one if they are known zero in one operand and one in the
1202       // other, and there is no input carry.
1203       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1204       
1205       // Bits are known zero if they are known zero in both operands and there
1206       // is no input carry.
1207       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1208     }
1209     break;
1210   case Instruction::Shl:
1211     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1212       uint64_t ShiftAmt = SA->getZExtValue();
1213       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1214                                KnownZero, KnownOne, Depth+1))
1215         return true;
1216       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217       KnownZero <<= ShiftAmt;
1218       KnownOne  <<= ShiftAmt;
1219       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1220     }
1221     break;
1222   case Instruction::LShr:
1223     // For a logical shift right
1224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225       unsigned ShiftAmt = SA->getZExtValue();
1226       
1227       // Compute the new bits that are at the top now.
1228       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1229       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1230       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1231       // Unsigned shift right.
1232       if (SimplifyDemandedBits(I->getOperand(0),
1233                               (DemandedMask << ShiftAmt) & TypeMask,
1234                                KnownZero, KnownOne, Depth+1))
1235         return true;
1236       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1237       KnownZero &= TypeMask;
1238       KnownOne  &= TypeMask;
1239       KnownZero >>= ShiftAmt;
1240       KnownOne  >>= ShiftAmt;
1241       KnownZero |= HighBits;  // high bits known zero.
1242     }
1243     break;
1244   case Instruction::AShr:
1245     // If this is an arithmetic shift right and only the low-bit is set, we can
1246     // always convert this into a logical shr, even if the shift amount is
1247     // variable.  The low bit of the shift cannot be an input sign bit unless
1248     // the shift amount is >= the size of the datatype, which is undefined.
1249     if (DemandedMask == 1) {
1250       // Perform the logical shift right.
1251       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1252                                     I->getOperand(1), I->getName());
1253       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1254       return UpdateValueUsesWith(I, NewVal);
1255     }    
1256     
1257     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258       unsigned ShiftAmt = SA->getZExtValue();
1259       
1260       // Compute the new bits that are at the top now.
1261       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1262       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1263       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1264       // Signed shift right.
1265       if (SimplifyDemandedBits(I->getOperand(0),
1266                                (DemandedMask << ShiftAmt) & TypeMask,
1267                                KnownZero, KnownOne, Depth+1))
1268         return true;
1269       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1270       KnownZero &= TypeMask;
1271       KnownOne  &= TypeMask;
1272       KnownZero >>= ShiftAmt;
1273       KnownOne  >>= ShiftAmt;
1274         
1275       // Handle the sign bits.
1276       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1277       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1278         
1279       // If the input sign bit is known to be zero, or if none of the top bits
1280       // are demanded, turn this into an unsigned shift right.
1281       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1282         // Perform the logical shift right.
1283         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1284                                       SA, I->getName());
1285         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1286         return UpdateValueUsesWith(I, NewVal);
1287       } else if (KnownOne & SignBit) { // New bits are known one.
1288         KnownOne |= HighBits;
1289       }
1290     }
1291     break;
1292   }
1293   
1294   // If the client is only demanding bits that we know, return the known
1295   // constant.
1296   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1297     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1298   return false;
1299 }  
1300
1301
1302 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1303 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1304 /// actually used by the caller.  This method analyzes which elements of the
1305 /// operand are undef and returns that information in UndefElts.
1306 ///
1307 /// If the information about demanded elements can be used to simplify the
1308 /// operation, the operation is simplified, then the resultant value is
1309 /// returned.  This returns null if no change was made.
1310 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1311                                                 uint64_t &UndefElts,
1312                                                 unsigned Depth) {
1313   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1314   assert(VWidth <= 64 && "Vector too wide to analyze!");
1315   uint64_t EltMask = ~0ULL >> (64-VWidth);
1316   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1317          "Invalid DemandedElts!");
1318
1319   if (isa<UndefValue>(V)) {
1320     // If the entire vector is undefined, just return this info.
1321     UndefElts = EltMask;
1322     return 0;
1323   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1324     UndefElts = EltMask;
1325     return UndefValue::get(V->getType());
1326   }
1327   
1328   UndefElts = 0;
1329   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1330     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1331     Constant *Undef = UndefValue::get(EltTy);
1332
1333     std::vector<Constant*> Elts;
1334     for (unsigned i = 0; i != VWidth; ++i)
1335       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1336         Elts.push_back(Undef);
1337         UndefElts |= (1ULL << i);
1338       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1339         Elts.push_back(Undef);
1340         UndefElts |= (1ULL << i);
1341       } else {                               // Otherwise, defined.
1342         Elts.push_back(CP->getOperand(i));
1343       }
1344         
1345     // If we changed the constant, return it.
1346     Constant *NewCP = ConstantPacked::get(Elts);
1347     return NewCP != CP ? NewCP : 0;
1348   } else if (isa<ConstantAggregateZero>(V)) {
1349     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1350     // set to undef.
1351     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1352     Constant *Zero = Constant::getNullValue(EltTy);
1353     Constant *Undef = UndefValue::get(EltTy);
1354     std::vector<Constant*> Elts;
1355     for (unsigned i = 0; i != VWidth; ++i)
1356       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1357     UndefElts = DemandedElts ^ EltMask;
1358     return ConstantPacked::get(Elts);
1359   }
1360   
1361   if (!V->hasOneUse()) {    // Other users may use these bits.
1362     if (Depth != 0) {       // Not at the root.
1363       // TODO: Just compute the UndefElts information recursively.
1364       return false;
1365     }
1366     return false;
1367   } else if (Depth == 10) {        // Limit search depth.
1368     return false;
1369   }
1370   
1371   Instruction *I = dyn_cast<Instruction>(V);
1372   if (!I) return false;        // Only analyze instructions.
1373   
1374   bool MadeChange = false;
1375   uint64_t UndefElts2;
1376   Value *TmpV;
1377   switch (I->getOpcode()) {
1378   default: break;
1379     
1380   case Instruction::InsertElement: {
1381     // If this is a variable index, we don't know which element it overwrites.
1382     // demand exactly the same input as we produce.
1383     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1384     if (Idx == 0) {
1385       // Note that we can't propagate undef elt info, because we don't know
1386       // which elt is getting updated.
1387       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1388                                         UndefElts2, Depth+1);
1389       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1390       break;
1391     }
1392     
1393     // If this is inserting an element that isn't demanded, remove this
1394     // insertelement.
1395     unsigned IdxNo = Idx->getZExtValue();
1396     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1397       return AddSoonDeadInstToWorklist(*I, 0);
1398     
1399     // Otherwise, the element inserted overwrites whatever was there, so the
1400     // input demanded set is simpler than the output set.
1401     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1402                                       DemandedElts & ~(1ULL << IdxNo),
1403                                       UndefElts, Depth+1);
1404     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1405
1406     // The inserted element is defined.
1407     UndefElts |= 1ULL << IdxNo;
1408     break;
1409   }
1410     
1411   case Instruction::And:
1412   case Instruction::Or:
1413   case Instruction::Xor:
1414   case Instruction::Add:
1415   case Instruction::Sub:
1416   case Instruction::Mul:
1417     // div/rem demand all inputs, because they don't want divide by zero.
1418     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1419                                       UndefElts, Depth+1);
1420     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1421     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1422                                       UndefElts2, Depth+1);
1423     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1424       
1425     // Output elements are undefined if both are undefined.  Consider things
1426     // like undef&0.  The result is known zero, not undef.
1427     UndefElts &= UndefElts2;
1428     break;
1429     
1430   case Instruction::Call: {
1431     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1432     if (!II) break;
1433     switch (II->getIntrinsicID()) {
1434     default: break;
1435       
1436     // Binary vector operations that work column-wise.  A dest element is a
1437     // function of the corresponding input elements from the two inputs.
1438     case Intrinsic::x86_sse_sub_ss:
1439     case Intrinsic::x86_sse_mul_ss:
1440     case Intrinsic::x86_sse_min_ss:
1441     case Intrinsic::x86_sse_max_ss:
1442     case Intrinsic::x86_sse2_sub_sd:
1443     case Intrinsic::x86_sse2_mul_sd:
1444     case Intrinsic::x86_sse2_min_sd:
1445     case Intrinsic::x86_sse2_max_sd:
1446       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1447                                         UndefElts, Depth+1);
1448       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1449       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1450                                         UndefElts2, Depth+1);
1451       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1452
1453       // If only the low elt is demanded and this is a scalarizable intrinsic,
1454       // scalarize it now.
1455       if (DemandedElts == 1) {
1456         switch (II->getIntrinsicID()) {
1457         default: break;
1458         case Intrinsic::x86_sse_sub_ss:
1459         case Intrinsic::x86_sse_mul_ss:
1460         case Intrinsic::x86_sse2_sub_sd:
1461         case Intrinsic::x86_sse2_mul_sd:
1462           // TODO: Lower MIN/MAX/ABS/etc
1463           Value *LHS = II->getOperand(1);
1464           Value *RHS = II->getOperand(2);
1465           // Extract the element as scalars.
1466           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1467           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1468           
1469           switch (II->getIntrinsicID()) {
1470           default: assert(0 && "Case stmts out of sync!");
1471           case Intrinsic::x86_sse_sub_ss:
1472           case Intrinsic::x86_sse2_sub_sd:
1473             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1474                                                         II->getName()), *II);
1475             break;
1476           case Intrinsic::x86_sse_mul_ss:
1477           case Intrinsic::x86_sse2_mul_sd:
1478             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1479                                                          II->getName()), *II);
1480             break;
1481           }
1482           
1483           Instruction *New =
1484             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1485                                   II->getName());
1486           InsertNewInstBefore(New, *II);
1487           AddSoonDeadInstToWorklist(*II, 0);
1488           return New;
1489         }            
1490       }
1491         
1492       // Output elements are undefined if both are undefined.  Consider things
1493       // like undef&0.  The result is known zero, not undef.
1494       UndefElts &= UndefElts2;
1495       break;
1496     }
1497     break;
1498   }
1499   }
1500   return MadeChange ? I : 0;
1501 }
1502
1503 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1504 // true when both operands are equal...
1505 //
1506 static bool isTrueWhenEqual(Instruction &I) {
1507   return I.getOpcode() == Instruction::SetEQ ||
1508          I.getOpcode() == Instruction::SetGE ||
1509          I.getOpcode() == Instruction::SetLE;
1510 }
1511
1512 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1513 /// function is designed to check a chain of associative operators for a
1514 /// potential to apply a certain optimization.  Since the optimization may be
1515 /// applicable if the expression was reassociated, this checks the chain, then
1516 /// reassociates the expression as necessary to expose the optimization
1517 /// opportunity.  This makes use of a special Functor, which must define
1518 /// 'shouldApply' and 'apply' methods.
1519 ///
1520 template<typename Functor>
1521 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1522   unsigned Opcode = Root.getOpcode();
1523   Value *LHS = Root.getOperand(0);
1524
1525   // Quick check, see if the immediate LHS matches...
1526   if (F.shouldApply(LHS))
1527     return F.apply(Root);
1528
1529   // Otherwise, if the LHS is not of the same opcode as the root, return.
1530   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1531   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1532     // Should we apply this transform to the RHS?
1533     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1534
1535     // If not to the RHS, check to see if we should apply to the LHS...
1536     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1537       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1538       ShouldApply = true;
1539     }
1540
1541     // If the functor wants to apply the optimization to the RHS of LHSI,
1542     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1543     if (ShouldApply) {
1544       BasicBlock *BB = Root.getParent();
1545
1546       // Now all of the instructions are in the current basic block, go ahead
1547       // and perform the reassociation.
1548       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1549
1550       // First move the selected RHS to the LHS of the root...
1551       Root.setOperand(0, LHSI->getOperand(1));
1552
1553       // Make what used to be the LHS of the root be the user of the root...
1554       Value *ExtraOperand = TmpLHSI->getOperand(1);
1555       if (&Root == TmpLHSI) {
1556         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1557         return 0;
1558       }
1559       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1560       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1561       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1562       BasicBlock::iterator ARI = &Root; ++ARI;
1563       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1564       ARI = Root;
1565
1566       // Now propagate the ExtraOperand down the chain of instructions until we
1567       // get to LHSI.
1568       while (TmpLHSI != LHSI) {
1569         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1570         // Move the instruction to immediately before the chain we are
1571         // constructing to avoid breaking dominance properties.
1572         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1573         BB->getInstList().insert(ARI, NextLHSI);
1574         ARI = NextLHSI;
1575
1576         Value *NextOp = NextLHSI->getOperand(1);
1577         NextLHSI->setOperand(1, ExtraOperand);
1578         TmpLHSI = NextLHSI;
1579         ExtraOperand = NextOp;
1580       }
1581
1582       // Now that the instructions are reassociated, have the functor perform
1583       // the transformation...
1584       return F.apply(Root);
1585     }
1586
1587     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1588   }
1589   return 0;
1590 }
1591
1592
1593 // AddRHS - Implements: X + X --> X << 1
1594 struct AddRHS {
1595   Value *RHS;
1596   AddRHS(Value *rhs) : RHS(rhs) {}
1597   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1598   Instruction *apply(BinaryOperator &Add) const {
1599     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1600                          ConstantInt::get(Type::UByteTy, 1));
1601   }
1602 };
1603
1604 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1605 //                 iff C1&C2 == 0
1606 struct AddMaskingAnd {
1607   Constant *C2;
1608   AddMaskingAnd(Constant *c) : C2(c) {}
1609   bool shouldApply(Value *LHS) const {
1610     ConstantInt *C1;
1611     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1612            ConstantExpr::getAnd(C1, C2)->isNullValue();
1613   }
1614   Instruction *apply(BinaryOperator &Add) const {
1615     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1616   }
1617 };
1618
1619 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1620                                              InstCombiner *IC) {
1621   if (isa<CastInst>(I)) {
1622     if (Constant *SOC = dyn_cast<Constant>(SO))
1623       return ConstantExpr::getCast(SOC, I.getType());
1624
1625     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1626                                                 SO->getName() + ".cast"), I);
1627   }
1628
1629   // Figure out if the constant is the left or the right argument.
1630   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1631   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1632
1633   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1634     if (ConstIsRHS)
1635       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1636     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1637   }
1638
1639   Value *Op0 = SO, *Op1 = ConstOperand;
1640   if (!ConstIsRHS)
1641     std::swap(Op0, Op1);
1642   Instruction *New;
1643   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1644     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1645   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1646     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1647   else {
1648     assert(0 && "Unknown binary instruction type!");
1649     abort();
1650   }
1651   return IC->InsertNewInstBefore(New, I);
1652 }
1653
1654 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1655 // constant as the other operand, try to fold the binary operator into the
1656 // select arguments.  This also works for Cast instructions, which obviously do
1657 // not have a second operand.
1658 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1659                                      InstCombiner *IC) {
1660   // Don't modify shared select instructions
1661   if (!SI->hasOneUse()) return 0;
1662   Value *TV = SI->getOperand(1);
1663   Value *FV = SI->getOperand(2);
1664
1665   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1666     // Bool selects with constant operands can be folded to logical ops.
1667     if (SI->getType() == Type::BoolTy) return 0;
1668
1669     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1670     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1671
1672     return new SelectInst(SI->getCondition(), SelectTrueVal,
1673                           SelectFalseVal);
1674   }
1675   return 0;
1676 }
1677
1678
1679 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1680 /// node as operand #0, see if we can fold the instruction into the PHI (which
1681 /// is only possible if all operands to the PHI are constants).
1682 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1683   PHINode *PN = cast<PHINode>(I.getOperand(0));
1684   unsigned NumPHIValues = PN->getNumIncomingValues();
1685   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1686
1687   // Check to see if all of the operands of the PHI are constants.  If there is
1688   // one non-constant value, remember the BB it is.  If there is more than one
1689   // bail out.
1690   BasicBlock *NonConstBB = 0;
1691   for (unsigned i = 0; i != NumPHIValues; ++i)
1692     if (!isa<Constant>(PN->getIncomingValue(i))) {
1693       if (NonConstBB) return 0;  // More than one non-const value.
1694       NonConstBB = PN->getIncomingBlock(i);
1695       
1696       // If the incoming non-constant value is in I's block, we have an infinite
1697       // loop.
1698       if (NonConstBB == I.getParent())
1699         return 0;
1700     }
1701   
1702   // If there is exactly one non-constant value, we can insert a copy of the
1703   // operation in that block.  However, if this is a critical edge, we would be
1704   // inserting the computation one some other paths (e.g. inside a loop).  Only
1705   // do this if the pred block is unconditionally branching into the phi block.
1706   if (NonConstBB) {
1707     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1708     if (!BI || !BI->isUnconditional()) return 0;
1709   }
1710
1711   // Okay, we can do the transformation: create the new PHI node.
1712   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1713   I.setName("");
1714   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1715   InsertNewInstBefore(NewPN, *PN);
1716
1717   // Next, add all of the operands to the PHI.
1718   if (I.getNumOperands() == 2) {
1719     Constant *C = cast<Constant>(I.getOperand(1));
1720     for (unsigned i = 0; i != NumPHIValues; ++i) {
1721       Value *InV;
1722       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1723         InV = ConstantExpr::get(I.getOpcode(), InC, C);
1724       } else {
1725         assert(PN->getIncomingBlock(i) == NonConstBB);
1726         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1727           InV = BinaryOperator::create(BO->getOpcode(),
1728                                        PN->getIncomingValue(i), C, "phitmp",
1729                                        NonConstBB->getTerminator());
1730         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1731           InV = new ShiftInst(SI->getOpcode(),
1732                               PN->getIncomingValue(i), C, "phitmp",
1733                               NonConstBB->getTerminator());
1734         else
1735           assert(0 && "Unknown binop!");
1736         
1737         WorkList.push_back(cast<Instruction>(InV));
1738       }
1739       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1740     }
1741   } else {
1742     assert(isa<CastInst>(I) && "Unary op should be a cast!");
1743     const Type *RetTy = I.getType();
1744     for (unsigned i = 0; i != NumPHIValues; ++i) {
1745       Value *InV;
1746       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1747         InV = ConstantExpr::getCast(InC, RetTy);
1748       } else {
1749         assert(PN->getIncomingBlock(i) == NonConstBB);
1750         InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1751                            NonConstBB->getTerminator());
1752         WorkList.push_back(cast<Instruction>(InV));
1753       }
1754       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1755     }
1756   }
1757   return ReplaceInstUsesWith(I, NewPN);
1758 }
1759
1760 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1761   bool Changed = SimplifyCommutative(I);
1762   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1763
1764   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1765     // X + undef -> undef
1766     if (isa<UndefValue>(RHS))
1767       return ReplaceInstUsesWith(I, RHS);
1768
1769     // X + 0 --> X
1770     if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1771       if (RHSC->isNullValue())
1772         return ReplaceInstUsesWith(I, LHS);
1773     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1774       if (CFP->isExactlyValue(-0.0))
1775         return ReplaceInstUsesWith(I, LHS);
1776     }
1777
1778     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1779       // X + (signbit) --> X ^ signbit
1780       uint64_t Val = CI->getZExtValue();
1781       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1782         return BinaryOperator::createXor(LHS, RHS);
1783       
1784       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1785       // (X & 254)+1 -> (X&254)|1
1786       uint64_t KnownZero, KnownOne;
1787       if (!isa<PackedType>(I.getType()) &&
1788           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1789                                KnownZero, KnownOne))
1790         return &I;
1791     }
1792
1793     if (isa<PHINode>(LHS))
1794       if (Instruction *NV = FoldOpIntoPhi(I))
1795         return NV;
1796     
1797     ConstantInt *XorRHS = 0;
1798     Value *XorLHS = 0;
1799     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1800       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1801       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1802       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1803       
1804       uint64_t C0080Val = 1ULL << 31;
1805       int64_t CFF80Val = -C0080Val;
1806       unsigned Size = 32;
1807       do {
1808         if (TySizeBits > Size) {
1809           bool Found = false;
1810           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1811           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1812           if (RHSSExt == CFF80Val) {
1813             if (XorRHS->getZExtValue() == C0080Val)
1814               Found = true;
1815           } else if (RHSZExt == C0080Val) {
1816             if (XorRHS->getSExtValue() == CFF80Val)
1817               Found = true;
1818           }
1819           if (Found) {
1820             // This is a sign extend if the top bits are known zero.
1821             uint64_t Mask = ~0ULL;
1822             Mask <<= 64-(TySizeBits-Size);
1823             Mask &= XorLHS->getType()->getIntegralTypeMask();
1824             if (!MaskedValueIsZero(XorLHS, Mask))
1825               Size = 0;  // Not a sign ext, but can't be any others either.
1826             goto FoundSExt;
1827           }
1828         }
1829         Size >>= 1;
1830         C0080Val >>= Size;
1831         CFF80Val >>= Size;
1832       } while (Size >= 8);
1833       
1834 FoundSExt:
1835       const Type *MiddleType = 0;
1836       switch (Size) {
1837       default: break;
1838       case 32: MiddleType = Type::IntTy; break;
1839       case 16: MiddleType = Type::ShortTy; break;
1840       case 8:  MiddleType = Type::SByteTy; break;
1841       }
1842       if (MiddleType) {
1843         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1844         InsertNewInstBefore(NewTrunc, I);
1845         return new CastInst(NewTrunc, I.getType());
1846       }
1847     }
1848   }
1849
1850   // X + X --> X << 1
1851   if (I.getType()->isInteger()) {
1852     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1853
1854     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1855       if (RHSI->getOpcode() == Instruction::Sub)
1856         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1857           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1858     }
1859     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1860       if (LHSI->getOpcode() == Instruction::Sub)
1861         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1862           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1863     }
1864   }
1865
1866   // -A + B  -->  B - A
1867   if (Value *V = dyn_castNegVal(LHS))
1868     return BinaryOperator::createSub(RHS, V);
1869
1870   // A + -B  -->  A - B
1871   if (!isa<Constant>(RHS))
1872     if (Value *V = dyn_castNegVal(RHS))
1873       return BinaryOperator::createSub(LHS, V);
1874
1875
1876   ConstantInt *C2;
1877   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1878     if (X == RHS)   // X*C + X --> X * (C+1)
1879       return BinaryOperator::createMul(RHS, AddOne(C2));
1880
1881     // X*C1 + X*C2 --> X * (C1+C2)
1882     ConstantInt *C1;
1883     if (X == dyn_castFoldableMul(RHS, C1))
1884       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1885   }
1886
1887   // X + X*C --> X * (C+1)
1888   if (dyn_castFoldableMul(RHS, C2) == LHS)
1889     return BinaryOperator::createMul(LHS, AddOne(C2));
1890
1891
1892   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1893   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1894     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1895
1896   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1897     Value *X = 0;
1898     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1899       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1900       return BinaryOperator::createSub(C, X);
1901     }
1902
1903     // (X & FF00) + xx00  -> (X+xx00) & FF00
1904     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1905       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1906       if (Anded == CRHS) {
1907         // See if all bits from the first bit set in the Add RHS up are included
1908         // in the mask.  First, get the rightmost bit.
1909         uint64_t AddRHSV = CRHS->getZExtValue();
1910
1911         // Form a mask of all bits from the lowest bit added through the top.
1912         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1913         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1914
1915         // See if the and mask includes all of these bits.
1916         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1917
1918         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1919           // Okay, the xform is safe.  Insert the new add pronto.
1920           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1921                                                             LHS->getName()), I);
1922           return BinaryOperator::createAnd(NewAdd, C2);
1923         }
1924       }
1925     }
1926
1927     // Try to fold constant add into select arguments.
1928     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1929       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1930         return R;
1931   }
1932
1933   // add (cast *A to intptrtype) B -> 
1934   //   cast (GEP (cast *A to sbyte*) B) -> 
1935   //     intptrtype
1936   {
1937     CastInst* CI = dyn_cast<CastInst>(LHS);
1938     Value* Other = RHS;
1939     if (!CI) {
1940       CI = dyn_cast<CastInst>(RHS);
1941       Other = LHS;
1942     }
1943     if (CI && CI->getType()->isSized() && 
1944         (CI->getType()->getPrimitiveSize() == 
1945          TD->getIntPtrType()->getPrimitiveSize()) 
1946         && isa<PointerType>(CI->getOperand(0)->getType())) {
1947       Value* I2 = InsertCastBefore(CI->getOperand(0),
1948                                    PointerType::get(Type::SByteTy), I);
1949       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1950       return new CastInst(I2, CI->getType());
1951     }
1952   }
1953
1954   return Changed ? &I : 0;
1955 }
1956
1957 // isSignBit - Return true if the value represented by the constant only has the
1958 // highest order bit set.
1959 static bool isSignBit(ConstantInt *CI) {
1960   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1961   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1962 }
1963
1964 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1965 ///
1966 static Value *RemoveNoopCast(Value *V) {
1967   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1968     const Type *CTy = CI->getType();
1969     const Type *OpTy = CI->getOperand(0)->getType();
1970     if (CTy->isInteger() && OpTy->isInteger()) {
1971       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1972         return RemoveNoopCast(CI->getOperand(0));
1973     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1974       return RemoveNoopCast(CI->getOperand(0));
1975   }
1976   return V;
1977 }
1978
1979 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1980   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1981
1982   if (Op0 == Op1)         // sub X, X  -> 0
1983     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1984
1985   // If this is a 'B = x-(-A)', change to B = x+A...
1986   if (Value *V = dyn_castNegVal(Op1))
1987     return BinaryOperator::createAdd(Op0, V);
1988
1989   if (isa<UndefValue>(Op0))
1990     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1991   if (isa<UndefValue>(Op1))
1992     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1993
1994   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1995     // Replace (-1 - A) with (~A)...
1996     if (C->isAllOnesValue())
1997       return BinaryOperator::createNot(Op1);
1998
1999     // C - ~X == X + (1+C)
2000     Value *X = 0;
2001     if (match(Op1, m_Not(m_Value(X))))
2002       return BinaryOperator::createAdd(X,
2003                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2004     // -((uint)X >> 31) -> ((int)X >> 31)
2005     // -((int)X >> 31) -> ((uint)X >> 31)
2006     if (C->isNullValue()) {
2007       Value *NoopCastedRHS = RemoveNoopCast(Op1);
2008       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
2009         if (SI->getOpcode() == Instruction::LShr) {
2010           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2011             // Check to see if we are shifting out everything but the sign bit.
2012             if (CU->getZExtValue() == 
2013                 SI->getType()->getPrimitiveSizeInBits()-1) {
2014               // Ok, the transformation is safe.  Insert AShr.
2015               return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2016                                     CU, SI->getName());
2017             }
2018           }
2019         }
2020         else if (SI->getOpcode() == Instruction::AShr) {
2021           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2022             // Check to see if we are shifting out everything but the sign bit.
2023             if (CU->getZExtValue() == 
2024                 SI->getType()->getPrimitiveSizeInBits()-1) {
2025               // Ok, the transformation is safe.  Insert LShr.
2026               return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2027                                     CU, SI->getName());
2028             }
2029           }
2030         } 
2031     }
2032
2033     // Try to fold constant sub into select arguments.
2034     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2035       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2036         return R;
2037
2038     if (isa<PHINode>(Op0))
2039       if (Instruction *NV = FoldOpIntoPhi(I))
2040         return NV;
2041   }
2042
2043   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2044     if (Op1I->getOpcode() == Instruction::Add &&
2045         !Op0->getType()->isFloatingPoint()) {
2046       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2047         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2048       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2049         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2050       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2051         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2052           // C1-(X+C2) --> (C1-C2)-X
2053           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2054                                            Op1I->getOperand(0));
2055       }
2056     }
2057
2058     if (Op1I->hasOneUse()) {
2059       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2060       // is not used by anyone else...
2061       //
2062       if (Op1I->getOpcode() == Instruction::Sub &&
2063           !Op1I->getType()->isFloatingPoint()) {
2064         // Swap the two operands of the subexpr...
2065         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2066         Op1I->setOperand(0, IIOp1);
2067         Op1I->setOperand(1, IIOp0);
2068
2069         // Create the new top level add instruction...
2070         return BinaryOperator::createAdd(Op0, Op1);
2071       }
2072
2073       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2074       //
2075       if (Op1I->getOpcode() == Instruction::And &&
2076           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2077         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2078
2079         Value *NewNot =
2080           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2081         return BinaryOperator::createAnd(Op0, NewNot);
2082       }
2083
2084       // 0 - (X sdiv C)  -> (X sdiv -C)
2085       if (Op1I->getOpcode() == Instruction::SDiv)
2086         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2087           if (CSI->isNullValue())
2088             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2089               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2090                                                ConstantExpr::getNeg(DivRHS));
2091
2092       // X - X*C --> X * (1-C)
2093       ConstantInt *C2 = 0;
2094       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2095         Constant *CP1 =
2096           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2097         return BinaryOperator::createMul(Op0, CP1);
2098       }
2099     }
2100   }
2101
2102   if (!Op0->getType()->isFloatingPoint())
2103     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2104       if (Op0I->getOpcode() == Instruction::Add) {
2105         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2106           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2107         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2108           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2109       } else if (Op0I->getOpcode() == Instruction::Sub) {
2110         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2111           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2112       }
2113
2114   ConstantInt *C1;
2115   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2116     if (X == Op1) { // X*C - X --> X * (C-1)
2117       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2118       return BinaryOperator::createMul(Op1, CP1);
2119     }
2120
2121     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2122     if (X == dyn_castFoldableMul(Op1, C2))
2123       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2124   }
2125   return 0;
2126 }
2127
2128 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2129 /// really just returns true if the most significant (sign) bit is set.
2130 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2131   if (RHS->getType()->isSigned()) {
2132     // True if source is LHS < 0 or LHS <= -1
2133     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2134            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2135   } else {
2136     ConstantInt *RHSC = cast<ConstantInt>(RHS);
2137     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2138     // the size of the integer type.
2139     if (Opcode == Instruction::SetGE)
2140       return RHSC->getZExtValue() ==
2141         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2142     if (Opcode == Instruction::SetGT)
2143       return RHSC->getZExtValue() ==
2144         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2145   }
2146   return false;
2147 }
2148
2149 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2150   bool Changed = SimplifyCommutative(I);
2151   Value *Op0 = I.getOperand(0);
2152
2153   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2154     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2155
2156   // Simplify mul instructions with a constant RHS...
2157   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2158     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2159
2160       // ((X << C1)*C2) == (X * (C2 << C1))
2161       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2162         if (SI->getOpcode() == Instruction::Shl)
2163           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2164             return BinaryOperator::createMul(SI->getOperand(0),
2165                                              ConstantExpr::getShl(CI, ShOp));
2166
2167       if (CI->isNullValue())
2168         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2169       if (CI->equalsInt(1))                  // X * 1  == X
2170         return ReplaceInstUsesWith(I, Op0);
2171       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2172         return BinaryOperator::createNeg(Op0, I.getName());
2173
2174       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2175       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2176         uint64_t C = Log2_64(Val);
2177         return new ShiftInst(Instruction::Shl, Op0,
2178                              ConstantInt::get(Type::UByteTy, C));
2179       }
2180     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2181       if (Op1F->isNullValue())
2182         return ReplaceInstUsesWith(I, Op1);
2183
2184       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2185       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2186       if (Op1F->getValue() == 1.0)
2187         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2188     }
2189     
2190     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2191       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2192           isa<ConstantInt>(Op0I->getOperand(1))) {
2193         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2194         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2195                                                      Op1, "tmp");
2196         InsertNewInstBefore(Add, I);
2197         Value *C1C2 = ConstantExpr::getMul(Op1, 
2198                                            cast<Constant>(Op0I->getOperand(1)));
2199         return BinaryOperator::createAdd(Add, C1C2);
2200         
2201       }
2202
2203     // Try to fold constant mul into select arguments.
2204     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2205       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2206         return R;
2207
2208     if (isa<PHINode>(Op0))
2209       if (Instruction *NV = FoldOpIntoPhi(I))
2210         return NV;
2211   }
2212
2213   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2214     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2215       return BinaryOperator::createMul(Op0v, Op1v);
2216
2217   // If one of the operands of the multiply is a cast from a boolean value, then
2218   // we know the bool is either zero or one, so this is a 'masking' multiply.
2219   // See if we can simplify things based on how the boolean was originally
2220   // formed.
2221   CastInst *BoolCast = 0;
2222   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2223     if (CI->getOperand(0)->getType() == Type::BoolTy)
2224       BoolCast = CI;
2225   if (!BoolCast)
2226     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2227       if (CI->getOperand(0)->getType() == Type::BoolTy)
2228         BoolCast = CI;
2229   if (BoolCast) {
2230     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2231       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2232       const Type *SCOpTy = SCIOp0->getType();
2233
2234       // If the setcc is true iff the sign bit of X is set, then convert this
2235       // multiply into a shift/and combination.
2236       if (isa<ConstantInt>(SCIOp1) &&
2237           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2238         // Shift the X value right to turn it into "all signbits".
2239         Constant *Amt = ConstantInt::get(Type::UByteTy,
2240                                           SCOpTy->getPrimitiveSizeInBits()-1);
2241         if (SCIOp0->getType()->isUnsigned()) {
2242           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2243           SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
2244         }
2245
2246         Value *V =
2247           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2248                                             BoolCast->getOperand(0)->getName()+
2249                                             ".mask"), I);
2250
2251         // If the multiply type is not the same as the source type, sign extend
2252         // or truncate to the multiply type.
2253         if (I.getType() != V->getType())
2254           V = InsertCastBefore(V, I.getType(), I);
2255
2256         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2257         return BinaryOperator::createAnd(V, OtherOp);
2258       }
2259     }
2260   }
2261
2262   return Changed ? &I : 0;
2263 }
2264
2265 /// This function implements the transforms on div instructions that work
2266 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2267 /// used by the visitors to those instructions.
2268 /// @brief Transforms common to all three div instructions
2269 Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
2270   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2271
2272   // undef / X -> 0
2273   if (isa<UndefValue>(Op0))
2274     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2275
2276   // X / undef -> undef
2277   if (isa<UndefValue>(Op1))
2278     return ReplaceInstUsesWith(I, Op1);
2279
2280   // Handle cases involving: div X, (select Cond, Y, Z)
2281   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2282     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2283     // same basic block, then we replace the select with Y, and the condition 
2284     // of the select with false (if the cond value is in the same BB).  If the
2285     // select has uses other than the div, this allows them to be simplified
2286     // also. Note that div X, Y is just as good as div X, 0 (undef)
2287     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2288       if (ST->isNullValue()) {
2289         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2290         if (CondI && CondI->getParent() == I.getParent())
2291           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2292         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2293           I.setOperand(1, SI->getOperand(2));
2294         else
2295           UpdateValueUsesWith(SI, SI->getOperand(2));
2296         return &I;
2297       }
2298
2299     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2300     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2301       if (ST->isNullValue()) {
2302         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2303         if (CondI && CondI->getParent() == I.getParent())
2304           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2305         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2306           I.setOperand(1, SI->getOperand(1));
2307         else
2308           UpdateValueUsesWith(SI, SI->getOperand(1));
2309         return &I;
2310       }
2311   }
2312
2313   return 0;
2314 }
2315
2316 /// This function implements the transforms common to both integer division
2317 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2318 /// division instructions.
2319 /// @brief Common integer divide transforms
2320 Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2321   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2322
2323   if (Instruction *Common = commonDivTransforms(I))
2324     return Common;
2325
2326   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2327     // div X, 1 == X
2328     if (RHS->equalsInt(1))
2329       return ReplaceInstUsesWith(I, Op0);
2330
2331     // (X / C1) / C2  -> X / (C1*C2)
2332     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2333       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2334         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2335           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2336                                         ConstantExpr::getMul(RHS, LHSRHS));
2337         }
2338
2339     if (!RHS->isNullValue()) { // avoid X udiv 0
2340       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2341         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2342           return R;
2343       if (isa<PHINode>(Op0))
2344         if (Instruction *NV = FoldOpIntoPhi(I))
2345           return NV;
2346     }
2347   }
2348
2349   // 0 / X == 0, we don't need to preserve faults!
2350   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2351     if (LHS->equalsInt(0))
2352       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2353
2354   return 0;
2355 }
2356
2357 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2359
2360   // Handle the integer div common cases
2361   if (Instruction *Common = commonIDivTransforms(I))
2362     return Common;
2363
2364   // X udiv C^2 -> X >> C
2365   // Check to see if this is an unsigned division with an exact power of 2,
2366   // if so, convert to a right shift.
2367   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2368     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2369       if (isPowerOf2_64(Val)) {
2370         uint64_t ShiftAmt = Log2_64(Val);
2371         return new ShiftInst(Instruction::LShr, Op0, 
2372                               ConstantInt::get(Type::UByteTy, ShiftAmt));
2373       }
2374   }
2375
2376   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2377   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2378     if (RHSI->getOpcode() == Instruction::Shl &&
2379         isa<ConstantInt>(RHSI->getOperand(0))) {
2380       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2381       if (isPowerOf2_64(C1)) {
2382         Value *N = RHSI->getOperand(1);
2383         const Type* NTy = N->getType();
2384         if (uint64_t C2 = Log2_64(C1)) {
2385           Constant *C2V = ConstantInt::get(NTy, C2);
2386           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2387         }
2388         return new ShiftInst(Instruction::LShr, Op0, N);
2389       }
2390     }
2391   }
2392   
2393   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2394   // where C1&C2 are powers of two.
2395   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2396     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2397       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2398         if (!STO->isNullValue() && !STO->isNullValue()) {
2399           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2400           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2401             // Compute the shift amounts
2402             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2403             // Construct the "on true" case of the select
2404             Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2405             Instruction *TSI = 
2406               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2407             TSI = InsertNewInstBefore(TSI, I);
2408     
2409             // Construct the "on false" case of the select
2410             Constant *FC = ConstantInt::get(Type::UByteTy, FSA); 
2411             Instruction *FSI = 
2412               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2413             FSI = InsertNewInstBefore(FSI, I);
2414
2415             // construct the select instruction and return it.
2416             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2417           }
2418         }
2419   }
2420   return 0;
2421 }
2422
2423 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2424   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2425
2426   // Handle the integer div common cases
2427   if (Instruction *Common = commonIDivTransforms(I))
2428     return Common;
2429
2430   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2431     // sdiv X, -1 == -X
2432     if (RHS->isAllOnesValue())
2433       return BinaryOperator::createNeg(Op0);
2434
2435     // -X/C -> X/-C
2436     if (Value *LHSNeg = dyn_castNegVal(Op0))
2437       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2438   }
2439
2440   // If the sign bits of both operands are zero (i.e. we can prove they are
2441   // unsigned inputs), turn this into a udiv.
2442   if (I.getType()->isInteger()) {
2443     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2444     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2445       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2446     }
2447   }      
2448   
2449   return 0;
2450 }
2451
2452 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2453   return commonDivTransforms(I);
2454 }
2455
2456 /// GetFactor - If we can prove that the specified value is at least a multiple
2457 /// of some factor, return that factor.
2458 static Constant *GetFactor(Value *V) {
2459   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2460     return CI;
2461   
2462   // Unless we can be tricky, we know this is a multiple of 1.
2463   Constant *Result = ConstantInt::get(V->getType(), 1);
2464   
2465   Instruction *I = dyn_cast<Instruction>(V);
2466   if (!I) return Result;
2467   
2468   if (I->getOpcode() == Instruction::Mul) {
2469     // Handle multiplies by a constant, etc.
2470     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2471                                 GetFactor(I->getOperand(1)));
2472   } else if (I->getOpcode() == Instruction::Shl) {
2473     // (X<<C) -> X * (1 << C)
2474     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2475       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2476       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2477     }
2478   } else if (I->getOpcode() == Instruction::And) {
2479     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2480       // X & 0xFFF0 is known to be a multiple of 16.
2481       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2482       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2483         return ConstantExpr::getShl(Result, 
2484                                     ConstantInt::get(Type::UByteTy, Zeros));
2485     }
2486   } else if (I->getOpcode() == Instruction::Cast) {
2487     Value *Op = I->getOperand(0);
2488     // Only handle int->int casts.
2489     if (!Op->getType()->isInteger()) return Result;
2490     return ConstantExpr::getCast(GetFactor(Op), V->getType());
2491   }    
2492   return Result;
2493 }
2494
2495 /// This function implements the transforms on rem instructions that work
2496 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2497 /// is used by the visitors to those instructions.
2498 /// @brief Transforms common to all three rem instructions
2499 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2500   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2501
2502   // 0 % X == 0, we don't need to preserve faults!
2503   if (Constant *LHS = dyn_cast<Constant>(Op0))
2504     if (LHS->isNullValue())
2505       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2506
2507   if (isa<UndefValue>(Op0))              // undef % X -> 0
2508     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2509   if (isa<UndefValue>(Op1))
2510     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2511
2512   // Handle cases involving: rem X, (select Cond, Y, Z)
2513   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2514     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2515     // the same basic block, then we replace the select with Y, and the
2516     // condition of the select with false (if the cond value is in the same
2517     // BB).  If the select has uses other than the div, this allows them to be
2518     // simplified also.
2519     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2520       if (ST->isNullValue()) {
2521         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2522         if (CondI && CondI->getParent() == I.getParent())
2523           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2524         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2525           I.setOperand(1, SI->getOperand(2));
2526         else
2527           UpdateValueUsesWith(SI, SI->getOperand(2));
2528         return &I;
2529       }
2530     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2531     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2532       if (ST->isNullValue()) {
2533         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2534         if (CondI && CondI->getParent() == I.getParent())
2535           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2536         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2537           I.setOperand(1, SI->getOperand(1));
2538         else
2539           UpdateValueUsesWith(SI, SI->getOperand(1));
2540         return &I;
2541       }
2542   }
2543
2544   return 0;
2545 }
2546
2547 /// This function implements the transforms common to both integer remainder
2548 /// instructions (urem and srem). It is called by the visitors to those integer
2549 /// remainder instructions.
2550 /// @brief Common integer remainder transforms
2551 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2552   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2553
2554   if (Instruction *common = commonRemTransforms(I))
2555     return common;
2556
2557   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2558     // X % 0 == undef, we don't need to preserve faults!
2559     if (RHS->equalsInt(0))
2560       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2561     
2562     if (RHS->equalsInt(1))  // X % 1 == 0
2563       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2564
2565     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2566       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2567         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2568           return R;
2569       } else if (isa<PHINode>(Op0I)) {
2570         if (Instruction *NV = FoldOpIntoPhi(I))
2571           return NV;
2572       }
2573       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2574       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2575         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2576     }
2577   }
2578
2579   return 0;
2580 }
2581
2582 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2583   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2584
2585   if (Instruction *common = commonIRemTransforms(I))
2586     return common;
2587   
2588   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2589     // X urem C^2 -> X and C
2590     // Check to see if this is an unsigned remainder with an exact power of 2,
2591     // if so, convert to a bitwise and.
2592     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2593       if (isPowerOf2_64(C->getZExtValue()))
2594         return BinaryOperator::createAnd(Op0, SubOne(C));
2595   }
2596
2597   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2598     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2599     if (RHSI->getOpcode() == Instruction::Shl &&
2600         isa<ConstantInt>(RHSI->getOperand(0))) {
2601       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2602       if (isPowerOf2_64(C1)) {
2603         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2604         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2605                                                                    "tmp"), I);
2606         return BinaryOperator::createAnd(Op0, Add);
2607       }
2608     }
2609   }
2610
2611   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2612   // where C1&C2 are powers of two.
2613   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2614     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2615       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2616         // STO == 0 and SFO == 0 handled above.
2617         if (isPowerOf2_64(STO->getZExtValue()) && 
2618             isPowerOf2_64(SFO->getZExtValue())) {
2619           Value *TrueAnd = InsertNewInstBefore(
2620             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2621           Value *FalseAnd = InsertNewInstBefore(
2622             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2623           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2624         }
2625       }
2626   }
2627   
2628   return 0;
2629 }
2630
2631 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2632   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2633
2634   if (Instruction *common = commonIRemTransforms(I))
2635     return common;
2636   
2637   if (Value *RHSNeg = dyn_castNegVal(Op1))
2638     if (!isa<ConstantInt>(RHSNeg) || 
2639         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2640       // X % -Y -> X % Y
2641       AddUsesToWorkList(I);
2642       I.setOperand(1, RHSNeg);
2643       return &I;
2644     }
2645  
2646   // If the top bits of both operands are zero (i.e. we can prove they are
2647   // unsigned inputs), turn this into a urem.
2648   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2649   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2650     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2651     return BinaryOperator::createURem(Op0, Op1, I.getName());
2652   }
2653
2654   return 0;
2655 }
2656
2657 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2658   return commonRemTransforms(I);
2659 }
2660
2661 // isMaxValueMinusOne - return true if this is Max-1
2662 static bool isMaxValueMinusOne(const ConstantInt *C) {
2663   if (C->getType()->isUnsigned()) 
2664     return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2665
2666   // Calculate 0111111111..11111
2667   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2668   int64_t Val = INT64_MAX;             // All ones
2669   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2670   return C->getSExtValue() == Val-1;
2671 }
2672
2673 // isMinValuePlusOne - return true if this is Min+1
2674 static bool isMinValuePlusOne(const ConstantInt *C) {
2675   if (C->getType()->isUnsigned())
2676     return C->getZExtValue() == 1;
2677
2678   // Calculate 1111111111000000000000
2679   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2680   int64_t Val = -1;                    // All ones
2681   Val <<= TypeBits-1;                  // Shift over to the right spot
2682   return C->getSExtValue() == Val+1;
2683 }
2684
2685 // isOneBitSet - Return true if there is exactly one bit set in the specified
2686 // constant.
2687 static bool isOneBitSet(const ConstantInt *CI) {
2688   uint64_t V = CI->getZExtValue();
2689   return V && (V & (V-1)) == 0;
2690 }
2691
2692 #if 0   // Currently unused
2693 // isLowOnes - Return true if the constant is of the form 0+1+.
2694 static bool isLowOnes(const ConstantInt *CI) {
2695   uint64_t V = CI->getZExtValue();
2696
2697   // There won't be bits set in parts that the type doesn't contain.
2698   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2699
2700   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2701   return U && V && (U & V) == 0;
2702 }
2703 #endif
2704
2705 // isHighOnes - Return true if the constant is of the form 1+0+.
2706 // This is the same as lowones(~X).
2707 static bool isHighOnes(const ConstantInt *CI) {
2708   uint64_t V = ~CI->getZExtValue();
2709   if (~V == 0) return false;  // 0's does not match "1+"
2710
2711   // There won't be bits set in parts that the type doesn't contain.
2712   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2713
2714   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2715   return U && V && (U & V) == 0;
2716 }
2717
2718
2719 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
2720 /// are carefully arranged to allow folding of expressions such as:
2721 ///
2722 ///      (A < B) | (A > B) --> (A != B)
2723 ///
2724 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2725 /// represents that the comparison is true if A == B, and bit value '1' is true
2726 /// if A < B.
2727 ///
2728 static unsigned getSetCondCode(const SetCondInst *SCI) {
2729   switch (SCI->getOpcode()) {
2730     // False -> 0
2731   case Instruction::SetGT: return 1;
2732   case Instruction::SetEQ: return 2;
2733   case Instruction::SetGE: return 3;
2734   case Instruction::SetLT: return 4;
2735   case Instruction::SetNE: return 5;
2736   case Instruction::SetLE: return 6;
2737     // True -> 7
2738   default:
2739     assert(0 && "Invalid SetCC opcode!");
2740     return 0;
2741   }
2742 }
2743
2744 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2745 /// opcode and two operands into either a constant true or false, or a brand new
2746 /// SetCC instruction.
2747 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2748   switch (Opcode) {
2749   case 0: return ConstantBool::getFalse();
2750   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2751   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2752   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2753   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2754   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2755   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2756   case 7: return ConstantBool::getTrue();
2757   default: assert(0 && "Illegal SetCCCode!"); return 0;
2758   }
2759 }
2760
2761 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2762 namespace {
2763 struct FoldSetCCLogical {
2764   InstCombiner &IC;
2765   Value *LHS, *RHS;
2766   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2767     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2768   bool shouldApply(Value *V) const {
2769     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2770       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2771               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2772     return false;
2773   }
2774   Instruction *apply(BinaryOperator &Log) const {
2775     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2776     if (SCI->getOperand(0) != LHS) {
2777       assert(SCI->getOperand(1) == LHS);
2778       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2779     }
2780
2781     unsigned LHSCode = getSetCondCode(SCI);
2782     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2783     unsigned Code;
2784     switch (Log.getOpcode()) {
2785     case Instruction::And: Code = LHSCode & RHSCode; break;
2786     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2787     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2788     default: assert(0 && "Illegal logical opcode!"); return 0;
2789     }
2790
2791     Value *RV = getSetCCValue(Code, LHS, RHS);
2792     if (Instruction *I = dyn_cast<Instruction>(RV))
2793       return I;
2794     // Otherwise, it's a constant boolean value...
2795     return IC.ReplaceInstUsesWith(Log, RV);
2796   }
2797 };
2798 } // end anonymous namespace
2799
2800 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2801 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2802 // guaranteed to be either a shift instruction or a binary operator.
2803 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2804                                     ConstantIntegral *OpRHS,
2805                                     ConstantIntegral *AndRHS,
2806                                     BinaryOperator &TheAnd) {
2807   Value *X = Op->getOperand(0);
2808   Constant *Together = 0;
2809   if (!isa<ShiftInst>(Op))
2810     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2811
2812   switch (Op->getOpcode()) {
2813   case Instruction::Xor:
2814     if (Op->hasOneUse()) {
2815       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2816       std::string OpName = Op->getName(); Op->setName("");
2817       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2818       InsertNewInstBefore(And, TheAnd);
2819       return BinaryOperator::createXor(And, Together);
2820     }
2821     break;
2822   case Instruction::Or:
2823     if (Together == AndRHS) // (X | C) & C --> C
2824       return ReplaceInstUsesWith(TheAnd, AndRHS);
2825
2826     if (Op->hasOneUse() && Together != OpRHS) {
2827       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2828       std::string Op0Name = Op->getName(); Op->setName("");
2829       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2830       InsertNewInstBefore(Or, TheAnd);
2831       return BinaryOperator::createAnd(Or, AndRHS);
2832     }
2833     break;
2834   case Instruction::Add:
2835     if (Op->hasOneUse()) {
2836       // Adding a one to a single bit bit-field should be turned into an XOR
2837       // of the bit.  First thing to check is to see if this AND is with a
2838       // single bit constant.
2839       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2840
2841       // Clear bits that are not part of the constant.
2842       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2843
2844       // If there is only one bit set...
2845       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2846         // Ok, at this point, we know that we are masking the result of the
2847         // ADD down to exactly one bit.  If the constant we are adding has
2848         // no bits set below this bit, then we can eliminate the ADD.
2849         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2850
2851         // Check to see if any bits below the one bit set in AndRHSV are set.
2852         if ((AddRHS & (AndRHSV-1)) == 0) {
2853           // If not, the only thing that can effect the output of the AND is
2854           // the bit specified by AndRHSV.  If that bit is set, the effect of
2855           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2856           // no effect.
2857           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2858             TheAnd.setOperand(0, X);
2859             return &TheAnd;
2860           } else {
2861             std::string Name = Op->getName(); Op->setName("");
2862             // Pull the XOR out of the AND.
2863             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2864             InsertNewInstBefore(NewAnd, TheAnd);
2865             return BinaryOperator::createXor(NewAnd, AndRHS);
2866           }
2867         }
2868       }
2869     }
2870     break;
2871
2872   case Instruction::Shl: {
2873     // We know that the AND will not produce any of the bits shifted in, so if
2874     // the anded constant includes them, clear them now!
2875     //
2876     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2877     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2878     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2879
2880     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2881       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2882     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2883       TheAnd.setOperand(1, CI);
2884       return &TheAnd;
2885     }
2886     break;
2887   }
2888   case Instruction::LShr:
2889   {
2890     // We know that the AND will not produce any of the bits shifted in, so if
2891     // the anded constant includes them, clear them now!  This only applies to
2892     // unsigned shifts, because a signed shr may bring in set bits!
2893     //
2894     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2895     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2896     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2897
2898     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2899       return ReplaceInstUsesWith(TheAnd, Op);
2900     } else if (CI != AndRHS) {
2901       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2902       return &TheAnd;
2903     }
2904     break;
2905   }
2906   case Instruction::AShr:
2907     // Signed shr.
2908     // See if this is shifting in some sign extension, then masking it out
2909     // with an and.
2910     if (Op->hasOneUse()) {
2911       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2912       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2913       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2914       if (CI == AndRHS) {          // Masking out bits shifted in.
2915         // Make the argument unsigned.
2916         Value *ShVal = Op->getOperand(0);
2917         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2918                                                   OpRHS, Op->getName()),
2919                                     TheAnd);
2920         Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2921         return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
2922       }
2923     }
2924     break;
2925   }
2926   return 0;
2927 }
2928
2929
2930 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2931 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2932 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2933 /// insert new instructions.
2934 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2935                                            bool Inside, Instruction &IB) {
2936   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2937          "Lo is not <= Hi in range emission code!");
2938   if (Inside) {
2939     if (Lo == Hi)  // Trivially false.
2940       return new SetCondInst(Instruction::SetNE, V, V);
2941     if (cast<ConstantIntegral>(Lo)->isMinValue())
2942       return new SetCondInst(Instruction::SetLT, V, Hi);
2943
2944     Constant *AddCST = ConstantExpr::getNeg(Lo);
2945     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2946     InsertNewInstBefore(Add, IB);
2947     // Convert to unsigned for the comparison.
2948     const Type *UnsType = Add->getType()->getUnsignedVersion();
2949     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2950     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2951     AddCST = ConstantExpr::getCast(AddCST, UnsType);
2952     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2953   }
2954
2955   if (Lo == Hi)  // Trivially true.
2956     return new SetCondInst(Instruction::SetEQ, V, V);
2957
2958   Hi = SubOne(cast<ConstantInt>(Hi));
2959
2960   // V < 0 || V >= Hi ->'V > Hi-1'
2961   if (cast<ConstantIntegral>(Lo)->isMinValue())
2962     return new SetCondInst(Instruction::SetGT, V, Hi);
2963
2964   // Emit X-Lo > Hi-Lo-1
2965   Constant *AddCST = ConstantExpr::getNeg(Lo);
2966   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2967   InsertNewInstBefore(Add, IB);
2968   // Convert to unsigned for the comparison.
2969   const Type *UnsType = Add->getType()->getUnsignedVersion();
2970   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2971   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2972   AddCST = ConstantExpr::getCast(AddCST, UnsType);
2973   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2974 }
2975
2976 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2977 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2978 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2979 // not, since all 1s are not contiguous.
2980 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2981   uint64_t V = Val->getZExtValue();
2982   if (!isShiftedMask_64(V)) return false;
2983
2984   // look for the first zero bit after the run of ones
2985   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2986   // look for the first non-zero bit
2987   ME = 64-CountLeadingZeros_64(V);
2988   return true;
2989 }
2990
2991
2992
2993 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2994 /// where isSub determines whether the operator is a sub.  If we can fold one of
2995 /// the following xforms:
2996 /// 
2997 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2998 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2999 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3000 ///
3001 /// return (A +/- B).
3002 ///
3003 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3004                                         ConstantIntegral *Mask, bool isSub,
3005                                         Instruction &I) {
3006   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3007   if (!LHSI || LHSI->getNumOperands() != 2 ||
3008       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3009
3010   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3011
3012   switch (LHSI->getOpcode()) {
3013   default: return 0;
3014   case Instruction::And:
3015     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3016       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3017       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3018         break;
3019
3020       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3021       // part, we don't need any explicit masks to take them out of A.  If that
3022       // is all N is, ignore it.
3023       unsigned MB, ME;
3024       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3025         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3026         Mask >>= 64-MB+1;
3027         if (MaskedValueIsZero(RHS, Mask))
3028           break;
3029       }
3030     }
3031     return 0;
3032   case Instruction::Or:
3033   case Instruction::Xor:
3034     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3035     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3036         ConstantExpr::getAnd(N, Mask)->isNullValue())
3037       break;
3038     return 0;
3039   }
3040   
3041   Instruction *New;
3042   if (isSub)
3043     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3044   else
3045     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3046   return InsertNewInstBefore(New, I);
3047 }
3048
3049 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3050   bool Changed = SimplifyCommutative(I);
3051   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3052
3053   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3054     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3055
3056   // and X, X = X
3057   if (Op0 == Op1)
3058     return ReplaceInstUsesWith(I, Op1);
3059
3060   // See if we can simplify any instructions used by the instruction whose sole 
3061   // purpose is to compute bits we don't care about.
3062   uint64_t KnownZero, KnownOne;
3063   if (!isa<PackedType>(I.getType()) &&
3064       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3065                            KnownZero, KnownOne))
3066     return &I;
3067   
3068   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3069     uint64_t AndRHSMask = AndRHS->getZExtValue();
3070     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3071     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3072
3073     // Optimize a variety of ((val OP C1) & C2) combinations...
3074     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3075       Instruction *Op0I = cast<Instruction>(Op0);
3076       Value *Op0LHS = Op0I->getOperand(0);
3077       Value *Op0RHS = Op0I->getOperand(1);
3078       switch (Op0I->getOpcode()) {
3079       case Instruction::Xor:
3080       case Instruction::Or:
3081         // If the mask is only needed on one incoming arm, push it up.
3082         if (Op0I->hasOneUse()) {
3083           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3084             // Not masking anything out for the LHS, move to RHS.
3085             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3086                                                    Op0RHS->getName()+".masked");
3087             InsertNewInstBefore(NewRHS, I);
3088             return BinaryOperator::create(
3089                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3090           }
3091           if (!isa<Constant>(Op0RHS) &&
3092               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3093             // Not masking anything out for the RHS, move to LHS.
3094             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3095                                                    Op0LHS->getName()+".masked");
3096             InsertNewInstBefore(NewLHS, I);
3097             return BinaryOperator::create(
3098                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3099           }
3100         }
3101
3102         break;
3103       case Instruction::Add:
3104         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3105         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3106         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3107         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3108           return BinaryOperator::createAnd(V, AndRHS);
3109         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3110           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3111         break;
3112
3113       case Instruction::Sub:
3114         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3115         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3116         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3117         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3118           return BinaryOperator::createAnd(V, AndRHS);
3119         break;
3120       }
3121
3122       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3123         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3124           return Res;
3125     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3126       const Type *SrcTy = CI->getOperand(0)->getType();
3127
3128       // If this is an integer truncation or change from signed-to-unsigned, and
3129       // if the source is an and/or with immediate, transform it.  This
3130       // frequently occurs for bitfield accesses.
3131       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3132         if (SrcTy->getPrimitiveSizeInBits() >= 
3133               I.getType()->getPrimitiveSizeInBits() &&
3134             CastOp->getNumOperands() == 2)
3135           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3136             if (CastOp->getOpcode() == Instruction::And) {
3137               // Change: and (cast (and X, C1) to T), C2
3138               // into  : and (cast X to T), trunc(C1)&C2
3139               // This will folds the two ands together, which may allow other
3140               // simplifications.
3141               Instruction *NewCast =
3142                 new CastInst(CastOp->getOperand(0), I.getType(),
3143                              CastOp->getName()+".shrunk");
3144               NewCast = InsertNewInstBefore(NewCast, I);
3145               
3146               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3147               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
3148               return BinaryOperator::createAnd(NewCast, C3);
3149             } else if (CastOp->getOpcode() == Instruction::Or) {
3150               // Change: and (cast (or X, C1) to T), C2
3151               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3152               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3153               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3154                 return ReplaceInstUsesWith(I, AndRHS);
3155             }
3156       }
3157     }
3158
3159     // Try to fold constant and into select arguments.
3160     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3161       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3162         return R;
3163     if (isa<PHINode>(Op0))
3164       if (Instruction *NV = FoldOpIntoPhi(I))
3165         return NV;
3166   }
3167
3168   Value *Op0NotVal = dyn_castNotVal(Op0);
3169   Value *Op1NotVal = dyn_castNotVal(Op1);
3170
3171   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3172     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3173
3174   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3175   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3176     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3177                                                I.getName()+".demorgan");
3178     InsertNewInstBefore(Or, I);
3179     return BinaryOperator::createNot(Or);
3180   }
3181   
3182   {
3183     Value *A = 0, *B = 0;
3184     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3185       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3186         return ReplaceInstUsesWith(I, Op1);
3187     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3188       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3189         return ReplaceInstUsesWith(I, Op0);
3190     
3191     if (Op0->hasOneUse() &&
3192         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3193       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3194         I.swapOperands();     // Simplify below
3195         std::swap(Op0, Op1);
3196       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3197         cast<BinaryOperator>(Op0)->swapOperands();
3198         I.swapOperands();     // Simplify below
3199         std::swap(Op0, Op1);
3200       }
3201     }
3202     if (Op1->hasOneUse() &&
3203         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3204       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3205         cast<BinaryOperator>(Op1)->swapOperands();
3206         std::swap(A, B);
3207       }
3208       if (A == Op0) {                                // A&(A^B) -> A & ~B
3209         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3210         InsertNewInstBefore(NotB, I);
3211         return BinaryOperator::createAnd(A, NotB);
3212       }
3213     }
3214   }
3215   
3216
3217   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3218     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3219     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3220       return R;
3221
3222     Value *LHSVal, *RHSVal;
3223     ConstantInt *LHSCst, *RHSCst;
3224     Instruction::BinaryOps LHSCC, RHSCC;
3225     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3226       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3227         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
3228             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3229             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3230             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3231           // Ensure that the larger constant is on the RHS.
3232           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3233           SetCondInst *LHS = cast<SetCondInst>(Op0);
3234           if (cast<ConstantBool>(Cmp)->getValue()) {
3235             std::swap(LHS, RHS);
3236             std::swap(LHSCst, RHSCst);
3237             std::swap(LHSCC, RHSCC);
3238           }
3239
3240           // At this point, we know we have have two setcc instructions
3241           // comparing a value against two constants and and'ing the result
3242           // together.  Because of the above check, we know that we only have
3243           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3244           // FoldSetCCLogical check above), that the two constants are not
3245           // equal.
3246           assert(LHSCst != RHSCst && "Compares not folded above?");
3247
3248           switch (LHSCC) {
3249           default: assert(0 && "Unknown integer condition code!");
3250           case Instruction::SetEQ:
3251             switch (RHSCC) {
3252             default: assert(0 && "Unknown integer condition code!");
3253             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
3254             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
3255               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3256             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
3257             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
3258               return ReplaceInstUsesWith(I, LHS);
3259             }
3260           case Instruction::SetNE:
3261             switch (RHSCC) {
3262             default: assert(0 && "Unknown integer condition code!");
3263             case Instruction::SetLT:
3264               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3265                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3266               break;                        // (X != 13 & X < 15) -> no change
3267             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
3268             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
3269               return ReplaceInstUsesWith(I, RHS);
3270             case Instruction::SetNE:
3271               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3272                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3273                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3274                                                       LHSVal->getName()+".off");
3275                 InsertNewInstBefore(Add, I);
3276                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3277                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3278                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3279                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3280                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3281               }
3282               break;                        // (X != 13 & X != 15) -> no change
3283             }
3284             break;
3285           case Instruction::SetLT:
3286             switch (RHSCC) {
3287             default: assert(0 && "Unknown integer condition code!");
3288             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
3289             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
3290               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3291             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
3292             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
3293               return ReplaceInstUsesWith(I, LHS);
3294             }
3295           case Instruction::SetGT:
3296             switch (RHSCC) {
3297             default: assert(0 && "Unknown integer condition code!");
3298             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
3299               return ReplaceInstUsesWith(I, LHS);
3300             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
3301               return ReplaceInstUsesWith(I, RHS);
3302             case Instruction::SetNE:
3303               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3304                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3305               break;                        // (X > 13 & X != 15) -> no change
3306             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
3307               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3308             }
3309           }
3310         }
3311   }
3312
3313   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3314   if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3315     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3316       const Type *SrcTy = Op0C->getOperand(0)->getType();
3317       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3318           // Only do this if the casts both really cause code to be generated.
3319           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3320           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3321         Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3322                                                        Op1C->getOperand(0),
3323                                                        I.getName());
3324         InsertNewInstBefore(NewOp, I);
3325         return new CastInst(NewOp, I.getType());
3326       }
3327     }
3328   }
3329     
3330   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3331   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3332     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3333       if (SI0->getOpcode() == SI1->getOpcode() && 
3334           SI0->getOperand(1) == SI1->getOperand(1) &&
3335           (SI0->hasOneUse() || SI1->hasOneUse())) {
3336         Instruction *NewOp =
3337           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3338                                                         SI1->getOperand(0),
3339                                                         SI0->getName()), I);
3340         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3341       }
3342   }
3343
3344   return Changed ? &I : 0;
3345 }
3346
3347 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3348 /// in the result.  If it does, and if the specified byte hasn't been filled in
3349 /// yet, fill it in and return false.
3350 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3351   Instruction *I = dyn_cast<Instruction>(V);
3352   if (I == 0) return true;
3353
3354   // If this is an or instruction, it is an inner node of the bswap.
3355   if (I->getOpcode() == Instruction::Or)
3356     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3357            CollectBSwapParts(I->getOperand(1), ByteValues);
3358   
3359   // If this is a shift by a constant int, and it is "24", then its operand
3360   // defines a byte.  We only handle unsigned types here.
3361   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3362     // Not shifting the entire input by N-1 bytes?
3363     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3364         8*(ByteValues.size()-1))
3365       return true;
3366     
3367     unsigned DestNo;
3368     if (I->getOpcode() == Instruction::Shl) {
3369       // X << 24 defines the top byte with the lowest of the input bytes.
3370       DestNo = ByteValues.size()-1;
3371     } else {
3372       // X >>u 24 defines the low byte with the highest of the input bytes.
3373       DestNo = 0;
3374     }
3375     
3376     // If the destination byte value is already defined, the values are or'd
3377     // together, which isn't a bswap (unless it's an or of the same bits).
3378     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3379       return true;
3380     ByteValues[DestNo] = I->getOperand(0);
3381     return false;
3382   }
3383   
3384   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3385   // don't have this.
3386   Value *Shift = 0, *ShiftLHS = 0;
3387   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3388   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3389       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3390     return true;
3391   Instruction *SI = cast<Instruction>(Shift);
3392
3393   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3394   if (ShiftAmt->getZExtValue() & 7 ||
3395       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3396     return true;
3397   
3398   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3399   unsigned DestByte;
3400   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3401     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3402       break;
3403   // Unknown mask for bswap.
3404   if (DestByte == ByteValues.size()) return true;
3405   
3406   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3407   unsigned SrcByte;
3408   if (SI->getOpcode() == Instruction::Shl)
3409     SrcByte = DestByte - ShiftBytes;
3410   else
3411     SrcByte = DestByte + ShiftBytes;
3412   
3413   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3414   if (SrcByte != ByteValues.size()-DestByte-1)
3415     return true;
3416   
3417   // If the destination byte value is already defined, the values are or'd
3418   // together, which isn't a bswap (unless it's an or of the same bits).
3419   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3420     return true;
3421   ByteValues[DestByte] = SI->getOperand(0);
3422   return false;
3423 }
3424
3425 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3426 /// If so, insert the new bswap intrinsic and return it.
3427 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3428   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3429   if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3430     return 0;
3431   
3432   /// ByteValues - For each byte of the result, we keep track of which value
3433   /// defines each byte.
3434   std::vector<Value*> ByteValues;
3435   ByteValues.resize(I.getType()->getPrimitiveSize());
3436     
3437   // Try to find all the pieces corresponding to the bswap.
3438   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3439       CollectBSwapParts(I.getOperand(1), ByteValues))
3440     return 0;
3441   
3442   // Check to see if all of the bytes come from the same value.
3443   Value *V = ByteValues[0];
3444   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3445   
3446   // Check to make sure that all of the bytes come from the same value.
3447   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3448     if (ByteValues[i] != V)
3449       return 0;
3450     
3451   // If they do then *success* we can turn this into a bswap.  Figure out what
3452   // bswap to make it into.
3453   Module *M = I.getParent()->getParent()->getParent();
3454   const char *FnName = 0;
3455   if (I.getType() == Type::UShortTy)
3456     FnName = "llvm.bswap.i16";
3457   else if (I.getType() == Type::UIntTy)
3458     FnName = "llvm.bswap.i32";
3459   else if (I.getType() == Type::ULongTy)
3460     FnName = "llvm.bswap.i64";
3461   else
3462     assert(0 && "Unknown integer type!");
3463   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3464   
3465   return new CallInst(F, V);
3466 }
3467
3468
3469 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3470   bool Changed = SimplifyCommutative(I);
3471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3472
3473   if (isa<UndefValue>(Op1))
3474     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3475                                ConstantIntegral::getAllOnesValue(I.getType()));
3476
3477   // or X, X = X
3478   if (Op0 == Op1)
3479     return ReplaceInstUsesWith(I, Op0);
3480
3481   // See if we can simplify any instructions used by the instruction whose sole 
3482   // purpose is to compute bits we don't care about.
3483   uint64_t KnownZero, KnownOne;
3484   if (!isa<PackedType>(I.getType()) &&
3485       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3486                            KnownZero, KnownOne))
3487     return &I;
3488   
3489   // or X, -1 == -1
3490   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3491     ConstantInt *C1 = 0; Value *X = 0;
3492     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3493     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3494       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3495       Op0->setName("");
3496       InsertNewInstBefore(Or, I);
3497       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3498     }
3499
3500     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3501     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3502       std::string Op0Name = Op0->getName(); Op0->setName("");
3503       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3504       InsertNewInstBefore(Or, I);
3505       return BinaryOperator::createXor(Or,
3506                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3507     }
3508
3509     // Try to fold constant and into select arguments.
3510     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3511       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3512         return R;
3513     if (isa<PHINode>(Op0))
3514       if (Instruction *NV = FoldOpIntoPhi(I))
3515         return NV;
3516   }
3517
3518   Value *A = 0, *B = 0;
3519   ConstantInt *C1 = 0, *C2 = 0;
3520
3521   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3522     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3523       return ReplaceInstUsesWith(I, Op1);
3524   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3525     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3526       return ReplaceInstUsesWith(I, Op0);
3527
3528   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3529   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3530   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3531       match(Op1, m_Or(m_Value(), m_Value())) ||
3532       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3533        match(Op1, m_Shift(m_Value(), m_Value())))) {
3534     if (Instruction *BSwap = MatchBSwap(I))
3535       return BSwap;
3536   }
3537   
3538   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3539   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3540       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3541     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3542     Op0->setName("");
3543     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3544   }
3545
3546   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3547   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3548       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3549     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3550     Op0->setName("");
3551     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3552   }
3553
3554   // (A & C1)|(B & C2)
3555   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3556       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3557
3558     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3559       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3560
3561
3562     // If we have: ((V + N) & C1) | (V & C2)
3563     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3564     // replace with V+N.
3565     if (C1 == ConstantExpr::getNot(C2)) {
3566       Value *V1 = 0, *V2 = 0;
3567       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3568           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3569         // Add commutes, try both ways.
3570         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3571           return ReplaceInstUsesWith(I, A);
3572         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3573           return ReplaceInstUsesWith(I, A);
3574       }
3575       // Or commutes, try both ways.
3576       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3577           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3578         // Add commutes, try both ways.
3579         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3580           return ReplaceInstUsesWith(I, B);
3581         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3582           return ReplaceInstUsesWith(I, B);
3583       }
3584     }
3585   }
3586   
3587   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3588   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3589     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3590       if (SI0->getOpcode() == SI1->getOpcode() && 
3591           SI0->getOperand(1) == SI1->getOperand(1) &&
3592           (SI0->hasOneUse() || SI1->hasOneUse())) {
3593         Instruction *NewOp =
3594         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3595                                                      SI1->getOperand(0),
3596                                                      SI0->getName()), I);
3597         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3598       }
3599   }
3600
3601   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3602     if (A == Op1)   // ~A | A == -1
3603       return ReplaceInstUsesWith(I,
3604                                 ConstantIntegral::getAllOnesValue(I.getType()));
3605   } else {
3606     A = 0;
3607   }
3608   // Note, A is still live here!
3609   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3610     if (Op0 == B)
3611       return ReplaceInstUsesWith(I,
3612                                 ConstantIntegral::getAllOnesValue(I.getType()));
3613
3614     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3615     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3616       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3617                                               I.getName()+".demorgan"), I);
3618       return BinaryOperator::createNot(And);
3619     }
3620   }
3621
3622   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3623   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3624     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3625       return R;
3626
3627     Value *LHSVal, *RHSVal;
3628     ConstantInt *LHSCst, *RHSCst;
3629     Instruction::BinaryOps LHSCC, RHSCC;
3630     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3631       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3632         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
3633             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3634             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3635             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3636           // Ensure that the larger constant is on the RHS.
3637           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3638           SetCondInst *LHS = cast<SetCondInst>(Op0);
3639           if (cast<ConstantBool>(Cmp)->getValue()) {
3640             std::swap(LHS, RHS);
3641             std::swap(LHSCst, RHSCst);
3642             std::swap(LHSCC, RHSCC);
3643           }
3644
3645           // At this point, we know we have have two setcc instructions
3646           // comparing a value against two constants and or'ing the result
3647           // together.  Because of the above check, we know that we only have
3648           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3649           // FoldSetCCLogical check above), that the two constants are not
3650           // equal.
3651           assert(LHSCst != RHSCst && "Compares not folded above?");
3652
3653           switch (LHSCC) {
3654           default: assert(0 && "Unknown integer condition code!");
3655           case Instruction::SetEQ:
3656             switch (RHSCC) {
3657             default: assert(0 && "Unknown integer condition code!");
3658             case Instruction::SetEQ:
3659               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3660                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3661                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3662                                                       LHSVal->getName()+".off");
3663                 InsertNewInstBefore(Add, I);
3664                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3665                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3666                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3667                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3668                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3669               }
3670               break;                  // (X == 13 | X == 15) -> no change
3671
3672             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
3673               break;
3674             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
3675             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
3676               return ReplaceInstUsesWith(I, RHS);
3677             }
3678             break;
3679           case Instruction::SetNE:
3680             switch (RHSCC) {
3681             default: assert(0 && "Unknown integer condition code!");
3682             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
3683             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
3684               return ReplaceInstUsesWith(I, LHS);
3685             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
3686             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
3687               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3688             }
3689             break;
3690           case Instruction::SetLT:
3691             switch (RHSCC) {
3692             default: assert(0 && "Unknown integer condition code!");
3693             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
3694               break;
3695             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
3696               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3697             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
3698             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
3699               return ReplaceInstUsesWith(I, RHS);
3700             }
3701             break;
3702           case Instruction::SetGT:
3703             switch (RHSCC) {
3704             default: assert(0 && "Unknown integer condition code!");
3705             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
3706             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
3707               return ReplaceInstUsesWith(I, LHS);
3708             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
3709             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
3710               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3711             }
3712           }
3713         }
3714   }
3715     
3716   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3717   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3718     const Type *SrcTy = Op0C->getOperand(0)->getType();
3719     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3720       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3721           // Only do this if the casts both really cause code to be generated.
3722           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3723           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3724         Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3725                                                       Op1C->getOperand(0),
3726                                                       I.getName());
3727         InsertNewInstBefore(NewOp, I);
3728         return new CastInst(NewOp, I.getType());
3729       }
3730   }
3731       
3732
3733   return Changed ? &I : 0;
3734 }
3735
3736 // XorSelf - Implements: X ^ X --> 0
3737 struct XorSelf {
3738   Value *RHS;
3739   XorSelf(Value *rhs) : RHS(rhs) {}
3740   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3741   Instruction *apply(BinaryOperator &Xor) const {
3742     return &Xor;
3743   }
3744 };
3745
3746
3747 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3748   bool Changed = SimplifyCommutative(I);
3749   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3750
3751   if (isa<UndefValue>(Op1))
3752     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3753
3754   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3755   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3756     assert(Result == &I && "AssociativeOpt didn't work?");
3757     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3758   }
3759   
3760   // See if we can simplify any instructions used by the instruction whose sole 
3761   // purpose is to compute bits we don't care about.
3762   uint64_t KnownZero, KnownOne;
3763   if (!isa<PackedType>(I.getType()) &&
3764       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3765                            KnownZero, KnownOne))
3766     return &I;
3767
3768   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3769     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3770       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3771       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3772         if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3773           return new SetCondInst(SCI->getInverseCondition(),
3774                                  SCI->getOperand(0), SCI->getOperand(1));
3775
3776       // ~(c-X) == X-c-1 == X+(-c-1)
3777       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3778         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3779           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3780           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3781                                               ConstantInt::get(I.getType(), 1));
3782           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3783         }
3784
3785       // ~(~X & Y) --> (X | ~Y)
3786       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3787         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3788         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3789           Instruction *NotY =
3790             BinaryOperator::createNot(Op0I->getOperand(1),
3791                                       Op0I->getOperand(1)->getName()+".not");
3792           InsertNewInstBefore(NotY, I);
3793           return BinaryOperator::createOr(Op0NotVal, NotY);
3794         }
3795       }
3796
3797       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3798         if (Op0I->getOpcode() == Instruction::Add) {
3799           // ~(X-c) --> (-c-1)-X
3800           if (RHS->isAllOnesValue()) {
3801             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3802             return BinaryOperator::createSub(
3803                            ConstantExpr::getSub(NegOp0CI,
3804                                              ConstantInt::get(I.getType(), 1)),
3805                                           Op0I->getOperand(0));
3806           }
3807         } else if (Op0I->getOpcode() == Instruction::Or) {
3808           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3809           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3810             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3811             // Anything in both C1 and C2 is known to be zero, remove it from
3812             // NewRHS.
3813             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3814             NewRHS = ConstantExpr::getAnd(NewRHS, 
3815                                           ConstantExpr::getNot(CommonBits));
3816             WorkList.push_back(Op0I);
3817             I.setOperand(0, Op0I->getOperand(0));
3818             I.setOperand(1, NewRHS);
3819             return &I;
3820           }
3821         }
3822     }
3823
3824     // Try to fold constant and into select arguments.
3825     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3826       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3827         return R;
3828     if (isa<PHINode>(Op0))
3829       if (Instruction *NV = FoldOpIntoPhi(I))
3830         return NV;
3831   }
3832
3833   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3834     if (X == Op1)
3835       return ReplaceInstUsesWith(I,
3836                                 ConstantIntegral::getAllOnesValue(I.getType()));
3837
3838   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3839     if (X == Op0)
3840       return ReplaceInstUsesWith(I,
3841                                 ConstantIntegral::getAllOnesValue(I.getType()));
3842
3843   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3844     if (Op1I->getOpcode() == Instruction::Or) {
3845       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3846         Op1I->swapOperands();
3847         I.swapOperands();
3848         std::swap(Op0, Op1);
3849       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3850         I.swapOperands();     // Simplified below.
3851         std::swap(Op0, Op1);
3852       }
3853     } else if (Op1I->getOpcode() == Instruction::Xor) {
3854       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3855         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3856       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3857         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3858     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3859       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3860         Op1I->swapOperands();
3861       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3862         I.swapOperands();     // Simplified below.
3863         std::swap(Op0, Op1);
3864       }
3865     }
3866
3867   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3868     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3869       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3870         Op0I->swapOperands();
3871       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3872         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3873         InsertNewInstBefore(NotB, I);
3874         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3875       }
3876     } else if (Op0I->getOpcode() == Instruction::Xor) {
3877       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3878         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3879       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3880         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3881     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3882       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3883         Op0I->swapOperands();
3884       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3885           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3886         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3887         InsertNewInstBefore(N, I);
3888         return BinaryOperator::createAnd(N, Op1);
3889       }
3890     }
3891
3892   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3893   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3894     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3895       return R;
3896
3897   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3898   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3899     const Type *SrcTy = Op0C->getOperand(0)->getType();
3900     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3901       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3902           // Only do this if the casts both really cause code to be generated.
3903           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3904           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3905         Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3906                                                        Op1C->getOperand(0),
3907                                                        I.getName());
3908         InsertNewInstBefore(NewOp, I);
3909         return new CastInst(NewOp, I.getType());
3910       }
3911   }
3912
3913   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
3914   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3915     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3916       if (SI0->getOpcode() == SI1->getOpcode() && 
3917           SI0->getOperand(1) == SI1->getOperand(1) &&
3918           (SI0->hasOneUse() || SI1->hasOneUse())) {
3919         Instruction *NewOp =
3920         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3921                                                       SI1->getOperand(0),
3922                                                       SI0->getName()), I);
3923         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3924       }
3925   }
3926     
3927   return Changed ? &I : 0;
3928 }
3929
3930 static bool isPositive(ConstantInt *C) {
3931   return C->getSExtValue() >= 0;
3932 }
3933
3934 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3935 /// overflowed for this type.
3936 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3937                             ConstantInt *In2) {
3938   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3939
3940   if (In1->getType()->isUnsigned())
3941     return cast<ConstantInt>(Result)->getZExtValue() <
3942            cast<ConstantInt>(In1)->getZExtValue();
3943   if (isPositive(In1) != isPositive(In2))
3944     return false;
3945   if (isPositive(In1))
3946     return cast<ConstantInt>(Result)->getSExtValue() <
3947            cast<ConstantInt>(In1)->getSExtValue();
3948   return cast<ConstantInt>(Result)->getSExtValue() >
3949          cast<ConstantInt>(In1)->getSExtValue();
3950 }
3951
3952 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3953 /// code necessary to compute the offset from the base pointer (without adding
3954 /// in the base pointer).  Return the result as a signed integer of intptr size.
3955 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3956   TargetData &TD = IC.getTargetData();
3957   gep_type_iterator GTI = gep_type_begin(GEP);
3958   const Type *UIntPtrTy = TD.getIntPtrType();
3959   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3960   Value *Result = Constant::getNullValue(SIntPtrTy);
3961
3962   // Build a mask for high order bits.
3963   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3964
3965   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3966     Value *Op = GEP->getOperand(i);
3967     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3968     Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3969                                             SIntPtrTy);
3970     if (Constant *OpC = dyn_cast<Constant>(Op)) {
3971       if (!OpC->isNullValue()) {
3972         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3973         Scale = ConstantExpr::getMul(OpC, Scale);
3974         if (Constant *RC = dyn_cast<Constant>(Result))
3975           Result = ConstantExpr::getAdd(RC, Scale);
3976         else {
3977           // Emit an add instruction.
3978           Result = IC.InsertNewInstBefore(
3979              BinaryOperator::createAdd(Result, Scale,
3980                                        GEP->getName()+".offs"), I);
3981         }
3982       }
3983     } else {
3984       // Convert to correct type.
3985       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3986                                                Op->getName()+".c"), I);
3987       if (Size != 1)
3988         // We'll let instcombine(mul) convert this to a shl if possible.
3989         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3990                                                     GEP->getName()+".idx"), I);
3991
3992       // Emit an add instruction.
3993       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3994                                                     GEP->getName()+".offs"), I);
3995     }
3996   }
3997   return Result;
3998 }
3999
4000 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
4001 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4002 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
4003                                         Instruction::BinaryOps Cond,
4004                                         Instruction &I) {
4005   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4006
4007   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4008     if (isa<PointerType>(CI->getOperand(0)->getType()))
4009       RHS = CI->getOperand(0);
4010
4011   Value *PtrBase = GEPLHS->getOperand(0);
4012   if (PtrBase == RHS) {
4013     // As an optimization, we don't actually have to compute the actual value of
4014     // OFFSET if this is a seteq or setne comparison, just return whether each
4015     // index is zero or not.
4016     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
4017       Instruction *InVal = 0;
4018       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4019       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4020         bool EmitIt = true;
4021         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4022           if (isa<UndefValue>(C))  // undef index -> undef.
4023             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4024           if (C->isNullValue())
4025             EmitIt = false;
4026           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4027             EmitIt = false;  // This is indexing into a zero sized array?
4028           } else if (isa<ConstantInt>(C))
4029             return ReplaceInstUsesWith(I, // No comparison is needed here.
4030                                  ConstantBool::get(Cond == Instruction::SetNE));
4031         }
4032
4033         if (EmitIt) {
4034           Instruction *Comp =
4035             new SetCondInst(Cond, GEPLHS->getOperand(i),
4036                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4037           if (InVal == 0)
4038             InVal = Comp;
4039           else {
4040             InVal = InsertNewInstBefore(InVal, I);
4041             InsertNewInstBefore(Comp, I);
4042             if (Cond == Instruction::SetNE)   // True if any are unequal
4043               InVal = BinaryOperator::createOr(InVal, Comp);
4044             else                              // True if all are equal
4045               InVal = BinaryOperator::createAnd(InVal, Comp);
4046           }
4047         }
4048       }
4049
4050       if (InVal)
4051         return InVal;
4052       else
4053         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4054                             ConstantBool::get(Cond == Instruction::SetEQ));
4055     }
4056
4057     // Only lower this if the setcc is the only user of the GEP or if we expect
4058     // the result to fold to a constant!
4059     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4060       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4061       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4062       return new SetCondInst(Cond, Offset,
4063                              Constant::getNullValue(Offset->getType()));
4064     }
4065   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4066     // If the base pointers are different, but the indices are the same, just
4067     // compare the base pointer.
4068     if (PtrBase != GEPRHS->getOperand(0)) {
4069       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4070       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4071                         GEPRHS->getOperand(0)->getType();
4072       if (IndicesTheSame)
4073         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4074           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4075             IndicesTheSame = false;
4076             break;
4077           }
4078
4079       // If all indices are the same, just compare the base pointers.
4080       if (IndicesTheSame)
4081         return new SetCondInst(Cond, GEPLHS->getOperand(0),
4082                                GEPRHS->getOperand(0));
4083
4084       // Otherwise, the base pointers are different and the indices are
4085       // different, bail out.
4086       return 0;
4087     }
4088
4089     // If one of the GEPs has all zero indices, recurse.
4090     bool AllZeros = true;
4091     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4092       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4093           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4094         AllZeros = false;
4095         break;
4096       }
4097     if (AllZeros)
4098       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4099                           SetCondInst::getSwappedCondition(Cond), I);
4100
4101     // If the other GEP has all zero indices, recurse.
4102     AllZeros = true;
4103     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4104       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4105           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4106         AllZeros = false;
4107         break;
4108       }
4109     if (AllZeros)
4110       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4111
4112     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4113       // If the GEPs only differ by one index, compare it.
4114       unsigned NumDifferences = 0;  // Keep track of # differences.
4115       unsigned DiffOperand = 0;     // The operand that differs.
4116       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4117         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4118           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4119                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4120             // Irreconcilable differences.
4121             NumDifferences = 2;
4122             break;
4123           } else {
4124             if (NumDifferences++) break;
4125             DiffOperand = i;
4126           }
4127         }
4128
4129       if (NumDifferences == 0)   // SAME GEP?
4130         return ReplaceInstUsesWith(I, // No comparison is needed here.
4131                                  ConstantBool::get(Cond == Instruction::SetEQ));
4132       else if (NumDifferences == 1) {
4133         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4134         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4135
4136         // Convert the operands to signed values to make sure to perform a
4137         // signed comparison.
4138         const Type *NewTy = LHSV->getType()->getSignedVersion();
4139         if (LHSV->getType() != NewTy)
4140           LHSV = InsertCastBefore(LHSV, NewTy, I);
4141         if (RHSV->getType() != NewTy)
4142           RHSV = InsertCastBefore(RHSV, NewTy, I);
4143         return new SetCondInst(Cond, LHSV, RHSV);
4144       }
4145     }
4146
4147     // Only lower this if the setcc is the only user of the GEP or if we expect
4148     // the result to fold to a constant!
4149     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4150         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4151       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4152       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4153       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4154       return new SetCondInst(Cond, L, R);
4155     }
4156   }
4157   return 0;
4158 }
4159
4160
4161 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4162   bool Changed = SimplifyCommutative(I);
4163   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4164   const Type *Ty = Op0->getType();
4165
4166   // setcc X, X
4167   if (Op0 == Op1)
4168     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4169
4170   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
4171     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4172
4173   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4174   // addresses never equal each other!  We already know that Op0 != Op1.
4175   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4176        isa<ConstantPointerNull>(Op0)) &&
4177       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4178        isa<ConstantPointerNull>(Op1)))
4179     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4180
4181   // setcc's with boolean values can always be turned into bitwise operations
4182   if (Ty == Type::BoolTy) {
4183     switch (I.getOpcode()) {
4184     default: assert(0 && "Invalid setcc instruction!");
4185     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
4186       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4187       InsertNewInstBefore(Xor, I);
4188       return BinaryOperator::createNot(Xor);
4189     }
4190     case Instruction::SetNE:
4191       return BinaryOperator::createXor(Op0, Op1);
4192
4193     case Instruction::SetGT:
4194       std::swap(Op0, Op1);                   // Change setgt -> setlt
4195       // FALL THROUGH
4196     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
4197       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4198       InsertNewInstBefore(Not, I);
4199       return BinaryOperator::createAnd(Not, Op1);
4200     }
4201     case Instruction::SetGE:
4202       std::swap(Op0, Op1);                   // Change setge -> setle
4203       // FALL THROUGH
4204     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
4205       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4206       InsertNewInstBefore(Not, I);
4207       return BinaryOperator::createOr(Not, Op1);
4208     }
4209     }
4210   }
4211
4212   // See if we are doing a comparison between a constant and an instruction that
4213   // can be folded into the comparison.
4214   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4215     // Check to see if we are comparing against the minimum or maximum value...
4216     if (CI->isMinValue()) {
4217       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
4218         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4219       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
4220         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4221       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
4222         return BinaryOperator::createSetEQ(Op0, Op1);
4223       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
4224         return BinaryOperator::createSetNE(Op0, Op1);
4225
4226     } else if (CI->isMaxValue()) {
4227       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
4228         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4229       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
4230         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4231       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
4232         return BinaryOperator::createSetEQ(Op0, Op1);
4233       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
4234         return BinaryOperator::createSetNE(Op0, Op1);
4235
4236       // Comparing against a value really close to min or max?
4237     } else if (isMinValuePlusOne(CI)) {
4238       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
4239         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4240       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
4241         return BinaryOperator::createSetNE(Op0, SubOne(CI));
4242
4243     } else if (isMaxValueMinusOne(CI)) {
4244       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
4245         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4246       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
4247         return BinaryOperator::createSetNE(Op0, AddOne(CI));
4248     }
4249
4250     // If we still have a setle or setge instruction, turn it into the
4251     // appropriate setlt or setgt instruction.  Since the border cases have
4252     // already been handled above, this requires little checking.
4253     //
4254     if (I.getOpcode() == Instruction::SetLE)
4255       return BinaryOperator::createSetLT(Op0, AddOne(CI));
4256     if (I.getOpcode() == Instruction::SetGE)
4257       return BinaryOperator::createSetGT(Op0, SubOne(CI));
4258
4259     
4260     // See if we can fold the comparison based on bits known to be zero or one
4261     // in the input.
4262     uint64_t KnownZero, KnownOne;
4263     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4264                              KnownZero, KnownOne, 0))
4265       return &I;
4266         
4267     // Given the known and unknown bits, compute a range that the LHS could be
4268     // in.
4269     if (KnownOne | KnownZero) {
4270       if (Ty->isUnsigned()) {   // Unsigned comparison.
4271         uint64_t Min, Max;
4272         uint64_t RHSVal = CI->getZExtValue();
4273         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4274                                                  Min, Max);
4275         switch (I.getOpcode()) {  // LE/GE have been folded already.
4276         default: assert(0 && "Unknown setcc opcode!");
4277         case Instruction::SetEQ:
4278           if (Max < RHSVal || Min > RHSVal)
4279             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4280           break;
4281         case Instruction::SetNE:
4282           if (Max < RHSVal || Min > RHSVal)
4283             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4284           break;
4285         case Instruction::SetLT:
4286           if (Max < RHSVal)
4287             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4288           if (Min > RHSVal)
4289             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4290           break;
4291         case Instruction::SetGT:
4292           if (Min > RHSVal)
4293             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4294           if (Max < RHSVal)
4295             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4296           break;
4297         }
4298       } else {              // Signed comparison.
4299         int64_t Min, Max;
4300         int64_t RHSVal = CI->getSExtValue();
4301         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4302                                                Min, Max);
4303         switch (I.getOpcode()) {  // LE/GE have been folded already.
4304         default: assert(0 && "Unknown setcc opcode!");
4305         case Instruction::SetEQ:
4306           if (Max < RHSVal || Min > RHSVal)
4307             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4308           break;
4309         case Instruction::SetNE:
4310           if (Max < RHSVal || Min > RHSVal)
4311             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4312           break;
4313         case Instruction::SetLT:
4314           if (Max < RHSVal)
4315             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4316           if (Min > RHSVal)
4317             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4318           break;
4319         case Instruction::SetGT:
4320           if (Min > RHSVal)
4321             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4322           if (Max < RHSVal)
4323             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4324           break;
4325         }
4326       }
4327     }
4328           
4329     // Since the RHS is a constantInt (CI), if the left hand side is an 
4330     // instruction, see if that instruction also has constants so that the 
4331     // instruction can be folded into the setcc
4332     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4333       switch (LHSI->getOpcode()) {
4334       case Instruction::And:
4335         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4336             LHSI->getOperand(0)->hasOneUse()) {
4337           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4338
4339           // If an operand is an AND of a truncating cast, we can widen the
4340           // and/compare to be the input width without changing the value
4341           // produced, eliminating a cast.
4342           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4343             // We can do this transformation if either the AND constant does not
4344             // have its sign bit set or if it is an equality comparison. 
4345             // Extending a relational comparison when we're checking the sign
4346             // bit would not work.
4347             if (Cast->hasOneUse() && Cast->isTruncIntCast() && 
4348                 (I.isEquality() ||
4349                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4350                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4351               ConstantInt *NewCST;
4352               ConstantInt *NewCI;
4353               if (Cast->getOperand(0)->getType()->isSigned()) {
4354                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4355                                            AndCST->getZExtValue());
4356                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4357                                           CI->getZExtValue());
4358               } else {
4359                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4360                                            AndCST->getZExtValue());
4361                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4362                                           CI->getZExtValue());
4363               }
4364               Instruction *NewAnd = 
4365                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4366                                           LHSI->getName());
4367               InsertNewInstBefore(NewAnd, I);
4368               return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4369             }
4370           }
4371           
4372           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4373           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4374           // happens a LOT in code produced by the C front-end, for bitfield
4375           // access.
4376           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4377
4378           // Check to see if there is a noop-cast between the shift and the and.
4379           if (!Shift) {
4380             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4381               if (CI->getOperand(0)->getType()->isIntegral() &&
4382                   CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4383                      CI->getType()->getPrimitiveSizeInBits())
4384                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4385           }
4386
4387           ConstantInt *ShAmt;
4388           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4389           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4390           const Type *AndTy = AndCST->getType();          // Type of the and.
4391
4392           // We can fold this as long as we can't shift unknown bits
4393           // into the mask.  This can only happen with signed shift
4394           // rights, as they sign-extend.
4395           if (ShAmt) {
4396             bool CanFold = Shift->isLogicalShift();
4397             if (!CanFold) {
4398               // To test for the bad case of the signed shr, see if any
4399               // of the bits shifted in could be tested after the mask.
4400               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4401               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4402
4403               Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4404               Constant *ShVal =
4405                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4406                                      OShAmt);
4407               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4408                 CanFold = true;
4409             }
4410
4411             if (CanFold) {
4412               Constant *NewCst;
4413               if (Shift->getOpcode() == Instruction::Shl)
4414                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4415               else
4416                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4417
4418               // Check to see if we are shifting out any of the bits being
4419               // compared.
4420               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4421                 // If we shifted bits out, the fold is not going to work out.
4422                 // As a special case, check to see if this means that the
4423                 // result is always true or false now.
4424                 if (I.getOpcode() == Instruction::SetEQ)
4425                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4426                 if (I.getOpcode() == Instruction::SetNE)
4427                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4428               } else {
4429                 I.setOperand(1, NewCst);
4430                 Constant *NewAndCST;
4431                 if (Shift->getOpcode() == Instruction::Shl)
4432                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4433                 else
4434                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4435                 LHSI->setOperand(1, NewAndCST);
4436                 if (AndTy == Ty) 
4437                   LHSI->setOperand(0, Shift->getOperand(0));
4438                 else {
4439                   Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4440                                                     *Shift);
4441                   LHSI->setOperand(0, NewCast);
4442                 }
4443                 WorkList.push_back(Shift); // Shift is dead.
4444                 AddUsesToWorkList(I);
4445                 return &I;
4446               }
4447             }
4448           }
4449           
4450           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4451           // preferable because it allows the C<<Y expression to be hoisted out
4452           // of a loop if Y is invariant and X is not.
4453           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4454               I.isEquality() && !Shift->isArithmeticShift() &&
4455               isa<Instruction>(Shift->getOperand(0))) {
4456             // Compute C << Y.
4457             Value *NS;
4458             if (Shift->getOpcode() == Instruction::LShr) {
4459               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4460                                  "tmp");
4461             } else {
4462               // Make sure we insert a logical shift.
4463               Constant *NewAndCST = AndCST;
4464               if (AndCST->getType()->isSigned())
4465                 NewAndCST = ConstantExpr::getCast(AndCST,
4466                                       AndCST->getType()->getUnsignedVersion());
4467               NS = new ShiftInst(Instruction::LShr, NewAndCST,
4468                                  Shift->getOperand(1), "tmp");
4469             }
4470             InsertNewInstBefore(cast<Instruction>(NS), I);
4471
4472             // If C's sign doesn't agree with the and, insert a cast now.
4473             if (NS->getType() != LHSI->getType())
4474               NS = InsertCastBefore(NS, LHSI->getType(), I);
4475
4476             Value *ShiftOp = Shift->getOperand(0);
4477             if (ShiftOp->getType() != LHSI->getType())
4478               ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4479               
4480             // Compute X & (C << Y).
4481             Instruction *NewAnd =
4482               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4483             InsertNewInstBefore(NewAnd, I);
4484             
4485             I.setOperand(0, NewAnd);
4486             return &I;
4487           }
4488         }
4489         break;
4490
4491       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
4492         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4493           if (I.isEquality()) {
4494             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4495
4496             // Check that the shift amount is in range.  If not, don't perform
4497             // undefined shifts.  When the shift is visited it will be
4498             // simplified.
4499             if (ShAmt->getZExtValue() >= TypeBits)
4500               break;
4501
4502             // If we are comparing against bits always shifted out, the
4503             // comparison cannot succeed.
4504             Constant *Comp =
4505               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4506             if (Comp != CI) {// Comparing against a bit that we know is zero.
4507               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4508               Constant *Cst = ConstantBool::get(IsSetNE);
4509               return ReplaceInstUsesWith(I, Cst);
4510             }
4511
4512             if (LHSI->hasOneUse()) {
4513               // Otherwise strength reduce the shift into an and.
4514               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4515               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4516
4517               Constant *Mask;
4518               if (CI->getType()->isUnsigned()) {
4519                 Mask = ConstantInt::get(CI->getType(), Val);
4520               } else if (ShAmtVal != 0) {
4521                 Mask = ConstantInt::get(CI->getType(), Val);
4522               } else {
4523                 Mask = ConstantInt::getAllOnesValue(CI->getType());
4524               }
4525
4526               Instruction *AndI =
4527                 BinaryOperator::createAnd(LHSI->getOperand(0),
4528                                           Mask, LHSI->getName()+".mask");
4529               Value *And = InsertNewInstBefore(AndI, I);
4530               return new SetCondInst(I.getOpcode(), And,
4531                                      ConstantExpr::getLShr(CI, ShAmt));
4532             }
4533           }
4534         }
4535         break;
4536
4537       case Instruction::LShr:         // (setcc (shr X, ShAmt), CI)
4538       case Instruction::AShr:
4539         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4540           if (I.isEquality()) {
4541             // Check that the shift amount is in range.  If not, don't perform
4542             // undefined shifts.  When the shift is visited it will be
4543             // simplified.
4544             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4545             if (ShAmt->getZExtValue() >= TypeBits)
4546               break;
4547
4548             // If we are comparing against bits always shifted out, the
4549             // comparison cannot succeed.
4550             Constant *Comp;
4551             if (CI->getType()->isUnsigned())
4552               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4553                                            ShAmt);
4554             else
4555               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4556                                            ShAmt);
4557
4558             if (Comp != CI) {// Comparing against a bit that we know is zero.
4559               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4560               Constant *Cst = ConstantBool::get(IsSetNE);
4561               return ReplaceInstUsesWith(I, Cst);
4562             }
4563
4564             if (LHSI->hasOneUse() || CI->isNullValue()) {
4565               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4566
4567               // Otherwise strength reduce the shift into an and.
4568               uint64_t Val = ~0ULL;          // All ones.
4569               Val <<= ShAmtVal;              // Shift over to the right spot.
4570
4571               Constant *Mask;
4572               if (CI->getType()->isUnsigned()) {
4573                 Val &= ~0ULL >> (64-TypeBits);
4574                 Mask = ConstantInt::get(CI->getType(), Val);
4575               } else {
4576                 Mask = ConstantInt::get(CI->getType(), Val);
4577               }
4578
4579               Instruction *AndI =
4580                 BinaryOperator::createAnd(LHSI->getOperand(0),
4581                                           Mask, LHSI->getName()+".mask");
4582               Value *And = InsertNewInstBefore(AndI, I);
4583               return new SetCondInst(I.getOpcode(), And,
4584                                      ConstantExpr::getShl(CI, ShAmt));
4585             }
4586           }
4587         }
4588         break;
4589
4590       case Instruction::SDiv:
4591       case Instruction::UDiv:
4592         // Fold: setcc ([us]div X, C1), C2 -> range test
4593         // Fold this div into the comparison, producing a range check. 
4594         // Determine, based on the divide type, what the range is being 
4595         // checked.  If there is an overflow on the low or high side, remember 
4596         // it, otherwise compute the range [low, hi) bounding the new value.
4597         // See: InsertRangeTest above for the kinds of replacements possible.
4598         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4599           // FIXME: If the operand types don't match the type of the divide 
4600           // then don't attempt this transform. The code below doesn't have the
4601           // logic to deal with a signed divide and an unsigned compare (and
4602           // vice versa). This is because (x /s C1) <s C2  produces different 
4603           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4604           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4605           // work. :(  The if statement below tests that condition and bails 
4606           // if it finds it. 
4607           const Type* DivRHSTy = DivRHS->getType();
4608           unsigned DivOpCode = LHSI->getOpcode();
4609           if (I.isEquality() &&
4610               ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4611                (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4612             break;
4613
4614           // Initialize the variables that will indicate the nature of the
4615           // range check.
4616           bool LoOverflow = false, HiOverflow = false;
4617           ConstantInt *LoBound = 0, *HiBound = 0;
4618
4619           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4620           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4621           // C2 (CI). By solving for X we can turn this into a range check 
4622           // instead of computing a divide. 
4623           ConstantInt *Prod = 
4624             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4625
4626           // Determine if the product overflows by seeing if the product is
4627           // not equal to the divide. Make sure we do the same kind of divide
4628           // as in the LHS instruction that we're folding. 
4629           bool ProdOV = !DivRHS->isNullValue() && 
4630             (DivOpCode == Instruction::SDiv ?  
4631              ConstantExpr::getSDiv(Prod, DivRHS) :
4632               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4633
4634           // Get the SetCC opcode
4635           Instruction::BinaryOps Opcode = I.getOpcode();
4636
4637           if (DivRHS->isNullValue()) {  
4638             // Don't hack on divide by zeros!
4639           } else if (DivOpCode == Instruction::UDiv) {  // udiv
4640             LoBound = Prod;
4641             LoOverflow = ProdOV;
4642             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4643           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4644             if (CI->isNullValue()) {       // (X / pos) op 0
4645               // Can't overflow.
4646               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4647               HiBound = DivRHS;
4648             } else if (isPositive(CI)) {   // (X / pos) op pos
4649               LoBound = Prod;
4650               LoOverflow = ProdOV;
4651               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4652             } else {                       // (X / pos) op neg
4653               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4654               LoOverflow = AddWithOverflow(LoBound, Prod,
4655                                            cast<ConstantInt>(DivRHSH));
4656               HiBound = Prod;
4657               HiOverflow = ProdOV;
4658             }
4659           } else {                         // Divisor is < 0.
4660             if (CI->isNullValue()) {       // (X / neg) op 0
4661               LoBound = AddOne(DivRHS);
4662               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4663               if (HiBound == DivRHS)
4664                 LoBound = 0;               // - INTMIN = INTMIN
4665             } else if (isPositive(CI)) {   // (X / neg) op pos
4666               HiOverflow = LoOverflow = ProdOV;
4667               if (!LoOverflow)
4668                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4669               HiBound = AddOne(Prod);
4670             } else {                       // (X / neg) op neg
4671               LoBound = Prod;
4672               LoOverflow = HiOverflow = ProdOV;
4673               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4674             }
4675
4676             // Dividing by a negate swaps the condition.
4677             Opcode = SetCondInst::getSwappedCondition(Opcode);
4678           }
4679
4680           if (LoBound) {
4681             Value *X = LHSI->getOperand(0);
4682             switch (Opcode) {
4683             default: assert(0 && "Unhandled setcc opcode!");
4684             case Instruction::SetEQ:
4685               if (LoOverflow && HiOverflow)
4686                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4687               else if (HiOverflow)
4688                 return new SetCondInst(Instruction::SetGE, X, LoBound);
4689               else if (LoOverflow)
4690                 return new SetCondInst(Instruction::SetLT, X, HiBound);
4691               else
4692                 return InsertRangeTest(X, LoBound, HiBound, true, I);
4693             case Instruction::SetNE:
4694               if (LoOverflow && HiOverflow)
4695                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4696               else if (HiOverflow)
4697                 return new SetCondInst(Instruction::SetLT, X, LoBound);
4698               else if (LoOverflow)
4699                 return new SetCondInst(Instruction::SetGE, X, HiBound);
4700               else
4701                 return InsertRangeTest(X, LoBound, HiBound, false, I);
4702             case Instruction::SetLT:
4703               if (LoOverflow)
4704                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4705               return new SetCondInst(Instruction::SetLT, X, LoBound);
4706             case Instruction::SetGT:
4707               if (HiOverflow)
4708                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4709               return new SetCondInst(Instruction::SetGE, X, HiBound);
4710             }
4711           }
4712         }
4713         break;
4714       }
4715
4716     // Simplify seteq and setne instructions...
4717     if (I.isEquality()) {
4718       bool isSetNE = I.getOpcode() == Instruction::SetNE;
4719
4720       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4721       // the second operand is a constant, simplify a bit.
4722       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4723         switch (BO->getOpcode()) {
4724         case Instruction::SRem:
4725           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4726           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4727               BO->hasOneUse()) {
4728             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4729             if (V > 1 && isPowerOf2_64(V)) {
4730               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4731                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4732               return BinaryOperator::create(I.getOpcode(), NewRem,
4733                 Constant::getNullValue(BO->getType()));
4734             }
4735           }
4736           break;
4737         case Instruction::Add:
4738           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4739           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4740             if (BO->hasOneUse())
4741               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4742                                      ConstantExpr::getSub(CI, BOp1C));
4743           } else if (CI->isNullValue()) {
4744             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4745             // efficiently invertible, or if the add has just this one use.
4746             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4747
4748             if (Value *NegVal = dyn_castNegVal(BOp1))
4749               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4750             else if (Value *NegVal = dyn_castNegVal(BOp0))
4751               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4752             else if (BO->hasOneUse()) {
4753               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4754               BO->setName("");
4755               InsertNewInstBefore(Neg, I);
4756               return new SetCondInst(I.getOpcode(), BOp0, Neg);
4757             }
4758           }
4759           break;
4760         case Instruction::Xor:
4761           // For the xor case, we can xor two constants together, eliminating
4762           // the explicit xor.
4763           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4764             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4765                                   ConstantExpr::getXor(CI, BOC));
4766
4767           // FALLTHROUGH
4768         case Instruction::Sub:
4769           // Replace (([sub|xor] A, B) != 0) with (A != B)
4770           if (CI->isNullValue())
4771             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4772                                    BO->getOperand(1));
4773           break;
4774
4775         case Instruction::Or:
4776           // If bits are being or'd in that are not present in the constant we
4777           // are comparing against, then the comparison could never succeed!
4778           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4779             Constant *NotCI = ConstantExpr::getNot(CI);
4780             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4781               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4782           }
4783           break;
4784
4785         case Instruction::And:
4786           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4787             // If bits are being compared against that are and'd out, then the
4788             // comparison can never succeed!
4789             if (!ConstantExpr::getAnd(CI,
4790                                       ConstantExpr::getNot(BOC))->isNullValue())
4791               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4792
4793             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4794             if (CI == BOC && isOneBitSet(CI))
4795               return new SetCondInst(isSetNE ? Instruction::SetEQ :
4796                                      Instruction::SetNE, Op0,
4797                                      Constant::getNullValue(CI->getType()));
4798
4799             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4800             // to be a signed value as appropriate.
4801             if (isSignBit(BOC)) {
4802               Value *X = BO->getOperand(0);
4803               // If 'X' is not signed, insert a cast now...
4804               if (!BOC->getType()->isSigned()) {
4805                 const Type *DestTy = BOC->getType()->getSignedVersion();
4806                 X = InsertCastBefore(X, DestTy, I);
4807               }
4808               return new SetCondInst(isSetNE ? Instruction::SetLT :
4809                                          Instruction::SetGE, X,
4810                                      Constant::getNullValue(X->getType()));
4811             }
4812
4813             // ((X & ~7) == 0) --> X < 8
4814             if (CI->isNullValue() && isHighOnes(BOC)) {
4815               Value *X = BO->getOperand(0);
4816               Constant *NegX = ConstantExpr::getNeg(BOC);
4817
4818               // If 'X' is signed, insert a cast now.
4819               if (NegX->getType()->isSigned()) {
4820                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4821                 X = InsertCastBefore(X, DestTy, I);
4822                 NegX = ConstantExpr::getCast(NegX, DestTy);
4823               }
4824
4825               return new SetCondInst(isSetNE ? Instruction::SetGE :
4826                                      Instruction::SetLT, X, NegX);
4827             }
4828
4829           }
4830         default: break;
4831         }
4832       }
4833     } else {  // Not a SetEQ/SetNE
4834       // If the LHS is a cast from an integral value of the same size,
4835       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4836         Value *CastOp = Cast->getOperand(0);
4837         const Type *SrcTy = CastOp->getType();
4838         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4839         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4840             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4841           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4842                  "Source and destination signednesses should differ!");
4843           if (Cast->getType()->isSigned()) {
4844             // If this is a signed comparison, check for comparisons in the
4845             // vicinity of zero.
4846             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4847               // X < 0  => x > 127
4848               return BinaryOperator::createSetGT(CastOp,
4849                          ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4850             else if (I.getOpcode() == Instruction::SetGT &&
4851                      cast<ConstantInt>(CI)->getSExtValue() == -1)
4852               // X > -1  => x < 128
4853               return BinaryOperator::createSetLT(CastOp,
4854                          ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4855           } else {
4856             ConstantInt *CUI = cast<ConstantInt>(CI);
4857             if (I.getOpcode() == Instruction::SetLT &&
4858                 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4859               // X < 128 => X > -1
4860               return BinaryOperator::createSetGT(CastOp,
4861                                                  ConstantInt::get(SrcTy, -1));
4862             else if (I.getOpcode() == Instruction::SetGT &&
4863                      CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4864               // X > 127 => X < 0
4865               return BinaryOperator::createSetLT(CastOp,
4866                                                  Constant::getNullValue(SrcTy));
4867           }
4868         }
4869       }
4870     }
4871   }
4872
4873   // Handle setcc with constant RHS's that can be integer, FP or pointer.
4874   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4875     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4876       switch (LHSI->getOpcode()) {
4877       case Instruction::GetElementPtr:
4878         if (RHSC->isNullValue()) {
4879           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4880           bool isAllZeros = true;
4881           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4882             if (!isa<Constant>(LHSI->getOperand(i)) ||
4883                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4884               isAllZeros = false;
4885               break;
4886             }
4887           if (isAllZeros)
4888             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4889                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4890         }
4891         break;
4892
4893       case Instruction::PHI:
4894         if (Instruction *NV = FoldOpIntoPhi(I))
4895           return NV;
4896         break;
4897       case Instruction::Select:
4898         // If either operand of the select is a constant, we can fold the
4899         // comparison into the select arms, which will cause one to be
4900         // constant folded and the select turned into a bitwise or.
4901         Value *Op1 = 0, *Op2 = 0;
4902         if (LHSI->hasOneUse()) {
4903           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4904             // Fold the known value into the constant operand.
4905             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4906             // Insert a new SetCC of the other select operand.
4907             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4908                                                       LHSI->getOperand(2), RHSC,
4909                                                       I.getName()), I);
4910           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4911             // Fold the known value into the constant operand.
4912             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4913             // Insert a new SetCC of the other select operand.
4914             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4915                                                       LHSI->getOperand(1), RHSC,
4916                                                       I.getName()), I);
4917           }
4918         }
4919
4920         if (Op1)
4921           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4922         break;
4923       }
4924   }
4925
4926   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4927   if (User *GEP = dyn_castGetElementPtr(Op0))
4928     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4929       return NI;
4930   if (User *GEP = dyn_castGetElementPtr(Op1))
4931     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4932                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
4933       return NI;
4934
4935   // Test to see if the operands of the setcc are casted versions of other
4936   // values.  If the cast can be stripped off both arguments, we do so now.
4937   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4938     Value *CastOp0 = CI->getOperand(0);
4939     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4940         (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4941       // We keep moving the cast from the left operand over to the right
4942       // operand, where it can often be eliminated completely.
4943       Op0 = CastOp0;
4944
4945       // If operand #1 is a cast instruction, see if we can eliminate it as
4946       // well.
4947       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4948         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4949                                                                Op0->getType()))
4950           Op1 = CI2->getOperand(0);
4951
4952       // If Op1 is a constant, we can fold the cast into the constant.
4953       if (Op1->getType() != Op0->getType())
4954         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4955           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4956         } else {
4957           // Otherwise, cast the RHS right before the setcc
4958           Op1 = InsertCastBefore(Op1, Op0->getType(), I);
4959         }
4960       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4961     }
4962
4963     // Handle the special case of: setcc (cast bool to X), <cst>
4964     // This comes up when you have code like
4965     //   int X = A < B;
4966     //   if (X) ...
4967     // For generality, we handle any zero-extension of any operand comparison
4968     // with a constant or another cast from the same type.
4969     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4970       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4971         return R;
4972   }
4973   
4974   if (I.isEquality()) {
4975     Value *A, *B;
4976     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4977         (A == Op1 || B == Op1)) {
4978       // (A^B) == A  ->  B == 0
4979       Value *OtherVal = A == Op1 ? B : A;
4980       return BinaryOperator::create(I.getOpcode(), OtherVal,
4981                                     Constant::getNullValue(A->getType()));
4982     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4983                (A == Op0 || B == Op0)) {
4984       // A == (A^B)  ->  B == 0
4985       Value *OtherVal = A == Op0 ? B : A;
4986       return BinaryOperator::create(I.getOpcode(), OtherVal,
4987                                     Constant::getNullValue(A->getType()));
4988     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4989       // (A-B) == A  ->  B == 0
4990       return BinaryOperator::create(I.getOpcode(), B,
4991                                     Constant::getNullValue(B->getType()));
4992     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4993       // A == (A-B)  ->  B == 0
4994       return BinaryOperator::create(I.getOpcode(), B,
4995                                     Constant::getNullValue(B->getType()));
4996     }
4997     
4998     Value *C, *D;
4999     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5000     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5001         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5002         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5003       Value *X = 0, *Y = 0, *Z = 0;
5004       
5005       if (A == C) {
5006         X = B; Y = D; Z = A;
5007       } else if (A == D) {
5008         X = B; Y = C; Z = A;
5009       } else if (B == C) {
5010         X = A; Y = D; Z = B;
5011       } else if (B == D) {
5012         X = A; Y = C; Z = B;
5013       }
5014       
5015       if (X) {   // Build (X^Y) & Z
5016         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5017         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5018         I.setOperand(0, Op1);
5019         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5020         return &I;
5021       }
5022     }
5023   }
5024   return Changed ? &I : 0;
5025 }
5026
5027 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5028 // We only handle extending casts so far.
5029 //
5030 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
5031   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
5032   const Type *SrcTy = LHSCIOp->getType();
5033   const Type *DestTy = SCI.getOperand(0)->getType();
5034   Value *RHSCIOp;
5035
5036   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
5037     return 0;
5038
5039   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
5040   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5041   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
5042
5043   // Is this a sign or zero extension?
5044   bool isSignSrc  = SrcTy->isSigned();
5045   bool isSignDest = DestTy->isSigned();
5046
5047   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5048     // Not an extension from the same type?
5049     RHSCIOp = CI->getOperand(0);
5050     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5051   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5052     // Compute the constant that would happen if we truncated to SrcTy then
5053     // reextended to DestTy.
5054     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
5055
5056     if (ConstantExpr::getCast(Res, DestTy) == CI) {
5057       // Make sure that src sign and dest sign match. For example,
5058       //
5059       // %A = cast short %X to uint
5060       // %B = setgt uint %A, 1330
5061       //
5062       // It is incorrect to transform this into 
5063       //
5064       // %B = setgt short %X, 1330 
5065       // 
5066       // because %A may have negative value. 
5067       // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5068       // OR operation is EQ/NE.
5069       if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
5070         RHSCIOp = Res;
5071       else
5072         return 0;
5073     } else {
5074       // If the value cannot be represented in the shorter type, we cannot emit
5075       // a simple comparison.
5076       if (SCI.getOpcode() == Instruction::SetEQ)
5077         return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
5078       if (SCI.getOpcode() == Instruction::SetNE)
5079         return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
5080
5081       // Evaluate the comparison for LT.
5082       Value *Result;
5083       if (DestTy->isSigned()) {
5084         // We're performing a signed comparison.
5085         if (isSignSrc) {
5086           // Signed extend and signed comparison.
5087           if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
5088             Result = ConstantBool::getFalse();
5089           else
5090             Result = ConstantBool::getTrue();           // X < (large) --> true
5091         } else {
5092           // Unsigned extend and signed comparison.
5093           if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5094             Result = ConstantBool::getFalse();
5095           else
5096             Result = ConstantBool::getTrue();
5097         }
5098       } else {
5099         // We're performing an unsigned comparison.
5100         if (!isSignSrc) {
5101           // Unsigned extend & compare -> always true.
5102           Result = ConstantBool::getTrue();
5103         } else {
5104           // We're performing an unsigned comp with a sign extended value.
5105           // This is true if the input is >= 0. [aka >s -1]
5106           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5107           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5108                                                   NegOne, SCI.getName()), SCI);
5109         }
5110       }
5111
5112       // Finally, return the value computed.
5113       if (SCI.getOpcode() == Instruction::SetLT) {
5114         return ReplaceInstUsesWith(SCI, Result);
5115       } else {
5116         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5117         if (Constant *CI = dyn_cast<Constant>(Result))
5118           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5119         else
5120           return BinaryOperator::createNot(Result);
5121       }
5122     }
5123   } else {
5124     return 0;
5125   }
5126
5127   // Okay, just insert a compare of the reduced operands now!
5128   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5129 }
5130
5131 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5132   assert(I.getOperand(1)->getType() == Type::UByteTy);
5133   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5134   bool isLeftShift = I.getOpcode() == Instruction::Shl;
5135
5136   // shl X, 0 == X and shr X, 0 == X
5137   // shl 0, X == 0 and shr 0, X == 0
5138   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5139       Op0 == Constant::getNullValue(Op0->getType()))
5140     return ReplaceInstUsesWith(I, Op0);
5141   
5142   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
5143     if (!isLeftShift && I.getType()->isSigned())
5144       return ReplaceInstUsesWith(I, Op0);
5145     else                         // undef << X -> 0   AND  undef >>u X -> 0
5146       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5147   }
5148   if (isa<UndefValue>(Op1)) {
5149     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5150       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5151     else
5152       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
5153   }
5154
5155   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5156   if (I.getOpcode() == Instruction::AShr)
5157     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5158       if (CSI->isAllOnesValue())
5159         return ReplaceInstUsesWith(I, CSI);
5160
5161   // Try to fold constant and into select arguments.
5162   if (isa<Constant>(Op0))
5163     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5164       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5165         return R;
5166
5167   // See if we can turn a signed shr into an unsigned shr.
5168   if (I.isArithmeticShift()) {
5169     if (MaskedValueIsZero(Op0,
5170                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5171       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5172     }
5173   }
5174
5175   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5176     if (CUI->getType()->isUnsigned())
5177       if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5178         return Res;
5179   return 0;
5180 }
5181
5182 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5183                                                ShiftInst &I) {
5184   bool isLeftShift = I.getOpcode() == Instruction::Shl;
5185   bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() : 
5186                                      I.getOpcode() == Instruction::AShr;
5187   bool isUnsignedShift = !isSignedShift;
5188
5189   // See if we can simplify any instructions used by the instruction whose sole 
5190   // purpose is to compute bits we don't care about.
5191   uint64_t KnownZero, KnownOne;
5192   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5193                            KnownZero, KnownOne))
5194     return &I;
5195   
5196   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5197   // of a signed value.
5198   //
5199   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5200   if (Op1->getZExtValue() >= TypeBits) {
5201     if (isUnsignedShift || isLeftShift)
5202       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5203     else {
5204       I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5205       return &I;
5206     }
5207   }
5208   
5209   // ((X*C1) << C2) == (X * (C1 << C2))
5210   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5211     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5212       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5213         return BinaryOperator::createMul(BO->getOperand(0),
5214                                          ConstantExpr::getShl(BOOp, Op1));
5215   
5216   // Try to fold constant and into select arguments.
5217   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5218     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5219       return R;
5220   if (isa<PHINode>(Op0))
5221     if (Instruction *NV = FoldOpIntoPhi(I))
5222       return NV;
5223   
5224   if (Op0->hasOneUse()) {
5225     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5226       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5227       Value *V1, *V2;
5228       ConstantInt *CC;
5229       switch (Op0BO->getOpcode()) {
5230         default: break;
5231         case Instruction::Add:
5232         case Instruction::And:
5233         case Instruction::Or:
5234         case Instruction::Xor:
5235           // These operators commute.
5236           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5237           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5238               match(Op0BO->getOperand(1),
5239                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5240             Instruction *YS = new ShiftInst(Instruction::Shl, 
5241                                             Op0BO->getOperand(0), Op1,
5242                                             Op0BO->getName());
5243             InsertNewInstBefore(YS, I); // (Y << C)
5244             Instruction *X = 
5245               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5246                                      Op0BO->getOperand(1)->getName());
5247             InsertNewInstBefore(X, I);  // (X + (Y << C))
5248             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5249             C2 = ConstantExpr::getShl(C2, Op1);
5250             return BinaryOperator::createAnd(X, C2);
5251           }
5252           
5253           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5254           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5255               match(Op0BO->getOperand(1),
5256                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5257                           m_ConstantInt(CC))) && V2 == Op1 &&
5258       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5259             Instruction *YS = new ShiftInst(Instruction::Shl, 
5260                                             Op0BO->getOperand(0), Op1,
5261                                             Op0BO->getName());
5262             InsertNewInstBefore(YS, I); // (Y << C)
5263             Instruction *XM =
5264               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5265                                         V1->getName()+".mask");
5266             InsertNewInstBefore(XM, I); // X & (CC << C)
5267             
5268             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5269           }
5270           
5271           // FALL THROUGH.
5272         case Instruction::Sub:
5273           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5274           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5275               match(Op0BO->getOperand(0),
5276                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5277             Instruction *YS = new ShiftInst(Instruction::Shl, 
5278                                             Op0BO->getOperand(1), Op1,
5279                                             Op0BO->getName());
5280             InsertNewInstBefore(YS, I); // (Y << C)
5281             Instruction *X =
5282               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5283                                      Op0BO->getOperand(0)->getName());
5284             InsertNewInstBefore(X, I);  // (X + (Y << C))
5285             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5286             C2 = ConstantExpr::getShl(C2, Op1);
5287             return BinaryOperator::createAnd(X, C2);
5288           }
5289           
5290           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5291           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5292               match(Op0BO->getOperand(0),
5293                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5294                           m_ConstantInt(CC))) && V2 == Op1 &&
5295               cast<BinaryOperator>(Op0BO->getOperand(0))
5296                   ->getOperand(0)->hasOneUse()) {
5297             Instruction *YS = new ShiftInst(Instruction::Shl, 
5298                                             Op0BO->getOperand(1), Op1,
5299                                             Op0BO->getName());
5300             InsertNewInstBefore(YS, I); // (Y << C)
5301             Instruction *XM =
5302               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5303                                         V1->getName()+".mask");
5304             InsertNewInstBefore(XM, I); // X & (CC << C)
5305             
5306             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5307           }
5308           
5309           break;
5310       }
5311       
5312       
5313       // If the operand is an bitwise operator with a constant RHS, and the
5314       // shift is the only use, we can pull it out of the shift.
5315       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5316         bool isValid = true;     // Valid only for And, Or, Xor
5317         bool highBitSet = false; // Transform if high bit of constant set?
5318         
5319         switch (Op0BO->getOpcode()) {
5320           default: isValid = false; break;   // Do not perform transform!
5321           case Instruction::Add:
5322             isValid = isLeftShift;
5323             break;
5324           case Instruction::Or:
5325           case Instruction::Xor:
5326             highBitSet = false;
5327             break;
5328           case Instruction::And:
5329             highBitSet = true;
5330             break;
5331         }
5332         
5333         // If this is a signed shift right, and the high bit is modified
5334         // by the logical operation, do not perform the transformation.
5335         // The highBitSet boolean indicates the value of the high bit of
5336         // the constant which would cause it to be modified for this
5337         // operation.
5338         //
5339         if (isValid && !isLeftShift && isSignedShift) {
5340           uint64_t Val = Op0C->getZExtValue();
5341           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5342         }
5343         
5344         if (isValid) {
5345           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5346           
5347           Instruction *NewShift =
5348             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5349                           Op0BO->getName());
5350           Op0BO->setName("");
5351           InsertNewInstBefore(NewShift, I);
5352           
5353           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5354                                         NewRHS);
5355         }
5356       }
5357     }
5358   }
5359   
5360   // Find out if this is a shift of a shift by a constant.
5361   ShiftInst *ShiftOp = 0;
5362   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5363     ShiftOp = Op0SI;
5364   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5365     // If this is a noop-integer case of a shift instruction, use the shift.
5366     if (CI->getOperand(0)->getType()->isInteger() &&
5367         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5368         CI->getType()->getPrimitiveSizeInBits() &&
5369         isa<ShiftInst>(CI->getOperand(0))) {
5370       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5371     }
5372   }
5373   
5374   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5375     // Find the operands and properties of the input shift.  Note that the
5376     // signedness of the input shift may differ from the current shift if there
5377     // is a noop cast between the two.
5378     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5379     bool isShiftOfSignedShift = isShiftOfLeftShift ? 
5380            ShiftOp->getType()->isSigned() : 
5381            ShiftOp->getOpcode() == Instruction::AShr;
5382     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5383     
5384     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5385
5386     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5387     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5388     
5389     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5390     if (isLeftShift == isShiftOfLeftShift) {
5391       // Do not fold these shifts if the first one is signed and the second one
5392       // is unsigned and this is a right shift.  Further, don't do any folding
5393       // on them.
5394       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5395         return 0;
5396       
5397       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5398       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5399         Amt = Op0->getType()->getPrimitiveSizeInBits();
5400       
5401       Value *Op = ShiftOp->getOperand(0);
5402       if (isShiftOfSignedShift != isSignedShift)
5403         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5404       ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
5405                            ConstantInt::get(Type::UByteTy, Amt));
5406       if (I.getType() == ShiftResult->getType())
5407         return ShiftResult;
5408       InsertNewInstBefore(ShiftResult, I);
5409       return new CastInst(ShiftResult, I.getType());
5410     }
5411     
5412     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5413     // signed types, we can only support the (A >> c1) << c2 configuration,
5414     // because it can not turn an arbitrary bit of A into a sign bit.
5415     if (isUnsignedShift || isLeftShift) {
5416       // Calculate bitmask for what gets shifted off the edge.
5417       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5418       if (isLeftShift)
5419         C = ConstantExpr::getShl(C, ShiftAmt1C);
5420       else
5421         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5422       
5423       Value *Op = ShiftOp->getOperand(0);
5424       if (Op->getType() != C->getType())
5425         Op = InsertCastBefore(Op, I.getType(), I);
5426       
5427       Instruction *Mask =
5428         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5429       InsertNewInstBefore(Mask, I);
5430       
5431       // Figure out what flavor of shift we should use...
5432       if (ShiftAmt1 == ShiftAmt2) {
5433         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5434       } else if (ShiftAmt1 < ShiftAmt2) {
5435         return new ShiftInst(I.getOpcode(), Mask,
5436                          ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5437       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5438         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5439           return new ShiftInst(Instruction::LShr, Mask, 
5440             ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5441         } else {
5442           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5443                     ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5444         }
5445       } else {
5446         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5447         Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
5448         Instruction *Shift =
5449           new ShiftInst(ShiftOp->getOpcode(), Op,
5450                         ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5451         InsertNewInstBefore(Shift, I);
5452         
5453         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5454         C = ConstantExpr::getShl(C, Op1);
5455         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5456         InsertNewInstBefore(Mask, I);
5457         return new CastInst(Mask, I.getType());
5458       }
5459     } else {
5460       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5461       // this case, C1 == C2 and C1 is 8, 16, or 32.
5462       if (ShiftAmt1 == ShiftAmt2) {
5463         const Type *SExtType = 0;
5464         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5465         case 8 : SExtType = Type::SByteTy; break;
5466         case 16: SExtType = Type::ShortTy; break;
5467         case 32: SExtType = Type::IntTy; break;
5468         }
5469         
5470         if (SExtType) {
5471           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5472                                                SExtType, "sext");
5473           InsertNewInstBefore(NewTrunc, I);
5474           return new CastInst(NewTrunc, I.getType());
5475         }
5476       }
5477     }
5478   }
5479   return 0;
5480 }
5481
5482
5483 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5484 /// expression.  If so, decompose it, returning some value X, such that Val is
5485 /// X*Scale+Offset.
5486 ///
5487 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5488                                         unsigned &Offset) {
5489   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5490   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5491     if (CI->getType()->isUnsigned()) {
5492       Offset = CI->getZExtValue();
5493       Scale  = 1;
5494       return ConstantInt::get(Type::UIntTy, 0);
5495     }
5496   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5497     if (I->getNumOperands() == 2) {
5498       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5499         if (CUI->getType()->isUnsigned()) {
5500           if (I->getOpcode() == Instruction::Shl) {
5501             // This is a value scaled by '1 << the shift amt'.
5502             Scale = 1U << CUI->getZExtValue();
5503             Offset = 0;
5504             return I->getOperand(0);
5505           } else if (I->getOpcode() == Instruction::Mul) {
5506             // This value is scaled by 'CUI'.
5507             Scale = CUI->getZExtValue();
5508             Offset = 0;
5509             return I->getOperand(0);
5510           } else if (I->getOpcode() == Instruction::Add) {
5511             // We have X+C.  Check to see if we really have (X*C2)+C1, 
5512             // where C1 is divisible by C2.
5513             unsigned SubScale;
5514             Value *SubVal = 
5515               DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5516             Offset += CUI->getZExtValue();
5517             if (SubScale > 1 && (Offset % SubScale == 0)) {
5518               Scale = SubScale;
5519               return SubVal;
5520             }
5521           }
5522         }
5523       }
5524     }
5525   }
5526
5527   // Otherwise, we can't look past this.
5528   Scale = 1;
5529   Offset = 0;
5530   return Val;
5531 }
5532
5533
5534 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5535 /// try to eliminate the cast by moving the type information into the alloc.
5536 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5537                                                    AllocationInst &AI) {
5538   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5539   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5540   
5541   // Remove any uses of AI that are dead.
5542   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5543   std::vector<Instruction*> DeadUsers;
5544   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5545     Instruction *User = cast<Instruction>(*UI++);
5546     if (isInstructionTriviallyDead(User)) {
5547       while (UI != E && *UI == User)
5548         ++UI; // If this instruction uses AI more than once, don't break UI.
5549       
5550       // Add operands to the worklist.
5551       AddUsesToWorkList(*User);
5552       ++NumDeadInst;
5553       DOUT << "IC: DCE: " << *User;
5554       
5555       User->eraseFromParent();
5556       removeFromWorkList(User);
5557     }
5558   }
5559   
5560   // Get the type really allocated and the type casted to.
5561   const Type *AllocElTy = AI.getAllocatedType();
5562   const Type *CastElTy = PTy->getElementType();
5563   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5564
5565   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5566   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5567   if (CastElTyAlign < AllocElTyAlign) return 0;
5568
5569   // If the allocation has multiple uses, only promote it if we are strictly
5570   // increasing the alignment of the resultant allocation.  If we keep it the
5571   // same, we open the door to infinite loops of various kinds.
5572   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5573
5574   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5575   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5576   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5577
5578   // See if we can satisfy the modulus by pulling a scale out of the array
5579   // size argument.
5580   unsigned ArraySizeScale, ArrayOffset;
5581   Value *NumElements = // See if the array size is a decomposable linear expr.
5582     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5583  
5584   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5585   // do the xform.
5586   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5587       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5588
5589   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5590   Value *Amt = 0;
5591   if (Scale == 1) {
5592     Amt = NumElements;
5593   } else {
5594     // If the allocation size is constant, form a constant mul expression
5595     Amt = ConstantInt::get(Type::UIntTy, Scale);
5596     if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5597       Amt = ConstantExpr::getMul(
5598               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5599     // otherwise multiply the amount and the number of elements
5600     else if (Scale != 1) {
5601       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5602       Amt = InsertNewInstBefore(Tmp, AI);
5603     }
5604   }
5605   
5606   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5607     Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5608     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5609     Amt = InsertNewInstBefore(Tmp, AI);
5610   }
5611   
5612   std::string Name = AI.getName(); AI.setName("");
5613   AllocationInst *New;
5614   if (isa<MallocInst>(AI))
5615     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5616   else
5617     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5618   InsertNewInstBefore(New, AI);
5619   
5620   // If the allocation has multiple uses, insert a cast and change all things
5621   // that used it to use the new cast.  This will also hack on CI, but it will
5622   // die soon.
5623   if (!AI.hasOneUse()) {
5624     AddUsesToWorkList(AI);
5625     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5626     InsertNewInstBefore(NewCast, AI);
5627     AI.replaceAllUsesWith(NewCast);
5628   }
5629   return ReplaceInstUsesWith(CI, New);
5630 }
5631
5632 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5633 /// and return it without inserting any new casts.  This is used by code that
5634 /// tries to decide whether promoting or shrinking integer operations to wider
5635 /// or smaller types will allow us to eliminate a truncate or extend.
5636 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5637                                        int &NumCastsRemoved) {
5638   if (isa<Constant>(V)) return true;
5639   
5640   Instruction *I = dyn_cast<Instruction>(V);
5641   if (!I || !I->hasOneUse()) return false;
5642   
5643   switch (I->getOpcode()) {
5644   case Instruction::And:
5645   case Instruction::Or:
5646   case Instruction::Xor:
5647     // These operators can all arbitrarily be extended or truncated.
5648     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5649            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5650   case Instruction::Cast:
5651     // If this is a cast from the destination type, we can trivially eliminate
5652     // it, and this will remove a cast overall.
5653     if (I->getOperand(0)->getType() == Ty) {
5654       // If the first operand is itself a cast, and is eliminable, do not count
5655       // this as an eliminable cast.  We would prefer to eliminate those two
5656       // casts first.
5657       if (isa<CastInst>(I->getOperand(0)))
5658         return true;
5659       
5660       ++NumCastsRemoved;
5661       return true;
5662     }
5663     // TODO: Can handle more cases here.
5664     break;
5665   }
5666   
5667   return false;
5668 }
5669
5670 /// EvaluateInDifferentType - Given an expression that 
5671 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5672 /// evaluate the expression.
5673 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5674   if (Constant *C = dyn_cast<Constant>(V))
5675     return ConstantExpr::getCast(C, Ty);
5676
5677   // Otherwise, it must be an instruction.
5678   Instruction *I = cast<Instruction>(V);
5679   Instruction *Res = 0;
5680   switch (I->getOpcode()) {
5681   case Instruction::And:
5682   case Instruction::Or:
5683   case Instruction::Xor: {
5684     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5685     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5686     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5687                                  LHS, RHS, I->getName());
5688     break;
5689   }
5690   case Instruction::Cast:
5691     // If this is a cast from the destination type, return the input.
5692     if (I->getOperand(0)->getType() == Ty)
5693       return I->getOperand(0);
5694     
5695     // TODO: Can handle more cases here.
5696     assert(0 && "Unreachable!");
5697     break;
5698   }
5699   
5700   return InsertNewInstBefore(Res, *I);
5701 }
5702
5703
5704 // CastInst simplification
5705 //
5706 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5707   Value *Src = CI.getOperand(0);
5708
5709   // If the user is casting a value to the same type, eliminate this cast
5710   // instruction...
5711   if (CI.getType() == Src->getType())
5712     return ReplaceInstUsesWith(CI, Src);
5713
5714   if (isa<UndefValue>(Src))   // cast undef -> undef
5715     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5716
5717   // If casting the result of another cast instruction, try to eliminate this
5718   // one!
5719   //
5720   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5721     Value *A = CSrc->getOperand(0);
5722     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5723                                CI.getType(), TD)) {
5724       // This instruction now refers directly to the cast's src operand.  This
5725       // has a good chance of making CSrc dead.
5726       CI.setOperand(0, CSrc->getOperand(0));
5727       return &CI;
5728     }
5729
5730     // If this is an A->B->A cast, and we are dealing with integral types, try
5731     // to convert this into a logical 'and' instruction.
5732     //
5733     if (A->getType()->isInteger() &&
5734         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5735         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
5736         CSrc->getType()->getPrimitiveSizeInBits() <
5737                     CI.getType()->getPrimitiveSizeInBits()&&
5738         A->getType()->getPrimitiveSizeInBits() ==
5739               CI.getType()->getPrimitiveSizeInBits()) {
5740       assert(CSrc->getType() != Type::ULongTy &&
5741              "Cannot have type bigger than ulong!");
5742       uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5743       Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5744                                           AndValue);
5745       AndOp = ConstantExpr::getCast(AndOp, A->getType());
5746       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5747       if (And->getType() != CI.getType()) {
5748         And->setName(CSrc->getName()+".mask");
5749         InsertNewInstBefore(And, CI);
5750         And = new CastInst(And, CI.getType());
5751       }
5752       return And;
5753     }
5754   }
5755   
5756   // If this is a cast to bool, turn it into the appropriate setne instruction.
5757   if (CI.getType() == Type::BoolTy)
5758     return BinaryOperator::createSetNE(CI.getOperand(0),
5759                        Constant::getNullValue(CI.getOperand(0)->getType()));
5760
5761   // See if we can simplify any instructions used by the LHS whose sole 
5762   // purpose is to compute bits we don't care about.
5763   if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5764     uint64_t KnownZero, KnownOne;
5765     if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5766                              KnownZero, KnownOne))
5767       return &CI;
5768   }
5769   
5770   // If casting the result of a getelementptr instruction with no offset, turn
5771   // this into a cast of the original pointer!
5772   //
5773   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5774     bool AllZeroOperands = true;
5775     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5776       if (!isa<Constant>(GEP->getOperand(i)) ||
5777           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5778         AllZeroOperands = false;
5779         break;
5780       }
5781     if (AllZeroOperands) {
5782       CI.setOperand(0, GEP->getOperand(0));
5783       return &CI;
5784     }
5785   }
5786     
5787   // If we are casting a malloc or alloca to a pointer to a type of the same
5788   // size, rewrite the allocation instruction to allocate the "right" type.
5789   //
5790   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5791     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5792       return V;
5793
5794   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5795     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5796       return NV;
5797   if (isa<PHINode>(Src))
5798     if (Instruction *NV = FoldOpIntoPhi(CI))
5799       return NV;
5800   
5801   // If the source and destination are pointers, and this cast is equivalent to
5802   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
5803   // This can enhance SROA and other transforms that want type-safe pointers.
5804   if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5805     if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5806       const Type *DstTy = DstPTy->getElementType();
5807       const Type *SrcTy = SrcPTy->getElementType();
5808       
5809       Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5810       unsigned NumZeros = 0;
5811       while (SrcTy != DstTy && 
5812              isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5813              SrcTy->getNumContainedTypes() /* not "{}" */) {
5814         SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5815         ++NumZeros;
5816       }
5817
5818       // If we found a path from the src to dest, create the getelementptr now.
5819       if (SrcTy == DstTy) {
5820         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5821         return new GetElementPtrInst(Src, Idxs);
5822       }
5823     }
5824       
5825   // If the source value is an instruction with only this use, we can attempt to
5826   // propagate the cast into the instruction.  Also, only handle integral types
5827   // for now.
5828   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5829     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5830         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
5831       
5832       int NumCastsRemoved = 0;
5833       if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5834         // If this cast is a truncate, evaluting in a different type always
5835         // eliminates the cast, so it is always a win.  If this is a noop-cast
5836         // this just removes a noop cast which isn't pointful, but simplifies
5837         // the code.  If this is a zero-extension, we need to do an AND to
5838         // maintain the clear top-part of the computation, so we require that
5839         // the input have eliminated at least one cast.  If this is a sign
5840         // extension, we insert two new casts (to do the extension) so we
5841         // require that two casts have been eliminated.
5842         bool DoXForm;
5843         switch (getCastType(Src->getType(), CI.getType())) {
5844         default: assert(0 && "Unknown cast type!");
5845         case Noop:
5846         case Truncate:
5847           DoXForm = true;
5848           break;
5849         case Zeroext:
5850           DoXForm = NumCastsRemoved >= 1;
5851           break;
5852         case Signext:
5853           DoXForm = NumCastsRemoved >= 2;
5854           break;
5855         }
5856         
5857         if (DoXForm) {
5858           Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5859           assert(Res->getType() == CI.getType());
5860           switch (getCastType(Src->getType(), CI.getType())) {
5861           default: assert(0 && "Unknown cast type!");
5862           case Noop:
5863           case Truncate:
5864             // Just replace this cast with the result.
5865             return ReplaceInstUsesWith(CI, Res);
5866           case Zeroext: {
5867             // We need to emit an AND to clear the high bits.
5868             unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5869             unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5870             assert(SrcBitSize < DestBitSize && "Not a zext?");
5871             Constant *C = 
5872               ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5873             C = ConstantExpr::getCast(C, CI.getType());
5874             return BinaryOperator::createAnd(Res, C);
5875           }
5876           case Signext:
5877             // We need to emit a cast to truncate, then a cast to sext.
5878             return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5879                                 CI.getType());
5880           }
5881         }
5882       }
5883       
5884       const Type *DestTy = CI.getType();
5885       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5886       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5887
5888       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5889       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5890
5891       switch (SrcI->getOpcode()) {
5892       case Instruction::Add:
5893       case Instruction::Mul:
5894       case Instruction::And:
5895       case Instruction::Or:
5896       case Instruction::Xor:
5897         // If we are discarding information, or just changing the sign, rewrite.
5898         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5899           // Don't insert two casts if they cannot be eliminated.  We allow two
5900           // casts to be inserted if the sizes are the same.  This could only be
5901           // converting signedness, which is a noop.
5902           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5903               !ValueRequiresCast(Op0, DestTy, TD)) {
5904             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5905             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5906             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5907                              ->getOpcode(), Op0c, Op1c);
5908           }
5909         }
5910
5911         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
5912         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5913             Op1 == ConstantBool::getTrue() &&
5914             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5915           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5916           return BinaryOperator::createXor(New,
5917                                            ConstantInt::get(CI.getType(), 1));
5918         }
5919         break;
5920       case Instruction::SDiv:
5921       case Instruction::UDiv:
5922       case Instruction::SRem:
5923       case Instruction::URem:
5924         // If we are just changing the sign, rewrite.
5925         if (DestBitSize == SrcBitSize) {
5926           // Don't insert two casts if they cannot be eliminated.  We allow two
5927           // casts to be inserted if the sizes are the same.  This could only be
5928           // converting signedness, which is a noop.
5929           if (!ValueRequiresCast(Op1, DestTy,TD) || 
5930               !ValueRequiresCast(Op0, DestTy, TD)) {
5931             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5932             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5933             return BinaryOperator::create(
5934               cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5935           }
5936         }
5937         break;
5938
5939       case Instruction::Shl:
5940         // Allow changing the sign of the source operand.  Do not allow changing
5941         // the size of the shift, UNLESS the shift amount is a constant.  We
5942         // must not change variable sized shifts to a smaller size, because it
5943         // is undefined to shift more bits out than exist in the value.
5944         if (DestBitSize == SrcBitSize ||
5945             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5946           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5947           return new ShiftInst(Instruction::Shl, Op0c, Op1);
5948         }
5949         break;
5950       case Instruction::AShr:
5951         // If this is a signed shr, and if all bits shifted in are about to be
5952         // truncated off, turn it into an unsigned shr to allow greater
5953         // simplifications.
5954         if (DestBitSize < SrcBitSize &&
5955             isa<ConstantInt>(Op1)) {
5956           unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5957           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5958             // Insert the new logical shift right.
5959             return new ShiftInst(Instruction::LShr, Op0, Op1);
5960           }
5961         }
5962         break;
5963
5964       case Instruction::SetEQ:
5965       case Instruction::SetNE:
5966         // We if we are just checking for a seteq of a single bit and casting it
5967         // to an integer.  If so, shift the bit to the appropriate place then
5968         // cast to integer to avoid the comparison.
5969         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5970           uint64_t Op1CV = Op1C->getZExtValue();
5971           // cast (X == 0) to int --> X^1        iff X has only the low bit set.
5972           // cast (X == 0) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5973           // cast (X == 1) to int --> X          iff X has only the low bit set.
5974           // cast (X == 2) to int --> X>>1       iff X has only the 2nd bit set.
5975           // cast (X != 0) to int --> X          iff X has only the low bit set.
5976           // cast (X != 0) to int --> X>>1       iff X has only the 2nd bit set.
5977           // cast (X != 1) to int --> X^1        iff X has only the low bit set.
5978           // cast (X != 2) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5979           if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5980             // If Op1C some other power of two, convert:
5981             uint64_t KnownZero, KnownOne;
5982             uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5983             ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5984             
5985             if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5986               bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5987               if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5988                 // (X&4) == 2 --> false
5989                 // (X&4) != 2 --> true
5990                 Constant *Res = ConstantBool::get(isSetNE);
5991                 Res = ConstantExpr::getCast(Res, CI.getType());
5992                 return ReplaceInstUsesWith(CI, Res);
5993               }
5994               
5995               unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5996               Value *In = Op0;
5997               if (ShiftAmt) {
5998                 // Perform a logical shr by shiftamt.
5999                 // Insert the shift to put the result in the low bit.
6000                 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
6001                                      ConstantInt::get(Type::UByteTy, ShiftAmt),
6002                                      In->getName()+".lobit"), CI);
6003               }
6004               
6005               if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6006                 Constant *One = ConstantInt::get(In->getType(), 1);
6007                 In = BinaryOperator::createXor(In, One, "tmp");
6008                 InsertNewInstBefore(cast<Instruction>(In), CI);
6009               }
6010               
6011               if (CI.getType() == In->getType())
6012                 return ReplaceInstUsesWith(CI, In);
6013               else
6014                 return new CastInst(In, CI.getType());
6015             }
6016           }
6017         }
6018         break;
6019       }
6020     }
6021     
6022     if (SrcI->hasOneUse()) {
6023       if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
6024         // Okay, we have (cast (shuffle ..)).  We know this cast is a bitconvert
6025         // because the inputs are known to be a vector.  Check to see if this is
6026         // a cast to a vector with the same # elts.
6027         if (isa<PackedType>(CI.getType()) && 
6028             cast<PackedType>(CI.getType())->getNumElements() == 
6029                   SVI->getType()->getNumElements()) {
6030           CastInst *Tmp;
6031           // If either of the operands is a cast from CI.getType(), then
6032           // evaluating the shuffle in the casted destination's type will allow
6033           // us to eliminate at least one cast.
6034           if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6035                Tmp->getOperand(0)->getType() == CI.getType()) ||
6036               ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6037                Tmp->getOperand(0)->getType() == CI.getType())) {
6038             Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
6039                                                  CI.getType(), &CI);
6040             Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
6041                                                  CI.getType(), &CI);
6042             // Return a new shuffle vector.  Use the same element ID's, as we
6043             // know the vector types match #elts.
6044             return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6045           }
6046         }
6047       }
6048     }
6049   }
6050       
6051   return 0;
6052 }
6053
6054 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6055 ///   %C = or %A, %B
6056 ///   %D = select %cond, %C, %A
6057 /// into:
6058 ///   %C = select %cond, %B, 0
6059 ///   %D = or %A, %C
6060 ///
6061 /// Assuming that the specified instruction is an operand to the select, return
6062 /// a bitmask indicating which operands of this instruction are foldable if they
6063 /// equal the other incoming value of the select.
6064 ///
6065 static unsigned GetSelectFoldableOperands(Instruction *I) {
6066   switch (I->getOpcode()) {
6067   case Instruction::Add:
6068   case Instruction::Mul:
6069   case Instruction::And:
6070   case Instruction::Or:
6071   case Instruction::Xor:
6072     return 3;              // Can fold through either operand.
6073   case Instruction::Sub:   // Can only fold on the amount subtracted.
6074   case Instruction::Shl:   // Can only fold on the shift amount.
6075   case Instruction::LShr:
6076   case Instruction::AShr:
6077     return 1;
6078   default:
6079     return 0;              // Cannot fold
6080   }
6081 }
6082
6083 /// GetSelectFoldableConstant - For the same transformation as the previous
6084 /// function, return the identity constant that goes into the select.
6085 static Constant *GetSelectFoldableConstant(Instruction *I) {
6086   switch (I->getOpcode()) {
6087   default: assert(0 && "This cannot happen!"); abort();
6088   case Instruction::Add:
6089   case Instruction::Sub:
6090   case Instruction::Or:
6091   case Instruction::Xor:
6092     return Constant::getNullValue(I->getType());
6093   case Instruction::Shl:
6094   case Instruction::LShr:
6095   case Instruction::AShr:
6096     return Constant::getNullValue(Type::UByteTy);
6097   case Instruction::And:
6098     return ConstantInt::getAllOnesValue(I->getType());
6099   case Instruction::Mul:
6100     return ConstantInt::get(I->getType(), 1);
6101   }
6102 }
6103
6104 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6105 /// have the same opcode and only one use each.  Try to simplify this.
6106 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6107                                           Instruction *FI) {
6108   if (TI->getNumOperands() == 1) {
6109     // If this is a non-volatile load or a cast from the same type,
6110     // merge.
6111     if (TI->getOpcode() == Instruction::Cast) {
6112       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6113         return 0;
6114     } else {
6115       return 0;  // unknown unary op.
6116     }
6117
6118     // Fold this by inserting a select from the input values.
6119     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6120                                        FI->getOperand(0), SI.getName()+".v");
6121     InsertNewInstBefore(NewSI, SI);
6122     return new CastInst(NewSI, TI->getType());
6123   }
6124
6125   // Only handle binary operators here.
6126   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6127     return 0;
6128
6129   // Figure out if the operations have any operands in common.
6130   Value *MatchOp, *OtherOpT, *OtherOpF;
6131   bool MatchIsOpZero;
6132   if (TI->getOperand(0) == FI->getOperand(0)) {
6133     MatchOp  = TI->getOperand(0);
6134     OtherOpT = TI->getOperand(1);
6135     OtherOpF = FI->getOperand(1);
6136     MatchIsOpZero = true;
6137   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6138     MatchOp  = TI->getOperand(1);
6139     OtherOpT = TI->getOperand(0);
6140     OtherOpF = FI->getOperand(0);
6141     MatchIsOpZero = false;
6142   } else if (!TI->isCommutative()) {
6143     return 0;
6144   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6145     MatchOp  = TI->getOperand(0);
6146     OtherOpT = TI->getOperand(1);
6147     OtherOpF = FI->getOperand(0);
6148     MatchIsOpZero = true;
6149   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6150     MatchOp  = TI->getOperand(1);
6151     OtherOpT = TI->getOperand(0);
6152     OtherOpF = FI->getOperand(1);
6153     MatchIsOpZero = true;
6154   } else {
6155     return 0;
6156   }
6157
6158   // If we reach here, they do have operations in common.
6159   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6160                                      OtherOpF, SI.getName()+".v");
6161   InsertNewInstBefore(NewSI, SI);
6162
6163   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6164     if (MatchIsOpZero)
6165       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6166     else
6167       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6168   } else {
6169     if (MatchIsOpZero)
6170       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6171     else
6172       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6173   }
6174 }
6175
6176 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6177   Value *CondVal = SI.getCondition();
6178   Value *TrueVal = SI.getTrueValue();
6179   Value *FalseVal = SI.getFalseValue();
6180
6181   // select true, X, Y  -> X
6182   // select false, X, Y -> Y
6183   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6184     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6185
6186   // select C, X, X -> X
6187   if (TrueVal == FalseVal)
6188     return ReplaceInstUsesWith(SI, TrueVal);
6189
6190   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6191     return ReplaceInstUsesWith(SI, FalseVal);
6192   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6193     return ReplaceInstUsesWith(SI, TrueVal);
6194   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6195     if (isa<Constant>(TrueVal))
6196       return ReplaceInstUsesWith(SI, TrueVal);
6197     else
6198       return ReplaceInstUsesWith(SI, FalseVal);
6199   }
6200
6201   if (SI.getType() == Type::BoolTy)
6202     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6203       if (C->getValue()) {
6204         // Change: A = select B, true, C --> A = or B, C
6205         return BinaryOperator::createOr(CondVal, FalseVal);
6206       } else {
6207         // Change: A = select B, false, C --> A = and !B, C
6208         Value *NotCond =
6209           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6210                                              "not."+CondVal->getName()), SI);
6211         return BinaryOperator::createAnd(NotCond, FalseVal);
6212       }
6213     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6214       if (C->getValue() == false) {
6215         // Change: A = select B, C, false --> A = and B, C
6216         return BinaryOperator::createAnd(CondVal, TrueVal);
6217       } else {
6218         // Change: A = select B, C, true --> A = or !B, C
6219         Value *NotCond =
6220           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6221                                              "not."+CondVal->getName()), SI);
6222         return BinaryOperator::createOr(NotCond, TrueVal);
6223       }
6224     }
6225
6226   // Selecting between two integer constants?
6227   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6228     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6229       // select C, 1, 0 -> cast C to int
6230       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6231         return new CastInst(CondVal, SI.getType());
6232       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6233         // select C, 0, 1 -> cast !C to int
6234         Value *NotCond =
6235           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6236                                                "not."+CondVal->getName()), SI);
6237         return new CastInst(NotCond, SI.getType());
6238       }
6239
6240       if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6241
6242         // (x <s 0) ? -1 : 0 -> sra x, 31
6243         // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6244         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6245           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6246             bool CanXForm = false;
6247             if (CmpCst->getType()->isSigned())
6248               CanXForm = CmpCst->isNullValue() && 
6249                          IC->getOpcode() == Instruction::SetLT;
6250             else {
6251               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6252               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6253                          IC->getOpcode() == Instruction::SetGT;
6254             }
6255             
6256             if (CanXForm) {
6257               // The comparison constant and the result are not neccessarily the
6258               // same width.  In any case, the first step to do is make sure
6259               // that X is signed.
6260               Value *X = IC->getOperand(0);
6261               if (!X->getType()->isSigned())
6262                 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6263               
6264               // Now that X is signed, we have to make the all ones value.  Do
6265               // this by inserting a new SRA.
6266               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6267               Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6268               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6269                                                ShAmt, "ones");
6270               InsertNewInstBefore(SRA, SI);
6271               
6272               // Finally, convert to the type of the select RHS.  If this is
6273               // smaller than the compare value, it will truncate the ones to
6274               // fit. If it is larger, it will sext the ones to fit.
6275               return new CastInst(SRA, SI.getType());
6276             }
6277           }
6278
6279
6280         // If one of the constants is zero (we know they can't both be) and we
6281         // have a setcc instruction with zero, and we have an 'and' with the
6282         // non-constant value, eliminate this whole mess.  This corresponds to
6283         // cases like this: ((X & 27) ? 27 : 0)
6284         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6285           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6286               cast<Constant>(IC->getOperand(1))->isNullValue())
6287             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6288               if (ICA->getOpcode() == Instruction::And &&
6289                   isa<ConstantInt>(ICA->getOperand(1)) &&
6290                   (ICA->getOperand(1) == TrueValC ||
6291                    ICA->getOperand(1) == FalseValC) &&
6292                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6293                 // Okay, now we know that everything is set up, we just don't
6294                 // know whether we have a setne or seteq and whether the true or
6295                 // false val is the zero.
6296                 bool ShouldNotVal = !TrueValC->isNullValue();
6297                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6298                 Value *V = ICA;
6299                 if (ShouldNotVal)
6300                   V = InsertNewInstBefore(BinaryOperator::create(
6301                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6302                 return ReplaceInstUsesWith(SI, V);
6303               }
6304       }
6305     }
6306
6307   // See if we are selecting two values based on a comparison of the two values.
6308   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6309     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6310       // Transform (X == Y) ? X : Y  -> Y
6311       if (SCI->getOpcode() == Instruction::SetEQ)
6312         return ReplaceInstUsesWith(SI, FalseVal);
6313       // Transform (X != Y) ? X : Y  -> X
6314       if (SCI->getOpcode() == Instruction::SetNE)
6315         return ReplaceInstUsesWith(SI, TrueVal);
6316       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6317
6318     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6319       // Transform (X == Y) ? Y : X  -> X
6320       if (SCI->getOpcode() == Instruction::SetEQ)
6321         return ReplaceInstUsesWith(SI, FalseVal);
6322       // Transform (X != Y) ? Y : X  -> Y
6323       if (SCI->getOpcode() == Instruction::SetNE)
6324         return ReplaceInstUsesWith(SI, TrueVal);
6325       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6326     }
6327   }
6328
6329   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6330     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6331       if (TI->hasOneUse() && FI->hasOneUse()) {
6332         Instruction *AddOp = 0, *SubOp = 0;
6333
6334         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6335         if (TI->getOpcode() == FI->getOpcode())
6336           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6337             return IV;
6338
6339         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6340         // even legal for FP.
6341         if (TI->getOpcode() == Instruction::Sub &&
6342             FI->getOpcode() == Instruction::Add) {
6343           AddOp = FI; SubOp = TI;
6344         } else if (FI->getOpcode() == Instruction::Sub &&
6345                    TI->getOpcode() == Instruction::Add) {
6346           AddOp = TI; SubOp = FI;
6347         }
6348
6349         if (AddOp) {
6350           Value *OtherAddOp = 0;
6351           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6352             OtherAddOp = AddOp->getOperand(1);
6353           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6354             OtherAddOp = AddOp->getOperand(0);
6355           }
6356
6357           if (OtherAddOp) {
6358             // So at this point we know we have (Y -> OtherAddOp):
6359             //        select C, (add X, Y), (sub X, Z)
6360             Value *NegVal;  // Compute -Z
6361             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6362               NegVal = ConstantExpr::getNeg(C);
6363             } else {
6364               NegVal = InsertNewInstBefore(
6365                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6366             }
6367
6368             Value *NewTrueOp = OtherAddOp;
6369             Value *NewFalseOp = NegVal;
6370             if (AddOp != TI)
6371               std::swap(NewTrueOp, NewFalseOp);
6372             Instruction *NewSel =
6373               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6374
6375             NewSel = InsertNewInstBefore(NewSel, SI);
6376             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6377           }
6378         }
6379       }
6380
6381   // See if we can fold the select into one of our operands.
6382   if (SI.getType()->isInteger()) {
6383     // See the comment above GetSelectFoldableOperands for a description of the
6384     // transformation we are doing here.
6385     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6386       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6387           !isa<Constant>(FalseVal))
6388         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6389           unsigned OpToFold = 0;
6390           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6391             OpToFold = 1;
6392           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6393             OpToFold = 2;
6394           }
6395
6396           if (OpToFold) {
6397             Constant *C = GetSelectFoldableConstant(TVI);
6398             std::string Name = TVI->getName(); TVI->setName("");
6399             Instruction *NewSel =
6400               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6401                              Name);
6402             InsertNewInstBefore(NewSel, SI);
6403             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6404               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6405             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6406               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6407             else {
6408               assert(0 && "Unknown instruction!!");
6409             }
6410           }
6411         }
6412
6413     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6414       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6415           !isa<Constant>(TrueVal))
6416         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6417           unsigned OpToFold = 0;
6418           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6419             OpToFold = 1;
6420           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6421             OpToFold = 2;
6422           }
6423
6424           if (OpToFold) {
6425             Constant *C = GetSelectFoldableConstant(FVI);
6426             std::string Name = FVI->getName(); FVI->setName("");
6427             Instruction *NewSel =
6428               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6429                              Name);
6430             InsertNewInstBefore(NewSel, SI);
6431             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6432               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6433             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6434               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6435             else {
6436               assert(0 && "Unknown instruction!!");
6437             }
6438           }
6439         }
6440   }
6441
6442   if (BinaryOperator::isNot(CondVal)) {
6443     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6444     SI.setOperand(1, FalseVal);
6445     SI.setOperand(2, TrueVal);
6446     return &SI;
6447   }
6448
6449   return 0;
6450 }
6451
6452 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6453 /// determine, return it, otherwise return 0.
6454 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6455   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6456     unsigned Align = GV->getAlignment();
6457     if (Align == 0 && TD) 
6458       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6459     return Align;
6460   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6461     unsigned Align = AI->getAlignment();
6462     if (Align == 0 && TD) {
6463       if (isa<AllocaInst>(AI))
6464         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6465       else if (isa<MallocInst>(AI)) {
6466         // Malloc returns maximally aligned memory.
6467         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6468         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6469         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6470       }
6471     }
6472     return Align;
6473   } else if (isa<CastInst>(V) ||
6474              (isa<ConstantExpr>(V) && 
6475               cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6476     User *CI = cast<User>(V);
6477     if (isa<PointerType>(CI->getOperand(0)->getType()))
6478       return GetKnownAlignment(CI->getOperand(0), TD);
6479     return 0;
6480   } else if (isa<GetElementPtrInst>(V) ||
6481              (isa<ConstantExpr>(V) && 
6482               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6483     User *GEPI = cast<User>(V);
6484     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6485     if (BaseAlignment == 0) return 0;
6486     
6487     // If all indexes are zero, it is just the alignment of the base pointer.
6488     bool AllZeroOperands = true;
6489     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6490       if (!isa<Constant>(GEPI->getOperand(i)) ||
6491           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6492         AllZeroOperands = false;
6493         break;
6494       }
6495     if (AllZeroOperands)
6496       return BaseAlignment;
6497     
6498     // Otherwise, if the base alignment is >= the alignment we expect for the
6499     // base pointer type, then we know that the resultant pointer is aligned at
6500     // least as much as its type requires.
6501     if (!TD) return 0;
6502
6503     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6504     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6505         <= BaseAlignment) {
6506       const Type *GEPTy = GEPI->getType();
6507       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6508     }
6509     return 0;
6510   }
6511   return 0;
6512 }
6513
6514
6515 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6516 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6517 /// the heavy lifting.
6518 ///
6519 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6520   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6521   if (!II) return visitCallSite(&CI);
6522   
6523   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6524   // visitCallSite.
6525   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6526     bool Changed = false;
6527
6528     // memmove/cpy/set of zero bytes is a noop.
6529     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6530       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6531
6532       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6533         if (CI->getZExtValue() == 1) {
6534           // Replace the instruction with just byte operations.  We would
6535           // transform other cases to loads/stores, but we don't know if
6536           // alignment is sufficient.
6537         }
6538     }
6539
6540     // If we have a memmove and the source operation is a constant global,
6541     // then the source and dest pointers can't alias, so we can change this
6542     // into a call to memcpy.
6543     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6544       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6545         if (GVSrc->isConstant()) {
6546           Module *M = CI.getParent()->getParent()->getParent();
6547           const char *Name;
6548           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6549               Type::UIntTy)
6550             Name = "llvm.memcpy.i32";
6551           else
6552             Name = "llvm.memcpy.i64";
6553           Function *MemCpy = M->getOrInsertFunction(Name,
6554                                      CI.getCalledFunction()->getFunctionType());
6555           CI.setOperand(0, MemCpy);
6556           Changed = true;
6557         }
6558     }
6559
6560     // If we can determine a pointer alignment that is bigger than currently
6561     // set, update the alignment.
6562     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6563       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6564       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6565       unsigned Align = std::min(Alignment1, Alignment2);
6566       if (MI->getAlignment()->getZExtValue() < Align) {
6567         MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6568         Changed = true;
6569       }
6570     } else if (isa<MemSetInst>(MI)) {
6571       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6572       if (MI->getAlignment()->getZExtValue() < Alignment) {
6573         MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6574         Changed = true;
6575       }
6576     }
6577           
6578     if (Changed) return II;
6579   } else {
6580     switch (II->getIntrinsicID()) {
6581     default: break;
6582     case Intrinsic::ppc_altivec_lvx:
6583     case Intrinsic::ppc_altivec_lvxl:
6584     case Intrinsic::x86_sse_loadu_ps:
6585     case Intrinsic::x86_sse2_loadu_pd:
6586     case Intrinsic::x86_sse2_loadu_dq:
6587       // Turn PPC lvx     -> load if the pointer is known aligned.
6588       // Turn X86 loadups -> load if the pointer is known aligned.
6589       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6590         Value *Ptr = InsertCastBefore(II->getOperand(1),
6591                                       PointerType::get(II->getType()), CI);
6592         return new LoadInst(Ptr);
6593       }
6594       break;
6595     case Intrinsic::ppc_altivec_stvx:
6596     case Intrinsic::ppc_altivec_stvxl:
6597       // Turn stvx -> store if the pointer is known aligned.
6598       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6599         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6600         Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6601         return new StoreInst(II->getOperand(1), Ptr);
6602       }
6603       break;
6604     case Intrinsic::x86_sse_storeu_ps:
6605     case Intrinsic::x86_sse2_storeu_pd:
6606     case Intrinsic::x86_sse2_storeu_dq:
6607     case Intrinsic::x86_sse2_storel_dq:
6608       // Turn X86 storeu -> store if the pointer is known aligned.
6609       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6610         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6611         Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6612         return new StoreInst(II->getOperand(2), Ptr);
6613       }
6614       break;
6615       
6616     case Intrinsic::x86_sse_cvttss2si: {
6617       // These intrinsics only demands the 0th element of its input vector.  If
6618       // we can simplify the input based on that, do so now.
6619       uint64_t UndefElts;
6620       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
6621                                                 UndefElts)) {
6622         II->setOperand(1, V);
6623         return II;
6624       }
6625       break;
6626     }
6627       
6628     case Intrinsic::ppc_altivec_vperm:
6629       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6630       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6631         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6632         
6633         // Check that all of the elements are integer constants or undefs.
6634         bool AllEltsOk = true;
6635         for (unsigned i = 0; i != 16; ++i) {
6636           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
6637               !isa<UndefValue>(Mask->getOperand(i))) {
6638             AllEltsOk = false;
6639             break;
6640           }
6641         }
6642         
6643         if (AllEltsOk) {
6644           // Cast the input vectors to byte vectors.
6645           Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6646           Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6647           Value *Result = UndefValue::get(Op0->getType());
6648           
6649           // Only extract each element once.
6650           Value *ExtractedElts[32];
6651           memset(ExtractedElts, 0, sizeof(ExtractedElts));
6652           
6653           for (unsigned i = 0; i != 16; ++i) {
6654             if (isa<UndefValue>(Mask->getOperand(i)))
6655               continue;
6656             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6657             Idx &= 31;  // Match the hardware behavior.
6658             
6659             if (ExtractedElts[Idx] == 0) {
6660               Instruction *Elt = 
6661                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6662               InsertNewInstBefore(Elt, CI);
6663               ExtractedElts[Idx] = Elt;
6664             }
6665           
6666             // Insert this value into the result vector.
6667             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6668             InsertNewInstBefore(cast<Instruction>(Result), CI);
6669           }
6670           return new CastInst(Result, CI.getType());
6671         }
6672       }
6673       break;
6674
6675     case Intrinsic::stackrestore: {
6676       // If the save is right next to the restore, remove the restore.  This can
6677       // happen when variable allocas are DCE'd.
6678       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6679         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6680           BasicBlock::iterator BI = SS;
6681           if (&*++BI == II)
6682             return EraseInstFromFunction(CI);
6683         }
6684       }
6685       
6686       // If the stack restore is in a return/unwind block and if there are no
6687       // allocas or calls between the restore and the return, nuke the restore.
6688       TerminatorInst *TI = II->getParent()->getTerminator();
6689       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6690         BasicBlock::iterator BI = II;
6691         bool CannotRemove = false;
6692         for (++BI; &*BI != TI; ++BI) {
6693           if (isa<AllocaInst>(BI) ||
6694               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6695             CannotRemove = true;
6696             break;
6697           }
6698         }
6699         if (!CannotRemove)
6700           return EraseInstFromFunction(CI);
6701       }
6702       break;
6703     }
6704     }
6705   }
6706
6707   return visitCallSite(II);
6708 }
6709
6710 // InvokeInst simplification
6711 //
6712 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6713   return visitCallSite(&II);
6714 }
6715
6716 // visitCallSite - Improvements for call and invoke instructions.
6717 //
6718 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6719   bool Changed = false;
6720
6721   // If the callee is a constexpr cast of a function, attempt to move the cast
6722   // to the arguments of the call/invoke.
6723   if (transformConstExprCastCall(CS)) return 0;
6724
6725   Value *Callee = CS.getCalledValue();
6726
6727   if (Function *CalleeF = dyn_cast<Function>(Callee))
6728     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6729       Instruction *OldCall = CS.getInstruction();
6730       // If the call and callee calling conventions don't match, this call must
6731       // be unreachable, as the call is undefined.
6732       new StoreInst(ConstantBool::getTrue(),
6733                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6734       if (!OldCall->use_empty())
6735         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6736       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
6737         return EraseInstFromFunction(*OldCall);
6738       return 0;
6739     }
6740
6741   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6742     // This instruction is not reachable, just remove it.  We insert a store to
6743     // undef so that we know that this code is not reachable, despite the fact
6744     // that we can't modify the CFG here.
6745     new StoreInst(ConstantBool::getTrue(),
6746                   UndefValue::get(PointerType::get(Type::BoolTy)),
6747                   CS.getInstruction());
6748
6749     if (!CS.getInstruction()->use_empty())
6750       CS.getInstruction()->
6751         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6752
6753     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6754       // Don't break the CFG, insert a dummy cond branch.
6755       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6756                      ConstantBool::getTrue(), II);
6757     }
6758     return EraseInstFromFunction(*CS.getInstruction());
6759   }
6760
6761   const PointerType *PTy = cast<PointerType>(Callee->getType());
6762   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6763   if (FTy->isVarArg()) {
6764     // See if we can optimize any arguments passed through the varargs area of
6765     // the call.
6766     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6767            E = CS.arg_end(); I != E; ++I)
6768       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6769         // If this cast does not effect the value passed through the varargs
6770         // area, we can eliminate the use of the cast.
6771         Value *Op = CI->getOperand(0);
6772         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6773           *I = Op;
6774           Changed = true;
6775         }
6776       }
6777   }
6778
6779   return Changed ? CS.getInstruction() : 0;
6780 }
6781
6782 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6783 // attempt to move the cast to the arguments of the call/invoke.
6784 //
6785 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6786   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6787   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6788   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6789     return false;
6790   Function *Callee = cast<Function>(CE->getOperand(0));
6791   Instruction *Caller = CS.getInstruction();
6792
6793   // Okay, this is a cast from a function to a different type.  Unless doing so
6794   // would cause a type conversion of one of our arguments, change this call to
6795   // be a direct call with arguments casted to the appropriate types.
6796   //
6797   const FunctionType *FT = Callee->getFunctionType();
6798   const Type *OldRetTy = Caller->getType();
6799
6800   // Check to see if we are changing the return type...
6801   if (OldRetTy != FT->getReturnType()) {
6802     if (Callee->isExternal() &&
6803         !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6804           (isa<PointerType>(FT->getReturnType()) && 
6805            TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6806         && !Caller->use_empty())
6807       return false;   // Cannot transform this return value...
6808
6809     // If the callsite is an invoke instruction, and the return value is used by
6810     // a PHI node in a successor, we cannot change the return type of the call
6811     // because there is no place to put the cast instruction (without breaking
6812     // the critical edge).  Bail out in this case.
6813     if (!Caller->use_empty())
6814       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6815         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6816              UI != E; ++UI)
6817           if (PHINode *PN = dyn_cast<PHINode>(*UI))
6818             if (PN->getParent() == II->getNormalDest() ||
6819                 PN->getParent() == II->getUnwindDest())
6820               return false;
6821   }
6822
6823   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6824   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6825
6826   CallSite::arg_iterator AI = CS.arg_begin();
6827   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6828     const Type *ParamTy = FT->getParamType(i);
6829     const Type *ActTy = (*AI)->getType();
6830     ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6831     //Either we can cast directly, or we can upconvert the argument
6832     bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6833       (ParamTy->isIntegral() && ActTy->isIntegral() &&
6834        ParamTy->isSigned() == ActTy->isSigned() &&
6835        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6836       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6837        c->getSExtValue() > 0);
6838     if (Callee->isExternal() && !isConvertible) return false;
6839   }
6840
6841   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6842       Callee->isExternal())
6843     return false;   // Do not delete arguments unless we have a function body...
6844
6845   // Okay, we decided that this is a safe thing to do: go ahead and start
6846   // inserting cast instructions as necessary...
6847   std::vector<Value*> Args;
6848   Args.reserve(NumActualArgs);
6849
6850   AI = CS.arg_begin();
6851   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6852     const Type *ParamTy = FT->getParamType(i);
6853     if ((*AI)->getType() == ParamTy) {
6854       Args.push_back(*AI);
6855     } else {
6856       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6857                                          *Caller));
6858     }
6859   }
6860
6861   // If the function takes more arguments than the call was taking, add them
6862   // now...
6863   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6864     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6865
6866   // If we are removing arguments to the function, emit an obnoxious warning...
6867   if (FT->getNumParams() < NumActualArgs)
6868     if (!FT->isVarArg()) {
6869       llvm_cerr << "WARNING: While resolving call to function '"
6870                 << Callee->getName() << "' arguments were dropped!\n";
6871     } else {
6872       // Add all of the arguments in their promoted form to the arg list...
6873       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6874         const Type *PTy = getPromotedType((*AI)->getType());
6875         if (PTy != (*AI)->getType()) {
6876           // Must promote to pass through va_arg area!
6877           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6878           InsertNewInstBefore(Cast, *Caller);
6879           Args.push_back(Cast);
6880         } else {
6881           Args.push_back(*AI);
6882         }
6883       }
6884     }
6885
6886   if (FT->getReturnType() == Type::VoidTy)
6887     Caller->setName("");   // Void type should not have a name...
6888
6889   Instruction *NC;
6890   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6891     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6892                         Args, Caller->getName(), Caller);
6893     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6894   } else {
6895     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6896     if (cast<CallInst>(Caller)->isTailCall())
6897       cast<CallInst>(NC)->setTailCall();
6898    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6899   }
6900
6901   // Insert a cast of the return type as necessary...
6902   Value *NV = NC;
6903   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6904     if (NV->getType() != Type::VoidTy) {
6905       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6906
6907       // If this is an invoke instruction, we should insert it after the first
6908       // non-phi, instruction in the normal successor block.
6909       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6910         BasicBlock::iterator I = II->getNormalDest()->begin();
6911         while (isa<PHINode>(I)) ++I;
6912         InsertNewInstBefore(NC, *I);
6913       } else {
6914         // Otherwise, it's a call, just insert cast right after the call instr
6915         InsertNewInstBefore(NC, *Caller);
6916       }
6917       AddUsersToWorkList(*Caller);
6918     } else {
6919       NV = UndefValue::get(Caller->getType());
6920     }
6921   }
6922
6923   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6924     Caller->replaceAllUsesWith(NV);
6925   Caller->getParent()->getInstList().erase(Caller);
6926   removeFromWorkList(Caller);
6927   return true;
6928 }
6929
6930 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6931 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6932 /// and a single binop.
6933 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6934   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6935   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6936          isa<GetElementPtrInst>(FirstInst));
6937   unsigned Opc = FirstInst->getOpcode();
6938   Value *LHSVal = FirstInst->getOperand(0);
6939   Value *RHSVal = FirstInst->getOperand(1);
6940     
6941   const Type *LHSType = LHSVal->getType();
6942   const Type *RHSType = RHSVal->getType();
6943   
6944   // Scan to see if all operands are the same opcode, all have one use, and all
6945   // kill their operands (i.e. the operands have one use).
6946   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
6947     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
6948     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6949         // Verify type of the LHS matches so we don't fold setcc's of different
6950         // types or GEP's with different index types.
6951         I->getOperand(0)->getType() != LHSType ||
6952         I->getOperand(1)->getType() != RHSType)
6953       return 0;
6954     
6955     // Keep track of which operand needs a phi node.
6956     if (I->getOperand(0) != LHSVal) LHSVal = 0;
6957     if (I->getOperand(1) != RHSVal) RHSVal = 0;
6958   }
6959   
6960   // Otherwise, this is safe to transform, determine if it is profitable.
6961
6962   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
6963   // Indexes are often folded into load/store instructions, so we don't want to
6964   // hide them behind a phi.
6965   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
6966     return 0;
6967   
6968   Value *InLHS = FirstInst->getOperand(0);
6969   Value *InRHS = FirstInst->getOperand(1);
6970   PHINode *NewLHS = 0, *NewRHS = 0;
6971   if (LHSVal == 0) {
6972     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6973     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6974     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6975     InsertNewInstBefore(NewLHS, PN);
6976     LHSVal = NewLHS;
6977   }
6978   
6979   if (RHSVal == 0) {
6980     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6981     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6982     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6983     InsertNewInstBefore(NewRHS, PN);
6984     RHSVal = NewRHS;
6985   }
6986   
6987   // Add all operands to the new PHIs.
6988   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6989     if (NewLHS) {
6990       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6991       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6992     }
6993     if (NewRHS) {
6994       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6995       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6996     }
6997   }
6998     
6999   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7000     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7001   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7002     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7003   else {
7004     assert(isa<GetElementPtrInst>(FirstInst));
7005     return new GetElementPtrInst(LHSVal, RHSVal);
7006   }
7007 }
7008
7009 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7010 /// of the block that defines it.  This means that it must be obvious the value
7011 /// of the load is not changed from the point of the load to the end of the
7012 /// block it is in.
7013 static bool isSafeToSinkLoad(LoadInst *L) {
7014   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7015   
7016   for (++BBI; BBI != E; ++BBI)
7017     if (BBI->mayWriteToMemory())
7018       return false;
7019   return true;
7020 }
7021
7022
7023 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7024 // operator and they all are only used by the PHI, PHI together their
7025 // inputs, and do the operation once, to the result of the PHI.
7026 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7027   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7028
7029   // Scan the instruction, looking for input operations that can be folded away.
7030   // If all input operands to the phi are the same instruction (e.g. a cast from
7031   // the same type or "+42") we can pull the operation through the PHI, reducing
7032   // code size and simplifying code.
7033   Constant *ConstantOp = 0;
7034   const Type *CastSrcTy = 0;
7035   bool isVolatile = false;
7036   if (isa<CastInst>(FirstInst)) {
7037     CastSrcTy = FirstInst->getOperand(0)->getType();
7038   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
7039     // Can fold binop or shift here if the RHS is a constant, otherwise call
7040     // FoldPHIArgBinOpIntoPHI.
7041     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7042     if (ConstantOp == 0)
7043       return FoldPHIArgBinOpIntoPHI(PN);
7044   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7045     isVolatile = LI->isVolatile();
7046     // We can't sink the load if the loaded value could be modified between the
7047     // load and the PHI.
7048     if (LI->getParent() != PN.getIncomingBlock(0) ||
7049         !isSafeToSinkLoad(LI))
7050       return 0;
7051   } else if (isa<GetElementPtrInst>(FirstInst)) {
7052     if (FirstInst->getNumOperands() == 2)
7053       return FoldPHIArgBinOpIntoPHI(PN);
7054     // Can't handle general GEPs yet.
7055     return 0;
7056   } else {
7057     return 0;  // Cannot fold this operation.
7058   }
7059
7060   // Check to see if all arguments are the same operation.
7061   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7062     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7063     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7064     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7065       return 0;
7066     if (CastSrcTy) {
7067       if (I->getOperand(0)->getType() != CastSrcTy)
7068         return 0;  // Cast operation must match.
7069     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7070       // We can't sink the load if the loaded value could be modified between the
7071       // load and the PHI.
7072       if (LI->isVolatile() != isVolatile ||
7073           LI->getParent() != PN.getIncomingBlock(i) ||
7074           !isSafeToSinkLoad(LI))
7075         return 0;
7076     } else if (I->getOperand(1) != ConstantOp) {
7077       return 0;
7078     }
7079   }
7080
7081   // Okay, they are all the same operation.  Create a new PHI node of the
7082   // correct type, and PHI together all of the LHS's of the instructions.
7083   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7084                                PN.getName()+".in");
7085   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7086
7087   Value *InVal = FirstInst->getOperand(0);
7088   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7089
7090   // Add all operands to the new PHI.
7091   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7092     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7093     if (NewInVal != InVal)
7094       InVal = 0;
7095     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7096   }
7097
7098   Value *PhiVal;
7099   if (InVal) {
7100     // The new PHI unions all of the same values together.  This is really
7101     // common, so we handle it intelligently here for compile-time speed.
7102     PhiVal = InVal;
7103     delete NewPN;
7104   } else {
7105     InsertNewInstBefore(NewPN, PN);
7106     PhiVal = NewPN;
7107   }
7108
7109   // Insert and return the new operation.
7110   if (isa<CastInst>(FirstInst))
7111     return new CastInst(PhiVal, PN.getType());
7112   else if (isa<LoadInst>(FirstInst))
7113     return new LoadInst(PhiVal, "", isVolatile);
7114   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7115     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7116   else
7117     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7118                          PhiVal, ConstantOp);
7119 }
7120
7121 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7122 /// that is dead.
7123 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7124   if (PN->use_empty()) return true;
7125   if (!PN->hasOneUse()) return false;
7126
7127   // Remember this node, and if we find the cycle, return.
7128   if (!PotentiallyDeadPHIs.insert(PN).second)
7129     return true;
7130
7131   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7132     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7133
7134   return false;
7135 }
7136
7137 // PHINode simplification
7138 //
7139 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7140   // If LCSSA is around, don't mess with Phi nodes
7141   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7142   
7143   if (Value *V = PN.hasConstantValue())
7144     return ReplaceInstUsesWith(PN, V);
7145
7146   // If all PHI operands are the same operation, pull them through the PHI,
7147   // reducing code size.
7148   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7149       PN.getIncomingValue(0)->hasOneUse())
7150     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7151       return Result;
7152
7153   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7154   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7155   // PHI)... break the cycle.
7156   if (PN.hasOneUse())
7157     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7158       std::set<PHINode*> PotentiallyDeadPHIs;
7159       PotentiallyDeadPHIs.insert(&PN);
7160       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7161         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7162     }
7163
7164   return 0;
7165 }
7166
7167 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7168                                       Instruction *InsertPoint,
7169                                       InstCombiner *IC) {
7170   unsigned PS = IC->getTargetData().getPointerSize();
7171   const Type *VTy = V->getType();
7172   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7173     // We must insert a cast to ensure we sign-extend.
7174     V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7175   return IC->InsertCastBefore(V, DTy, *InsertPoint);
7176 }
7177
7178
7179 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7180   Value *PtrOp = GEP.getOperand(0);
7181   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7182   // If so, eliminate the noop.
7183   if (GEP.getNumOperands() == 1)
7184     return ReplaceInstUsesWith(GEP, PtrOp);
7185
7186   if (isa<UndefValue>(GEP.getOperand(0)))
7187     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7188
7189   bool HasZeroPointerIndex = false;
7190   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7191     HasZeroPointerIndex = C->isNullValue();
7192
7193   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7194     return ReplaceInstUsesWith(GEP, PtrOp);
7195
7196   // Eliminate unneeded casts for indices.
7197   bool MadeChange = false;
7198   gep_type_iterator GTI = gep_type_begin(GEP);
7199   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7200     if (isa<SequentialType>(*GTI)) {
7201       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7202         Value *Src = CI->getOperand(0);
7203         const Type *SrcTy = Src->getType();
7204         const Type *DestTy = CI->getType();
7205         if (Src->getType()->isInteger()) {
7206           if (SrcTy->getPrimitiveSizeInBits() ==
7207                        DestTy->getPrimitiveSizeInBits()) {
7208             // We can always eliminate a cast from ulong or long to the other.
7209             // We can always eliminate a cast from uint to int or the other on
7210             // 32-bit pointer platforms.
7211             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7212               MadeChange = true;
7213               GEP.setOperand(i, Src);
7214             }
7215           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7216                      SrcTy->getPrimitiveSize() == 4) {
7217             // We can always eliminate a cast from int to [u]long.  We can
7218             // eliminate a cast from uint to [u]long iff the target is a 32-bit
7219             // pointer target.
7220             if (SrcTy->isSigned() ||
7221                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7222               MadeChange = true;
7223               GEP.setOperand(i, Src);
7224             }
7225           }
7226         }
7227       }
7228       // If we are using a wider index than needed for this platform, shrink it
7229       // to what we need.  If the incoming value needs a cast instruction,
7230       // insert it.  This explicit cast can make subsequent optimizations more
7231       // obvious.
7232       Value *Op = GEP.getOperand(i);
7233       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7234         if (Constant *C = dyn_cast<Constant>(Op)) {
7235           GEP.setOperand(i, ConstantExpr::getCast(C,
7236                                      TD->getIntPtrType()->getSignedVersion()));
7237           MadeChange = true;
7238         } else {
7239           Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
7240           GEP.setOperand(i, Op);
7241           MadeChange = true;
7242         }
7243
7244       // If this is a constant idx, make sure to canonicalize it to be a signed
7245       // operand, otherwise CSE and other optimizations are pessimized.
7246       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7247         if (CUI->getType()->isUnsigned()) {
7248           GEP.setOperand(i, 
7249             ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7250           MadeChange = true;
7251         }
7252     }
7253   if (MadeChange) return &GEP;
7254
7255   // Combine Indices - If the source pointer to this getelementptr instruction
7256   // is a getelementptr instruction, combine the indices of the two
7257   // getelementptr instructions into a single instruction.
7258   //
7259   std::vector<Value*> SrcGEPOperands;
7260   if (User *Src = dyn_castGetElementPtr(PtrOp))
7261     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7262
7263   if (!SrcGEPOperands.empty()) {
7264     // Note that if our source is a gep chain itself that we wait for that
7265     // chain to be resolved before we perform this transformation.  This
7266     // avoids us creating a TON of code in some cases.
7267     //
7268     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7269         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7270       return 0;   // Wait until our source is folded to completion.
7271
7272     std::vector<Value *> Indices;
7273
7274     // Find out whether the last index in the source GEP is a sequential idx.
7275     bool EndsWithSequential = false;
7276     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7277            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7278       EndsWithSequential = !isa<StructType>(*I);
7279
7280     // Can we combine the two pointer arithmetics offsets?
7281     if (EndsWithSequential) {
7282       // Replace: gep (gep %P, long B), long A, ...
7283       // With:    T = long A+B; gep %P, T, ...
7284       //
7285       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7286       if (SO1 == Constant::getNullValue(SO1->getType())) {
7287         Sum = GO1;
7288       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7289         Sum = SO1;
7290       } else {
7291         // If they aren't the same type, convert both to an integer of the
7292         // target's pointer size.
7293         if (SO1->getType() != GO1->getType()) {
7294           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7295             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7296           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7297             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7298           } else {
7299             unsigned PS = TD->getPointerSize();
7300             if (SO1->getType()->getPrimitiveSize() == PS) {
7301               // Convert GO1 to SO1's type.
7302               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7303
7304             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7305               // Convert SO1 to GO1's type.
7306               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7307             } else {
7308               const Type *PT = TD->getIntPtrType();
7309               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7310               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7311             }
7312           }
7313         }
7314         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7315           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7316         else {
7317           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7318           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7319         }
7320       }
7321
7322       // Recycle the GEP we already have if possible.
7323       if (SrcGEPOperands.size() == 2) {
7324         GEP.setOperand(0, SrcGEPOperands[0]);
7325         GEP.setOperand(1, Sum);
7326         return &GEP;
7327       } else {
7328         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7329                        SrcGEPOperands.end()-1);
7330         Indices.push_back(Sum);
7331         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7332       }
7333     } else if (isa<Constant>(*GEP.idx_begin()) &&
7334                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7335                SrcGEPOperands.size() != 1) {
7336       // Otherwise we can do the fold if the first index of the GEP is a zero
7337       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7338                      SrcGEPOperands.end());
7339       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7340     }
7341
7342     if (!Indices.empty())
7343       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7344
7345   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7346     // GEP of global variable.  If all of the indices for this GEP are
7347     // constants, we can promote this to a constexpr instead of an instruction.
7348
7349     // Scan for nonconstants...
7350     std::vector<Constant*> Indices;
7351     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7352     for (; I != E && isa<Constant>(*I); ++I)
7353       Indices.push_back(cast<Constant>(*I));
7354
7355     if (I == E) {  // If they are all constants...
7356       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7357
7358       // Replace all uses of the GEP with the new constexpr...
7359       return ReplaceInstUsesWith(GEP, CE);
7360     }
7361   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
7362     if (!isa<PointerType>(X->getType())) {
7363       // Not interesting.  Source pointer must be a cast from pointer.
7364     } else if (HasZeroPointerIndex) {
7365       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7366       // into     : GEP [10 x ubyte]* X, long 0, ...
7367       //
7368       // This occurs when the program declares an array extern like "int X[];"
7369       //
7370       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7371       const PointerType *XTy = cast<PointerType>(X->getType());
7372       if (const ArrayType *XATy =
7373           dyn_cast<ArrayType>(XTy->getElementType()))
7374         if (const ArrayType *CATy =
7375             dyn_cast<ArrayType>(CPTy->getElementType()))
7376           if (CATy->getElementType() == XATy->getElementType()) {
7377             // At this point, we know that the cast source type is a pointer
7378             // to an array of the same type as the destination pointer
7379             // array.  Because the array type is never stepped over (there
7380             // is a leading zero) we can fold the cast into this GEP.
7381             GEP.setOperand(0, X);
7382             return &GEP;
7383           }
7384     } else if (GEP.getNumOperands() == 2) {
7385       // Transform things like:
7386       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7387       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7388       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7389       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7390       if (isa<ArrayType>(SrcElTy) &&
7391           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7392           TD->getTypeSize(ResElTy)) {
7393         Value *V = InsertNewInstBefore(
7394                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7395                                      GEP.getOperand(1), GEP.getName()), GEP);
7396         return new CastInst(V, GEP.getType());
7397       }
7398       
7399       // Transform things like:
7400       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7401       //   (where tmp = 8*tmp2) into:
7402       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7403       
7404       if (isa<ArrayType>(SrcElTy) &&
7405           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7406         uint64_t ArrayEltSize =
7407             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7408         
7409         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7410         // allow either a mul, shift, or constant here.
7411         Value *NewIdx = 0;
7412         ConstantInt *Scale = 0;
7413         if (ArrayEltSize == 1) {
7414           NewIdx = GEP.getOperand(1);
7415           Scale = ConstantInt::get(NewIdx->getType(), 1);
7416         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7417           NewIdx = ConstantInt::get(CI->getType(), 1);
7418           Scale = CI;
7419         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7420           if (Inst->getOpcode() == Instruction::Shl &&
7421               isa<ConstantInt>(Inst->getOperand(1))) {
7422             unsigned ShAmt =
7423               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7424             if (Inst->getType()->isSigned())
7425               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7426             else
7427               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7428             NewIdx = Inst->getOperand(0);
7429           } else if (Inst->getOpcode() == Instruction::Mul &&
7430                      isa<ConstantInt>(Inst->getOperand(1))) {
7431             Scale = cast<ConstantInt>(Inst->getOperand(1));
7432             NewIdx = Inst->getOperand(0);
7433           }
7434         }
7435
7436         // If the index will be to exactly the right offset with the scale taken
7437         // out, perform the transformation.
7438         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7439           if (isa<ConstantInt>(Scale))
7440             Scale = ConstantInt::get(Scale->getType(),
7441                                       Scale->getZExtValue() / ArrayEltSize);
7442           if (Scale->getZExtValue() != 1) {
7443             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7444             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7445             NewIdx = InsertNewInstBefore(Sc, GEP);
7446           }
7447
7448           // Insert the new GEP instruction.
7449           Instruction *Idx =
7450             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7451                                   NewIdx, GEP.getName());
7452           Idx = InsertNewInstBefore(Idx, GEP);
7453           return new CastInst(Idx, GEP.getType());
7454         }
7455       }
7456     }
7457   }
7458
7459   return 0;
7460 }
7461
7462 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7463   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7464   if (AI.isArrayAllocation())    // Check C != 1
7465     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7466       const Type *NewTy = 
7467         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7468       AllocationInst *New = 0;
7469
7470       // Create and insert the replacement instruction...
7471       if (isa<MallocInst>(AI))
7472         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7473       else {
7474         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7475         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7476       }
7477
7478       InsertNewInstBefore(New, AI);
7479
7480       // Scan to the end of the allocation instructions, to skip over a block of
7481       // allocas if possible...
7482       //
7483       BasicBlock::iterator It = New;
7484       while (isa<AllocationInst>(*It)) ++It;
7485
7486       // Now that I is pointing to the first non-allocation-inst in the block,
7487       // insert our getelementptr instruction...
7488       //
7489       Value *NullIdx = Constant::getNullValue(Type::IntTy);
7490       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7491                                        New->getName()+".sub", It);
7492
7493       // Now make everything use the getelementptr instead of the original
7494       // allocation.
7495       return ReplaceInstUsesWith(AI, V);
7496     } else if (isa<UndefValue>(AI.getArraySize())) {
7497       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7498     }
7499
7500   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7501   // Note that we only do this for alloca's, because malloc should allocate and
7502   // return a unique pointer, even for a zero byte allocation.
7503   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7504       TD->getTypeSize(AI.getAllocatedType()) == 0)
7505     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7506
7507   return 0;
7508 }
7509
7510 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7511   Value *Op = FI.getOperand(0);
7512
7513   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7514   if (CastInst *CI = dyn_cast<CastInst>(Op))
7515     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7516       FI.setOperand(0, CI->getOperand(0));
7517       return &FI;
7518     }
7519
7520   // free undef -> unreachable.
7521   if (isa<UndefValue>(Op)) {
7522     // Insert a new store to null because we cannot modify the CFG here.
7523     new StoreInst(ConstantBool::getTrue(),
7524                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7525     return EraseInstFromFunction(FI);
7526   }
7527
7528   // If we have 'free null' delete the instruction.  This can happen in stl code
7529   // when lots of inlining happens.
7530   if (isa<ConstantPointerNull>(Op))
7531     return EraseInstFromFunction(FI);
7532
7533   return 0;
7534 }
7535
7536
7537 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7538 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7539   User *CI = cast<User>(LI.getOperand(0));
7540   Value *CastOp = CI->getOperand(0);
7541
7542   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7543   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7544     const Type *SrcPTy = SrcTy->getElementType();
7545
7546     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7547         isa<PackedType>(DestPTy)) {
7548       // If the source is an array, the code below will not succeed.  Check to
7549       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7550       // constants.
7551       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7552         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7553           if (ASrcTy->getNumElements() != 0) {
7554             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7555             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7556             SrcTy = cast<PointerType>(CastOp->getType());
7557             SrcPTy = SrcTy->getElementType();
7558           }
7559
7560       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7561            isa<PackedType>(SrcPTy)) &&
7562           // Do not allow turning this into a load of an integer, which is then
7563           // casted to a pointer, this pessimizes pointer analysis a lot.
7564           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7565           IC.getTargetData().getTypeSize(SrcPTy) ==
7566                IC.getTargetData().getTypeSize(DestPTy)) {
7567
7568         // Okay, we are casting from one integer or pointer type to another of
7569         // the same size.  Instead of casting the pointer before the load, cast
7570         // the result of the loaded value.
7571         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7572                                                              CI->getName(),
7573                                                          LI.isVolatile()),LI);
7574         // Now cast the result of the load.
7575         return new CastInst(NewLoad, LI.getType());
7576       }
7577     }
7578   }
7579   return 0;
7580 }
7581
7582 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7583 /// from this value cannot trap.  If it is not obviously safe to load from the
7584 /// specified pointer, we do a quick local scan of the basic block containing
7585 /// ScanFrom, to determine if the address is already accessed.
7586 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7587   // If it is an alloca or global variable, it is always safe to load from.
7588   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7589
7590   // Otherwise, be a little bit agressive by scanning the local block where we
7591   // want to check to see if the pointer is already being loaded or stored
7592   // from/to.  If so, the previous load or store would have already trapped,
7593   // so there is no harm doing an extra load (also, CSE will later eliminate
7594   // the load entirely).
7595   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7596
7597   while (BBI != E) {
7598     --BBI;
7599
7600     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7601       if (LI->getOperand(0) == V) return true;
7602     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7603       if (SI->getOperand(1) == V) return true;
7604
7605   }
7606   return false;
7607 }
7608
7609 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7610   Value *Op = LI.getOperand(0);
7611
7612   // load (cast X) --> cast (load X) iff safe
7613   if (isa<CastInst>(Op))
7614     if (Instruction *Res = InstCombineLoadCast(*this, LI))
7615       return Res;
7616
7617   // None of the following transforms are legal for volatile loads.
7618   if (LI.isVolatile()) return 0;
7619   
7620   if (&LI.getParent()->front() != &LI) {
7621     BasicBlock::iterator BBI = &LI; --BBI;
7622     // If the instruction immediately before this is a store to the same
7623     // address, do a simple form of store->load forwarding.
7624     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7625       if (SI->getOperand(1) == LI.getOperand(0))
7626         return ReplaceInstUsesWith(LI, SI->getOperand(0));
7627     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7628       if (LIB->getOperand(0) == LI.getOperand(0))
7629         return ReplaceInstUsesWith(LI, LIB);
7630   }
7631
7632   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7633     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7634         isa<UndefValue>(GEPI->getOperand(0))) {
7635       // Insert a new store to null instruction before the load to indicate
7636       // that this code is not reachable.  We do this instead of inserting
7637       // an unreachable instruction directly because we cannot modify the
7638       // CFG.
7639       new StoreInst(UndefValue::get(LI.getType()),
7640                     Constant::getNullValue(Op->getType()), &LI);
7641       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7642     }
7643
7644   if (Constant *C = dyn_cast<Constant>(Op)) {
7645     // load null/undef -> undef
7646     if ((C->isNullValue() || isa<UndefValue>(C))) {
7647       // Insert a new store to null instruction before the load to indicate that
7648       // this code is not reachable.  We do this instead of inserting an
7649       // unreachable instruction directly because we cannot modify the CFG.
7650       new StoreInst(UndefValue::get(LI.getType()),
7651                     Constant::getNullValue(Op->getType()), &LI);
7652       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7653     }
7654
7655     // Instcombine load (constant global) into the value loaded.
7656     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7657       if (GV->isConstant() && !GV->isExternal())
7658         return ReplaceInstUsesWith(LI, GV->getInitializer());
7659
7660     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7661     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7662       if (CE->getOpcode() == Instruction::GetElementPtr) {
7663         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7664           if (GV->isConstant() && !GV->isExternal())
7665             if (Constant *V = 
7666                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7667               return ReplaceInstUsesWith(LI, V);
7668         if (CE->getOperand(0)->isNullValue()) {
7669           // Insert a new store to null instruction before the load to indicate
7670           // that this code is not reachable.  We do this instead of inserting
7671           // an unreachable instruction directly because we cannot modify the
7672           // CFG.
7673           new StoreInst(UndefValue::get(LI.getType()),
7674                         Constant::getNullValue(Op->getType()), &LI);
7675           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7676         }
7677
7678       } else if (CE->getOpcode() == Instruction::Cast) {
7679         if (Instruction *Res = InstCombineLoadCast(*this, LI))
7680           return Res;
7681       }
7682   }
7683
7684   if (Op->hasOneUse()) {
7685     // Change select and PHI nodes to select values instead of addresses: this
7686     // helps alias analysis out a lot, allows many others simplifications, and
7687     // exposes redundancy in the code.
7688     //
7689     // Note that we cannot do the transformation unless we know that the
7690     // introduced loads cannot trap!  Something like this is valid as long as
7691     // the condition is always false: load (select bool %C, int* null, int* %G),
7692     // but it would not be valid if we transformed it to load from null
7693     // unconditionally.
7694     //
7695     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7696       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
7697       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7698           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7699         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7700                                      SI->getOperand(1)->getName()+".val"), LI);
7701         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7702                                      SI->getOperand(2)->getName()+".val"), LI);
7703         return new SelectInst(SI->getCondition(), V1, V2);
7704       }
7705
7706       // load (select (cond, null, P)) -> load P
7707       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7708         if (C->isNullValue()) {
7709           LI.setOperand(0, SI->getOperand(2));
7710           return &LI;
7711         }
7712
7713       // load (select (cond, P, null)) -> load P
7714       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7715         if (C->isNullValue()) {
7716           LI.setOperand(0, SI->getOperand(1));
7717           return &LI;
7718         }
7719     }
7720   }
7721   return 0;
7722 }
7723
7724 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7725 /// when possible.
7726 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7727   User *CI = cast<User>(SI.getOperand(1));
7728   Value *CastOp = CI->getOperand(0);
7729
7730   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7731   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7732     const Type *SrcPTy = SrcTy->getElementType();
7733
7734     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7735       // If the source is an array, the code below will not succeed.  Check to
7736       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7737       // constants.
7738       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7739         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7740           if (ASrcTy->getNumElements() != 0) {
7741             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7742             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7743             SrcTy = cast<PointerType>(CastOp->getType());
7744             SrcPTy = SrcTy->getElementType();
7745           }
7746
7747       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7748           IC.getTargetData().getTypeSize(SrcPTy) ==
7749                IC.getTargetData().getTypeSize(DestPTy)) {
7750
7751         // Okay, we are casting from one integer or pointer type to another of
7752         // the same size.  Instead of casting the pointer before the store, cast
7753         // the value to be stored.
7754         Value *NewCast;
7755         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7756           NewCast = ConstantExpr::getCast(C, SrcPTy);
7757         else
7758           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7759                                                         SrcPTy,
7760                                          SI.getOperand(0)->getName()+".c"), SI);
7761
7762         return new StoreInst(NewCast, CastOp);
7763       }
7764     }
7765   }
7766   return 0;
7767 }
7768
7769 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7770   Value *Val = SI.getOperand(0);
7771   Value *Ptr = SI.getOperand(1);
7772
7773   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
7774     EraseInstFromFunction(SI);
7775     ++NumCombined;
7776     return 0;
7777   }
7778
7779   // Do really simple DSE, to catch cases where there are several consequtive
7780   // stores to the same location, separated by a few arithmetic operations. This
7781   // situation often occurs with bitfield accesses.
7782   BasicBlock::iterator BBI = &SI;
7783   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7784        --ScanInsts) {
7785     --BBI;
7786     
7787     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7788       // Prev store isn't volatile, and stores to the same location?
7789       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7790         ++NumDeadStore;
7791         ++BBI;
7792         EraseInstFromFunction(*PrevSI);
7793         continue;
7794       }
7795       break;
7796     }
7797     
7798     // If this is a load, we have to stop.  However, if the loaded value is from
7799     // the pointer we're loading and is producing the pointer we're storing,
7800     // then *this* store is dead (X = load P; store X -> P).
7801     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7802       if (LI == Val && LI->getOperand(0) == Ptr) {
7803         EraseInstFromFunction(SI);
7804         ++NumCombined;
7805         return 0;
7806       }
7807       // Otherwise, this is a load from some other location.  Stores before it
7808       // may not be dead.
7809       break;
7810     }
7811     
7812     // Don't skip over loads or things that can modify memory.
7813     if (BBI->mayWriteToMemory())
7814       break;
7815   }
7816   
7817   
7818   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
7819
7820   // store X, null    -> turns into 'unreachable' in SimplifyCFG
7821   if (isa<ConstantPointerNull>(Ptr)) {
7822     if (!isa<UndefValue>(Val)) {
7823       SI.setOperand(0, UndefValue::get(Val->getType()));
7824       if (Instruction *U = dyn_cast<Instruction>(Val))
7825         WorkList.push_back(U);  // Dropped a use.
7826       ++NumCombined;
7827     }
7828     return 0;  // Do not modify these!
7829   }
7830
7831   // store undef, Ptr -> noop
7832   if (isa<UndefValue>(Val)) {
7833     EraseInstFromFunction(SI);
7834     ++NumCombined;
7835     return 0;
7836   }
7837
7838   // If the pointer destination is a cast, see if we can fold the cast into the
7839   // source instead.
7840   if (isa<CastInst>(Ptr))
7841     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7842       return Res;
7843   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7844     if (CE->getOpcode() == Instruction::Cast)
7845       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7846         return Res;
7847
7848   
7849   // If this store is the last instruction in the basic block, and if the block
7850   // ends with an unconditional branch, try to move it to the successor block.
7851   BBI = &SI; ++BBI;
7852   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7853     if (BI->isUnconditional()) {
7854       // Check to see if the successor block has exactly two incoming edges.  If
7855       // so, see if the other predecessor contains a store to the same location.
7856       // if so, insert a PHI node (if needed) and move the stores down.
7857       BasicBlock *Dest = BI->getSuccessor(0);
7858
7859       pred_iterator PI = pred_begin(Dest);
7860       BasicBlock *Other = 0;
7861       if (*PI != BI->getParent())
7862         Other = *PI;
7863       ++PI;
7864       if (PI != pred_end(Dest)) {
7865         if (*PI != BI->getParent())
7866           if (Other)
7867             Other = 0;
7868           else
7869             Other = *PI;
7870         if (++PI != pred_end(Dest))
7871           Other = 0;
7872       }
7873       if (Other) {  // If only one other pred...
7874         BBI = Other->getTerminator();
7875         // Make sure this other block ends in an unconditional branch and that
7876         // there is an instruction before the branch.
7877         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7878             BBI != Other->begin()) {
7879           --BBI;
7880           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7881           
7882           // If this instruction is a store to the same location.
7883           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7884             // Okay, we know we can perform this transformation.  Insert a PHI
7885             // node now if we need it.
7886             Value *MergedVal = OtherStore->getOperand(0);
7887             if (MergedVal != SI.getOperand(0)) {
7888               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7889               PN->reserveOperandSpace(2);
7890               PN->addIncoming(SI.getOperand(0), SI.getParent());
7891               PN->addIncoming(OtherStore->getOperand(0), Other);
7892               MergedVal = InsertNewInstBefore(PN, Dest->front());
7893             }
7894             
7895             // Advance to a place where it is safe to insert the new store and
7896             // insert it.
7897             BBI = Dest->begin();
7898             while (isa<PHINode>(BBI)) ++BBI;
7899             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7900                                               OtherStore->isVolatile()), *BBI);
7901
7902             // Nuke the old stores.
7903             EraseInstFromFunction(SI);
7904             EraseInstFromFunction(*OtherStore);
7905             ++NumCombined;
7906             return 0;
7907           }
7908         }
7909       }
7910     }
7911   
7912   return 0;
7913 }
7914
7915
7916 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7917   // Change br (not X), label True, label False to: br X, label False, True
7918   Value *X = 0;
7919   BasicBlock *TrueDest;
7920   BasicBlock *FalseDest;
7921   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7922       !isa<Constant>(X)) {
7923     // Swap Destinations and condition...
7924     BI.setCondition(X);
7925     BI.setSuccessor(0, FalseDest);
7926     BI.setSuccessor(1, TrueDest);
7927     return &BI;
7928   }
7929
7930   // Cannonicalize setne -> seteq
7931   Instruction::BinaryOps Op; Value *Y;
7932   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7933                       TrueDest, FalseDest)))
7934     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7935          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7936       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7937       std::string Name = I->getName(); I->setName("");
7938       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7939       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
7940       // Swap Destinations and condition...
7941       BI.setCondition(NewSCC);
7942       BI.setSuccessor(0, FalseDest);
7943       BI.setSuccessor(1, TrueDest);
7944       removeFromWorkList(I);
7945       I->getParent()->getInstList().erase(I);
7946       WorkList.push_back(cast<Instruction>(NewSCC));
7947       return &BI;
7948     }
7949
7950   return 0;
7951 }
7952
7953 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7954   Value *Cond = SI.getCondition();
7955   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7956     if (I->getOpcode() == Instruction::Add)
7957       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7958         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7959         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7960           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7961                                                 AddRHS));
7962         SI.setOperand(0, I->getOperand(0));
7963         WorkList.push_back(I);
7964         return &SI;
7965       }
7966   }
7967   return 0;
7968 }
7969
7970 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7971 /// is to leave as a vector operation.
7972 static bool CheapToScalarize(Value *V, bool isConstant) {
7973   if (isa<ConstantAggregateZero>(V)) 
7974     return true;
7975   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7976     if (isConstant) return true;
7977     // If all elts are the same, we can extract.
7978     Constant *Op0 = C->getOperand(0);
7979     for (unsigned i = 1; i < C->getNumOperands(); ++i)
7980       if (C->getOperand(i) != Op0)
7981         return false;
7982     return true;
7983   }
7984   Instruction *I = dyn_cast<Instruction>(V);
7985   if (!I) return false;
7986   
7987   // Insert element gets simplified to the inserted element or is deleted if
7988   // this is constant idx extract element and its a constant idx insertelt.
7989   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7990       isa<ConstantInt>(I->getOperand(2)))
7991     return true;
7992   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7993     return true;
7994   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7995     if (BO->hasOneUse() &&
7996         (CheapToScalarize(BO->getOperand(0), isConstant) ||
7997          CheapToScalarize(BO->getOperand(1), isConstant)))
7998       return true;
7999   
8000   return false;
8001 }
8002
8003 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8004 /// elements into values that are larger than the #elts in the input.
8005 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8006   unsigned NElts = SVI->getType()->getNumElements();
8007   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8008     return std::vector<unsigned>(NElts, 0);
8009   if (isa<UndefValue>(SVI->getOperand(2)))
8010     return std::vector<unsigned>(NElts, 2*NElts);
8011
8012   std::vector<unsigned> Result;
8013   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8014   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8015     if (isa<UndefValue>(CP->getOperand(i)))
8016       Result.push_back(NElts*2);  // undef -> 8
8017     else
8018       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8019   return Result;
8020 }
8021
8022 /// FindScalarElement - Given a vector and an element number, see if the scalar
8023 /// value is already around as a register, for example if it were inserted then
8024 /// extracted from the vector.
8025 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8026   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8027   const PackedType *PTy = cast<PackedType>(V->getType());
8028   unsigned Width = PTy->getNumElements();
8029   if (EltNo >= Width)  // Out of range access.
8030     return UndefValue::get(PTy->getElementType());
8031   
8032   if (isa<UndefValue>(V))
8033     return UndefValue::get(PTy->getElementType());
8034   else if (isa<ConstantAggregateZero>(V))
8035     return Constant::getNullValue(PTy->getElementType());
8036   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8037     return CP->getOperand(EltNo);
8038   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8039     // If this is an insert to a variable element, we don't know what it is.
8040     if (!isa<ConstantInt>(III->getOperand(2))) 
8041       return 0;
8042     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8043     
8044     // If this is an insert to the element we are looking for, return the
8045     // inserted value.
8046     if (EltNo == IIElt) 
8047       return III->getOperand(1);
8048     
8049     // Otherwise, the insertelement doesn't modify the value, recurse on its
8050     // vector input.
8051     return FindScalarElement(III->getOperand(0), EltNo);
8052   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8053     unsigned InEl = getShuffleMask(SVI)[EltNo];
8054     if (InEl < Width)
8055       return FindScalarElement(SVI->getOperand(0), InEl);
8056     else if (InEl < Width*2)
8057       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8058     else
8059       return UndefValue::get(PTy->getElementType());
8060   }
8061   
8062   // Otherwise, we don't know.
8063   return 0;
8064 }
8065
8066 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8067
8068   // If packed val is undef, replace extract with scalar undef.
8069   if (isa<UndefValue>(EI.getOperand(0)))
8070     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8071
8072   // If packed val is constant 0, replace extract with scalar 0.
8073   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8074     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8075   
8076   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8077     // If packed val is constant with uniform operands, replace EI
8078     // with that operand
8079     Constant *op0 = C->getOperand(0);
8080     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8081       if (C->getOperand(i) != op0) {
8082         op0 = 0; 
8083         break;
8084       }
8085     if (op0)
8086       return ReplaceInstUsesWith(EI, op0);
8087   }
8088   
8089   // If extracting a specified index from the vector, see if we can recursively
8090   // find a previously computed scalar that was inserted into the vector.
8091   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8092     // This instruction only demands the single element from the input vector.
8093     // If the input vector has a single use, simplify it based on this use
8094     // property.
8095     uint64_t IndexVal = IdxC->getZExtValue();
8096     if (EI.getOperand(0)->hasOneUse()) {
8097       uint64_t UndefElts;
8098       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8099                                                 1 << IndexVal,
8100                                                 UndefElts)) {
8101         EI.setOperand(0, V);
8102         return &EI;
8103       }
8104     }
8105     
8106     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8107       return ReplaceInstUsesWith(EI, Elt);
8108   }
8109   
8110   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8111     if (I->hasOneUse()) {
8112       // Push extractelement into predecessor operation if legal and
8113       // profitable to do so
8114       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8115         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8116         if (CheapToScalarize(BO, isConstantElt)) {
8117           ExtractElementInst *newEI0 = 
8118             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8119                                    EI.getName()+".lhs");
8120           ExtractElementInst *newEI1 =
8121             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8122                                    EI.getName()+".rhs");
8123           InsertNewInstBefore(newEI0, EI);
8124           InsertNewInstBefore(newEI1, EI);
8125           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8126         }
8127       } else if (isa<LoadInst>(I)) {
8128         Value *Ptr = InsertCastBefore(I->getOperand(0),
8129                                       PointerType::get(EI.getType()), EI);
8130         GetElementPtrInst *GEP = 
8131           new GetElementPtrInst(Ptr, EI.getOperand(1),
8132                                 I->getName() + ".gep");
8133         InsertNewInstBefore(GEP, EI);
8134         return new LoadInst(GEP);
8135       }
8136     }
8137     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8138       // Extracting the inserted element?
8139       if (IE->getOperand(2) == EI.getOperand(1))
8140         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8141       // If the inserted and extracted elements are constants, they must not
8142       // be the same value, extract from the pre-inserted value instead.
8143       if (isa<Constant>(IE->getOperand(2)) &&
8144           isa<Constant>(EI.getOperand(1))) {
8145         AddUsesToWorkList(EI);
8146         EI.setOperand(0, IE->getOperand(0));
8147         return &EI;
8148       }
8149     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8150       // If this is extracting an element from a shufflevector, figure out where
8151       // it came from and extract from the appropriate input element instead.
8152       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8153         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8154         Value *Src;
8155         if (SrcIdx < SVI->getType()->getNumElements())
8156           Src = SVI->getOperand(0);
8157         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8158           SrcIdx -= SVI->getType()->getNumElements();
8159           Src = SVI->getOperand(1);
8160         } else {
8161           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8162         }
8163         return new ExtractElementInst(Src, SrcIdx);
8164       }
8165     }
8166   }
8167   return 0;
8168 }
8169
8170 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8171 /// elements from either LHS or RHS, return the shuffle mask and true. 
8172 /// Otherwise, return false.
8173 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8174                                          std::vector<Constant*> &Mask) {
8175   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8176          "Invalid CollectSingleShuffleElements");
8177   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8178
8179   if (isa<UndefValue>(V)) {
8180     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8181     return true;
8182   } else if (V == LHS) {
8183     for (unsigned i = 0; i != NumElts; ++i)
8184       Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8185     return true;
8186   } else if (V == RHS) {
8187     for (unsigned i = 0; i != NumElts; ++i)
8188       Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8189     return true;
8190   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8191     // If this is an insert of an extract from some other vector, include it.
8192     Value *VecOp    = IEI->getOperand(0);
8193     Value *ScalarOp = IEI->getOperand(1);
8194     Value *IdxOp    = IEI->getOperand(2);
8195     
8196     if (!isa<ConstantInt>(IdxOp))
8197       return false;
8198     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8199     
8200     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8201       // Okay, we can handle this if the vector we are insertinting into is
8202       // transitively ok.
8203       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8204         // If so, update the mask to reflect the inserted undef.
8205         Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8206         return true;
8207       }      
8208     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8209       if (isa<ConstantInt>(EI->getOperand(1)) &&
8210           EI->getOperand(0)->getType() == V->getType()) {
8211         unsigned ExtractedIdx =
8212           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8213         
8214         // This must be extracting from either LHS or RHS.
8215         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8216           // Okay, we can handle this if the vector we are insertinting into is
8217           // transitively ok.
8218           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8219             // If so, update the mask to reflect the inserted value.
8220             if (EI->getOperand(0) == LHS) {
8221               Mask[InsertedIdx & (NumElts-1)] = 
8222                  ConstantInt::get(Type::UIntTy, ExtractedIdx);
8223             } else {
8224               assert(EI->getOperand(0) == RHS);
8225               Mask[InsertedIdx & (NumElts-1)] = 
8226                 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8227               
8228             }
8229             return true;
8230           }
8231         }
8232       }
8233     }
8234   }
8235   // TODO: Handle shufflevector here!
8236   
8237   return false;
8238 }
8239
8240 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8241 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8242 /// that computes V and the LHS value of the shuffle.
8243 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8244                                      Value *&RHS) {
8245   assert(isa<PackedType>(V->getType()) && 
8246          (RHS == 0 || V->getType() == RHS->getType()) &&
8247          "Invalid shuffle!");
8248   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8249
8250   if (isa<UndefValue>(V)) {
8251     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8252     return V;
8253   } else if (isa<ConstantAggregateZero>(V)) {
8254     Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8255     return V;
8256   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8257     // If this is an insert of an extract from some other vector, include it.
8258     Value *VecOp    = IEI->getOperand(0);
8259     Value *ScalarOp = IEI->getOperand(1);
8260     Value *IdxOp    = IEI->getOperand(2);
8261     
8262     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8263       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8264           EI->getOperand(0)->getType() == V->getType()) {
8265         unsigned ExtractedIdx =
8266           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8267         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8268         
8269         // Either the extracted from or inserted into vector must be RHSVec,
8270         // otherwise we'd end up with a shuffle of three inputs.
8271         if (EI->getOperand(0) == RHS || RHS == 0) {
8272           RHS = EI->getOperand(0);
8273           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8274           Mask[InsertedIdx & (NumElts-1)] = 
8275             ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8276           return V;
8277         }
8278         
8279         if (VecOp == RHS) {
8280           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8281           // Everything but the extracted element is replaced with the RHS.
8282           for (unsigned i = 0; i != NumElts; ++i) {
8283             if (i != InsertedIdx)
8284               Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8285           }
8286           return V;
8287         }
8288         
8289         // If this insertelement is a chain that comes from exactly these two
8290         // vectors, return the vector and the effective shuffle.
8291         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8292           return EI->getOperand(0);
8293         
8294       }
8295     }
8296   }
8297   // TODO: Handle shufflevector here!
8298   
8299   // Otherwise, can't do anything fancy.  Return an identity vector.
8300   for (unsigned i = 0; i != NumElts; ++i)
8301     Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8302   return V;
8303 }
8304
8305 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8306   Value *VecOp    = IE.getOperand(0);
8307   Value *ScalarOp = IE.getOperand(1);
8308   Value *IdxOp    = IE.getOperand(2);
8309   
8310   // If the inserted element was extracted from some other vector, and if the 
8311   // indexes are constant, try to turn this into a shufflevector operation.
8312   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8313     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8314         EI->getOperand(0)->getType() == IE.getType()) {
8315       unsigned NumVectorElts = IE.getType()->getNumElements();
8316       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8317       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8318       
8319       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8320         return ReplaceInstUsesWith(IE, VecOp);
8321       
8322       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8323         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8324       
8325       // If we are extracting a value from a vector, then inserting it right
8326       // back into the same place, just use the input vector.
8327       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8328         return ReplaceInstUsesWith(IE, VecOp);      
8329       
8330       // We could theoretically do this for ANY input.  However, doing so could
8331       // turn chains of insertelement instructions into a chain of shufflevector
8332       // instructions, and right now we do not merge shufflevectors.  As such,
8333       // only do this in a situation where it is clear that there is benefit.
8334       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8335         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8336         // the values of VecOp, except then one read from EIOp0.
8337         // Build a new shuffle mask.
8338         std::vector<Constant*> Mask;
8339         if (isa<UndefValue>(VecOp))
8340           Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8341         else {
8342           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8343           Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8344                                                        NumVectorElts));
8345         } 
8346         Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8347         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8348                                      ConstantPacked::get(Mask));
8349       }
8350       
8351       // If this insertelement isn't used by some other insertelement, turn it
8352       // (and any insertelements it points to), into one big shuffle.
8353       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8354         std::vector<Constant*> Mask;
8355         Value *RHS = 0;
8356         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8357         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8358         // We now have a shuffle of LHS, RHS, Mask.
8359         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8360       }
8361     }
8362   }
8363
8364   return 0;
8365 }
8366
8367
8368 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8369   Value *LHS = SVI.getOperand(0);
8370   Value *RHS = SVI.getOperand(1);
8371   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8372
8373   bool MadeChange = false;
8374   
8375   // Undefined shuffle mask -> undefined value.
8376   if (isa<UndefValue>(SVI.getOperand(2)))
8377     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8378   
8379   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8380   // the undef, change them to undefs.
8381   
8382   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8383   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8384   if (LHS == RHS || isa<UndefValue>(LHS)) {
8385     if (isa<UndefValue>(LHS) && LHS == RHS) {
8386       // shuffle(undef,undef,mask) -> undef.
8387       return ReplaceInstUsesWith(SVI, LHS);
8388     }
8389     
8390     // Remap any references to RHS to use LHS.
8391     std::vector<Constant*> Elts;
8392     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8393       if (Mask[i] >= 2*e)
8394         Elts.push_back(UndefValue::get(Type::UIntTy));
8395       else {
8396         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8397             (Mask[i] <  e && isa<UndefValue>(LHS)))
8398           Mask[i] = 2*e;     // Turn into undef.
8399         else
8400           Mask[i] &= (e-1);  // Force to LHS.
8401         Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8402       }
8403     }
8404     SVI.setOperand(0, SVI.getOperand(1));
8405     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8406     SVI.setOperand(2, ConstantPacked::get(Elts));
8407     LHS = SVI.getOperand(0);
8408     RHS = SVI.getOperand(1);
8409     MadeChange = true;
8410   }
8411   
8412   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8413   bool isLHSID = true, isRHSID = true;
8414     
8415   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8416     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8417     // Is this an identity shuffle of the LHS value?
8418     isLHSID &= (Mask[i] == i);
8419       
8420     // Is this an identity shuffle of the RHS value?
8421     isRHSID &= (Mask[i]-e == i);
8422   }
8423
8424   // Eliminate identity shuffles.
8425   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8426   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8427   
8428   // If the LHS is a shufflevector itself, see if we can combine it with this
8429   // one without producing an unusual shuffle.  Here we are really conservative:
8430   // we are absolutely afraid of producing a shuffle mask not in the input
8431   // program, because the code gen may not be smart enough to turn a merged
8432   // shuffle into two specific shuffles: it may produce worse code.  As such,
8433   // we only merge two shuffles if the result is one of the two input shuffle
8434   // masks.  In this case, merging the shuffles just removes one instruction,
8435   // which we know is safe.  This is good for things like turning:
8436   // (splat(splat)) -> splat.
8437   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8438     if (isa<UndefValue>(RHS)) {
8439       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8440
8441       std::vector<unsigned> NewMask;
8442       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8443         if (Mask[i] >= 2*e)
8444           NewMask.push_back(2*e);
8445         else
8446           NewMask.push_back(LHSMask[Mask[i]]);
8447       
8448       // If the result mask is equal to the src shuffle or this shuffle mask, do
8449       // the replacement.
8450       if (NewMask == LHSMask || NewMask == Mask) {
8451         std::vector<Constant*> Elts;
8452         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8453           if (NewMask[i] >= e*2) {
8454             Elts.push_back(UndefValue::get(Type::UIntTy));
8455           } else {
8456             Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8457           }
8458         }
8459         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8460                                      LHSSVI->getOperand(1),
8461                                      ConstantPacked::get(Elts));
8462       }
8463     }
8464   }
8465   
8466   return MadeChange ? &SVI : 0;
8467 }
8468
8469
8470
8471 void InstCombiner::removeFromWorkList(Instruction *I) {
8472   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8473                  WorkList.end());
8474 }
8475
8476
8477 /// TryToSinkInstruction - Try to move the specified instruction from its
8478 /// current block into the beginning of DestBlock, which can only happen if it's
8479 /// safe to move the instruction past all of the instructions between it and the
8480 /// end of its block.
8481 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8482   assert(I->hasOneUse() && "Invariants didn't hold!");
8483
8484   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8485   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8486
8487   // Do not sink alloca instructions out of the entry block.
8488   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8489     return false;
8490
8491   // We can only sink load instructions if there is nothing between the load and
8492   // the end of block that could change the value.
8493   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8494     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8495          Scan != E; ++Scan)
8496       if (Scan->mayWriteToMemory())
8497         return false;
8498   }
8499
8500   BasicBlock::iterator InsertPos = DestBlock->begin();
8501   while (isa<PHINode>(InsertPos)) ++InsertPos;
8502
8503   I->moveBefore(InsertPos);
8504   ++NumSunkInst;
8505   return true;
8506 }
8507
8508 /// OptimizeConstantExpr - Given a constant expression and target data layout
8509 /// information, symbolically evaluation the constant expr to something simpler
8510 /// if possible.
8511 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8512   if (!TD) return CE;
8513   
8514   Constant *Ptr = CE->getOperand(0);
8515   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8516       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8517     // If this is a constant expr gep that is effectively computing an
8518     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8519     bool isFoldableGEP = true;
8520     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8521       if (!isa<ConstantInt>(CE->getOperand(i)))
8522         isFoldableGEP = false;
8523     if (isFoldableGEP) {
8524       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8525       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8526       Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8527       C = ConstantExpr::getCast(C, TD->getIntPtrType());
8528       return ConstantExpr::getCast(C, CE->getType());
8529     }
8530   }
8531   
8532   return CE;
8533 }
8534
8535
8536 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8537 /// all reachable code to the worklist.
8538 ///
8539 /// This has a couple of tricks to make the code faster and more powerful.  In
8540 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8541 /// them to the worklist (this significantly speeds up instcombine on code where
8542 /// many instructions are dead or constant).  Additionally, if we find a branch
8543 /// whose condition is a known constant, we only visit the reachable successors.
8544 ///
8545 static void AddReachableCodeToWorklist(BasicBlock *BB, 
8546                                        std::set<BasicBlock*> &Visited,
8547                                        std::vector<Instruction*> &WorkList,
8548                                        const TargetData *TD) {
8549   // We have now visited this block!  If we've already been here, bail out.
8550   if (!Visited.insert(BB).second) return;
8551     
8552   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8553     Instruction *Inst = BBI++;
8554     
8555     // DCE instruction if trivially dead.
8556     if (isInstructionTriviallyDead(Inst)) {
8557       ++NumDeadInst;
8558       DOUT << "IC: DCE: " << *Inst;
8559       Inst->eraseFromParent();
8560       continue;
8561     }
8562     
8563     // ConstantProp instruction if trivially constant.
8564     if (Constant *C = ConstantFoldInstruction(Inst)) {
8565       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8566         C = OptimizeConstantExpr(CE, TD);
8567       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
8568       Inst->replaceAllUsesWith(C);
8569       ++NumConstProp;
8570       Inst->eraseFromParent();
8571       continue;
8572     }
8573     
8574     WorkList.push_back(Inst);
8575   }
8576
8577   // Recursively visit successors.  If this is a branch or switch on a constant,
8578   // only visit the reachable successor.
8579   TerminatorInst *TI = BB->getTerminator();
8580   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8581     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8582       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8583       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8584                                  TD);
8585       return;
8586     }
8587   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8588     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8589       // See if this is an explicit destination.
8590       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8591         if (SI->getCaseValue(i) == Cond) {
8592           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8593           return;
8594         }
8595       
8596       // Otherwise it is the default destination.
8597       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8598       return;
8599     }
8600   }
8601   
8602   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8603     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8604 }
8605
8606 bool InstCombiner::runOnFunction(Function &F) {
8607   bool Changed = false;
8608   TD = &getAnalysis<TargetData>();
8609
8610   {
8611     // Do a depth-first traversal of the function, populate the worklist with
8612     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
8613     // track of which blocks we visit.
8614     std::set<BasicBlock*> Visited;
8615     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8616
8617     // Do a quick scan over the function.  If we find any blocks that are
8618     // unreachable, remove any instructions inside of them.  This prevents
8619     // the instcombine code from having to deal with some bad special cases.
8620     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8621       if (!Visited.count(BB)) {
8622         Instruction *Term = BB->getTerminator();
8623         while (Term != BB->begin()) {   // Remove instrs bottom-up
8624           BasicBlock::iterator I = Term; --I;
8625
8626           DOUT << "IC: DCE: " << *I;
8627           ++NumDeadInst;
8628
8629           if (!I->use_empty())
8630             I->replaceAllUsesWith(UndefValue::get(I->getType()));
8631           I->eraseFromParent();
8632         }
8633       }
8634   }
8635
8636   while (!WorkList.empty()) {
8637     Instruction *I = WorkList.back();  // Get an instruction from the worklist
8638     WorkList.pop_back();
8639
8640     // Check to see if we can DCE the instruction.
8641     if (isInstructionTriviallyDead(I)) {
8642       // Add operands to the worklist.
8643       if (I->getNumOperands() < 4)
8644         AddUsesToWorkList(*I);
8645       ++NumDeadInst;
8646
8647       DOUT << "IC: DCE: " << *I;
8648
8649       I->eraseFromParent();
8650       removeFromWorkList(I);
8651       continue;
8652     }
8653
8654     // Instruction isn't dead, see if we can constant propagate it.
8655     if (Constant *C = ConstantFoldInstruction(I)) {
8656       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8657         C = OptimizeConstantExpr(CE, TD);
8658       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
8659
8660       // Add operands to the worklist.
8661       AddUsesToWorkList(*I);
8662       ReplaceInstUsesWith(*I, C);
8663
8664       ++NumConstProp;
8665       I->eraseFromParent();
8666       removeFromWorkList(I);
8667       continue;
8668     }
8669
8670     // See if we can trivially sink this instruction to a successor basic block.
8671     if (I->hasOneUse()) {
8672       BasicBlock *BB = I->getParent();
8673       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8674       if (UserParent != BB) {
8675         bool UserIsSuccessor = false;
8676         // See if the user is one of our successors.
8677         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8678           if (*SI == UserParent) {
8679             UserIsSuccessor = true;
8680             break;
8681           }
8682
8683         // If the user is one of our immediate successors, and if that successor
8684         // only has us as a predecessors (we'd have to split the critical edge
8685         // otherwise), we can keep going.
8686         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8687             next(pred_begin(UserParent)) == pred_end(UserParent))
8688           // Okay, the CFG is simple enough, try to sink this instruction.
8689           Changed |= TryToSinkInstruction(I, UserParent);
8690       }
8691     }
8692
8693     // Now that we have an instruction, try combining it to simplify it...
8694     if (Instruction *Result = visit(*I)) {
8695       ++NumCombined;
8696       // Should we replace the old instruction with a new one?
8697       if (Result != I) {
8698         DOUT << "IC: Old = " << *I
8699              << "    New = " << *Result;
8700
8701         // Everything uses the new instruction now.
8702         I->replaceAllUsesWith(Result);
8703
8704         // Push the new instruction and any users onto the worklist.
8705         WorkList.push_back(Result);
8706         AddUsersToWorkList(*Result);
8707
8708         // Move the name to the new instruction first...
8709         std::string OldName = I->getName(); I->setName("");
8710         Result->setName(OldName);
8711
8712         // Insert the new instruction into the basic block...
8713         BasicBlock *InstParent = I->getParent();
8714         BasicBlock::iterator InsertPos = I;
8715
8716         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
8717           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8718             ++InsertPos;
8719
8720         InstParent->getInstList().insert(InsertPos, Result);
8721
8722         // Make sure that we reprocess all operands now that we reduced their
8723         // use counts.
8724         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8725           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8726             WorkList.push_back(OpI);
8727
8728         // Instructions can end up on the worklist more than once.  Make sure
8729         // we do not process an instruction that has been deleted.
8730         removeFromWorkList(I);
8731
8732         // Erase the old instruction.
8733         InstParent->getInstList().erase(I);
8734       } else {
8735         DOUT << "IC: MOD = " << *I;
8736
8737         // If the instruction was modified, it's possible that it is now dead.
8738         // if so, remove it.
8739         if (isInstructionTriviallyDead(I)) {
8740           // Make sure we process all operands now that we are reducing their
8741           // use counts.
8742           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8743             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8744               WorkList.push_back(OpI);
8745
8746           // Instructions may end up in the worklist more than once.  Erase all
8747           // occurrences of this instruction.
8748           removeFromWorkList(I);
8749           I->eraseFromParent();
8750         } else {
8751           WorkList.push_back(Result);
8752           AddUsersToWorkList(*Result);
8753         }
8754       }
8755       Changed = true;
8756     }
8757   }
8758
8759   return Changed;
8760 }
8761
8762 FunctionPass *llvm::createInstructionCombiningPass() {
8763   return new InstCombiner();
8764 }
8765