Change this to work with renamed intrinsics.
[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/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 #include <iostream>
56 using namespace llvm;
57 using namespace llvm::PatternMatch;
58
59 namespace {
60   Statistic<> NumCombined ("instcombine", "Number of insts combined");
61   Statistic<> NumConstProp("instcombine", "Number of constant folds");
62   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63   Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65
66   class InstCombiner : 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     // removeFromWorkList - remove all instances of I from the worklist.
92     void removeFromWorkList(Instruction *I);
93   public:
94     virtual bool runOnFunction(Function &F);
95
96     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97       AU.addRequired<TargetData>();
98       AU.setPreservesCFG();
99     }
100
101     TargetData &getTargetData() const { return *TD; }
102
103     // Visitation implementation - Implement instruction combining for different
104     // instruction types.  The semantics are as follows:
105     // Return Value:
106     //    null        - No change was made
107     //     I          - Change was made, I is still valid, I may be dead though
108     //   otherwise    - Change was made, replace I with returned instruction
109     //
110     Instruction *visitAdd(BinaryOperator &I);
111     Instruction *visitSub(BinaryOperator &I);
112     Instruction *visitMul(BinaryOperator &I);
113     Instruction *visitDiv(BinaryOperator &I);
114     Instruction *visitRem(BinaryOperator &I);
115     Instruction *visitAnd(BinaryOperator &I);
116     Instruction *visitOr (BinaryOperator &I);
117     Instruction *visitXor(BinaryOperator &I);
118     Instruction *visitSetCondInst(SetCondInst &I);
119     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
121     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122                               Instruction::BinaryOps Cond, Instruction &I);
123     Instruction *visitShiftInst(ShiftInst &I);
124     Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125                                      ShiftInst &I);
126     Instruction *visitCastInst(CastInst &CI);
127     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128                                 Instruction *FI);
129     Instruction *visitSelectInst(SelectInst &CI);
130     Instruction *visitCallInst(CallInst &CI);
131     Instruction *visitInvokeInst(InvokeInst &II);
132     Instruction *visitPHINode(PHINode &PN);
133     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
134     Instruction *visitAllocationInst(AllocationInst &AI);
135     Instruction *visitFreeInst(FreeInst &FI);
136     Instruction *visitLoadInst(LoadInst &LI);
137     Instruction *visitStoreInst(StoreInst &SI);
138     Instruction *visitBranchInst(BranchInst &BI);
139     Instruction *visitSwitchInst(SwitchInst &SI);
140     Instruction *visitExtractElementInst(ExtractElementInst &EI);
141
142     // visitInstruction - Specify what to return for unhandled instructions...
143     Instruction *visitInstruction(Instruction &I) { return 0; }
144
145   private:
146     Instruction *visitCallSite(CallSite CS);
147     bool transformConstExprCastCall(CallSite CS);
148
149   public:
150     // InsertNewInstBefore - insert an instruction New before instruction Old
151     // in the program.  Add the new instruction to the worklist.
152     //
153     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
154       assert(New && New->getParent() == 0 &&
155              "New instruction already inserted into a basic block!");
156       BasicBlock *BB = Old.getParent();
157       BB->getInstList().insert(&Old, New);  // Insert inst
158       WorkList.push_back(New);              // Add to worklist
159       return New;
160     }
161
162     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163     /// This also adds the cast to the worklist.  Finally, this returns the
164     /// cast.
165     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166       if (V->getType() == Ty) return V;
167
168       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169       WorkList.push_back(C);
170       return C;
171     }
172
173     // ReplaceInstUsesWith - This method is to be used when an instruction is
174     // found to be dead, replacable with another preexisting expression.  Here
175     // we add all uses of I to the worklist, replace all uses of I with the new
176     // value, then return I, so that the inst combiner will know that I was
177     // modified.
178     //
179     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
180       AddUsersToWorkList(I);         // Add all modified instrs to worklist
181       if (&I != V) {
182         I.replaceAllUsesWith(V);
183         return &I;
184       } else {
185         // If we are replacing the instruction with itself, this must be in a
186         // segment of unreachable code, so just clobber the instruction.
187         I.replaceAllUsesWith(UndefValue::get(I.getType()));
188         return &I;
189       }
190     }
191
192     // UpdateValueUsesWith - This method is to be used when an value is
193     // found to be replacable with another preexisting expression or was
194     // updated.  Here we add all uses of I to the worklist, replace all uses of
195     // I with the new value (unless the instruction was just updated), then
196     // return true, so that the inst combiner will know that I was modified.
197     //
198     bool UpdateValueUsesWith(Value *Old, Value *New) {
199       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
200       if (Old != New)
201         Old->replaceAllUsesWith(New);
202       if (Instruction *I = dyn_cast<Instruction>(Old))
203         WorkList.push_back(I);
204       if (Instruction *I = dyn_cast<Instruction>(New))
205         WorkList.push_back(I);
206       return true;
207     }
208     
209     // EraseInstFromFunction - When dealing with an instruction that has side
210     // effects or produces a void value, we can't rely on DCE to delete the
211     // instruction.  Instead, visit methods should return the value returned by
212     // this function.
213     Instruction *EraseInstFromFunction(Instruction &I) {
214       assert(I.use_empty() && "Cannot erase instruction that is used!");
215       AddUsesToWorkList(I);
216       removeFromWorkList(&I);
217       I.eraseFromParent();
218       return 0;  // Don't do anything with FI
219     }
220
221   private:
222     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
223     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
224     /// casts that are known to not do anything...
225     ///
226     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
227                                    Instruction *InsertBefore);
228
229     // SimplifyCommutative - This performs a few simplifications for commutative
230     // operators.
231     bool SimplifyCommutative(BinaryOperator &I);
232
233     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
234                               uint64_t &KnownZero, uint64_t &KnownOne,
235                               unsigned Depth = 0);
236
237     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
238     // PHI node as operand #0, see if we can fold the instruction into the PHI
239     // (which is only possible if all operands to the PHI are constants).
240     Instruction *FoldOpIntoPhi(Instruction &I);
241
242     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
243     // operator and they all are only used by the PHI, PHI together their
244     // inputs, and do the operation once, to the result of the PHI.
245     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
246
247     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
248                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
249     
250     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
251                               bool isSub, Instruction &I);
252     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
253                                  bool Inside, Instruction &IB);
254     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
255   };
256
257   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
258 }
259
260 // getComplexity:  Assign a complexity or rank value to LLVM Values...
261 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
262 static unsigned getComplexity(Value *V) {
263   if (isa<Instruction>(V)) {
264     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
265       return 3;
266     return 4;
267   }
268   if (isa<Argument>(V)) return 3;
269   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
270 }
271
272 // isOnlyUse - Return true if this instruction will be deleted if we stop using
273 // it.
274 static bool isOnlyUse(Value *V) {
275   return V->hasOneUse() || isa<Constant>(V);
276 }
277
278 // getPromotedType - Return the specified type promoted as it would be to pass
279 // though a va_arg area...
280 static const Type *getPromotedType(const Type *Ty) {
281   switch (Ty->getTypeID()) {
282   case Type::SByteTyID:
283   case Type::ShortTyID:  return Type::IntTy;
284   case Type::UByteTyID:
285   case Type::UShortTyID: return Type::UIntTy;
286   case Type::FloatTyID:  return Type::DoubleTy;
287   default:               return Ty;
288   }
289 }
290
291 /// isCast - If the specified operand is a CastInst or a constant expr cast,
292 /// return the operand value, otherwise return null.
293 static Value *isCast(Value *V) {
294   if (CastInst *I = dyn_cast<CastInst>(V))
295     return I->getOperand(0);
296   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297     if (CE->getOpcode() == Instruction::Cast)
298       return CE->getOperand(0);
299   return 0;
300 }
301
302 // SimplifyCommutative - This performs a few simplifications for commutative
303 // operators:
304 //
305 //  1. Order operands such that they are listed from right (least complex) to
306 //     left (most complex).  This puts constants before unary operators before
307 //     binary operators.
308 //
309 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
310 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
311 //
312 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
313   bool Changed = false;
314   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
315     Changed = !I.swapOperands();
316
317   if (!I.isAssociative()) return Changed;
318   Instruction::BinaryOps Opcode = I.getOpcode();
319   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
320     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
321       if (isa<Constant>(I.getOperand(1))) {
322         Constant *Folded = ConstantExpr::get(I.getOpcode(),
323                                              cast<Constant>(I.getOperand(1)),
324                                              cast<Constant>(Op->getOperand(1)));
325         I.setOperand(0, Op->getOperand(0));
326         I.setOperand(1, Folded);
327         return true;
328       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
329         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
330             isOnlyUse(Op) && isOnlyUse(Op1)) {
331           Constant *C1 = cast<Constant>(Op->getOperand(1));
332           Constant *C2 = cast<Constant>(Op1->getOperand(1));
333
334           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
335           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
336           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
337                                                     Op1->getOperand(0),
338                                                     Op1->getName(), &I);
339           WorkList.push_back(New);
340           I.setOperand(0, New);
341           I.setOperand(1, Folded);
342           return true;
343         }
344     }
345   return Changed;
346 }
347
348 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
349 // if the LHS is a constant zero (which is the 'negate' form).
350 //
351 static inline Value *dyn_castNegVal(Value *V) {
352   if (BinaryOperator::isNeg(V))
353     return BinaryOperator::getNegArgument(V);
354
355   // Constants can be considered to be negated values if they can be folded.
356   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
357     return ConstantExpr::getNeg(C);
358   return 0;
359 }
360
361 static inline Value *dyn_castNotVal(Value *V) {
362   if (BinaryOperator::isNot(V))
363     return BinaryOperator::getNotArgument(V);
364
365   // Constants can be considered to be not'ed values...
366   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
367     return ConstantExpr::getNot(C);
368   return 0;
369 }
370
371 // dyn_castFoldableMul - If this value is a multiply that can be folded into
372 // other computations (because it has a constant operand), return the
373 // non-constant operand of the multiply, and set CST to point to the multiplier.
374 // Otherwise, return null.
375 //
376 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
377   if (V->hasOneUse() && V->getType()->isInteger())
378     if (Instruction *I = dyn_cast<Instruction>(V)) {
379       if (I->getOpcode() == Instruction::Mul)
380         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
381           return I->getOperand(0);
382       if (I->getOpcode() == Instruction::Shl)
383         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
384           // The multiplier is really 1 << CST.
385           Constant *One = ConstantInt::get(V->getType(), 1);
386           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
387           return I->getOperand(0);
388         }
389     }
390   return 0;
391 }
392
393 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
394 /// expression, return it.
395 static User *dyn_castGetElementPtr(Value *V) {
396   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
397   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
398     if (CE->getOpcode() == Instruction::GetElementPtr)
399       return cast<User>(V);
400   return false;
401 }
402
403 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
404 static ConstantInt *AddOne(ConstantInt *C) {
405   return cast<ConstantInt>(ConstantExpr::getAdd(C,
406                                          ConstantInt::get(C->getType(), 1)));
407 }
408 static ConstantInt *SubOne(ConstantInt *C) {
409   return cast<ConstantInt>(ConstantExpr::getSub(C,
410                                          ConstantInt::get(C->getType(), 1)));
411 }
412
413 /// GetConstantInType - Return a ConstantInt with the specified type and value.
414 ///
415 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
416   if (Ty->isUnsigned())
417     return ConstantUInt::get(Ty, Val);
418   else if (Ty->getTypeID() == Type::BoolTyID)
419     return ConstantBool::get(Val);
420   int64_t SVal = Val;
421   SVal <<= 64-Ty->getPrimitiveSizeInBits();
422   SVal >>= 64-Ty->getPrimitiveSizeInBits();
423   return ConstantSInt::get(Ty, SVal);
424 }
425
426
427 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
428 /// known to be either zero or one and return them in the KnownZero/KnownOne
429 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
430 /// processing.
431 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
432                               uint64_t &KnownOne, unsigned Depth = 0) {
433   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
434   // we cannot optimize based on the assumption that it is zero without changing
435   // it to be an explicit zero.  If we don't change it to zero, other code could
436   // optimized based on the contradictory assumption that it is non-zero.
437   // Because instcombine aggressively folds operations with undef args anyway,
438   // this won't lose us code quality.
439   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
440     // We know all of the bits for a constant!
441     KnownOne = CI->getZExtValue() & Mask;
442     KnownZero = ~KnownOne & Mask;
443     return;
444   }
445
446   KnownZero = KnownOne = 0;   // Don't know anything.
447   if (Depth == 6 || Mask == 0)
448     return;  // Limit search depth.
449
450   uint64_t KnownZero2, KnownOne2;
451   Instruction *I = dyn_cast<Instruction>(V);
452   if (!I) return;
453
454   switch (I->getOpcode()) {
455   case Instruction::And:
456     // If either the LHS or the RHS are Zero, the result is zero.
457     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
458     Mask &= ~KnownZero;
459     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
460     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
461     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
462     
463     // Output known-1 bits are only known if set in both the LHS & RHS.
464     KnownOne &= KnownOne2;
465     // Output known-0 are known to be clear if zero in either the LHS | RHS.
466     KnownZero |= KnownZero2;
467     return;
468   case Instruction::Or:
469     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
470     Mask &= ~KnownOne;
471     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
472     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
473     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
474     
475     // Output known-0 bits are only known if clear in both the LHS & RHS.
476     KnownZero &= KnownZero2;
477     // Output known-1 are known to be set if set in either the LHS | RHS.
478     KnownOne |= KnownOne2;
479     return;
480   case Instruction::Xor: {
481     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
482     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
483     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
484     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
485     
486     // Output known-0 bits are known if clear or set in both the LHS & RHS.
487     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
488     // Output known-1 are known to be set if set in only one of the LHS, RHS.
489     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
490     KnownZero = KnownZeroOut;
491     return;
492   }
493   case Instruction::Select:
494     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
495     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
496     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
497     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
498
499     // Only known if known in both the LHS and RHS.
500     KnownOne &= KnownOne2;
501     KnownZero &= KnownZero2;
502     return;
503   case Instruction::Cast: {
504     const Type *SrcTy = I->getOperand(0)->getType();
505     if (!SrcTy->isIntegral()) return;
506     
507     // If this is an integer truncate or noop, just look in the input.
508     if (SrcTy->getPrimitiveSizeInBits() >= 
509            I->getType()->getPrimitiveSizeInBits()) {
510       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
511       return;
512     }
513
514     // Sign or Zero extension.  Compute the bits in the result that are not
515     // present in the input.
516     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
517     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
518       
519     // Handle zero extension.
520     if (!SrcTy->isSigned()) {
521       Mask &= SrcTy->getIntegralTypeMask();
522       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
523       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
524       // The top bits are known to be zero.
525       KnownZero |= NewBits;
526     } else {
527       // Sign extension.
528       Mask &= SrcTy->getIntegralTypeMask();
529       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
530       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
531
532       // If the sign bit of the input is known set or clear, then we know the
533       // top bits of the result.
534       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
535       if (KnownZero & InSignBit) {          // Input sign bit known zero
536         KnownZero |= NewBits;
537         KnownOne &= ~NewBits;
538       } else if (KnownOne & InSignBit) {    // Input sign bit known set
539         KnownOne |= NewBits;
540         KnownZero &= ~NewBits;
541       } else {                              // Input sign bit unknown
542         KnownZero &= ~NewBits;
543         KnownOne &= ~NewBits;
544       }
545     }
546     return;
547   }
548   case Instruction::Shl:
549     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
550     if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
551       Mask >>= SA->getValue();
552       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
553       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
554       KnownZero <<= SA->getValue();
555       KnownOne  <<= SA->getValue();
556       KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
557       return;
558     }
559     break;
560   case Instruction::Shr:
561     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
562     if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
563       // Compute the new bits that are at the top now.
564       uint64_t HighBits = (1ULL << SA->getValue())-1;
565       HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
566       
567       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
568         Mask <<= SA->getValue();
569         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
570         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
571         KnownZero >>= SA->getValue();
572         KnownOne  >>= SA->getValue();
573         KnownZero |= HighBits;  // high bits known zero.
574       } else {
575         Mask <<= SA->getValue();
576         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
577         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
578         KnownZero >>= SA->getValue();
579         KnownOne  >>= SA->getValue();
580         
581         // Handle the sign bits.
582         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
583         SignBit >>= SA->getValue();  // Adjust to where it is now in the mask.
584         
585         if (KnownZero & SignBit) {       // New bits are known zero.
586           KnownZero |= HighBits;
587         } else if (KnownOne & SignBit) { // New bits are known one.
588           KnownOne |= HighBits;
589         }
590       }
591       return;
592     }
593     break;
594   }
595 }
596
597 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
598 /// this predicate to simplify operations downstream.  Mask is known to be zero
599 /// for bits that V cannot have.
600 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
601   uint64_t KnownZero, KnownOne;
602   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
603   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
604   return (KnownZero & Mask) == Mask;
605 }
606
607 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
608 /// specified instruction is a constant integer.  If so, check to see if there
609 /// are any bits set in the constant that are not demanded.  If so, shrink the
610 /// constant and return true.
611 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
612                                    uint64_t Demanded) {
613   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
614   if (!OpC) return false;
615
616   // If there are no bits set that aren't demanded, nothing to do.
617   if ((~Demanded & OpC->getZExtValue()) == 0)
618     return false;
619
620   // This is producing any bits that are not needed, shrink the RHS.
621   uint64_t Val = Demanded & OpC->getZExtValue();
622   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
623   return true;
624 }
625
626 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
627 // set of known zero and one bits, compute the maximum and minimum values that
628 // could have the specified known zero and known one bits, returning them in
629 // min/max.
630 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
631                                                    uint64_t KnownZero,
632                                                    uint64_t KnownOne,
633                                                    int64_t &Min, int64_t &Max) {
634   uint64_t TypeBits = Ty->getIntegralTypeMask();
635   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
636
637   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
638   
639   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
640   // bit if it is unknown.
641   Min = KnownOne;
642   Max = KnownOne|UnknownBits;
643   
644   if (SignBit & UnknownBits) { // Sign bit is unknown
645     Min |= SignBit;
646     Max &= ~SignBit;
647   }
648   
649   // Sign extend the min/max values.
650   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
651   Min = (Min << ShAmt) >> ShAmt;
652   Max = (Max << ShAmt) >> ShAmt;
653 }
654
655 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
656 // a set of known zero and one bits, compute the maximum and minimum values that
657 // could have the specified known zero and known one bits, returning them in
658 // min/max.
659 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
660                                                      uint64_t KnownZero,
661                                                      uint64_t KnownOne,
662                                                      uint64_t &Min,
663                                                      uint64_t &Max) {
664   uint64_t TypeBits = Ty->getIntegralTypeMask();
665   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
666   
667   // The minimum value is when the unknown bits are all zeros.
668   Min = KnownOne;
669   // The maximum value is when the unknown bits are all ones.
670   Max = KnownOne|UnknownBits;
671 }
672
673
674 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
675 /// DemandedMask bits of the result of V are ever used downstream.  If we can
676 /// use this information to simplify V, do so and return true.  Otherwise,
677 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
678 /// the expression (used to simplify the caller).  The KnownZero/One bits may
679 /// only be accurate for those bits in the DemandedMask.
680 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
681                                         uint64_t &KnownZero, uint64_t &KnownOne,
682                                         unsigned Depth) {
683   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
684     // We know all of the bits for a constant!
685     KnownOne = CI->getZExtValue() & DemandedMask;
686     KnownZero = ~KnownOne & DemandedMask;
687     return false;
688   }
689   
690   KnownZero = KnownOne = 0;
691   if (!V->hasOneUse()) {    // Other users may use these bits.
692     if (Depth != 0) {       // Not at the root.
693       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
694       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
695       return false;
696     }
697     // If this is the root being simplified, allow it to have multiple uses,
698     // just set the DemandedMask to all bits.
699     DemandedMask = V->getType()->getIntegralTypeMask();
700   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
701     if (V != UndefValue::get(V->getType()))
702       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
703     return false;
704   } else if (Depth == 6) {        // Limit search depth.
705     return false;
706   }
707   
708   Instruction *I = dyn_cast<Instruction>(V);
709   if (!I) return false;        // Only analyze instructions.
710
711   uint64_t KnownZero2, KnownOne2;
712   switch (I->getOpcode()) {
713   default: break;
714   case Instruction::And:
715     // If either the LHS or the RHS are Zero, the result is zero.
716     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
717                              KnownZero, KnownOne, Depth+1))
718       return true;
719     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
720
721     // If something is known zero on the RHS, the bits aren't demanded on the
722     // LHS.
723     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
724                              KnownZero2, KnownOne2, Depth+1))
725       return true;
726     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
727
728     // If all of the demanded bits are known one on one side, return the other.
729     // These bits cannot contribute to the result of the 'and'.
730     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
731       return UpdateValueUsesWith(I, I->getOperand(0));
732     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
733       return UpdateValueUsesWith(I, I->getOperand(1));
734     
735     // If all of the demanded bits in the inputs are known zeros, return zero.
736     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
737       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
738       
739     // If the RHS is a constant, see if we can simplify it.
740     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
741       return UpdateValueUsesWith(I, I);
742       
743     // Output known-1 bits are only known if set in both the LHS & RHS.
744     KnownOne &= KnownOne2;
745     // Output known-0 are known to be clear if zero in either the LHS | RHS.
746     KnownZero |= KnownZero2;
747     break;
748   case Instruction::Or:
749     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
750                              KnownZero, KnownOne, Depth+1))
751       return true;
752     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
753     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
754                              KnownZero2, KnownOne2, Depth+1))
755       return true;
756     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
757     
758     // If all of the demanded bits are known zero on one side, return the other.
759     // These bits cannot contribute to the result of the 'or'.
760     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
761       return UpdateValueUsesWith(I, I->getOperand(0));
762     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
763       return UpdateValueUsesWith(I, I->getOperand(1));
764
765     // If all of the potentially set bits on one side are known to be set on
766     // the other side, just use the 'other' side.
767     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
768         (DemandedMask & (~KnownZero)))
769       return UpdateValueUsesWith(I, I->getOperand(0));
770     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
771         (DemandedMask & (~KnownZero2)))
772       return UpdateValueUsesWith(I, I->getOperand(1));
773         
774     // If the RHS is a constant, see if we can simplify it.
775     if (ShrinkDemandedConstant(I, 1, DemandedMask))
776       return UpdateValueUsesWith(I, I);
777           
778     // Output known-0 bits are only known if clear in both the LHS & RHS.
779     KnownZero &= KnownZero2;
780     // Output known-1 are known to be set if set in either the LHS | RHS.
781     KnownOne |= KnownOne2;
782     break;
783   case Instruction::Xor: {
784     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
785                              KnownZero, KnownOne, Depth+1))
786       return true;
787     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
788     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
789                              KnownZero2, KnownOne2, Depth+1))
790       return true;
791     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
792     
793     // If all of the demanded bits are known zero on one side, return the other.
794     // These bits cannot contribute to the result of the 'xor'.
795     if ((DemandedMask & KnownZero) == DemandedMask)
796       return UpdateValueUsesWith(I, I->getOperand(0));
797     if ((DemandedMask & KnownZero2) == DemandedMask)
798       return UpdateValueUsesWith(I, I->getOperand(1));
799     
800     // Output known-0 bits are known if clear or set in both the LHS & RHS.
801     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
802     // Output known-1 are known to be set if set in only one of the LHS, RHS.
803     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
804     
805     // If all of the unknown bits are known to be zero on one side or the other
806     // (but not both) turn this into an *inclusive* or.
807     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
808     if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
809       if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
810         Instruction *Or =
811           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
812                                    I->getName());
813         InsertNewInstBefore(Or, *I);
814         return UpdateValueUsesWith(I, Or);
815       }
816     }
817     
818     // If all of the demanded bits on one side are known, and all of the set
819     // bits on that side are also known to be set on the other side, turn this
820     // into an AND, as we know the bits will be cleared.
821     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
822     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
823       if ((KnownOne & KnownOne2) == KnownOne) {
824         Constant *AndC = GetConstantInType(I->getType(), 
825                                            ~KnownOne & DemandedMask);
826         Instruction *And = 
827           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
828         InsertNewInstBefore(And, *I);
829         return UpdateValueUsesWith(I, And);
830       }
831     }
832     
833     // If the RHS is a constant, see if we can simplify it.
834     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
835     if (ShrinkDemandedConstant(I, 1, DemandedMask))
836       return UpdateValueUsesWith(I, I);
837     
838     KnownZero = KnownZeroOut;
839     KnownOne  = KnownOneOut;
840     break;
841   }
842   case Instruction::Select:
843     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
844                              KnownZero, KnownOne, Depth+1))
845       return true;
846     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
847                              KnownZero2, KnownOne2, Depth+1))
848       return true;
849     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
850     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
851     
852     // If the operands are constants, see if we can simplify them.
853     if (ShrinkDemandedConstant(I, 1, DemandedMask))
854       return UpdateValueUsesWith(I, I);
855     if (ShrinkDemandedConstant(I, 2, DemandedMask))
856       return UpdateValueUsesWith(I, I);
857     
858     // Only known if known in both the LHS and RHS.
859     KnownOne &= KnownOne2;
860     KnownZero &= KnownZero2;
861     break;
862   case Instruction::Cast: {
863     const Type *SrcTy = I->getOperand(0)->getType();
864     if (!SrcTy->isIntegral()) return false;
865     
866     // If this is an integer truncate or noop, just look in the input.
867     if (SrcTy->getPrimitiveSizeInBits() >= 
868         I->getType()->getPrimitiveSizeInBits()) {
869       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
870                                KnownZero, KnownOne, Depth+1))
871         return true;
872       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
873       break;
874     }
875     
876     // Sign or Zero extension.  Compute the bits in the result that are not
877     // present in the input.
878     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
879     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
880     
881     // Handle zero extension.
882     if (!SrcTy->isSigned()) {
883       DemandedMask &= SrcTy->getIntegralTypeMask();
884       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
885                                KnownZero, KnownOne, Depth+1))
886         return true;
887       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
888       // The top bits are known to be zero.
889       KnownZero |= NewBits;
890     } else {
891       // Sign extension.
892       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
893       int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
894
895       // If any of the sign extended bits are demanded, we know that the sign
896       // bit is demanded.
897       if (NewBits & DemandedMask)
898         InputDemandedBits |= InSignBit;
899       
900       if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
901                                KnownZero, KnownOne, Depth+1))
902         return true;
903       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
904       
905       // If the sign bit of the input is known set or clear, then we know the
906       // top bits of the result.
907
908       // If the input sign bit is known zero, or if the NewBits are not demanded
909       // convert this into a zero extension.
910       if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
911         // Convert to unsigned first.
912         Instruction *NewVal;
913         NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
914                               I->getOperand(0)->getName());
915         InsertNewInstBefore(NewVal, *I);
916         // Then cast that to the destination type.
917         NewVal = new CastInst(NewVal, I->getType(), I->getName());
918         InsertNewInstBefore(NewVal, *I);
919         return UpdateValueUsesWith(I, NewVal);
920       } else if (KnownOne & InSignBit) {    // Input sign bit known set
921         KnownOne |= NewBits;
922         KnownZero &= ~NewBits;
923       } else {                              // Input sign bit unknown
924         KnownZero &= ~NewBits;
925         KnownOne &= ~NewBits;
926       }
927     }
928     break;
929   }
930   case Instruction::Shl:
931     if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
932       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(), 
933                                KnownZero, KnownOne, Depth+1))
934         return true;
935       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
936       KnownZero <<= SA->getValue();
937       KnownOne  <<= SA->getValue();
938       KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
939     }
940     break;
941   case Instruction::Shr:
942     if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
943       unsigned ShAmt = SA->getValue();
944       
945       // Compute the new bits that are at the top now.
946       uint64_t HighBits = (1ULL << ShAmt)-1;
947       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
948       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
949       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
950         if (SimplifyDemandedBits(I->getOperand(0),
951                                  (DemandedMask << ShAmt) & TypeMask,
952                                  KnownZero, KnownOne, Depth+1))
953           return true;
954         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
955         KnownZero &= TypeMask;
956         KnownOne  &= TypeMask;
957         KnownZero >>= ShAmt;
958         KnownOne  >>= ShAmt;
959         KnownZero |= HighBits;  // high bits known zero.
960       } else {                            // Signed shift right.
961         if (SimplifyDemandedBits(I->getOperand(0),
962                                  (DemandedMask << ShAmt) & TypeMask,
963                                  KnownZero, KnownOne, Depth+1))
964           return true;
965         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
966         KnownZero &= TypeMask;
967         KnownOne  &= TypeMask;
968         KnownZero >>= SA->getValue();
969         KnownOne  >>= SA->getValue();
970         
971         // Handle the sign bits.
972         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
973         SignBit >>= SA->getValue();  // Adjust to where it is now in the mask.
974         
975         // If the input sign bit is known to be zero, or if none of the top bits
976         // are demanded, turn this into an unsigned shift right.
977         if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
978           // Convert the input to unsigned.
979           Instruction *NewVal;
980           NewVal = new CastInst(I->getOperand(0), 
981                                 I->getType()->getUnsignedVersion(),
982                                 I->getOperand(0)->getName());
983           InsertNewInstBefore(NewVal, *I);
984           // Perform the unsigned shift right.
985           NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
986           InsertNewInstBefore(NewVal, *I);
987           // Then cast that to the destination type.
988           NewVal = new CastInst(NewVal, I->getType(), I->getName());
989           InsertNewInstBefore(NewVal, *I);
990           return UpdateValueUsesWith(I, NewVal);
991         } else if (KnownOne & SignBit) { // New bits are known one.
992           KnownOne |= HighBits;
993         }
994       }
995     }
996     break;
997   }
998   
999   // If the client is only demanding bits that we know, return the known
1000   // constant.
1001   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1002     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1003   return false;
1004 }  
1005
1006 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1007 // true when both operands are equal...
1008 //
1009 static bool isTrueWhenEqual(Instruction &I) {
1010   return I.getOpcode() == Instruction::SetEQ ||
1011          I.getOpcode() == Instruction::SetGE ||
1012          I.getOpcode() == Instruction::SetLE;
1013 }
1014
1015 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1016 /// function is designed to check a chain of associative operators for a
1017 /// potential to apply a certain optimization.  Since the optimization may be
1018 /// applicable if the expression was reassociated, this checks the chain, then
1019 /// reassociates the expression as necessary to expose the optimization
1020 /// opportunity.  This makes use of a special Functor, which must define
1021 /// 'shouldApply' and 'apply' methods.
1022 ///
1023 template<typename Functor>
1024 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1025   unsigned Opcode = Root.getOpcode();
1026   Value *LHS = Root.getOperand(0);
1027
1028   // Quick check, see if the immediate LHS matches...
1029   if (F.shouldApply(LHS))
1030     return F.apply(Root);
1031
1032   // Otherwise, if the LHS is not of the same opcode as the root, return.
1033   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1034   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1035     // Should we apply this transform to the RHS?
1036     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1037
1038     // If not to the RHS, check to see if we should apply to the LHS...
1039     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1040       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1041       ShouldApply = true;
1042     }
1043
1044     // If the functor wants to apply the optimization to the RHS of LHSI,
1045     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1046     if (ShouldApply) {
1047       BasicBlock *BB = Root.getParent();
1048
1049       // Now all of the instructions are in the current basic block, go ahead
1050       // and perform the reassociation.
1051       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1052
1053       // First move the selected RHS to the LHS of the root...
1054       Root.setOperand(0, LHSI->getOperand(1));
1055
1056       // Make what used to be the LHS of the root be the user of the root...
1057       Value *ExtraOperand = TmpLHSI->getOperand(1);
1058       if (&Root == TmpLHSI) {
1059         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1060         return 0;
1061       }
1062       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1063       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1064       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1065       BasicBlock::iterator ARI = &Root; ++ARI;
1066       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1067       ARI = Root;
1068
1069       // Now propagate the ExtraOperand down the chain of instructions until we
1070       // get to LHSI.
1071       while (TmpLHSI != LHSI) {
1072         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1073         // Move the instruction to immediately before the chain we are
1074         // constructing to avoid breaking dominance properties.
1075         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1076         BB->getInstList().insert(ARI, NextLHSI);
1077         ARI = NextLHSI;
1078
1079         Value *NextOp = NextLHSI->getOperand(1);
1080         NextLHSI->setOperand(1, ExtraOperand);
1081         TmpLHSI = NextLHSI;
1082         ExtraOperand = NextOp;
1083       }
1084
1085       // Now that the instructions are reassociated, have the functor perform
1086       // the transformation...
1087       return F.apply(Root);
1088     }
1089
1090     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1091   }
1092   return 0;
1093 }
1094
1095
1096 // AddRHS - Implements: X + X --> X << 1
1097 struct AddRHS {
1098   Value *RHS;
1099   AddRHS(Value *rhs) : RHS(rhs) {}
1100   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1101   Instruction *apply(BinaryOperator &Add) const {
1102     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1103                          ConstantInt::get(Type::UByteTy, 1));
1104   }
1105 };
1106
1107 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1108 //                 iff C1&C2 == 0
1109 struct AddMaskingAnd {
1110   Constant *C2;
1111   AddMaskingAnd(Constant *c) : C2(c) {}
1112   bool shouldApply(Value *LHS) const {
1113     ConstantInt *C1;
1114     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1115            ConstantExpr::getAnd(C1, C2)->isNullValue();
1116   }
1117   Instruction *apply(BinaryOperator &Add) const {
1118     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1119   }
1120 };
1121
1122 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1123                                              InstCombiner *IC) {
1124   if (isa<CastInst>(I)) {
1125     if (Constant *SOC = dyn_cast<Constant>(SO))
1126       return ConstantExpr::getCast(SOC, I.getType());
1127
1128     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1129                                                 SO->getName() + ".cast"), I);
1130   }
1131
1132   // Figure out if the constant is the left or the right argument.
1133   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1134   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1135
1136   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1137     if (ConstIsRHS)
1138       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1139     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1140   }
1141
1142   Value *Op0 = SO, *Op1 = ConstOperand;
1143   if (!ConstIsRHS)
1144     std::swap(Op0, Op1);
1145   Instruction *New;
1146   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1147     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1148   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1149     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1150   else {
1151     assert(0 && "Unknown binary instruction type!");
1152     abort();
1153   }
1154   return IC->InsertNewInstBefore(New, I);
1155 }
1156
1157 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1158 // constant as the other operand, try to fold the binary operator into the
1159 // select arguments.  This also works for Cast instructions, which obviously do
1160 // not have a second operand.
1161 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1162                                      InstCombiner *IC) {
1163   // Don't modify shared select instructions
1164   if (!SI->hasOneUse()) return 0;
1165   Value *TV = SI->getOperand(1);
1166   Value *FV = SI->getOperand(2);
1167
1168   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1169     // Bool selects with constant operands can be folded to logical ops.
1170     if (SI->getType() == Type::BoolTy) return 0;
1171
1172     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1173     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1174
1175     return new SelectInst(SI->getCondition(), SelectTrueVal,
1176                           SelectFalseVal);
1177   }
1178   return 0;
1179 }
1180
1181
1182 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1183 /// node as operand #0, see if we can fold the instruction into the PHI (which
1184 /// is only possible if all operands to the PHI are constants).
1185 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1186   PHINode *PN = cast<PHINode>(I.getOperand(0));
1187   unsigned NumPHIValues = PN->getNumIncomingValues();
1188   if (!PN->hasOneUse() || NumPHIValues == 0 ||
1189       !isa<Constant>(PN->getIncomingValue(0))) return 0;
1190
1191   // Check to see if all of the operands of the PHI are constants.  If not, we
1192   // cannot do the transformation.
1193   for (unsigned i = 1; i != NumPHIValues; ++i)
1194     if (!isa<Constant>(PN->getIncomingValue(i)))
1195       return 0;
1196
1197   // Okay, we can do the transformation: create the new PHI node.
1198   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1199   I.setName("");
1200   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1201   InsertNewInstBefore(NewPN, *PN);
1202
1203   // Next, add all of the operands to the PHI.
1204   if (I.getNumOperands() == 2) {
1205     Constant *C = cast<Constant>(I.getOperand(1));
1206     for (unsigned i = 0; i != NumPHIValues; ++i) {
1207       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1208       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1209                          PN->getIncomingBlock(i));
1210     }
1211   } else {
1212     assert(isa<CastInst>(I) && "Unary op should be a cast!");
1213     const Type *RetTy = I.getType();
1214     for (unsigned i = 0; i != NumPHIValues; ++i) {
1215       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1216       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1217                          PN->getIncomingBlock(i));
1218     }
1219   }
1220   return ReplaceInstUsesWith(I, NewPN);
1221 }
1222
1223 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1224   bool Changed = SimplifyCommutative(I);
1225   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1226
1227   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1228     // X + undef -> undef
1229     if (isa<UndefValue>(RHS))
1230       return ReplaceInstUsesWith(I, RHS);
1231
1232     // X + 0 --> X
1233     if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1234       if (RHSC->isNullValue())
1235         return ReplaceInstUsesWith(I, LHS);
1236     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1237       if (CFP->isExactlyValue(-0.0))
1238         return ReplaceInstUsesWith(I, LHS);
1239     }
1240
1241     // X + (signbit) --> X ^ signbit
1242     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1243       uint64_t Val = CI->getZExtValue();
1244       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1245         return BinaryOperator::createXor(LHS, RHS);
1246     }
1247
1248     if (isa<PHINode>(LHS))
1249       if (Instruction *NV = FoldOpIntoPhi(I))
1250         return NV;
1251     
1252     ConstantInt *XorRHS = 0;
1253     Value *XorLHS = 0;
1254     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1255       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1256       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1257       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1258       
1259       uint64_t C0080Val = 1ULL << 31;
1260       int64_t CFF80Val = -C0080Val;
1261       unsigned Size = 32;
1262       do {
1263         if (TySizeBits > Size) {
1264           bool Found = false;
1265           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1266           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1267           if (RHSSExt == CFF80Val) {
1268             if (XorRHS->getZExtValue() == C0080Val)
1269               Found = true;
1270           } else if (RHSZExt == C0080Val) {
1271             if (XorRHS->getSExtValue() == CFF80Val)
1272               Found = true;
1273           }
1274           if (Found) {
1275             // This is a sign extend if the top bits are known zero.
1276             uint64_t Mask = ~0ULL;
1277             Mask <<= 64-(TySizeBits-Size);
1278             Mask &= XorLHS->getType()->getIntegralTypeMask();
1279             if (!MaskedValueIsZero(XorLHS, Mask))
1280               Size = 0;  // Not a sign ext, but can't be any others either.
1281             goto FoundSExt;
1282           }
1283         }
1284         Size >>= 1;
1285         C0080Val >>= Size;
1286         CFF80Val >>= Size;
1287       } while (Size >= 8);
1288       
1289 FoundSExt:
1290       const Type *MiddleType = 0;
1291       switch (Size) {
1292       default: break;
1293       case 32: MiddleType = Type::IntTy; break;
1294       case 16: MiddleType = Type::ShortTy; break;
1295       case 8:  MiddleType = Type::SByteTy; break;
1296       }
1297       if (MiddleType) {
1298         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1299         InsertNewInstBefore(NewTrunc, I);
1300         return new CastInst(NewTrunc, I.getType());
1301       }
1302     }
1303   }
1304
1305   // X + X --> X << 1
1306   if (I.getType()->isInteger()) {
1307     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1308
1309     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1310       if (RHSI->getOpcode() == Instruction::Sub)
1311         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1312           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1313     }
1314     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1315       if (LHSI->getOpcode() == Instruction::Sub)
1316         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1317           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1318     }
1319   }
1320
1321   // -A + B  -->  B - A
1322   if (Value *V = dyn_castNegVal(LHS))
1323     return BinaryOperator::createSub(RHS, V);
1324
1325   // A + -B  -->  A - B
1326   if (!isa<Constant>(RHS))
1327     if (Value *V = dyn_castNegVal(RHS))
1328       return BinaryOperator::createSub(LHS, V);
1329
1330
1331   ConstantInt *C2;
1332   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1333     if (X == RHS)   // X*C + X --> X * (C+1)
1334       return BinaryOperator::createMul(RHS, AddOne(C2));
1335
1336     // X*C1 + X*C2 --> X * (C1+C2)
1337     ConstantInt *C1;
1338     if (X == dyn_castFoldableMul(RHS, C1))
1339       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1340   }
1341
1342   // X + X*C --> X * (C+1)
1343   if (dyn_castFoldableMul(RHS, C2) == LHS)
1344     return BinaryOperator::createMul(LHS, AddOne(C2));
1345
1346
1347   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1348   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1349     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1350
1351   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1352     Value *X = 0;
1353     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1354       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1355       return BinaryOperator::createSub(C, X);
1356     }
1357
1358     // (X & FF00) + xx00  -> (X+xx00) & FF00
1359     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1360       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1361       if (Anded == CRHS) {
1362         // See if all bits from the first bit set in the Add RHS up are included
1363         // in the mask.  First, get the rightmost bit.
1364         uint64_t AddRHSV = CRHS->getRawValue();
1365
1366         // Form a mask of all bits from the lowest bit added through the top.
1367         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1368         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1369
1370         // See if the and mask includes all of these bits.
1371         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1372
1373         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1374           // Okay, the xform is safe.  Insert the new add pronto.
1375           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1376                                                             LHS->getName()), I);
1377           return BinaryOperator::createAnd(NewAdd, C2);
1378         }
1379       }
1380     }
1381
1382     // Try to fold constant add into select arguments.
1383     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1384       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1385         return R;
1386   }
1387
1388   return Changed ? &I : 0;
1389 }
1390
1391 // isSignBit - Return true if the value represented by the constant only has the
1392 // highest order bit set.
1393 static bool isSignBit(ConstantInt *CI) {
1394   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1395   return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1396 }
1397
1398 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1399 ///
1400 static Value *RemoveNoopCast(Value *V) {
1401   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1402     const Type *CTy = CI->getType();
1403     const Type *OpTy = CI->getOperand(0)->getType();
1404     if (CTy->isInteger() && OpTy->isInteger()) {
1405       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1406         return RemoveNoopCast(CI->getOperand(0));
1407     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1408       return RemoveNoopCast(CI->getOperand(0));
1409   }
1410   return V;
1411 }
1412
1413 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1414   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1415
1416   if (Op0 == Op1)         // sub X, X  -> 0
1417     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1418
1419   // If this is a 'B = x-(-A)', change to B = x+A...
1420   if (Value *V = dyn_castNegVal(Op1))
1421     return BinaryOperator::createAdd(Op0, V);
1422
1423   if (isa<UndefValue>(Op0))
1424     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1425   if (isa<UndefValue>(Op1))
1426     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1427
1428   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1429     // Replace (-1 - A) with (~A)...
1430     if (C->isAllOnesValue())
1431       return BinaryOperator::createNot(Op1);
1432
1433     // C - ~X == X + (1+C)
1434     Value *X = 0;
1435     if (match(Op1, m_Not(m_Value(X))))
1436       return BinaryOperator::createAdd(X,
1437                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1438     // -((uint)X >> 31) -> ((int)X >> 31)
1439     // -((int)X >> 31) -> ((uint)X >> 31)
1440     if (C->isNullValue()) {
1441       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1442       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1443         if (SI->getOpcode() == Instruction::Shr)
1444           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1445             const Type *NewTy;
1446             if (SI->getType()->isSigned())
1447               NewTy = SI->getType()->getUnsignedVersion();
1448             else
1449               NewTy = SI->getType()->getSignedVersion();
1450             // Check to see if we are shifting out everything but the sign bit.
1451             if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1452               // Ok, the transformation is safe.  Insert a cast of the incoming
1453               // value, then the new shift, then the new cast.
1454               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1455                                                  SI->getOperand(0)->getName());
1456               Value *InV = InsertNewInstBefore(FirstCast, I);
1457               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1458                                                     CU, SI->getName());
1459               if (NewShift->getType() == I.getType())
1460                 return NewShift;
1461               else {
1462                 InV = InsertNewInstBefore(NewShift, I);
1463                 return new CastInst(NewShift, I.getType());
1464               }
1465             }
1466           }
1467     }
1468
1469     // Try to fold constant sub into select arguments.
1470     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1471       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1472         return R;
1473
1474     if (isa<PHINode>(Op0))
1475       if (Instruction *NV = FoldOpIntoPhi(I))
1476         return NV;
1477   }
1478
1479   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1480     if (Op1I->getOpcode() == Instruction::Add &&
1481         !Op0->getType()->isFloatingPoint()) {
1482       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1483         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1484       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
1485         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1486       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1487         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1488           // C1-(X+C2) --> (C1-C2)-X
1489           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1490                                            Op1I->getOperand(0));
1491       }
1492     }
1493
1494     if (Op1I->hasOneUse()) {
1495       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1496       // is not used by anyone else...
1497       //
1498       if (Op1I->getOpcode() == Instruction::Sub &&
1499           !Op1I->getType()->isFloatingPoint()) {
1500         // Swap the two operands of the subexpr...
1501         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1502         Op1I->setOperand(0, IIOp1);
1503         Op1I->setOperand(1, IIOp0);
1504
1505         // Create the new top level add instruction...
1506         return BinaryOperator::createAdd(Op0, Op1);
1507       }
1508
1509       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1510       //
1511       if (Op1I->getOpcode() == Instruction::And &&
1512           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1513         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1514
1515         Value *NewNot =
1516           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1517         return BinaryOperator::createAnd(Op0, NewNot);
1518       }
1519
1520       // -(X sdiv C)  -> (X sdiv -C)
1521       if (Op1I->getOpcode() == Instruction::Div)
1522         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1523           if (CSI->isNullValue())
1524             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1525               return BinaryOperator::createDiv(Op1I->getOperand(0),
1526                                                ConstantExpr::getNeg(DivRHS));
1527
1528       // X - X*C --> X * (1-C)
1529       ConstantInt *C2 = 0;
1530       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1531         Constant *CP1 =
1532           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1533         return BinaryOperator::createMul(Op0, CP1);
1534       }
1535     }
1536   }
1537
1538   if (!Op0->getType()->isFloatingPoint())
1539     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1540       if (Op0I->getOpcode() == Instruction::Add) {
1541         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
1542           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1543         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
1544           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1545       } else if (Op0I->getOpcode() == Instruction::Sub) {
1546         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
1547           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1548       }
1549
1550   ConstantInt *C1;
1551   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1552     if (X == Op1) { // X*C - X --> X * (C-1)
1553       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1554       return BinaryOperator::createMul(Op1, CP1);
1555     }
1556
1557     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
1558     if (X == dyn_castFoldableMul(Op1, C2))
1559       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1560   }
1561   return 0;
1562 }
1563
1564 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1565 /// really just returns true if the most significant (sign) bit is set.
1566 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1567   if (RHS->getType()->isSigned()) {
1568     // True if source is LHS < 0 or LHS <= -1
1569     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1570            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1571   } else {
1572     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1573     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1574     // the size of the integer type.
1575     if (Opcode == Instruction::SetGE)
1576       return RHSC->getValue() ==
1577         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1578     if (Opcode == Instruction::SetGT)
1579       return RHSC->getValue() ==
1580         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1581   }
1582   return false;
1583 }
1584
1585 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1586   bool Changed = SimplifyCommutative(I);
1587   Value *Op0 = I.getOperand(0);
1588
1589   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
1590     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1591
1592   // Simplify mul instructions with a constant RHS...
1593   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1594     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1595
1596       // ((X << C1)*C2) == (X * (C2 << C1))
1597       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1598         if (SI->getOpcode() == Instruction::Shl)
1599           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1600             return BinaryOperator::createMul(SI->getOperand(0),
1601                                              ConstantExpr::getShl(CI, ShOp));
1602
1603       if (CI->isNullValue())
1604         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
1605       if (CI->equalsInt(1))                  // X * 1  == X
1606         return ReplaceInstUsesWith(I, Op0);
1607       if (CI->isAllOnesValue())              // X * -1 == 0 - X
1608         return BinaryOperator::createNeg(Op0, I.getName());
1609
1610       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1611       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
1612         uint64_t C = Log2_64(Val);
1613         return new ShiftInst(Instruction::Shl, Op0,
1614                              ConstantUInt::get(Type::UByteTy, C));
1615       }
1616     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1617       if (Op1F->isNullValue())
1618         return ReplaceInstUsesWith(I, Op1);
1619
1620       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
1621       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1622       if (Op1F->getValue() == 1.0)
1623         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
1624     }
1625
1626     // Try to fold constant mul into select arguments.
1627     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1628       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1629         return R;
1630
1631     if (isa<PHINode>(Op0))
1632       if (Instruction *NV = FoldOpIntoPhi(I))
1633         return NV;
1634   }
1635
1636   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
1637     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1638       return BinaryOperator::createMul(Op0v, Op1v);
1639
1640   // If one of the operands of the multiply is a cast from a boolean value, then
1641   // we know the bool is either zero or one, so this is a 'masking' multiply.
1642   // See if we can simplify things based on how the boolean was originally
1643   // formed.
1644   CastInst *BoolCast = 0;
1645   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1646     if (CI->getOperand(0)->getType() == Type::BoolTy)
1647       BoolCast = CI;
1648   if (!BoolCast)
1649     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1650       if (CI->getOperand(0)->getType() == Type::BoolTy)
1651         BoolCast = CI;
1652   if (BoolCast) {
1653     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1654       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1655       const Type *SCOpTy = SCIOp0->getType();
1656
1657       // If the setcc is true iff the sign bit of X is set, then convert this
1658       // multiply into a shift/and combination.
1659       if (isa<ConstantInt>(SCIOp1) &&
1660           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1661         // Shift the X value right to turn it into "all signbits".
1662         Constant *Amt = ConstantUInt::get(Type::UByteTy,
1663                                           SCOpTy->getPrimitiveSizeInBits()-1);
1664         if (SCIOp0->getType()->isUnsigned()) {
1665           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1666           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1667                                                     SCIOp0->getName()), I);
1668         }
1669
1670         Value *V =
1671           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1672                                             BoolCast->getOperand(0)->getName()+
1673                                             ".mask"), I);
1674
1675         // If the multiply type is not the same as the source type, sign extend
1676         // or truncate to the multiply type.
1677         if (I.getType() != V->getType())
1678           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1679
1680         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1681         return BinaryOperator::createAnd(V, OtherOp);
1682       }
1683     }
1684   }
1685
1686   return Changed ? &I : 0;
1687 }
1688
1689 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1690   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1691
1692   if (isa<UndefValue>(Op0))              // undef / X -> 0
1693     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1694   if (isa<UndefValue>(Op1))
1695     return ReplaceInstUsesWith(I, Op1);  // X / undef -> undef
1696
1697   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1698     // div X, 1 == X
1699     if (RHS->equalsInt(1))
1700       return ReplaceInstUsesWith(I, Op0);
1701
1702     // div X, -1 == -X
1703     if (RHS->isAllOnesValue())
1704       return BinaryOperator::createNeg(Op0);
1705
1706     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1707       if (LHS->getOpcode() == Instruction::Div)
1708         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1709           // (X / C1) / C2  -> X / (C1*C2)
1710           return BinaryOperator::createDiv(LHS->getOperand(0),
1711                                            ConstantExpr::getMul(RHS, LHSRHS));
1712         }
1713
1714     // Check to see if this is an unsigned division with an exact power of 2,
1715     // if so, convert to a right shift.
1716     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1717       if (uint64_t Val = C->getValue())    // Don't break X / 0
1718         if (isPowerOf2_64(Val)) {
1719           uint64_t C = Log2_64(Val);
1720           return new ShiftInst(Instruction::Shr, Op0,
1721                                ConstantUInt::get(Type::UByteTy, C));
1722         }
1723
1724     // -X/C -> X/-C
1725     if (RHS->getType()->isSigned())
1726       if (Value *LHSNeg = dyn_castNegVal(Op0))
1727         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1728
1729     if (!RHS->isNullValue()) {
1730       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1731         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1732           return R;
1733       if (isa<PHINode>(Op0))
1734         if (Instruction *NV = FoldOpIntoPhi(I))
1735           return NV;
1736     }
1737   }
1738
1739   // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1740   // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1741   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1742     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1743       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1744         if (STO->getValue() == 0) { // Couldn't be this argument.
1745           I.setOperand(1, SFO);
1746           return &I;
1747         } else if (SFO->getValue() == 0) {
1748           I.setOperand(1, STO);
1749           return &I;
1750         }
1751
1752         uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1753         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1754           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1755           Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1756           Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1757                                            TC, SI->getName()+".t");
1758           TSI = InsertNewInstBefore(TSI, I);
1759
1760           Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1761           Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1762                                            FC, SI->getName()+".f");
1763           FSI = InsertNewInstBefore(FSI, I);
1764           return new SelectInst(SI->getOperand(0), TSI, FSI);
1765         }
1766       }
1767
1768   // 0 / X == 0, we don't need to preserve faults!
1769   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1770     if (LHS->equalsInt(0))
1771       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1772
1773   if (I.getType()->isSigned()) {
1774     // If the sign bits of both operands are zero (i.e. we can prove they are
1775     // unsigned inputs), turn this into a udiv.
1776     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1777     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1778       const Type *NTy = Op0->getType()->getUnsignedVersion();
1779       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1780       InsertNewInstBefore(LHS, I);
1781       Value *RHS;
1782       if (Constant *R = dyn_cast<Constant>(Op1))
1783         RHS = ConstantExpr::getCast(R, NTy);
1784       else
1785         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1786       Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1787       InsertNewInstBefore(Div, I);
1788       return new CastInst(Div, I.getType());
1789     }      
1790   } else {
1791     // Known to be an unsigned division.
1792     if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1793       // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1794       if (RHSI->getOpcode() == Instruction::Shl &&
1795           isa<ConstantUInt>(RHSI->getOperand(0))) {
1796         unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1797         if (isPowerOf2_64(C1)) {
1798           unsigned C2 = Log2_64(C1);
1799           Value *Add = RHSI->getOperand(1);
1800           if (C2) {
1801             Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1802             Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1803                                                                 "tmp"), I);
1804           }
1805           return new ShiftInst(Instruction::Shr, Op0, Add);
1806         }
1807       }
1808     }
1809   }
1810   
1811   return 0;
1812 }
1813
1814
1815 /// GetFactor - If we can prove that the specified value is at least a multiple
1816 /// of some factor, return that factor.
1817 static Constant *GetFactor(Value *V) {
1818   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1819     return CI;
1820   
1821   // Unless we can be tricky, we know this is a multiple of 1.
1822   Constant *Result = ConstantInt::get(V->getType(), 1);
1823   
1824   Instruction *I = dyn_cast<Instruction>(V);
1825   if (!I) return Result;
1826   
1827   if (I->getOpcode() == Instruction::Mul) {
1828     // Handle multiplies by a constant, etc.
1829     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1830                                 GetFactor(I->getOperand(1)));
1831   } else if (I->getOpcode() == Instruction::Shl) {
1832     // (X<<C) -> X * (1 << C)
1833     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1834       ShRHS = ConstantExpr::getShl(Result, ShRHS);
1835       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1836     }
1837   } else if (I->getOpcode() == Instruction::And) {
1838     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1839       // X & 0xFFF0 is known to be a multiple of 16.
1840       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1841       if (Zeros != V->getType()->getPrimitiveSizeInBits())
1842         return ConstantExpr::getShl(Result, 
1843                                     ConstantUInt::get(Type::UByteTy, Zeros));
1844     }
1845   } else if (I->getOpcode() == Instruction::Cast) {
1846     Value *Op = I->getOperand(0);
1847     // Only handle int->int casts.
1848     if (!Op->getType()->isInteger()) return Result;
1849     return ConstantExpr::getCast(GetFactor(Op), V->getType());
1850   }    
1851   return Result;
1852 }
1853
1854 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1855   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1856   
1857   // 0 % X == 0, we don't need to preserve faults!
1858   if (Constant *LHS = dyn_cast<Constant>(Op0))
1859     if (LHS->isNullValue())
1860       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1861
1862   if (isa<UndefValue>(Op0))              // undef % X -> 0
1863     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1864   if (isa<UndefValue>(Op1))
1865     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
1866   
1867   if (I.getType()->isSigned()) {
1868     if (Value *RHSNeg = dyn_castNegVal(Op1))
1869       if (!isa<ConstantSInt>(RHSNeg) ||
1870           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1871         // X % -Y -> X % Y
1872         AddUsesToWorkList(I);
1873         I.setOperand(1, RHSNeg);
1874         return &I;
1875       }
1876    
1877     // If the top bits of both operands are zero (i.e. we can prove they are
1878     // unsigned inputs), turn this into a urem.
1879     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1880     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1881       const Type *NTy = Op0->getType()->getUnsignedVersion();
1882       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1883       InsertNewInstBefore(LHS, I);
1884       Value *RHS;
1885       if (Constant *R = dyn_cast<Constant>(Op1))
1886         RHS = ConstantExpr::getCast(R, NTy);
1887       else
1888         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1889       Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1890       InsertNewInstBefore(Rem, I);
1891       return new CastInst(Rem, I.getType());
1892     }
1893   }
1894
1895   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1896     // X % 0 == undef, we don't need to preserve faults!
1897     if (RHS->equalsInt(0))
1898       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1899     
1900     if (RHS->equalsInt(1))  // X % 1 == 0
1901       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1902
1903     // Check to see if this is an unsigned remainder with an exact power of 2,
1904     // if so, convert to a bitwise and.
1905     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1906       if (isPowerOf2_64(C->getValue()))
1907         return BinaryOperator::createAnd(Op0, SubOne(C));
1908
1909     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1910       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1911         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1912           return R;
1913       } else if (isa<PHINode>(Op0I)) {
1914         if (Instruction *NV = FoldOpIntoPhi(I))
1915           return NV;
1916       }
1917       
1918       // X*C1%C2 --> 0  iff  C1%C2 == 0
1919       if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1920         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1921     }
1922   }
1923
1924   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1925     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1926     if (I.getType()->isUnsigned() && 
1927         RHSI->getOpcode() == Instruction::Shl &&
1928         isa<ConstantUInt>(RHSI->getOperand(0))) {
1929       unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1930       if (isPowerOf2_64(C1)) {
1931         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1932         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1933                                                                    "tmp"), I);
1934         return BinaryOperator::createAnd(Op0, Add);
1935       }
1936     }
1937     
1938     // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1939     // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1940     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1941       if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1942         if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1943           if (STO->getValue() == 0) { // Couldn't be this argument.
1944             I.setOperand(1, SFO);
1945             return &I;
1946           } else if (SFO->getValue() == 0) {
1947             I.setOperand(1, STO);
1948             return &I;
1949           }
1950           
1951           if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1952             Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1953                                           SubOne(STO), SI->getName()+".t"), I);
1954             Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1955                                           SubOne(SFO), SI->getName()+".f"), I);
1956             return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1957           }
1958         }
1959   }
1960   
1961   return 0;
1962 }
1963
1964 // isMaxValueMinusOne - return true if this is Max-1
1965 static bool isMaxValueMinusOne(const ConstantInt *C) {
1966   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1967     return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1968
1969   const ConstantSInt *CS = cast<ConstantSInt>(C);
1970
1971   // Calculate 0111111111..11111
1972   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1973   int64_t Val = INT64_MAX;             // All ones
1974   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1975   return CS->getValue() == Val-1;
1976 }
1977
1978 // isMinValuePlusOne - return true if this is Min+1
1979 static bool isMinValuePlusOne(const ConstantInt *C) {
1980   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1981     return CU->getValue() == 1;
1982
1983   const ConstantSInt *CS = cast<ConstantSInt>(C);
1984
1985   // Calculate 1111111111000000000000
1986   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1987   int64_t Val = -1;                    // All ones
1988   Val <<= TypeBits-1;                  // Shift over to the right spot
1989   return CS->getValue() == Val+1;
1990 }
1991
1992 // isOneBitSet - Return true if there is exactly one bit set in the specified
1993 // constant.
1994 static bool isOneBitSet(const ConstantInt *CI) {
1995   uint64_t V = CI->getRawValue();
1996   return V && (V & (V-1)) == 0;
1997 }
1998
1999 #if 0   // Currently unused
2000 // isLowOnes - Return true if the constant is of the form 0+1+.
2001 static bool isLowOnes(const ConstantInt *CI) {
2002   uint64_t V = CI->getRawValue();
2003
2004   // There won't be bits set in parts that the type doesn't contain.
2005   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2006
2007   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2008   return U && V && (U & V) == 0;
2009 }
2010 #endif
2011
2012 // isHighOnes - Return true if the constant is of the form 1+0+.
2013 // This is the same as lowones(~X).
2014 static bool isHighOnes(const ConstantInt *CI) {
2015   uint64_t V = ~CI->getRawValue();
2016   if (~V == 0) return false;  // 0's does not match "1+"
2017
2018   // There won't be bits set in parts that the type doesn't contain.
2019   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2020
2021   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2022   return U && V && (U & V) == 0;
2023 }
2024
2025
2026 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
2027 /// are carefully arranged to allow folding of expressions such as:
2028 ///
2029 ///      (A < B) | (A > B) --> (A != B)
2030 ///
2031 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2032 /// represents that the comparison is true if A == B, and bit value '1' is true
2033 /// if A < B.
2034 ///
2035 static unsigned getSetCondCode(const SetCondInst *SCI) {
2036   switch (SCI->getOpcode()) {
2037     // False -> 0
2038   case Instruction::SetGT: return 1;
2039   case Instruction::SetEQ: return 2;
2040   case Instruction::SetGE: return 3;
2041   case Instruction::SetLT: return 4;
2042   case Instruction::SetNE: return 5;
2043   case Instruction::SetLE: return 6;
2044     // True -> 7
2045   default:
2046     assert(0 && "Invalid SetCC opcode!");
2047     return 0;
2048   }
2049 }
2050
2051 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2052 /// opcode and two operands into either a constant true or false, or a brand new
2053 /// SetCC instruction.
2054 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2055   switch (Opcode) {
2056   case 0: return ConstantBool::False;
2057   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2058   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2059   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2060   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2061   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2062   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2063   case 7: return ConstantBool::True;
2064   default: assert(0 && "Illegal SetCCCode!"); return 0;
2065   }
2066 }
2067
2068 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2069 struct FoldSetCCLogical {
2070   InstCombiner &IC;
2071   Value *LHS, *RHS;
2072   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2073     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2074   bool shouldApply(Value *V) const {
2075     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2076       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2077               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2078     return false;
2079   }
2080   Instruction *apply(BinaryOperator &Log) const {
2081     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2082     if (SCI->getOperand(0) != LHS) {
2083       assert(SCI->getOperand(1) == LHS);
2084       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2085     }
2086
2087     unsigned LHSCode = getSetCondCode(SCI);
2088     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2089     unsigned Code;
2090     switch (Log.getOpcode()) {
2091     case Instruction::And: Code = LHSCode & RHSCode; break;
2092     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2093     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2094     default: assert(0 && "Illegal logical opcode!"); return 0;
2095     }
2096
2097     Value *RV = getSetCCValue(Code, LHS, RHS);
2098     if (Instruction *I = dyn_cast<Instruction>(RV))
2099       return I;
2100     // Otherwise, it's a constant boolean value...
2101     return IC.ReplaceInstUsesWith(Log, RV);
2102   }
2103 };
2104
2105 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2106 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2107 // guaranteed to be either a shift instruction or a binary operator.
2108 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2109                                     ConstantIntegral *OpRHS,
2110                                     ConstantIntegral *AndRHS,
2111                                     BinaryOperator &TheAnd) {
2112   Value *X = Op->getOperand(0);
2113   Constant *Together = 0;
2114   if (!isa<ShiftInst>(Op))
2115     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2116
2117   switch (Op->getOpcode()) {
2118   case Instruction::Xor:
2119     if (Op->hasOneUse()) {
2120       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2121       std::string OpName = Op->getName(); Op->setName("");
2122       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2123       InsertNewInstBefore(And, TheAnd);
2124       return BinaryOperator::createXor(And, Together);
2125     }
2126     break;
2127   case Instruction::Or:
2128     if (Together == AndRHS) // (X | C) & C --> C
2129       return ReplaceInstUsesWith(TheAnd, AndRHS);
2130
2131     if (Op->hasOneUse() && Together != OpRHS) {
2132       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2133       std::string Op0Name = Op->getName(); Op->setName("");
2134       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2135       InsertNewInstBefore(Or, TheAnd);
2136       return BinaryOperator::createAnd(Or, AndRHS);
2137     }
2138     break;
2139   case Instruction::Add:
2140     if (Op->hasOneUse()) {
2141       // Adding a one to a single bit bit-field should be turned into an XOR
2142       // of the bit.  First thing to check is to see if this AND is with a
2143       // single bit constant.
2144       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2145
2146       // Clear bits that are not part of the constant.
2147       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2148
2149       // If there is only one bit set...
2150       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2151         // Ok, at this point, we know that we are masking the result of the
2152         // ADD down to exactly one bit.  If the constant we are adding has
2153         // no bits set below this bit, then we can eliminate the ADD.
2154         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2155
2156         // Check to see if any bits below the one bit set in AndRHSV are set.
2157         if ((AddRHS & (AndRHSV-1)) == 0) {
2158           // If not, the only thing that can effect the output of the AND is
2159           // the bit specified by AndRHSV.  If that bit is set, the effect of
2160           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2161           // no effect.
2162           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2163             TheAnd.setOperand(0, X);
2164             return &TheAnd;
2165           } else {
2166             std::string Name = Op->getName(); Op->setName("");
2167             // Pull the XOR out of the AND.
2168             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2169             InsertNewInstBefore(NewAnd, TheAnd);
2170             return BinaryOperator::createXor(NewAnd, AndRHS);
2171           }
2172         }
2173       }
2174     }
2175     break;
2176
2177   case Instruction::Shl: {
2178     // We know that the AND will not produce any of the bits shifted in, so if
2179     // the anded constant includes them, clear them now!
2180     //
2181     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2182     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2183     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2184
2185     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2186       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2187     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2188       TheAnd.setOperand(1, CI);
2189       return &TheAnd;
2190     }
2191     break;
2192   }
2193   case Instruction::Shr:
2194     // We know that the AND will not produce any of the bits shifted in, so if
2195     // the anded constant includes them, clear them now!  This only applies to
2196     // unsigned shifts, because a signed shr may bring in set bits!
2197     //
2198     if (AndRHS->getType()->isUnsigned()) {
2199       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2200       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2201       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2202
2203       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2204         return ReplaceInstUsesWith(TheAnd, Op);
2205       } else if (CI != AndRHS) {
2206         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2207         return &TheAnd;
2208       }
2209     } else {   // Signed shr.
2210       // See if this is shifting in some sign extension, then masking it out
2211       // with an and.
2212       if (Op->hasOneUse()) {
2213         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2214         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2215         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2216         if (CI == AndRHS) {          // Masking out bits shifted in.
2217           // Make the argument unsigned.
2218           Value *ShVal = Op->getOperand(0);
2219           ShVal = InsertCastBefore(ShVal,
2220                                    ShVal->getType()->getUnsignedVersion(),
2221                                    TheAnd);
2222           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2223                                                     OpRHS, Op->getName()),
2224                                       TheAnd);
2225           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2226           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2227                                                              TheAnd.getName()),
2228                                       TheAnd);
2229           return new CastInst(ShVal, Op->getType());
2230         }
2231       }
2232     }
2233     break;
2234   }
2235   return 0;
2236 }
2237
2238
2239 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2240 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2241 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2242 /// insert new instructions.
2243 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2244                                            bool Inside, Instruction &IB) {
2245   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2246          "Lo is not <= Hi in range emission code!");
2247   if (Inside) {
2248     if (Lo == Hi)  // Trivially false.
2249       return new SetCondInst(Instruction::SetNE, V, V);
2250     if (cast<ConstantIntegral>(Lo)->isMinValue())
2251       return new SetCondInst(Instruction::SetLT, V, Hi);
2252
2253     Constant *AddCST = ConstantExpr::getNeg(Lo);
2254     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2255     InsertNewInstBefore(Add, IB);
2256     // Convert to unsigned for the comparison.
2257     const Type *UnsType = Add->getType()->getUnsignedVersion();
2258     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2259     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2260     AddCST = ConstantExpr::getCast(AddCST, UnsType);
2261     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2262   }
2263
2264   if (Lo == Hi)  // Trivially true.
2265     return new SetCondInst(Instruction::SetEQ, V, V);
2266
2267   Hi = SubOne(cast<ConstantInt>(Hi));
2268   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2269     return new SetCondInst(Instruction::SetGT, V, Hi);
2270
2271   // Emit X-Lo > Hi-Lo-1
2272   Constant *AddCST = ConstantExpr::getNeg(Lo);
2273   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2274   InsertNewInstBefore(Add, IB);
2275   // Convert to unsigned for the comparison.
2276   const Type *UnsType = Add->getType()->getUnsignedVersion();
2277   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2278   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2279   AddCST = ConstantExpr::getCast(AddCST, UnsType);
2280   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2281 }
2282
2283 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2284 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2285 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2286 // not, since all 1s are not contiguous.
2287 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2288   uint64_t V = Val->getRawValue();
2289   if (!isShiftedMask_64(V)) return false;
2290
2291   // look for the first zero bit after the run of ones
2292   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2293   // look for the first non-zero bit
2294   ME = 64-CountLeadingZeros_64(V);
2295   return true;
2296 }
2297
2298
2299
2300 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2301 /// where isSub determines whether the operator is a sub.  If we can fold one of
2302 /// the following xforms:
2303 /// 
2304 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2305 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2306 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2307 ///
2308 /// return (A +/- B).
2309 ///
2310 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2311                                         ConstantIntegral *Mask, bool isSub,
2312                                         Instruction &I) {
2313   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2314   if (!LHSI || LHSI->getNumOperands() != 2 ||
2315       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2316
2317   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2318
2319   switch (LHSI->getOpcode()) {
2320   default: return 0;
2321   case Instruction::And:
2322     if (ConstantExpr::getAnd(N, Mask) == Mask) {
2323       // If the AndRHS is a power of two minus one (0+1+), this is simple.
2324       if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2325         break;
2326
2327       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2328       // part, we don't need any explicit masks to take them out of A.  If that
2329       // is all N is, ignore it.
2330       unsigned MB, ME;
2331       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
2332         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2333         Mask >>= 64-MB+1;
2334         if (MaskedValueIsZero(RHS, Mask))
2335           break;
2336       }
2337     }
2338     return 0;
2339   case Instruction::Or:
2340   case Instruction::Xor:
2341     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2342     if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2343         ConstantExpr::getAnd(N, Mask)->isNullValue())
2344       break;
2345     return 0;
2346   }
2347   
2348   Instruction *New;
2349   if (isSub)
2350     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2351   else
2352     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2353   return InsertNewInstBefore(New, I);
2354 }
2355
2356 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2357   bool Changed = SimplifyCommutative(I);
2358   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2359
2360   if (isa<UndefValue>(Op1))                         // X & undef -> 0
2361     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2362
2363   // and X, X = X
2364   if (Op0 == Op1)
2365     return ReplaceInstUsesWith(I, Op1);
2366
2367   // See if we can simplify any instructions used by the instruction whose sole 
2368   // purpose is to compute bits we don't care about.
2369   uint64_t KnownZero, KnownOne;
2370   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2371                            KnownZero, KnownOne))
2372     return &I;
2373   
2374   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2375     uint64_t AndRHSMask = AndRHS->getZExtValue();
2376     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2377     uint64_t NotAndRHS = AndRHSMask^TypeMask;
2378
2379     // Optimize a variety of ((val OP C1) & C2) combinations...
2380     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2381       Instruction *Op0I = cast<Instruction>(Op0);
2382       Value *Op0LHS = Op0I->getOperand(0);
2383       Value *Op0RHS = Op0I->getOperand(1);
2384       switch (Op0I->getOpcode()) {
2385       case Instruction::Xor:
2386       case Instruction::Or:
2387         // If the mask is only needed on one incoming arm, push it up.
2388         if (Op0I->hasOneUse()) {
2389           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2390             // Not masking anything out for the LHS, move to RHS.
2391             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2392                                                    Op0RHS->getName()+".masked");
2393             InsertNewInstBefore(NewRHS, I);
2394             return BinaryOperator::create(
2395                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2396           }
2397           if (!isa<Constant>(Op0RHS) &&
2398               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2399             // Not masking anything out for the RHS, move to LHS.
2400             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2401                                                    Op0LHS->getName()+".masked");
2402             InsertNewInstBefore(NewLHS, I);
2403             return BinaryOperator::create(
2404                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2405           }
2406         }
2407
2408         break;
2409       case Instruction::Add:
2410         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2411         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2412         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2413         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2414           return BinaryOperator::createAnd(V, AndRHS);
2415         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2416           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
2417         break;
2418
2419       case Instruction::Sub:
2420         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2421         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2422         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2423         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2424           return BinaryOperator::createAnd(V, AndRHS);
2425         break;
2426       }
2427
2428       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2429         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2430           return Res;
2431     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2432       const Type *SrcTy = CI->getOperand(0)->getType();
2433
2434       // If this is an integer truncation or change from signed-to-unsigned, and
2435       // if the source is an and/or with immediate, transform it.  This
2436       // frequently occurs for bitfield accesses.
2437       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2438         if (SrcTy->getPrimitiveSizeInBits() >= 
2439               I.getType()->getPrimitiveSizeInBits() &&
2440             CastOp->getNumOperands() == 2)
2441           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2442             if (CastOp->getOpcode() == Instruction::And) {
2443               // Change: and (cast (and X, C1) to T), C2
2444               // into  : and (cast X to T), trunc(C1)&C2
2445               // This will folds the two ands together, which may allow other
2446               // simplifications.
2447               Instruction *NewCast =
2448                 new CastInst(CastOp->getOperand(0), I.getType(),
2449                              CastOp->getName()+".shrunk");
2450               NewCast = InsertNewInstBefore(NewCast, I);
2451               
2452               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2453               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
2454               return BinaryOperator::createAnd(NewCast, C3);
2455             } else if (CastOp->getOpcode() == Instruction::Or) {
2456               // Change: and (cast (or X, C1) to T), C2
2457               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2458               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2459               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
2460                 return ReplaceInstUsesWith(I, AndRHS);
2461             }
2462       }
2463     }
2464
2465     // Try to fold constant and into select arguments.
2466     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2467       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2468         return R;
2469     if (isa<PHINode>(Op0))
2470       if (Instruction *NV = FoldOpIntoPhi(I))
2471         return NV;
2472   }
2473
2474   Value *Op0NotVal = dyn_castNotVal(Op0);
2475   Value *Op1NotVal = dyn_castNotVal(Op1);
2476
2477   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
2478     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2479
2480   // (~A & ~B) == (~(A | B)) - De Morgan's Law
2481   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2482     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2483                                                I.getName()+".demorgan");
2484     InsertNewInstBefore(Or, I);
2485     return BinaryOperator::createNot(Or);
2486   }
2487   
2488   {
2489     Value *A = 0, *B = 0;
2490     ConstantInt *C1 = 0, *C2 = 0;
2491     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2492       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
2493         return ReplaceInstUsesWith(I, Op1);
2494     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2495       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
2496         return ReplaceInstUsesWith(I, Op0);
2497   }
2498   
2499
2500   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2501     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2502     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2503       return R;
2504
2505     Value *LHSVal, *RHSVal;
2506     ConstantInt *LHSCst, *RHSCst;
2507     Instruction::BinaryOps LHSCC, RHSCC;
2508     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2509       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2510         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
2511             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2512             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2513             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2514           // Ensure that the larger constant is on the RHS.
2515           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2516           SetCondInst *LHS = cast<SetCondInst>(Op0);
2517           if (cast<ConstantBool>(Cmp)->getValue()) {
2518             std::swap(LHS, RHS);
2519             std::swap(LHSCst, RHSCst);
2520             std::swap(LHSCC, RHSCC);
2521           }
2522
2523           // At this point, we know we have have two setcc instructions
2524           // comparing a value against two constants and and'ing the result
2525           // together.  Because of the above check, we know that we only have
2526           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2527           // FoldSetCCLogical check above), that the two constants are not
2528           // equal.
2529           assert(LHSCst != RHSCst && "Compares not folded above?");
2530
2531           switch (LHSCC) {
2532           default: assert(0 && "Unknown integer condition code!");
2533           case Instruction::SetEQ:
2534             switch (RHSCC) {
2535             default: assert(0 && "Unknown integer condition code!");
2536             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
2537             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
2538               return ReplaceInstUsesWith(I, ConstantBool::False);
2539             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
2540             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
2541               return ReplaceInstUsesWith(I, LHS);
2542             }
2543           case Instruction::SetNE:
2544             switch (RHSCC) {
2545             default: assert(0 && "Unknown integer condition code!");
2546             case Instruction::SetLT:
2547               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2548                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2549               break;                        // (X != 13 & X < 15) -> no change
2550             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
2551             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
2552               return ReplaceInstUsesWith(I, RHS);
2553             case Instruction::SetNE:
2554               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2555                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2556                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2557                                                       LHSVal->getName()+".off");
2558                 InsertNewInstBefore(Add, I);
2559                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2560                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2561                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2562                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2563                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2564               }
2565               break;                        // (X != 13 & X != 15) -> no change
2566             }
2567             break;
2568           case Instruction::SetLT:
2569             switch (RHSCC) {
2570             default: assert(0 && "Unknown integer condition code!");
2571             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
2572             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
2573               return ReplaceInstUsesWith(I, ConstantBool::False);
2574             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
2575             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
2576               return ReplaceInstUsesWith(I, LHS);
2577             }
2578           case Instruction::SetGT:
2579             switch (RHSCC) {
2580             default: assert(0 && "Unknown integer condition code!");
2581             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
2582               return ReplaceInstUsesWith(I, LHS);
2583             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
2584               return ReplaceInstUsesWith(I, RHS);
2585             case Instruction::SetNE:
2586               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2587                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2588               break;                        // (X > 13 & X != 15) -> no change
2589             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
2590               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2591             }
2592           }
2593         }
2594   }
2595
2596   return Changed ? &I : 0;
2597 }
2598
2599 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2600   bool Changed = SimplifyCommutative(I);
2601   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2602
2603   if (isa<UndefValue>(Op1))
2604     return ReplaceInstUsesWith(I,                         // X | undef -> -1
2605                                ConstantIntegral::getAllOnesValue(I.getType()));
2606
2607   // or X, X = X
2608   if (Op0 == Op1)
2609     return ReplaceInstUsesWith(I, Op0);
2610
2611   // See if we can simplify any instructions used by the instruction whose sole 
2612   // purpose is to compute bits we don't care about.
2613   uint64_t KnownZero, KnownOne;
2614   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2615                            KnownZero, KnownOne))
2616     return &I;
2617   
2618   // or X, -1 == -1
2619   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2620     ConstantInt *C1 = 0; Value *X = 0;
2621     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2622     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2623       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2624       Op0->setName("");
2625       InsertNewInstBefore(Or, I);
2626       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2627     }
2628
2629     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2630     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2631       std::string Op0Name = Op0->getName(); Op0->setName("");
2632       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2633       InsertNewInstBefore(Or, I);
2634       return BinaryOperator::createXor(Or,
2635                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2636     }
2637
2638     // Try to fold constant and into select arguments.
2639     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2640       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2641         return R;
2642     if (isa<PHINode>(Op0))
2643       if (Instruction *NV = FoldOpIntoPhi(I))
2644         return NV;
2645   }
2646
2647   Value *A = 0, *B = 0;
2648   ConstantInt *C1 = 0, *C2 = 0;
2649
2650   if (match(Op0, m_And(m_Value(A), m_Value(B))))
2651     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
2652       return ReplaceInstUsesWith(I, Op1);
2653   if (match(Op1, m_And(m_Value(A), m_Value(B))))
2654     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
2655       return ReplaceInstUsesWith(I, Op0);
2656
2657   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2658   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2659       MaskedValueIsZero(Op1, C1->getZExtValue())) {
2660     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2661     Op0->setName("");
2662     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2663   }
2664
2665   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2666   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2667       MaskedValueIsZero(Op0, C1->getZExtValue())) {
2668     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2669     Op0->setName("");
2670     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2671   }
2672
2673   // (A & C1)|(B & C2)
2674   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2675       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2676
2677     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
2678       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2679
2680
2681     // If we have: ((V + N) & C1) | (V & C2)
2682     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2683     // replace with V+N.
2684     if (C1 == ConstantExpr::getNot(C2)) {
2685       Value *V1 = 0, *V2 = 0;
2686       if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2687           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2688         // Add commutes, try both ways.
2689         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2690           return ReplaceInstUsesWith(I, A);
2691         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2692           return ReplaceInstUsesWith(I, A);
2693       }
2694       // Or commutes, try both ways.
2695       if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2696           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2697         // Add commutes, try both ways.
2698         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2699           return ReplaceInstUsesWith(I, B);
2700         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2701           return ReplaceInstUsesWith(I, B);
2702       }
2703     }
2704   }
2705
2706   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
2707     if (A == Op1)   // ~A | A == -1
2708       return ReplaceInstUsesWith(I,
2709                                 ConstantIntegral::getAllOnesValue(I.getType()));
2710   } else {
2711     A = 0;
2712   }
2713   // Note, A is still live here!
2714   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
2715     if (Op0 == B)
2716       return ReplaceInstUsesWith(I,
2717                                 ConstantIntegral::getAllOnesValue(I.getType()));
2718
2719     // (~A | ~B) == (~(A & B)) - De Morgan's Law
2720     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2721       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2722                                               I.getName()+".demorgan"), I);
2723       return BinaryOperator::createNot(And);
2724     }
2725   }
2726
2727   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2728   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2729     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2730       return R;
2731
2732     Value *LHSVal, *RHSVal;
2733     ConstantInt *LHSCst, *RHSCst;
2734     Instruction::BinaryOps LHSCC, RHSCC;
2735     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2736       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2737         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
2738             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2739             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2740             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2741           // Ensure that the larger constant is on the RHS.
2742           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2743           SetCondInst *LHS = cast<SetCondInst>(Op0);
2744           if (cast<ConstantBool>(Cmp)->getValue()) {
2745             std::swap(LHS, RHS);
2746             std::swap(LHSCst, RHSCst);
2747             std::swap(LHSCC, RHSCC);
2748           }
2749
2750           // At this point, we know we have have two setcc instructions
2751           // comparing a value against two constants and or'ing the result
2752           // together.  Because of the above check, we know that we only have
2753           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2754           // FoldSetCCLogical check above), that the two constants are not
2755           // equal.
2756           assert(LHSCst != RHSCst && "Compares not folded above?");
2757
2758           switch (LHSCC) {
2759           default: assert(0 && "Unknown integer condition code!");
2760           case Instruction::SetEQ:
2761             switch (RHSCC) {
2762             default: assert(0 && "Unknown integer condition code!");
2763             case Instruction::SetEQ:
2764               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2765                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2766                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2767                                                       LHSVal->getName()+".off");
2768                 InsertNewInstBefore(Add, I);
2769                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2770                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2771                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2772                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2773                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2774               }
2775               break;                  // (X == 13 | X == 15) -> no change
2776
2777             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
2778               break;
2779             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
2780             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
2781               return ReplaceInstUsesWith(I, RHS);
2782             }
2783             break;
2784           case Instruction::SetNE:
2785             switch (RHSCC) {
2786             default: assert(0 && "Unknown integer condition code!");
2787             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
2788             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
2789               return ReplaceInstUsesWith(I, LHS);
2790             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
2791             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
2792               return ReplaceInstUsesWith(I, ConstantBool::True);
2793             }
2794             break;
2795           case Instruction::SetLT:
2796             switch (RHSCC) {
2797             default: assert(0 && "Unknown integer condition code!");
2798             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
2799               break;
2800             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
2801               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2802             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
2803             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
2804               return ReplaceInstUsesWith(I, RHS);
2805             }
2806             break;
2807           case Instruction::SetGT:
2808             switch (RHSCC) {
2809             default: assert(0 && "Unknown integer condition code!");
2810             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
2811             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
2812               return ReplaceInstUsesWith(I, LHS);
2813             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
2814             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
2815               return ReplaceInstUsesWith(I, ConstantBool::True);
2816             }
2817           }
2818         }
2819   }
2820
2821   return Changed ? &I : 0;
2822 }
2823
2824 // XorSelf - Implements: X ^ X --> 0
2825 struct XorSelf {
2826   Value *RHS;
2827   XorSelf(Value *rhs) : RHS(rhs) {}
2828   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2829   Instruction *apply(BinaryOperator &Xor) const {
2830     return &Xor;
2831   }
2832 };
2833
2834
2835 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2836   bool Changed = SimplifyCommutative(I);
2837   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2838
2839   if (isa<UndefValue>(Op1))
2840     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
2841
2842   // xor X, X = 0, even if X is nested in a sequence of Xor's.
2843   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2844     assert(Result == &I && "AssociativeOpt didn't work?");
2845     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2846   }
2847   
2848   // See if we can simplify any instructions used by the instruction whose sole 
2849   // purpose is to compute bits we don't care about.
2850   uint64_t KnownZero, KnownOne;
2851   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2852                            KnownZero, KnownOne))
2853     return &I;
2854
2855   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2856     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2857       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2858       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2859         if (RHS == ConstantBool::True && SCI->hasOneUse())
2860           return new SetCondInst(SCI->getInverseCondition(),
2861                                  SCI->getOperand(0), SCI->getOperand(1));
2862
2863       // ~(c-X) == X-c-1 == X+(-c-1)
2864       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2865         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2866           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2867           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2868                                               ConstantInt::get(I.getType(), 1));
2869           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2870         }
2871
2872       // ~(~X & Y) --> (X | ~Y)
2873       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2874         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2875         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2876           Instruction *NotY =
2877             BinaryOperator::createNot(Op0I->getOperand(1),
2878                                       Op0I->getOperand(1)->getName()+".not");
2879           InsertNewInstBefore(NotY, I);
2880           return BinaryOperator::createOr(Op0NotVal, NotY);
2881         }
2882       }
2883
2884       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2885         if (Op0I->getOpcode() == Instruction::Add) {
2886           // ~(X-c) --> (-c-1)-X
2887           if (RHS->isAllOnesValue()) {
2888             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2889             return BinaryOperator::createSub(
2890                            ConstantExpr::getSub(NegOp0CI,
2891                                              ConstantInt::get(I.getType(), 1)),
2892                                           Op0I->getOperand(0));
2893           }
2894         } else if (Op0I->getOpcode() == Instruction::Or) {
2895           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2896           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2897             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2898             // Anything in both C1 and C2 is known to be zero, remove it from
2899             // NewRHS.
2900             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2901             NewRHS = ConstantExpr::getAnd(NewRHS, 
2902                                           ConstantExpr::getNot(CommonBits));
2903             WorkList.push_back(Op0I);
2904             I.setOperand(0, Op0I->getOperand(0));
2905             I.setOperand(1, NewRHS);
2906             return &I;
2907           }
2908         }
2909     }
2910
2911     // Try to fold constant and into select arguments.
2912     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2913       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2914         return R;
2915     if (isa<PHINode>(Op0))
2916       if (Instruction *NV = FoldOpIntoPhi(I))
2917         return NV;
2918   }
2919
2920   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
2921     if (X == Op1)
2922       return ReplaceInstUsesWith(I,
2923                                 ConstantIntegral::getAllOnesValue(I.getType()));
2924
2925   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
2926     if (X == Op0)
2927       return ReplaceInstUsesWith(I,
2928                                 ConstantIntegral::getAllOnesValue(I.getType()));
2929
2930   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2931     if (Op1I->getOpcode() == Instruction::Or) {
2932       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
2933         cast<BinaryOperator>(Op1I)->swapOperands();
2934         I.swapOperands();
2935         std::swap(Op0, Op1);
2936       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
2937         I.swapOperands();
2938         std::swap(Op0, Op1);
2939       }
2940     } else if (Op1I->getOpcode() == Instruction::Xor) {
2941       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
2942         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2943       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
2944         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2945     }
2946
2947   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2948     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2949       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
2950         cast<BinaryOperator>(Op0I)->swapOperands();
2951       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
2952         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2953                                                      Op1->getName()+".not"), I);
2954         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2955       }
2956     } else if (Op0I->getOpcode() == Instruction::Xor) {
2957       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
2958         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2959       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
2960         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2961     }
2962
2963   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2964   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2965     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2966       return R;
2967
2968   return Changed ? &I : 0;
2969 }
2970
2971 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2972 /// overflowed for this type.
2973 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2974                             ConstantInt *In2) {
2975   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2976   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2977 }
2978
2979 static bool isPositive(ConstantInt *C) {
2980   return cast<ConstantSInt>(C)->getValue() >= 0;
2981 }
2982
2983 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2984 /// overflowed for this type.
2985 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2986                             ConstantInt *In2) {
2987   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2988
2989   if (In1->getType()->isUnsigned())
2990     return cast<ConstantUInt>(Result)->getValue() <
2991            cast<ConstantUInt>(In1)->getValue();
2992   if (isPositive(In1) != isPositive(In2))
2993     return false;
2994   if (isPositive(In1))
2995     return cast<ConstantSInt>(Result)->getValue() <
2996            cast<ConstantSInt>(In1)->getValue();
2997   return cast<ConstantSInt>(Result)->getValue() >
2998          cast<ConstantSInt>(In1)->getValue();
2999 }
3000
3001 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3002 /// code necessary to compute the offset from the base pointer (without adding
3003 /// in the base pointer).  Return the result as a signed integer of intptr size.
3004 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3005   TargetData &TD = IC.getTargetData();
3006   gep_type_iterator GTI = gep_type_begin(GEP);
3007   const Type *UIntPtrTy = TD.getIntPtrType();
3008   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3009   Value *Result = Constant::getNullValue(SIntPtrTy);
3010
3011   // Build a mask for high order bits.
3012   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3013
3014   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3015     Value *Op = GEP->getOperand(i);
3016     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3017     Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3018                                             SIntPtrTy);
3019     if (Constant *OpC = dyn_cast<Constant>(Op)) {
3020       if (!OpC->isNullValue()) {
3021         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3022         Scale = ConstantExpr::getMul(OpC, Scale);
3023         if (Constant *RC = dyn_cast<Constant>(Result))
3024           Result = ConstantExpr::getAdd(RC, Scale);
3025         else {
3026           // Emit an add instruction.
3027           Result = IC.InsertNewInstBefore(
3028              BinaryOperator::createAdd(Result, Scale,
3029                                        GEP->getName()+".offs"), I);
3030         }
3031       }
3032     } else {
3033       // Convert to correct type.
3034       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3035                                                Op->getName()+".c"), I);
3036       if (Size != 1)
3037         // We'll let instcombine(mul) convert this to a shl if possible.
3038         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3039                                                     GEP->getName()+".idx"), I);
3040
3041       // Emit an add instruction.
3042       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3043                                                     GEP->getName()+".offs"), I);
3044     }
3045   }
3046   return Result;
3047 }
3048
3049 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3050 /// else.  At this point we know that the GEP is on the LHS of the comparison.
3051 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3052                                         Instruction::BinaryOps Cond,
3053                                         Instruction &I) {
3054   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3055
3056   if (CastInst *CI = dyn_cast<CastInst>(RHS))
3057     if (isa<PointerType>(CI->getOperand(0)->getType()))
3058       RHS = CI->getOperand(0);
3059
3060   Value *PtrBase = GEPLHS->getOperand(0);
3061   if (PtrBase == RHS) {
3062     // As an optimization, we don't actually have to compute the actual value of
3063     // OFFSET if this is a seteq or setne comparison, just return whether each
3064     // index is zero or not.
3065     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3066       Instruction *InVal = 0;
3067       gep_type_iterator GTI = gep_type_begin(GEPLHS);
3068       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3069         bool EmitIt = true;
3070         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3071           if (isa<UndefValue>(C))  // undef index -> undef.
3072             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3073           if (C->isNullValue())
3074             EmitIt = false;
3075           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3076             EmitIt = false;  // This is indexing into a zero sized array?
3077           } else if (isa<ConstantInt>(C))
3078             return ReplaceInstUsesWith(I, // No comparison is needed here.
3079                                  ConstantBool::get(Cond == Instruction::SetNE));
3080         }
3081
3082         if (EmitIt) {
3083           Instruction *Comp =
3084             new SetCondInst(Cond, GEPLHS->getOperand(i),
3085                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3086           if (InVal == 0)
3087             InVal = Comp;
3088           else {
3089             InVal = InsertNewInstBefore(InVal, I);
3090             InsertNewInstBefore(Comp, I);
3091             if (Cond == Instruction::SetNE)   // True if any are unequal
3092               InVal = BinaryOperator::createOr(InVal, Comp);
3093             else                              // True if all are equal
3094               InVal = BinaryOperator::createAnd(InVal, Comp);
3095           }
3096         }
3097       }
3098
3099       if (InVal)
3100         return InVal;
3101       else
3102         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3103                             ConstantBool::get(Cond == Instruction::SetEQ));
3104     }
3105
3106     // Only lower this if the setcc is the only user of the GEP or if we expect
3107     // the result to fold to a constant!
3108     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3109       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
3110       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3111       return new SetCondInst(Cond, Offset,
3112                              Constant::getNullValue(Offset->getType()));
3113     }
3114   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3115     // If the base pointers are different, but the indices are the same, just
3116     // compare the base pointer.
3117     if (PtrBase != GEPRHS->getOperand(0)) {
3118       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3119       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3120                         GEPRHS->getOperand(0)->getType();
3121       if (IndicesTheSame)
3122         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3123           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3124             IndicesTheSame = false;
3125             break;
3126           }
3127
3128       // If all indices are the same, just compare the base pointers.
3129       if (IndicesTheSame)
3130         return new SetCondInst(Cond, GEPLHS->getOperand(0),
3131                                GEPRHS->getOperand(0));
3132
3133       // Otherwise, the base pointers are different and the indices are
3134       // different, bail out.
3135       return 0;
3136     }
3137
3138     // If one of the GEPs has all zero indices, recurse.
3139     bool AllZeros = true;
3140     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3141       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3142           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3143         AllZeros = false;
3144         break;
3145       }
3146     if (AllZeros)
3147       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3148                           SetCondInst::getSwappedCondition(Cond), I);
3149
3150     // If the other GEP has all zero indices, recurse.
3151     AllZeros = true;
3152     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3153       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3154           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3155         AllZeros = false;
3156         break;
3157       }
3158     if (AllZeros)
3159       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3160
3161     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3162       // If the GEPs only differ by one index, compare it.
3163       unsigned NumDifferences = 0;  // Keep track of # differences.
3164       unsigned DiffOperand = 0;     // The operand that differs.
3165       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3166         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3167           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3168                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3169             // Irreconcilable differences.
3170             NumDifferences = 2;
3171             break;
3172           } else {
3173             if (NumDifferences++) break;
3174             DiffOperand = i;
3175           }
3176         }
3177
3178       if (NumDifferences == 0)   // SAME GEP?
3179         return ReplaceInstUsesWith(I, // No comparison is needed here.
3180                                  ConstantBool::get(Cond == Instruction::SetEQ));
3181       else if (NumDifferences == 1) {
3182         Value *LHSV = GEPLHS->getOperand(DiffOperand);
3183         Value *RHSV = GEPRHS->getOperand(DiffOperand);
3184
3185         // Convert the operands to signed values to make sure to perform a
3186         // signed comparison.
3187         const Type *NewTy = LHSV->getType()->getSignedVersion();
3188         if (LHSV->getType() != NewTy)
3189           LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3190                                                   LHSV->getName()), I);
3191         if (RHSV->getType() != NewTy)
3192           RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3193                                                   RHSV->getName()), I);
3194         return new SetCondInst(Cond, LHSV, RHSV);
3195       }
3196     }
3197
3198     // Only lower this if the setcc is the only user of the GEP or if we expect
3199     // the result to fold to a constant!
3200     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3201         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3202       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
3203       Value *L = EmitGEPOffset(GEPLHS, I, *this);
3204       Value *R = EmitGEPOffset(GEPRHS, I, *this);
3205       return new SetCondInst(Cond, L, R);
3206     }
3207   }
3208   return 0;
3209 }
3210
3211
3212 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3213   bool Changed = SimplifyCommutative(I);
3214   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215   const Type *Ty = Op0->getType();
3216
3217   // setcc X, X
3218   if (Op0 == Op1)
3219     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3220
3221   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
3222     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3223
3224   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3225   // addresses never equal each other!  We already know that Op0 != Op1.
3226   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3227        isa<ConstantPointerNull>(Op0)) &&
3228       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3229        isa<ConstantPointerNull>(Op1)))
3230     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3231
3232   // setcc's with boolean values can always be turned into bitwise operations
3233   if (Ty == Type::BoolTy) {
3234     switch (I.getOpcode()) {
3235     default: assert(0 && "Invalid setcc instruction!");
3236     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
3237       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3238       InsertNewInstBefore(Xor, I);
3239       return BinaryOperator::createNot(Xor);
3240     }
3241     case Instruction::SetNE:
3242       return BinaryOperator::createXor(Op0, Op1);
3243
3244     case Instruction::SetGT:
3245       std::swap(Op0, Op1);                   // Change setgt -> setlt
3246       // FALL THROUGH
3247     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
3248       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3249       InsertNewInstBefore(Not, I);
3250       return BinaryOperator::createAnd(Not, Op1);
3251     }
3252     case Instruction::SetGE:
3253       std::swap(Op0, Op1);                   // Change setge -> setle
3254       // FALL THROUGH
3255     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
3256       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3257       InsertNewInstBefore(Not, I);
3258       return BinaryOperator::createOr(Not, Op1);
3259     }
3260     }
3261   }
3262
3263   // See if we are doing a comparison between a constant and an instruction that
3264   // can be folded into the comparison.
3265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3266     // Check to see if we are comparing against the minimum or maximum value...
3267     if (CI->isMinValue()) {
3268       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
3269         return ReplaceInstUsesWith(I, ConstantBool::False);
3270       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
3271         return ReplaceInstUsesWith(I, ConstantBool::True);
3272       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
3273         return BinaryOperator::createSetEQ(Op0, Op1);
3274       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
3275         return BinaryOperator::createSetNE(Op0, Op1);
3276
3277     } else if (CI->isMaxValue()) {
3278       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
3279         return ReplaceInstUsesWith(I, ConstantBool::False);
3280       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
3281         return ReplaceInstUsesWith(I, ConstantBool::True);
3282       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
3283         return BinaryOperator::createSetEQ(Op0, Op1);
3284       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
3285         return BinaryOperator::createSetNE(Op0, Op1);
3286
3287       // Comparing against a value really close to min or max?
3288     } else if (isMinValuePlusOne(CI)) {
3289       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
3290         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3291       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
3292         return BinaryOperator::createSetNE(Op0, SubOne(CI));
3293
3294     } else if (isMaxValueMinusOne(CI)) {
3295       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
3296         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3297       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
3298         return BinaryOperator::createSetNE(Op0, AddOne(CI));
3299     }
3300
3301     // If we still have a setle or setge instruction, turn it into the
3302     // appropriate setlt or setgt instruction.  Since the border cases have
3303     // already been handled above, this requires little checking.
3304     //
3305     if (I.getOpcode() == Instruction::SetLE)
3306       return BinaryOperator::createSetLT(Op0, AddOne(CI));
3307     if (I.getOpcode() == Instruction::SetGE)
3308       return BinaryOperator::createSetGT(Op0, SubOne(CI));
3309
3310     
3311     // See if we can fold the comparison based on bits known to be zero or one
3312     // in the input.
3313     uint64_t KnownZero, KnownOne;
3314     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3315                              KnownZero, KnownOne, 0))
3316       return &I;
3317         
3318     // Given the known and unknown bits, compute a range that the LHS could be
3319     // in.
3320     if (KnownOne | KnownZero) {
3321       if (Ty->isUnsigned()) {   // Unsigned comparison.
3322         uint64_t Min, Max;
3323         uint64_t RHSVal = CI->getZExtValue();
3324         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3325                                                  Min, Max);
3326         switch (I.getOpcode()) {  // LE/GE have been folded already.
3327         default: assert(0 && "Unknown setcc opcode!");
3328         case Instruction::SetEQ:
3329           if (Max < RHSVal || Min > RHSVal)
3330             return ReplaceInstUsesWith(I, ConstantBool::False);
3331           break;
3332         case Instruction::SetNE:
3333           if (Max < RHSVal || Min > RHSVal)
3334             return ReplaceInstUsesWith(I, ConstantBool::True);
3335           break;
3336         case Instruction::SetLT:
3337           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3338           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3339           break;
3340         case Instruction::SetGT:
3341           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3342           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3343           break;
3344         }
3345       } else {              // Signed comparison.
3346         int64_t Min, Max;
3347         int64_t RHSVal = CI->getSExtValue();
3348         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3349                                                Min, Max);
3350         switch (I.getOpcode()) {  // LE/GE have been folded already.
3351         default: assert(0 && "Unknown setcc opcode!");
3352         case Instruction::SetEQ:
3353           if (Max < RHSVal || Min > RHSVal)
3354             return ReplaceInstUsesWith(I, ConstantBool::False);
3355           break;
3356         case Instruction::SetNE:
3357           if (Max < RHSVal || Min > RHSVal)
3358             return ReplaceInstUsesWith(I, ConstantBool::True);
3359           break;
3360         case Instruction::SetLT:
3361           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3362           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3363           break;
3364         case Instruction::SetGT:
3365           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3366           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3367           break;
3368         }
3369       }
3370     }
3371           
3372     
3373     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3374       switch (LHSI->getOpcode()) {
3375       case Instruction::And:
3376         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3377             LHSI->getOperand(0)->hasOneUse()) {
3378           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3379           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
3380           // happens a LOT in code produced by the C front-end, for bitfield
3381           // access.
3382           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3383           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3384
3385           // Check to see if there is a noop-cast between the shift and the and.
3386           if (!Shift) {
3387             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3388               if (CI->getOperand(0)->getType()->isIntegral() &&
3389                   CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3390                      CI->getType()->getPrimitiveSizeInBits())
3391                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3392           }
3393           
3394           ConstantUInt *ShAmt;
3395           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3396           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
3397           const Type *AndTy = AndCST->getType();          // Type of the and.
3398
3399           // We can fold this as long as we can't shift unknown bits
3400           // into the mask.  This can only happen with signed shift
3401           // rights, as they sign-extend.
3402           if (ShAmt) {
3403             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3404                            Ty->isUnsigned();
3405             if (!CanFold) {
3406               // To test for the bad case of the signed shr, see if any
3407               // of the bits shifted in could be tested after the mask.
3408               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3409               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3410
3411               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3412               Constant *ShVal =
3413                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
3414                                      OShAmt);
3415               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3416                 CanFold = true;
3417             }
3418
3419             if (CanFold) {
3420               Constant *NewCst;
3421               if (Shift->getOpcode() == Instruction::Shl)
3422                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3423               else
3424                 NewCst = ConstantExpr::getShl(CI, ShAmt);
3425
3426               // Check to see if we are shifting out any of the bits being
3427               // compared.
3428               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3429                 // If we shifted bits out, the fold is not going to work out.
3430                 // As a special case, check to see if this means that the
3431                 // result is always true or false now.
3432                 if (I.getOpcode() == Instruction::SetEQ)
3433                   return ReplaceInstUsesWith(I, ConstantBool::False);
3434                 if (I.getOpcode() == Instruction::SetNE)
3435                   return ReplaceInstUsesWith(I, ConstantBool::True);
3436               } else {
3437                 I.setOperand(1, NewCst);
3438                 Constant *NewAndCST;
3439                 if (Shift->getOpcode() == Instruction::Shl)
3440                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3441                 else
3442                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3443                 LHSI->setOperand(1, NewAndCST);
3444                 if (AndTy == Ty) 
3445                   LHSI->setOperand(0, Shift->getOperand(0));
3446                 else {
3447                   Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3448                                                     *Shift);
3449                   LHSI->setOperand(0, NewCast);
3450                 }
3451                 WorkList.push_back(Shift); // Shift is dead.
3452                 AddUsesToWorkList(I);
3453                 return &I;
3454               }
3455             }
3456           }
3457         }
3458         break;
3459
3460       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
3461         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3462           switch (I.getOpcode()) {
3463           default: break;
3464           case Instruction::SetEQ:
3465           case Instruction::SetNE: {
3466             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3467
3468             // Check that the shift amount is in range.  If not, don't perform
3469             // undefined shifts.  When the shift is visited it will be
3470             // simplified.
3471             if (ShAmt->getValue() >= TypeBits)
3472               break;
3473
3474             // If we are comparing against bits always shifted out, the
3475             // comparison cannot succeed.
3476             Constant *Comp =
3477               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3478             if (Comp != CI) {// Comparing against a bit that we know is zero.
3479               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3480               Constant *Cst = ConstantBool::get(IsSetNE);
3481               return ReplaceInstUsesWith(I, Cst);
3482             }
3483
3484             if (LHSI->hasOneUse()) {
3485               // Otherwise strength reduce the shift into an and.
3486               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3487               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3488
3489               Constant *Mask;
3490               if (CI->getType()->isUnsigned()) {
3491                 Mask = ConstantUInt::get(CI->getType(), Val);
3492               } else if (ShAmtVal != 0) {
3493                 Mask = ConstantSInt::get(CI->getType(), Val);
3494               } else {
3495                 Mask = ConstantInt::getAllOnesValue(CI->getType());
3496               }
3497
3498               Instruction *AndI =
3499                 BinaryOperator::createAnd(LHSI->getOperand(0),
3500                                           Mask, LHSI->getName()+".mask");
3501               Value *And = InsertNewInstBefore(AndI, I);
3502               return new SetCondInst(I.getOpcode(), And,
3503                                      ConstantExpr::getUShr(CI, ShAmt));
3504             }
3505           }
3506           }
3507         }
3508         break;
3509
3510       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
3511         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3512           switch (I.getOpcode()) {
3513           default: break;
3514           case Instruction::SetEQ:
3515           case Instruction::SetNE: {
3516
3517             // Check that the shift amount is in range.  If not, don't perform
3518             // undefined shifts.  When the shift is visited it will be
3519             // simplified.
3520             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3521             if (ShAmt->getValue() >= TypeBits)
3522               break;
3523
3524             // If we are comparing against bits always shifted out, the
3525             // comparison cannot succeed.
3526             Constant *Comp =
3527               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3528
3529             if (Comp != CI) {// Comparing against a bit that we know is zero.
3530               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3531               Constant *Cst = ConstantBool::get(IsSetNE);
3532               return ReplaceInstUsesWith(I, Cst);
3533             }
3534
3535             if (LHSI->hasOneUse() || CI->isNullValue()) {
3536               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3537
3538               // Otherwise strength reduce the shift into an and.
3539               uint64_t Val = ~0ULL;          // All ones.
3540               Val <<= ShAmtVal;              // Shift over to the right spot.
3541
3542               Constant *Mask;
3543               if (CI->getType()->isUnsigned()) {
3544                 Val &= ~0ULL >> (64-TypeBits);
3545                 Mask = ConstantUInt::get(CI->getType(), Val);
3546               } else {
3547                 Mask = ConstantSInt::get(CI->getType(), Val);
3548               }
3549
3550               Instruction *AndI =
3551                 BinaryOperator::createAnd(LHSI->getOperand(0),
3552                                           Mask, LHSI->getName()+".mask");
3553               Value *And = InsertNewInstBefore(AndI, I);
3554               return new SetCondInst(I.getOpcode(), And,
3555                                      ConstantExpr::getShl(CI, ShAmt));
3556             }
3557             break;
3558           }
3559           }
3560         }
3561         break;
3562
3563       case Instruction::Div:
3564         // Fold: (div X, C1) op C2 -> range check
3565         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3566           // Fold this div into the comparison, producing a range check.
3567           // Determine, based on the divide type, what the range is being
3568           // checked.  If there is an overflow on the low or high side, remember
3569           // it, otherwise compute the range [low, hi) bounding the new value.
3570           bool LoOverflow = false, HiOverflow = 0;
3571           ConstantInt *LoBound = 0, *HiBound = 0;
3572
3573           ConstantInt *Prod;
3574           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3575
3576           Instruction::BinaryOps Opcode = I.getOpcode();
3577
3578           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
3579           } else if (LHSI->getType()->isUnsigned()) {  // udiv
3580             LoBound = Prod;
3581             LoOverflow = ProdOV;
3582             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3583           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
3584             if (CI->isNullValue()) {       // (X / pos) op 0
3585               // Can't overflow.
3586               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3587               HiBound = DivRHS;
3588             } else if (isPositive(CI)) {   // (X / pos) op pos
3589               LoBound = Prod;
3590               LoOverflow = ProdOV;
3591               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3592             } else {                       // (X / pos) op neg
3593               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3594               LoOverflow = AddWithOverflow(LoBound, Prod,
3595                                            cast<ConstantInt>(DivRHSH));
3596               HiBound = Prod;
3597               HiOverflow = ProdOV;
3598             }
3599           } else {                                     // Divisor is < 0.
3600             if (CI->isNullValue()) {       // (X / neg) op 0
3601               LoBound = AddOne(DivRHS);
3602               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3603               if (HiBound == DivRHS)
3604                 LoBound = 0;  // - INTMIN = INTMIN
3605             } else if (isPositive(CI)) {   // (X / neg) op pos
3606               HiOverflow = LoOverflow = ProdOV;
3607               if (!LoOverflow)
3608                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3609               HiBound = AddOne(Prod);
3610             } else {                       // (X / neg) op neg
3611               LoBound = Prod;
3612               LoOverflow = HiOverflow = ProdOV;
3613               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3614             }
3615
3616             // Dividing by a negate swaps the condition.
3617             Opcode = SetCondInst::getSwappedCondition(Opcode);
3618           }
3619
3620           if (LoBound) {
3621             Value *X = LHSI->getOperand(0);
3622             switch (Opcode) {
3623             default: assert(0 && "Unhandled setcc opcode!");
3624             case Instruction::SetEQ:
3625               if (LoOverflow && HiOverflow)
3626                 return ReplaceInstUsesWith(I, ConstantBool::False);
3627               else if (HiOverflow)
3628                 return new SetCondInst(Instruction::SetGE, X, LoBound);
3629               else if (LoOverflow)
3630                 return new SetCondInst(Instruction::SetLT, X, HiBound);
3631               else
3632                 return InsertRangeTest(X, LoBound, HiBound, true, I);
3633             case Instruction::SetNE:
3634               if (LoOverflow && HiOverflow)
3635                 return ReplaceInstUsesWith(I, ConstantBool::True);
3636               else if (HiOverflow)
3637                 return new SetCondInst(Instruction::SetLT, X, LoBound);
3638               else if (LoOverflow)
3639                 return new SetCondInst(Instruction::SetGE, X, HiBound);
3640               else
3641                 return InsertRangeTest(X, LoBound, HiBound, false, I);
3642             case Instruction::SetLT:
3643               if (LoOverflow)
3644                 return ReplaceInstUsesWith(I, ConstantBool::False);
3645               return new SetCondInst(Instruction::SetLT, X, LoBound);
3646             case Instruction::SetGT:
3647               if (HiOverflow)
3648                 return ReplaceInstUsesWith(I, ConstantBool::False);
3649               return new SetCondInst(Instruction::SetGE, X, HiBound);
3650             }
3651           }
3652         }
3653         break;
3654       }
3655
3656     // Simplify seteq and setne instructions...
3657     if (I.getOpcode() == Instruction::SetEQ ||
3658         I.getOpcode() == Instruction::SetNE) {
3659       bool isSetNE = I.getOpcode() == Instruction::SetNE;
3660
3661       // If the first operand is (and|or|xor) with a constant, and the second
3662       // operand is a constant, simplify a bit.
3663       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3664         switch (BO->getOpcode()) {
3665         case Instruction::Rem:
3666           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3667           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3668               BO->hasOneUse() &&
3669               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3670             int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3671             if (isPowerOf2_64(V)) {
3672               unsigned L2 = Log2_64(V);
3673               const Type *UTy = BO->getType()->getUnsignedVersion();
3674               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3675                                                              UTy, "tmp"), I);
3676               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3677               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3678                                                     RHSCst, BO->getName()), I);
3679               return BinaryOperator::create(I.getOpcode(), NewRem,
3680                                             Constant::getNullValue(UTy));
3681             }
3682           }
3683           break;
3684
3685         case Instruction::Add:
3686           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3687           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3688             if (BO->hasOneUse())
3689               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3690                                      ConstantExpr::getSub(CI, BOp1C));
3691           } else if (CI->isNullValue()) {
3692             // Replace ((add A, B) != 0) with (A != -B) if A or B is
3693             // efficiently invertible, or if the add has just this one use.
3694             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3695
3696             if (Value *NegVal = dyn_castNegVal(BOp1))
3697               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3698             else if (Value *NegVal = dyn_castNegVal(BOp0))
3699               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3700             else if (BO->hasOneUse()) {
3701               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3702               BO->setName("");
3703               InsertNewInstBefore(Neg, I);
3704               return new SetCondInst(I.getOpcode(), BOp0, Neg);
3705             }
3706           }
3707           break;
3708         case Instruction::Xor:
3709           // For the xor case, we can xor two constants together, eliminating
3710           // the explicit xor.
3711           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3712             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3713                                   ConstantExpr::getXor(CI, BOC));
3714
3715           // FALLTHROUGH
3716         case Instruction::Sub:
3717           // Replace (([sub|xor] A, B) != 0) with (A != B)
3718           if (CI->isNullValue())
3719             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3720                                    BO->getOperand(1));
3721           break;
3722
3723         case Instruction::Or:
3724           // If bits are being or'd in that are not present in the constant we
3725           // are comparing against, then the comparison could never succeed!
3726           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3727             Constant *NotCI = ConstantExpr::getNot(CI);
3728             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3729               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3730           }
3731           break;
3732
3733         case Instruction::And:
3734           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3735             // If bits are being compared against that are and'd out, then the
3736             // comparison can never succeed!
3737             if (!ConstantExpr::getAnd(CI,
3738                                       ConstantExpr::getNot(BOC))->isNullValue())
3739               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3740
3741             // If we have ((X & C) == C), turn it into ((X & C) != 0).
3742             if (CI == BOC && isOneBitSet(CI))
3743               return new SetCondInst(isSetNE ? Instruction::SetEQ :
3744                                      Instruction::SetNE, Op0,
3745                                      Constant::getNullValue(CI->getType()));
3746
3747             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3748             // to be a signed value as appropriate.
3749             if (isSignBit(BOC)) {
3750               Value *X = BO->getOperand(0);
3751               // If 'X' is not signed, insert a cast now...
3752               if (!BOC->getType()->isSigned()) {
3753                 const Type *DestTy = BOC->getType()->getSignedVersion();
3754                 X = InsertCastBefore(X, DestTy, I);
3755               }
3756               return new SetCondInst(isSetNE ? Instruction::SetLT :
3757                                          Instruction::SetGE, X,
3758                                      Constant::getNullValue(X->getType()));
3759             }
3760
3761             // ((X & ~7) == 0) --> X < 8
3762             if (CI->isNullValue() && isHighOnes(BOC)) {
3763               Value *X = BO->getOperand(0);
3764               Constant *NegX = ConstantExpr::getNeg(BOC);
3765
3766               // If 'X' is signed, insert a cast now.
3767               if (NegX->getType()->isSigned()) {
3768                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3769                 X = InsertCastBefore(X, DestTy, I);
3770                 NegX = ConstantExpr::getCast(NegX, DestTy);
3771               }
3772
3773               return new SetCondInst(isSetNE ? Instruction::SetGE :
3774                                      Instruction::SetLT, X, NegX);
3775             }
3776
3777           }
3778         default: break;
3779         }
3780       }
3781     } else {  // Not a SetEQ/SetNE
3782       // If the LHS is a cast from an integral value of the same size,
3783       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3784         Value *CastOp = Cast->getOperand(0);
3785         const Type *SrcTy = CastOp->getType();
3786         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3787         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3788             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3789           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3790                  "Source and destination signednesses should differ!");
3791           if (Cast->getType()->isSigned()) {
3792             // If this is a signed comparison, check for comparisons in the
3793             // vicinity of zero.
3794             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3795               // X < 0  => x > 127
3796               return BinaryOperator::createSetGT(CastOp,
3797                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3798             else if (I.getOpcode() == Instruction::SetGT &&
3799                      cast<ConstantSInt>(CI)->getValue() == -1)
3800               // X > -1  => x < 128
3801               return BinaryOperator::createSetLT(CastOp,
3802                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3803           } else {
3804             ConstantUInt *CUI = cast<ConstantUInt>(CI);
3805             if (I.getOpcode() == Instruction::SetLT &&
3806                 CUI->getValue() == 1ULL << (SrcTySize-1))
3807               // X < 128 => X > -1
3808               return BinaryOperator::createSetGT(CastOp,
3809                                                  ConstantSInt::get(SrcTy, -1));
3810             else if (I.getOpcode() == Instruction::SetGT &&
3811                      CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3812               // X > 127 => X < 0
3813               return BinaryOperator::createSetLT(CastOp,
3814                                                  Constant::getNullValue(SrcTy));
3815           }
3816         }
3817       }
3818     }
3819   }
3820
3821   // Handle setcc with constant RHS's that can be integer, FP or pointer.
3822   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3823     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3824       switch (LHSI->getOpcode()) {
3825       case Instruction::GetElementPtr:
3826         if (RHSC->isNullValue()) {
3827           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3828           bool isAllZeros = true;
3829           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3830             if (!isa<Constant>(LHSI->getOperand(i)) ||
3831                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3832               isAllZeros = false;
3833               break;
3834             }
3835           if (isAllZeros)
3836             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3837                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
3838         }
3839         break;
3840
3841       case Instruction::PHI:
3842         if (Instruction *NV = FoldOpIntoPhi(I))
3843           return NV;
3844         break;
3845       case Instruction::Select:
3846         // If either operand of the select is a constant, we can fold the
3847         // comparison into the select arms, which will cause one to be
3848         // constant folded and the select turned into a bitwise or.
3849         Value *Op1 = 0, *Op2 = 0;
3850         if (LHSI->hasOneUse()) {
3851           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3852             // Fold the known value into the constant operand.
3853             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3854             // Insert a new SetCC of the other select operand.
3855             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3856                                                       LHSI->getOperand(2), RHSC,
3857                                                       I.getName()), I);
3858           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3859             // Fold the known value into the constant operand.
3860             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3861             // Insert a new SetCC of the other select operand.
3862             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3863                                                       LHSI->getOperand(1), RHSC,
3864                                                       I.getName()), I);
3865           }
3866         }
3867
3868         if (Op1)
3869           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3870         break;
3871       }
3872   }
3873
3874   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3875   if (User *GEP = dyn_castGetElementPtr(Op0))
3876     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3877       return NI;
3878   if (User *GEP = dyn_castGetElementPtr(Op1))
3879     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3880                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
3881       return NI;
3882
3883   // Test to see if the operands of the setcc are casted versions of other
3884   // values.  If the cast can be stripped off both arguments, we do so now.
3885   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3886     Value *CastOp0 = CI->getOperand(0);
3887     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3888         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3889         (I.getOpcode() == Instruction::SetEQ ||
3890          I.getOpcode() == Instruction::SetNE)) {
3891       // We keep moving the cast from the left operand over to the right
3892       // operand, where it can often be eliminated completely.
3893       Op0 = CastOp0;
3894
3895       // If operand #1 is a cast instruction, see if we can eliminate it as
3896       // well.
3897       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3898         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3899                                                                Op0->getType()))
3900           Op1 = CI2->getOperand(0);
3901
3902       // If Op1 is a constant, we can fold the cast into the constant.
3903       if (Op1->getType() != Op0->getType())
3904         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3905           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3906         } else {
3907           // Otherwise, cast the RHS right before the setcc
3908           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3909           InsertNewInstBefore(cast<Instruction>(Op1), I);
3910         }
3911       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3912     }
3913
3914     // Handle the special case of: setcc (cast bool to X), <cst>
3915     // This comes up when you have code like
3916     //   int X = A < B;
3917     //   if (X) ...
3918     // For generality, we handle any zero-extension of any operand comparison
3919     // with a constant or another cast from the same type.
3920     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3921       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3922         return R;
3923   }
3924   
3925   if (I.getOpcode() == Instruction::SetNE ||
3926       I.getOpcode() == Instruction::SetEQ) {
3927     Value *A, *B;
3928     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3929         (A == Op1 || B == Op1)) {
3930       // (A^B) == A  ->  B == 0
3931       Value *OtherVal = A == Op1 ? B : A;
3932       return BinaryOperator::create(I.getOpcode(), OtherVal,
3933                                     Constant::getNullValue(A->getType()));
3934     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3935                (A == Op0 || B == Op0)) {
3936       // A == (A^B)  ->  B == 0
3937       Value *OtherVal = A == Op0 ? B : A;
3938       return BinaryOperator::create(I.getOpcode(), OtherVal,
3939                                     Constant::getNullValue(A->getType()));
3940     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
3941       // (A-B) == A  ->  B == 0
3942       return BinaryOperator::create(I.getOpcode(), B,
3943                                     Constant::getNullValue(B->getType()));
3944     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
3945       // A == (A-B)  ->  B == 0
3946       return BinaryOperator::create(I.getOpcode(), B,
3947                                     Constant::getNullValue(B->getType()));
3948     }
3949   }
3950   return Changed ? &I : 0;
3951 }
3952
3953 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3954 // We only handle extending casts so far.
3955 //
3956 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3957   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3958   const Type *SrcTy = LHSCIOp->getType();
3959   const Type *DestTy = SCI.getOperand(0)->getType();
3960   Value *RHSCIOp;
3961
3962   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3963     return 0;
3964
3965   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
3966   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3967   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
3968
3969   // Is this a sign or zero extension?
3970   bool isSignSrc  = SrcTy->isSigned();
3971   bool isSignDest = DestTy->isSigned();
3972
3973   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3974     // Not an extension from the same type?
3975     RHSCIOp = CI->getOperand(0);
3976     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3977   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3978     // Compute the constant that would happen if we truncated to SrcTy then
3979     // reextended to DestTy.
3980     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3981
3982     if (ConstantExpr::getCast(Res, DestTy) == CI) {
3983       RHSCIOp = Res;
3984     } else {
3985       // If the value cannot be represented in the shorter type, we cannot emit
3986       // a simple comparison.
3987       if (SCI.getOpcode() == Instruction::SetEQ)
3988         return ReplaceInstUsesWith(SCI, ConstantBool::False);
3989       if (SCI.getOpcode() == Instruction::SetNE)
3990         return ReplaceInstUsesWith(SCI, ConstantBool::True);
3991
3992       // Evaluate the comparison for LT.
3993       Value *Result;
3994       if (DestTy->isSigned()) {
3995         // We're performing a signed comparison.
3996         if (isSignSrc) {
3997           // Signed extend and signed comparison.
3998           if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3999             Result = ConstantBool::False;
4000           else
4001             Result = ConstantBool::True;              // X < (large) --> true
4002         } else {
4003           // Unsigned extend and signed comparison.
4004           if (cast<ConstantSInt>(CI)->getValue() < 0)
4005             Result = ConstantBool::False;
4006           else
4007             Result = ConstantBool::True;
4008         }
4009       } else {
4010         // We're performing an unsigned comparison.
4011         if (!isSignSrc) {
4012           // Unsigned extend & compare -> always true.
4013           Result = ConstantBool::True;
4014         } else {
4015           // We're performing an unsigned comp with a sign extended value.
4016           // This is true if the input is >= 0. [aka >s -1]
4017           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4018           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4019                                                   NegOne, SCI.getName()), SCI);
4020         }
4021       }
4022
4023       // Finally, return the value computed.
4024       if (SCI.getOpcode() == Instruction::SetLT) {
4025         return ReplaceInstUsesWith(SCI, Result);
4026       } else {
4027         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4028         if (Constant *CI = dyn_cast<Constant>(Result))
4029           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4030         else
4031           return BinaryOperator::createNot(Result);
4032       }
4033     }
4034   } else {
4035     return 0;
4036   }
4037
4038   // Okay, just insert a compare of the reduced operands now!
4039   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4040 }
4041
4042 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4043   assert(I.getOperand(1)->getType() == Type::UByteTy);
4044   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4045   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4046
4047   // shl X, 0 == X and shr X, 0 == X
4048   // shl 0, X == 0 and shr 0, X == 0
4049   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4050       Op0 == Constant::getNullValue(Op0->getType()))
4051     return ReplaceInstUsesWith(I, Op0);
4052   
4053   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
4054     if (!isLeftShift && I.getType()->isSigned())
4055       return ReplaceInstUsesWith(I, Op0);
4056     else                         // undef << X -> 0   AND  undef >>u X -> 0
4057       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4058   }
4059   if (isa<UndefValue>(Op1)) {
4060     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4061       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4062     else
4063       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
4064   }
4065
4066   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
4067   if (!isLeftShift)
4068     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4069       if (CSI->isAllOnesValue())
4070         return ReplaceInstUsesWith(I, CSI);
4071
4072   // Try to fold constant and into select arguments.
4073   if (isa<Constant>(Op0))
4074     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4075       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4076         return R;
4077
4078   // See if we can turn a signed shr into an unsigned shr.
4079   if (!isLeftShift && I.getType()->isSigned()) {
4080     if (MaskedValueIsZero(Op0,
4081                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4082       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4083       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4084                                             I.getName()), I);
4085       return new CastInst(V, I.getType());
4086     }
4087   }
4088
4089   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4090     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4091       return Res;
4092   return 0;
4093 }
4094
4095 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4096                                                ShiftInst &I) {
4097   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4098   bool isSignedShift = Op0->getType()->isSigned();
4099   bool isUnsignedShift = !isSignedShift;
4100
4101   // See if we can simplify any instructions used by the instruction whose sole 
4102   // purpose is to compute bits we don't care about.
4103   uint64_t KnownZero, KnownOne;
4104   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4105                            KnownZero, KnownOne))
4106     return &I;
4107   
4108   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4109   // of a signed value.
4110   //
4111   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4112   if (Op1->getValue() >= TypeBits) {
4113     if (isUnsignedShift || isLeftShift)
4114       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4115     else {
4116       I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4117       return &I;
4118     }
4119   }
4120   
4121   // ((X*C1) << C2) == (X * (C1 << C2))
4122   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4123     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4124       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4125         return BinaryOperator::createMul(BO->getOperand(0),
4126                                          ConstantExpr::getShl(BOOp, Op1));
4127   
4128   // Try to fold constant and into select arguments.
4129   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4130     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4131       return R;
4132   if (isa<PHINode>(Op0))
4133     if (Instruction *NV = FoldOpIntoPhi(I))
4134       return NV;
4135   
4136   if (Op0->hasOneUse()) {
4137     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4138       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
4139       Value *V1, *V2;
4140       ConstantInt *CC;
4141       switch (Op0BO->getOpcode()) {
4142         default: break;
4143         case Instruction::Add:
4144         case Instruction::And:
4145         case Instruction::Or:
4146         case Instruction::Xor:
4147           // These operators commute.
4148           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
4149           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4150               match(Op0BO->getOperand(1),
4151                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4152             Instruction *YS = new ShiftInst(Instruction::Shl, 
4153                                             Op0BO->getOperand(0), Op1,
4154                                             Op0BO->getName());
4155             InsertNewInstBefore(YS, I); // (Y << C)
4156             Instruction *X = 
4157               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4158                                      Op0BO->getOperand(1)->getName());
4159             InsertNewInstBefore(X, I);  // (X + (Y << C))
4160             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4161             C2 = ConstantExpr::getShl(C2, Op1);
4162             return BinaryOperator::createAnd(X, C2);
4163           }
4164           
4165           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
4166           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4167               match(Op0BO->getOperand(1),
4168                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
4169                           m_ConstantInt(CC))) && V2 == Op1 &&
4170       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4171             Instruction *YS = new ShiftInst(Instruction::Shl, 
4172                                             Op0BO->getOperand(0), Op1,
4173                                             Op0BO->getName());
4174             InsertNewInstBefore(YS, I); // (Y << C)
4175             Instruction *XM =
4176               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4177                                         V1->getName()+".mask");
4178             InsertNewInstBefore(XM, I); // X & (CC << C)
4179             
4180             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4181           }
4182           
4183           // FALL THROUGH.
4184         case Instruction::Sub:
4185           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
4186           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4187               match(Op0BO->getOperand(0),
4188                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4189             Instruction *YS = new ShiftInst(Instruction::Shl, 
4190                                             Op0BO->getOperand(1), Op1,
4191                                             Op0BO->getName());
4192             InsertNewInstBefore(YS, I); // (Y << C)
4193             Instruction *X =
4194               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4195                                      Op0BO->getOperand(0)->getName());
4196             InsertNewInstBefore(X, I);  // (X + (Y << C))
4197             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4198             C2 = ConstantExpr::getShl(C2, Op1);
4199             return BinaryOperator::createAnd(X, C2);
4200           }
4201           
4202           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4203               match(Op0BO->getOperand(0),
4204                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
4205                           m_ConstantInt(CC))) && V2 == Op1 &&
4206               cast<BinaryOperator>(Op0BO->getOperand(0))
4207                   ->getOperand(0)->hasOneUse()) {
4208             Instruction *YS = new ShiftInst(Instruction::Shl, 
4209                                             Op0BO->getOperand(1), Op1,
4210                                             Op0BO->getName());
4211             InsertNewInstBefore(YS, I); // (Y << C)
4212             Instruction *XM =
4213               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4214                                         V1->getName()+".mask");
4215             InsertNewInstBefore(XM, I); // X & (CC << C)
4216             
4217             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4218           }
4219           
4220           break;
4221       }
4222       
4223       
4224       // If the operand is an bitwise operator with a constant RHS, and the
4225       // shift is the only use, we can pull it out of the shift.
4226       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4227         bool isValid = true;     // Valid only for And, Or, Xor
4228         bool highBitSet = false; // Transform if high bit of constant set?
4229         
4230         switch (Op0BO->getOpcode()) {
4231           default: isValid = false; break;   // Do not perform transform!
4232           case Instruction::Add:
4233             isValid = isLeftShift;
4234             break;
4235           case Instruction::Or:
4236           case Instruction::Xor:
4237             highBitSet = false;
4238             break;
4239           case Instruction::And:
4240             highBitSet = true;
4241             break;
4242         }
4243         
4244         // If this is a signed shift right, and the high bit is modified
4245         // by the logical operation, do not perform the transformation.
4246         // The highBitSet boolean indicates the value of the high bit of
4247         // the constant which would cause it to be modified for this
4248         // operation.
4249         //
4250         if (isValid && !isLeftShift && isSignedShift) {
4251           uint64_t Val = Op0C->getRawValue();
4252           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4253         }
4254         
4255         if (isValid) {
4256           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4257           
4258           Instruction *NewShift =
4259             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4260                           Op0BO->getName());
4261           Op0BO->setName("");
4262           InsertNewInstBefore(NewShift, I);
4263           
4264           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4265                                         NewRHS);
4266         }
4267       }
4268     }
4269   }
4270   
4271   // Find out if this is a shift of a shift by a constant.
4272   ShiftInst *ShiftOp = 0;
4273   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4274     ShiftOp = Op0SI;
4275   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4276     // If this is a noop-integer case of a shift instruction, use the shift.
4277     if (CI->getOperand(0)->getType()->isInteger() &&
4278         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4279         CI->getType()->getPrimitiveSizeInBits() &&
4280         isa<ShiftInst>(CI->getOperand(0))) {
4281       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4282     }
4283   }
4284   
4285   if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4286     // Find the operands and properties of the input shift.  Note that the
4287     // signedness of the input shift may differ from the current shift if there
4288     // is a noop cast between the two.
4289     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4290     bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4291     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4292     
4293     ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4294
4295     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4296     unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4297     
4298     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
4299     if (isLeftShift == isShiftOfLeftShift) {
4300       // Do not fold these shifts if the first one is signed and the second one
4301       // is unsigned and this is a right shift.  Further, don't do any folding
4302       // on them.
4303       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4304         return 0;
4305       
4306       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
4307       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4308         Amt = Op0->getType()->getPrimitiveSizeInBits();
4309       
4310       Value *Op = ShiftOp->getOperand(0);
4311       if (isShiftOfSignedShift != isSignedShift)
4312         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4313       return new ShiftInst(I.getOpcode(), Op,
4314                            ConstantUInt::get(Type::UByteTy, Amt));
4315     }
4316     
4317     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
4318     // signed types, we can only support the (A >> c1) << c2 configuration,
4319     // because it can not turn an arbitrary bit of A into a sign bit.
4320     if (isUnsignedShift || isLeftShift) {
4321       // Calculate bitmask for what gets shifted off the edge.
4322       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4323       if (isLeftShift)
4324         C = ConstantExpr::getShl(C, ShiftAmt1C);
4325       else
4326         C = ConstantExpr::getUShr(C, ShiftAmt1C);
4327       
4328       Value *Op = ShiftOp->getOperand(0);
4329       if (isShiftOfSignedShift != isSignedShift)
4330         Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4331       
4332       Instruction *Mask =
4333         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4334       InsertNewInstBefore(Mask, I);
4335       
4336       // Figure out what flavor of shift we should use...
4337       if (ShiftAmt1 == ShiftAmt2) {
4338         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
4339       } else if (ShiftAmt1 < ShiftAmt2) {
4340         return new ShiftInst(I.getOpcode(), Mask,
4341                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4342       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4343         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4344           // Make sure to emit an unsigned shift right, not a signed one.
4345           Mask = InsertNewInstBefore(new CastInst(Mask, 
4346                                         Mask->getType()->getUnsignedVersion(),
4347                                                   Op->getName()), I);
4348           Mask = new ShiftInst(Instruction::Shr, Mask,
4349                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4350           InsertNewInstBefore(Mask, I);
4351           return new CastInst(Mask, I.getType());
4352         } else {
4353           return new ShiftInst(ShiftOp->getOpcode(), Mask,
4354                     ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4355         }
4356       } else {
4357         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
4358         Op = InsertNewInstBefore(new CastInst(Mask,
4359                                               I.getType()->getSignedVersion(),
4360                                               Mask->getName()), I);
4361         Instruction *Shift =
4362           new ShiftInst(ShiftOp->getOpcode(), Op,
4363                         ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4364         InsertNewInstBefore(Shift, I);
4365         
4366         C = ConstantIntegral::getAllOnesValue(Shift->getType());
4367         C = ConstantExpr::getShl(C, Op1);
4368         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4369         InsertNewInstBefore(Mask, I);
4370         return new CastInst(Mask, I.getType());
4371       }
4372     } else {
4373       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
4374       // this case, C1 == C2 and C1 is 8, 16, or 32.
4375       if (ShiftAmt1 == ShiftAmt2) {
4376         const Type *SExtType = 0;
4377         switch (ShiftAmt1) {
4378         case 8 : SExtType = Type::SByteTy; break;
4379         case 16: SExtType = Type::ShortTy; break;
4380         case 32: SExtType = Type::IntTy; break;
4381         }
4382         
4383         if (SExtType) {
4384           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4385                                                SExtType, "sext");
4386           InsertNewInstBefore(NewTrunc, I);
4387           return new CastInst(NewTrunc, I.getType());
4388         }
4389       }
4390     }
4391   }
4392   return 0;
4393 }
4394
4395 enum CastType {
4396   Noop     = 0,
4397   Truncate = 1,
4398   Signext  = 2,
4399   Zeroext  = 3
4400 };
4401
4402 /// getCastType - In the future, we will split the cast instruction into these
4403 /// various types.  Until then, we have to do the analysis here.
4404 static CastType getCastType(const Type *Src, const Type *Dest) {
4405   assert(Src->isIntegral() && Dest->isIntegral() &&
4406          "Only works on integral types!");
4407   unsigned SrcSize = Src->getPrimitiveSizeInBits();
4408   unsigned DestSize = Dest->getPrimitiveSizeInBits();
4409
4410   if (SrcSize == DestSize) return Noop;
4411   if (SrcSize > DestSize)  return Truncate;
4412   if (Src->isSigned()) return Signext;
4413   return Zeroext;
4414 }
4415
4416
4417 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4418 // instruction.
4419 //
4420 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4421                                    const Type *DstTy, TargetData *TD) {
4422
4423   // It is legal to eliminate the instruction if casting A->B->A if the sizes
4424   // are identical and the bits don't get reinterpreted (for example
4425   // int->float->int would not be allowed).
4426   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
4427     return true;
4428
4429   // If we are casting between pointer and integer types, treat pointers as
4430   // integers of the appropriate size for the code below.
4431   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4432   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4433   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
4434
4435   // Allow free casting and conversion of sizes as long as the sign doesn't
4436   // change...
4437   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
4438     CastType FirstCast = getCastType(SrcTy, MidTy);
4439     CastType SecondCast = getCastType(MidTy, DstTy);
4440
4441     // Capture the effect of these two casts.  If the result is a legal cast,
4442     // the CastType is stored here, otherwise a special code is used.
4443     static const unsigned CastResult[] = {
4444       // First cast is noop
4445       0, 1, 2, 3,
4446       // First cast is a truncate
4447       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
4448       // First cast is a sign ext
4449       2, 5, 2, 4,         // signext->zeroext never ok
4450       // First cast is a zero ext
4451       3, 5, 3, 3,
4452     };
4453
4454     unsigned Result = CastResult[FirstCast*4+SecondCast];
4455     switch (Result) {
4456     default: assert(0 && "Illegal table value!");
4457     case 0:
4458     case 1:
4459     case 2:
4460     case 3:
4461       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4462       // truncates, we could eliminate more casts.
4463       return (unsigned)getCastType(SrcTy, DstTy) == Result;
4464     case 4:
4465       return false;  // Not possible to eliminate this here.
4466     case 5:
4467       // Sign or zero extend followed by truncate is always ok if the result
4468       // is a truncate or noop.
4469       CastType ResultCast = getCastType(SrcTy, DstTy);
4470       if (ResultCast == Noop || ResultCast == Truncate)
4471         return true;
4472       // Otherwise we are still growing the value, we are only safe if the
4473       // result will match the sign/zeroextendness of the result.
4474       return ResultCast == FirstCast;
4475     }
4476   }
4477   
4478   // If this is a cast from 'float -> double -> integer', cast from
4479   // 'float -> integer' directly, as the value isn't changed by the 
4480   // float->double conversion.
4481   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4482       DstTy->isIntegral() && 
4483       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4484     return true;
4485   
4486   return false;
4487 }
4488
4489 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4490   if (V->getType() == Ty || isa<Constant>(V)) return false;
4491   if (const CastInst *CI = dyn_cast<CastInst>(V))
4492     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4493                                TD))
4494       return false;
4495   return true;
4496 }
4497
4498 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4499 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
4500 /// casts that are known to not do anything...
4501 ///
4502 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4503                                              Instruction *InsertBefore) {
4504   if (V->getType() == DestTy) return V;
4505   if (Constant *C = dyn_cast<Constant>(V))
4506     return ConstantExpr::getCast(C, DestTy);
4507
4508   CastInst *CI = new CastInst(V, DestTy, V->getName());
4509   InsertNewInstBefore(CI, *InsertBefore);
4510   return CI;
4511 }
4512
4513 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4514 /// expression.  If so, decompose it, returning some value X, such that Val is
4515 /// X*Scale+Offset.
4516 ///
4517 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4518                                         unsigned &Offset) {
4519   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4520   if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4521     Offset = CI->getValue();
4522     Scale  = 1;
4523     return ConstantUInt::get(Type::UIntTy, 0);
4524   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4525     if (I->getNumOperands() == 2) {
4526       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4527         if (I->getOpcode() == Instruction::Shl) {
4528           // This is a value scaled by '1 << the shift amt'.
4529           Scale = 1U << CUI->getValue();
4530           Offset = 0;
4531           return I->getOperand(0);
4532         } else if (I->getOpcode() == Instruction::Mul) {
4533           // This value is scaled by 'CUI'.
4534           Scale = CUI->getValue();
4535           Offset = 0;
4536           return I->getOperand(0);
4537         } else if (I->getOpcode() == Instruction::Add) {
4538           // We have X+C.  Check to see if we really have (X*C2)+C1, where C1 is
4539           // divisible by C2.
4540           unsigned SubScale;
4541           Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4542                                                     Offset);
4543           Offset += CUI->getValue();
4544           if (SubScale > 1 && (Offset % SubScale == 0)) {
4545             Scale = SubScale;
4546             return SubVal;
4547           }
4548         }
4549       }
4550     }
4551   }
4552
4553   // Otherwise, we can't look past this.
4554   Scale = 1;
4555   Offset = 0;
4556   return Val;
4557 }
4558
4559
4560 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4561 /// try to eliminate the cast by moving the type information into the alloc.
4562 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4563                                                    AllocationInst &AI) {
4564   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4565   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
4566   
4567   // Remove any uses of AI that are dead.
4568   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4569   std::vector<Instruction*> DeadUsers;
4570   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4571     Instruction *User = cast<Instruction>(*UI++);
4572     if (isInstructionTriviallyDead(User)) {
4573       while (UI != E && *UI == User)
4574         ++UI; // If this instruction uses AI more than once, don't break UI.
4575       
4576       // Add operands to the worklist.
4577       AddUsesToWorkList(*User);
4578       ++NumDeadInst;
4579       DEBUG(std::cerr << "IC: DCE: " << *User);
4580       
4581       User->eraseFromParent();
4582       removeFromWorkList(User);
4583     }
4584   }
4585   
4586   // Get the type really allocated and the type casted to.
4587   const Type *AllocElTy = AI.getAllocatedType();
4588   const Type *CastElTy = PTy->getElementType();
4589   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4590
4591   unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4592   unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4593   if (CastElTyAlign < AllocElTyAlign) return 0;
4594
4595   // If the allocation has multiple uses, only promote it if we are strictly
4596   // increasing the alignment of the resultant allocation.  If we keep it the
4597   // same, we open the door to infinite loops of various kinds.
4598   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4599
4600   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4601   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4602   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4603
4604   // See if we can satisfy the modulus by pulling a scale out of the array
4605   // size argument.
4606   unsigned ArraySizeScale, ArrayOffset;
4607   Value *NumElements = // See if the array size is a decomposable linear expr.
4608     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4609  
4610   // If we can now satisfy the modulus, by using a non-1 scale, we really can
4611   // do the xform.
4612   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4613       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
4614
4615   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4616   Value *Amt = 0;
4617   if (Scale == 1) {
4618     Amt = NumElements;
4619   } else {
4620     Amt = ConstantUInt::get(Type::UIntTy, Scale);
4621     if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4622       Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4623     else if (Scale != 1) {
4624       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4625       Amt = InsertNewInstBefore(Tmp, AI);
4626     }
4627   }
4628   
4629   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4630     Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4631     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4632     Amt = InsertNewInstBefore(Tmp, AI);
4633   }
4634   
4635   std::string Name = AI.getName(); AI.setName("");
4636   AllocationInst *New;
4637   if (isa<MallocInst>(AI))
4638     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4639   else
4640     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4641   InsertNewInstBefore(New, AI);
4642   
4643   // If the allocation has multiple uses, insert a cast and change all things
4644   // that used it to use the new cast.  This will also hack on CI, but it will
4645   // die soon.
4646   if (!AI.hasOneUse()) {
4647     AddUsesToWorkList(AI);
4648     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4649     InsertNewInstBefore(NewCast, AI);
4650     AI.replaceAllUsesWith(NewCast);
4651   }
4652   return ReplaceInstUsesWith(CI, New);
4653 }
4654
4655
4656 // CastInst simplification
4657 //
4658 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4659   Value *Src = CI.getOperand(0);
4660
4661   // If the user is casting a value to the same type, eliminate this cast
4662   // instruction...
4663   if (CI.getType() == Src->getType())
4664     return ReplaceInstUsesWith(CI, Src);
4665
4666   if (isa<UndefValue>(Src))   // cast undef -> undef
4667     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4668
4669   // If casting the result of another cast instruction, try to eliminate this
4670   // one!
4671   //
4672   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
4673     Value *A = CSrc->getOperand(0);
4674     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4675                                CI.getType(), TD)) {
4676       // This instruction now refers directly to the cast's src operand.  This
4677       // has a good chance of making CSrc dead.
4678       CI.setOperand(0, CSrc->getOperand(0));
4679       return &CI;
4680     }
4681
4682     // If this is an A->B->A cast, and we are dealing with integral types, try
4683     // to convert this into a logical 'and' instruction.
4684     //
4685     if (A->getType()->isInteger() &&
4686         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4687         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
4688         CSrc->getType()->getPrimitiveSizeInBits() <
4689                     CI.getType()->getPrimitiveSizeInBits()&&
4690         A->getType()->getPrimitiveSizeInBits() ==
4691               CI.getType()->getPrimitiveSizeInBits()) {
4692       assert(CSrc->getType() != Type::ULongTy &&
4693              "Cannot have type bigger than ulong!");
4694       uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4695       Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4696                                           AndValue);
4697       AndOp = ConstantExpr::getCast(AndOp, A->getType());
4698       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4699       if (And->getType() != CI.getType()) {
4700         And->setName(CSrc->getName()+".mask");
4701         InsertNewInstBefore(And, CI);
4702         And = new CastInst(And, CI.getType());
4703       }
4704       return And;
4705     }
4706   }
4707   
4708   // If this is a cast to bool, turn it into the appropriate setne instruction.
4709   if (CI.getType() == Type::BoolTy)
4710     return BinaryOperator::createSetNE(CI.getOperand(0),
4711                        Constant::getNullValue(CI.getOperand(0)->getType()));
4712
4713   // See if we can simplify any instructions used by the LHS whose sole 
4714   // purpose is to compute bits we don't care about.
4715   if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4716     uint64_t KnownZero, KnownOne;
4717     if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4718                              KnownZero, KnownOne))
4719       return &CI;
4720   }
4721   
4722   // If casting the result of a getelementptr instruction with no offset, turn
4723   // this into a cast of the original pointer!
4724   //
4725   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4726     bool AllZeroOperands = true;
4727     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4728       if (!isa<Constant>(GEP->getOperand(i)) ||
4729           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4730         AllZeroOperands = false;
4731         break;
4732       }
4733     if (AllZeroOperands) {
4734       CI.setOperand(0, GEP->getOperand(0));
4735       return &CI;
4736     }
4737   }
4738
4739   // If we are casting a malloc or alloca to a pointer to a type of the same
4740   // size, rewrite the allocation instruction to allocate the "right" type.
4741   //
4742   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4743     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4744       return V;
4745
4746   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4747     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4748       return NV;
4749   if (isa<PHINode>(Src))
4750     if (Instruction *NV = FoldOpIntoPhi(CI))
4751       return NV;
4752
4753   // If the source value is an instruction with only this use, we can attempt to
4754   // propagate the cast into the instruction.  Also, only handle integral types
4755   // for now.
4756   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4757     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4758         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
4759       const Type *DestTy = CI.getType();
4760       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4761       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4762
4763       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4764       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4765
4766       switch (SrcI->getOpcode()) {
4767       case Instruction::Add:
4768       case Instruction::Mul:
4769       case Instruction::And:
4770       case Instruction::Or:
4771       case Instruction::Xor:
4772         // If we are discarding information, or just changing the sign, rewrite.
4773         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4774           // Don't insert two casts if they cannot be eliminated.  We allow two
4775           // casts to be inserted if the sizes are the same.  This could only be
4776           // converting signedness, which is a noop.
4777           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4778               !ValueRequiresCast(Op0, DestTy, TD)) {
4779             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4780             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4781             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4782                              ->getOpcode(), Op0c, Op1c);
4783           }
4784         }
4785
4786         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
4787         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4788             Op1 == ConstantBool::True &&
4789             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4790           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4791           return BinaryOperator::createXor(New,
4792                                            ConstantInt::get(CI.getType(), 1));
4793         }
4794         break;
4795       case Instruction::Shl:
4796         // Allow changing the sign of the source operand.  Do not allow changing
4797         // the size of the shift, UNLESS the shift amount is a constant.  We
4798         // mush not change variable sized shifts to a smaller size, because it
4799         // is undefined to shift more bits out than exist in the value.
4800         if (DestBitSize == SrcBitSize ||
4801             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4802           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4803           return new ShiftInst(Instruction::Shl, Op0c, Op1);
4804         }
4805         break;
4806       case Instruction::Shr:
4807         // If this is a signed shr, and if all bits shifted in are about to be
4808         // truncated off, turn it into an unsigned shr to allow greater
4809         // simplifications.
4810         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4811             isa<ConstantInt>(Op1)) {
4812           unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4813           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4814             // Convert to unsigned.
4815             Value *N1 = InsertOperandCastBefore(Op0,
4816                                      Op0->getType()->getUnsignedVersion(), &CI);
4817             // Insert the new shift, which is now unsigned.
4818             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4819                                                    Op1, Src->getName()), CI);
4820             return new CastInst(N1, CI.getType());
4821           }
4822         }
4823         break;
4824
4825       case Instruction::SetEQ:
4826       case Instruction::SetNE:
4827         // We if we are just checking for a seteq of a single bit and casting it
4828         // to an integer.  If so, shift the bit to the appropriate place then
4829         // cast to integer to avoid the comparison.
4830         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4831           uint64_t Op1CV = Op1C->getZExtValue();
4832           // cast (X == 0) to int --> X^1        iff X has only the low bit set.
4833           // cast (X == 0) to int --> (X>>1)^1   iff X has only the 2nd bit set.
4834           // cast (X == 1) to int --> X          iff X has only the low bit set.
4835           // cast (X == 2) to int --> X>>1       iff X has only the 2nd bit set.
4836           // cast (X != 0) to int --> X          iff X has only the low bit set.
4837           // cast (X != 0) to int --> X>>1       iff X has only the 2nd bit set.
4838           // cast (X != 1) to int --> X^1        iff X has only the low bit set.
4839           // cast (X != 2) to int --> (X>>1)^1   iff X has only the 2nd bit set.
4840           if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4841             // If Op1C some other power of two, convert:
4842             uint64_t KnownZero, KnownOne;
4843             uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4844             ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4845             
4846             if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4847               bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4848               if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4849                 // (X&4) == 2 --> false
4850                 // (X&4) != 2 --> true
4851                 Constant *Res = ConstantBool::get(isSetNE);
4852                 Res = ConstantExpr::getCast(Res, CI.getType());
4853                 return ReplaceInstUsesWith(CI, Res);
4854               }
4855               
4856               unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4857               Value *In = Op0;
4858               if (ShiftAmt) {
4859                 // Perform an unsigned shr by shiftamt.  Convert input to
4860                 // unsigned if it is signed.
4861                 if (In->getType()->isSigned())
4862                   In = InsertNewInstBefore(new CastInst(In,
4863                         In->getType()->getUnsignedVersion(), In->getName()),CI);
4864                 // Insert the shift to put the result in the low bit.
4865                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4866                                      ConstantInt::get(Type::UByteTy, ShiftAmt),
4867                                      In->getName()+".lobit"), CI);
4868               }
4869               
4870               if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4871                 Constant *One = ConstantInt::get(In->getType(), 1);
4872                 In = BinaryOperator::createXor(In, One, "tmp");
4873                 InsertNewInstBefore(cast<Instruction>(In), CI);
4874               }
4875               
4876               if (CI.getType() == In->getType())
4877                 return ReplaceInstUsesWith(CI, In);
4878               else
4879                 return new CastInst(In, CI.getType());
4880             }
4881           }
4882         }
4883         break;
4884       }
4885     }
4886       
4887   return 0;
4888 }
4889
4890 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4891 ///   %C = or %A, %B
4892 ///   %D = select %cond, %C, %A
4893 /// into:
4894 ///   %C = select %cond, %B, 0
4895 ///   %D = or %A, %C
4896 ///
4897 /// Assuming that the specified instruction is an operand to the select, return
4898 /// a bitmask indicating which operands of this instruction are foldable if they
4899 /// equal the other incoming value of the select.
4900 ///
4901 static unsigned GetSelectFoldableOperands(Instruction *I) {
4902   switch (I->getOpcode()) {
4903   case Instruction::Add:
4904   case Instruction::Mul:
4905   case Instruction::And:
4906   case Instruction::Or:
4907   case Instruction::Xor:
4908     return 3;              // Can fold through either operand.
4909   case Instruction::Sub:   // Can only fold on the amount subtracted.
4910   case Instruction::Shl:   // Can only fold on the shift amount.
4911   case Instruction::Shr:
4912     return 1;
4913   default:
4914     return 0;              // Cannot fold
4915   }
4916 }
4917
4918 /// GetSelectFoldableConstant - For the same transformation as the previous
4919 /// function, return the identity constant that goes into the select.
4920 static Constant *GetSelectFoldableConstant(Instruction *I) {
4921   switch (I->getOpcode()) {
4922   default: assert(0 && "This cannot happen!"); abort();
4923   case Instruction::Add:
4924   case Instruction::Sub:
4925   case Instruction::Or:
4926   case Instruction::Xor:
4927     return Constant::getNullValue(I->getType());
4928   case Instruction::Shl:
4929   case Instruction::Shr:
4930     return Constant::getNullValue(Type::UByteTy);
4931   case Instruction::And:
4932     return ConstantInt::getAllOnesValue(I->getType());
4933   case Instruction::Mul:
4934     return ConstantInt::get(I->getType(), 1);
4935   }
4936 }
4937
4938 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4939 /// have the same opcode and only one use each.  Try to simplify this.
4940 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4941                                           Instruction *FI) {
4942   if (TI->getNumOperands() == 1) {
4943     // If this is a non-volatile load or a cast from the same type,
4944     // merge.
4945     if (TI->getOpcode() == Instruction::Cast) {
4946       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4947         return 0;
4948     } else {
4949       return 0;  // unknown unary op.
4950     }
4951
4952     // Fold this by inserting a select from the input values.
4953     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4954                                        FI->getOperand(0), SI.getName()+".v");
4955     InsertNewInstBefore(NewSI, SI);
4956     return new CastInst(NewSI, TI->getType());
4957   }
4958
4959   // Only handle binary operators here.
4960   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4961     return 0;
4962
4963   // Figure out if the operations have any operands in common.
4964   Value *MatchOp, *OtherOpT, *OtherOpF;
4965   bool MatchIsOpZero;
4966   if (TI->getOperand(0) == FI->getOperand(0)) {
4967     MatchOp  = TI->getOperand(0);
4968     OtherOpT = TI->getOperand(1);
4969     OtherOpF = FI->getOperand(1);
4970     MatchIsOpZero = true;
4971   } else if (TI->getOperand(1) == FI->getOperand(1)) {
4972     MatchOp  = TI->getOperand(1);
4973     OtherOpT = TI->getOperand(0);
4974     OtherOpF = FI->getOperand(0);
4975     MatchIsOpZero = false;
4976   } else if (!TI->isCommutative()) {
4977     return 0;
4978   } else if (TI->getOperand(0) == FI->getOperand(1)) {
4979     MatchOp  = TI->getOperand(0);
4980     OtherOpT = TI->getOperand(1);
4981     OtherOpF = FI->getOperand(0);
4982     MatchIsOpZero = true;
4983   } else if (TI->getOperand(1) == FI->getOperand(0)) {
4984     MatchOp  = TI->getOperand(1);
4985     OtherOpT = TI->getOperand(0);
4986     OtherOpF = FI->getOperand(1);
4987     MatchIsOpZero = true;
4988   } else {
4989     return 0;
4990   }
4991
4992   // If we reach here, they do have operations in common.
4993   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4994                                      OtherOpF, SI.getName()+".v");
4995   InsertNewInstBefore(NewSI, SI);
4996
4997   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4998     if (MatchIsOpZero)
4999       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5000     else
5001       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5002   } else {
5003     if (MatchIsOpZero)
5004       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5005     else
5006       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5007   }
5008 }
5009
5010 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5011   Value *CondVal = SI.getCondition();
5012   Value *TrueVal = SI.getTrueValue();
5013   Value *FalseVal = SI.getFalseValue();
5014
5015   // select true, X, Y  -> X
5016   // select false, X, Y -> Y
5017   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5018     if (C == ConstantBool::True)
5019       return ReplaceInstUsesWith(SI, TrueVal);
5020     else {
5021       assert(C == ConstantBool::False);
5022       return ReplaceInstUsesWith(SI, FalseVal);
5023     }
5024
5025   // select C, X, X -> X
5026   if (TrueVal == FalseVal)
5027     return ReplaceInstUsesWith(SI, TrueVal);
5028
5029   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
5030     return ReplaceInstUsesWith(SI, FalseVal);
5031   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
5032     return ReplaceInstUsesWith(SI, TrueVal);
5033   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
5034     if (isa<Constant>(TrueVal))
5035       return ReplaceInstUsesWith(SI, TrueVal);
5036     else
5037       return ReplaceInstUsesWith(SI, FalseVal);
5038   }
5039
5040   if (SI.getType() == Type::BoolTy)
5041     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5042       if (C == ConstantBool::True) {
5043         // Change: A = select B, true, C --> A = or B, C
5044         return BinaryOperator::createOr(CondVal, FalseVal);
5045       } else {
5046         // Change: A = select B, false, C --> A = and !B, C
5047         Value *NotCond =
5048           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5049                                              "not."+CondVal->getName()), SI);
5050         return BinaryOperator::createAnd(NotCond, FalseVal);
5051       }
5052     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5053       if (C == ConstantBool::False) {
5054         // Change: A = select B, C, false --> A = and B, C
5055         return BinaryOperator::createAnd(CondVal, TrueVal);
5056       } else {
5057         // Change: A = select B, C, true --> A = or !B, C
5058         Value *NotCond =
5059           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5060                                              "not."+CondVal->getName()), SI);
5061         return BinaryOperator::createOr(NotCond, TrueVal);
5062       }
5063     }
5064
5065   // Selecting between two integer constants?
5066   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5067     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5068       // select C, 1, 0 -> cast C to int
5069       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5070         return new CastInst(CondVal, SI.getType());
5071       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5072         // select C, 0, 1 -> cast !C to int
5073         Value *NotCond =
5074           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5075                                                "not."+CondVal->getName()), SI);
5076         return new CastInst(NotCond, SI.getType());
5077       }
5078
5079       // If one of the constants is zero (we know they can't both be) and we
5080       // have a setcc instruction with zero, and we have an 'and' with the
5081       // non-constant value, eliminate this whole mess.  This corresponds to
5082       // cases like this: ((X & 27) ? 27 : 0)
5083       if (TrueValC->isNullValue() || FalseValC->isNullValue())
5084         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5085           if ((IC->getOpcode() == Instruction::SetEQ ||
5086                IC->getOpcode() == Instruction::SetNE) &&
5087               isa<ConstantInt>(IC->getOperand(1)) &&
5088               cast<Constant>(IC->getOperand(1))->isNullValue())
5089             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5090               if (ICA->getOpcode() == Instruction::And &&
5091                   isa<ConstantInt>(ICA->getOperand(1)) &&
5092                   (ICA->getOperand(1) == TrueValC ||
5093                    ICA->getOperand(1) == FalseValC) &&
5094                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5095                 // Okay, now we know that everything is set up, we just don't
5096                 // know whether we have a setne or seteq and whether the true or
5097                 // false val is the zero.
5098                 bool ShouldNotVal = !TrueValC->isNullValue();
5099                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5100                 Value *V = ICA;
5101                 if (ShouldNotVal)
5102                   V = InsertNewInstBefore(BinaryOperator::create(
5103                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
5104                 return ReplaceInstUsesWith(SI, V);
5105               }
5106     }
5107
5108   // See if we are selecting two values based on a comparison of the two values.
5109   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5110     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5111       // Transform (X == Y) ? X : Y  -> Y
5112       if (SCI->getOpcode() == Instruction::SetEQ)
5113         return ReplaceInstUsesWith(SI, FalseVal);
5114       // Transform (X != Y) ? X : Y  -> X
5115       if (SCI->getOpcode() == Instruction::SetNE)
5116         return ReplaceInstUsesWith(SI, TrueVal);
5117       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5118
5119     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5120       // Transform (X == Y) ? Y : X  -> X
5121       if (SCI->getOpcode() == Instruction::SetEQ)
5122         return ReplaceInstUsesWith(SI, FalseVal);
5123       // Transform (X != Y) ? Y : X  -> Y
5124       if (SCI->getOpcode() == Instruction::SetNE)
5125         return ReplaceInstUsesWith(SI, TrueVal);
5126       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5127     }
5128   }
5129
5130   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5131     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5132       if (TI->hasOneUse() && FI->hasOneUse()) {
5133         bool isInverse = false;
5134         Instruction *AddOp = 0, *SubOp = 0;
5135
5136         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5137         if (TI->getOpcode() == FI->getOpcode())
5138           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5139             return IV;
5140
5141         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
5142         // even legal for FP.
5143         if (TI->getOpcode() == Instruction::Sub &&
5144             FI->getOpcode() == Instruction::Add) {
5145           AddOp = FI; SubOp = TI;
5146         } else if (FI->getOpcode() == Instruction::Sub &&
5147                    TI->getOpcode() == Instruction::Add) {
5148           AddOp = TI; SubOp = FI;
5149         }
5150
5151         if (AddOp) {
5152           Value *OtherAddOp = 0;
5153           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5154             OtherAddOp = AddOp->getOperand(1);
5155           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5156             OtherAddOp = AddOp->getOperand(0);
5157           }
5158
5159           if (OtherAddOp) {
5160             // So at this point we know we have (Y -> OtherAddOp):
5161             //        select C, (add X, Y), (sub X, Z)
5162             Value *NegVal;  // Compute -Z
5163             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5164               NegVal = ConstantExpr::getNeg(C);
5165             } else {
5166               NegVal = InsertNewInstBefore(
5167                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5168             }
5169
5170             Value *NewTrueOp = OtherAddOp;
5171             Value *NewFalseOp = NegVal;
5172             if (AddOp != TI)
5173               std::swap(NewTrueOp, NewFalseOp);
5174             Instruction *NewSel =
5175               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5176
5177             NewSel = InsertNewInstBefore(NewSel, SI);
5178             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5179           }
5180         }
5181       }
5182
5183   // See if we can fold the select into one of our operands.
5184   if (SI.getType()->isInteger()) {
5185     // See the comment above GetSelectFoldableOperands for a description of the
5186     // transformation we are doing here.
5187     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5188       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5189           !isa<Constant>(FalseVal))
5190         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5191           unsigned OpToFold = 0;
5192           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5193             OpToFold = 1;
5194           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5195             OpToFold = 2;
5196           }
5197
5198           if (OpToFold) {
5199             Constant *C = GetSelectFoldableConstant(TVI);
5200             std::string Name = TVI->getName(); TVI->setName("");
5201             Instruction *NewSel =
5202               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5203                              Name);
5204             InsertNewInstBefore(NewSel, SI);
5205             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5206               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5207             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5208               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5209             else {
5210               assert(0 && "Unknown instruction!!");
5211             }
5212           }
5213         }
5214
5215     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5216       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5217           !isa<Constant>(TrueVal))
5218         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5219           unsigned OpToFold = 0;
5220           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5221             OpToFold = 1;
5222           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5223             OpToFold = 2;
5224           }
5225
5226           if (OpToFold) {
5227             Constant *C = GetSelectFoldableConstant(FVI);
5228             std::string Name = FVI->getName(); FVI->setName("");
5229             Instruction *NewSel =
5230               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5231                              Name);
5232             InsertNewInstBefore(NewSel, SI);
5233             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5234               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5235             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5236               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5237             else {
5238               assert(0 && "Unknown instruction!!");
5239             }
5240           }
5241         }
5242   }
5243
5244   if (BinaryOperator::isNot(CondVal)) {
5245     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5246     SI.setOperand(1, FalseVal);
5247     SI.setOperand(2, TrueVal);
5248     return &SI;
5249   }
5250
5251   return 0;
5252 }
5253
5254
5255 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
5256 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
5257 /// the heavy lifting.
5258 ///
5259 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5260   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5261   if (!II) return visitCallSite(&CI);
5262   
5263   // Intrinsics cannot occur in an invoke, so handle them here instead of in
5264   // visitCallSite.
5265   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5266     bool Changed = false;
5267
5268     // memmove/cpy/set of zero bytes is a noop.
5269     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5270       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5271
5272       // FIXME: Increase alignment here.
5273
5274       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5275         if (CI->getRawValue() == 1) {
5276           // Replace the instruction with just byte operations.  We would
5277           // transform other cases to loads/stores, but we don't know if
5278           // alignment is sufficient.
5279         }
5280     }
5281
5282     // If we have a memmove and the source operation is a constant global,
5283     // then the source and dest pointers can't alias, so we can change this
5284     // into a call to memcpy.
5285     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
5286       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5287         if (GVSrc->isConstant()) {
5288           Module *M = CI.getParent()->getParent()->getParent();
5289           const char *Name;
5290           if (CI.getCalledFunction()->getFunctionType()->getParamType(3) == 
5291               Type::UIntTy)
5292             Name = "llvm.memcpy.i32";
5293           else
5294             Name = "llvm.memcpy.i64";
5295           Function *MemCpy = M->getOrInsertFunction(Name,
5296                                      CI.getCalledFunction()->getFunctionType());
5297           CI.setOperand(0, MemCpy);
5298           Changed = true;
5299         }
5300
5301     if (Changed) return II;
5302   } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
5303     // If this stoppoint is at the same source location as the previous
5304     // stoppoint in the chain, it is not needed.
5305     if (DbgStopPointInst *PrevSPI =
5306         dyn_cast<DbgStopPointInst>(SPI->getChain()))
5307       if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5308           SPI->getColNo() == PrevSPI->getColNo()) {
5309         SPI->replaceAllUsesWith(PrevSPI);
5310         return EraseInstFromFunction(CI);
5311       }
5312   } else {
5313     switch (II->getIntrinsicID()) {
5314     default: break;
5315     case Intrinsic::stackrestore: {
5316       // If the save is right next to the restore, remove the restore.  This can
5317       // happen when variable allocas are DCE'd.
5318       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5319         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5320           BasicBlock::iterator BI = SS;
5321           if (&*++BI == II)
5322             return EraseInstFromFunction(CI);
5323         }
5324       }
5325       
5326       // If the stack restore is in a return/unwind block and if there are no
5327       // allocas or calls between the restore and the return, nuke the restore.
5328       TerminatorInst *TI = II->getParent()->getTerminator();
5329       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5330         BasicBlock::iterator BI = II;
5331         bool CannotRemove = false;
5332         for (++BI; &*BI != TI; ++BI) {
5333           if (isa<AllocaInst>(BI) ||
5334               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5335             CannotRemove = true;
5336             break;
5337           }
5338         }
5339         if (!CannotRemove)
5340           return EraseInstFromFunction(CI);
5341       }
5342       break;
5343     }
5344     }
5345   }
5346
5347   return visitCallSite(II);
5348 }
5349
5350 // InvokeInst simplification
5351 //
5352 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5353   return visitCallSite(&II);
5354 }
5355
5356 // visitCallSite - Improvements for call and invoke instructions.
5357 //
5358 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5359   bool Changed = false;
5360
5361   // If the callee is a constexpr cast of a function, attempt to move the cast
5362   // to the arguments of the call/invoke.
5363   if (transformConstExprCastCall(CS)) return 0;
5364
5365   Value *Callee = CS.getCalledValue();
5366
5367   if (Function *CalleeF = dyn_cast<Function>(Callee))
5368     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5369       Instruction *OldCall = CS.getInstruction();
5370       // If the call and callee calling conventions don't match, this call must
5371       // be unreachable, as the call is undefined.
5372       new StoreInst(ConstantBool::True,
5373                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5374       if (!OldCall->use_empty())
5375         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5376       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
5377         return EraseInstFromFunction(*OldCall);
5378       return 0;
5379     }
5380
5381   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5382     // This instruction is not reachable, just remove it.  We insert a store to
5383     // undef so that we know that this code is not reachable, despite the fact
5384     // that we can't modify the CFG here.
5385     new StoreInst(ConstantBool::True,
5386                   UndefValue::get(PointerType::get(Type::BoolTy)),
5387                   CS.getInstruction());
5388
5389     if (!CS.getInstruction()->use_empty())
5390       CS.getInstruction()->
5391         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5392
5393     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5394       // Don't break the CFG, insert a dummy cond branch.
5395       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5396                      ConstantBool::True, II);
5397     }
5398     return EraseInstFromFunction(*CS.getInstruction());
5399   }
5400
5401   const PointerType *PTy = cast<PointerType>(Callee->getType());
5402   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5403   if (FTy->isVarArg()) {
5404     // See if we can optimize any arguments passed through the varargs area of
5405     // the call.
5406     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5407            E = CS.arg_end(); I != E; ++I)
5408       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5409         // If this cast does not effect the value passed through the varargs
5410         // area, we can eliminate the use of the cast.
5411         Value *Op = CI->getOperand(0);
5412         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5413           *I = Op;
5414           Changed = true;
5415         }
5416       }
5417   }
5418
5419   return Changed ? CS.getInstruction() : 0;
5420 }
5421
5422 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5423 // attempt to move the cast to the arguments of the call/invoke.
5424 //
5425 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5426   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5427   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5428   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5429     return false;
5430   Function *Callee = cast<Function>(CE->getOperand(0));
5431   Instruction *Caller = CS.getInstruction();
5432
5433   // Okay, this is a cast from a function to a different type.  Unless doing so
5434   // would cause a type conversion of one of our arguments, change this call to
5435   // be a direct call with arguments casted to the appropriate types.
5436   //
5437   const FunctionType *FT = Callee->getFunctionType();
5438   const Type *OldRetTy = Caller->getType();
5439
5440   // Check to see if we are changing the return type...
5441   if (OldRetTy != FT->getReturnType()) {
5442     if (Callee->isExternal() &&
5443         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5444         !Caller->use_empty())
5445       return false;   // Cannot transform this return value...
5446
5447     // If the callsite is an invoke instruction, and the return value is used by
5448     // a PHI node in a successor, we cannot change the return type of the call
5449     // because there is no place to put the cast instruction (without breaking
5450     // the critical edge).  Bail out in this case.
5451     if (!Caller->use_empty())
5452       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5453         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5454              UI != E; ++UI)
5455           if (PHINode *PN = dyn_cast<PHINode>(*UI))
5456             if (PN->getParent() == II->getNormalDest() ||
5457                 PN->getParent() == II->getUnwindDest())
5458               return false;
5459   }
5460
5461   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5462   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5463
5464   CallSite::arg_iterator AI = CS.arg_begin();
5465   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5466     const Type *ParamTy = FT->getParamType(i);
5467     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5468     if (Callee->isExternal() && !isConvertible) return false;
5469   }
5470
5471   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5472       Callee->isExternal())
5473     return false;   // Do not delete arguments unless we have a function body...
5474
5475   // Okay, we decided that this is a safe thing to do: go ahead and start
5476   // inserting cast instructions as necessary...
5477   std::vector<Value*> Args;
5478   Args.reserve(NumActualArgs);
5479
5480   AI = CS.arg_begin();
5481   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5482     const Type *ParamTy = FT->getParamType(i);
5483     if ((*AI)->getType() == ParamTy) {
5484       Args.push_back(*AI);
5485     } else {
5486       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5487                                          *Caller));
5488     }
5489   }
5490
5491   // If the function takes more arguments than the call was taking, add them
5492   // now...
5493   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5494     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5495
5496   // If we are removing arguments to the function, emit an obnoxious warning...
5497   if (FT->getNumParams() < NumActualArgs)
5498     if (!FT->isVarArg()) {
5499       std::cerr << "WARNING: While resolving call to function '"
5500                 << Callee->getName() << "' arguments were dropped!\n";
5501     } else {
5502       // Add all of the arguments in their promoted form to the arg list...
5503       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5504         const Type *PTy = getPromotedType((*AI)->getType());
5505         if (PTy != (*AI)->getType()) {
5506           // Must promote to pass through va_arg area!
5507           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5508           InsertNewInstBefore(Cast, *Caller);
5509           Args.push_back(Cast);
5510         } else {
5511           Args.push_back(*AI);
5512         }
5513       }
5514     }
5515
5516   if (FT->getReturnType() == Type::VoidTy)
5517     Caller->setName("");   // Void type should not have a name...
5518
5519   Instruction *NC;
5520   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5521     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5522                         Args, Caller->getName(), Caller);
5523     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5524   } else {
5525     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5526     if (cast<CallInst>(Caller)->isTailCall())
5527       cast<CallInst>(NC)->setTailCall();
5528    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5529   }
5530
5531   // Insert a cast of the return type as necessary...
5532   Value *NV = NC;
5533   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5534     if (NV->getType() != Type::VoidTy) {
5535       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5536
5537       // If this is an invoke instruction, we should insert it after the first
5538       // non-phi, instruction in the normal successor block.
5539       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5540         BasicBlock::iterator I = II->getNormalDest()->begin();
5541         while (isa<PHINode>(I)) ++I;
5542         InsertNewInstBefore(NC, *I);
5543       } else {
5544         // Otherwise, it's a call, just insert cast right after the call instr
5545         InsertNewInstBefore(NC, *Caller);
5546       }
5547       AddUsersToWorkList(*Caller);
5548     } else {
5549       NV = UndefValue::get(Caller->getType());
5550     }
5551   }
5552
5553   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5554     Caller->replaceAllUsesWith(NV);
5555   Caller->getParent()->getInstList().erase(Caller);
5556   removeFromWorkList(Caller);
5557   return true;
5558 }
5559
5560
5561 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5562 // operator and they all are only used by the PHI, PHI together their
5563 // inputs, and do the operation once, to the result of the PHI.
5564 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5565   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5566
5567   // Scan the instruction, looking for input operations that can be folded away.
5568   // If all input operands to the phi are the same instruction (e.g. a cast from
5569   // the same type or "+42") we can pull the operation through the PHI, reducing
5570   // code size and simplifying code.
5571   Constant *ConstantOp = 0;
5572   const Type *CastSrcTy = 0;
5573   if (isa<CastInst>(FirstInst)) {
5574     CastSrcTy = FirstInst->getOperand(0)->getType();
5575   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5576     // Can fold binop or shift if the RHS is a constant.
5577     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5578     if (ConstantOp == 0) return 0;
5579   } else {
5580     return 0;  // Cannot fold this operation.
5581   }
5582
5583   // Check to see if all arguments are the same operation.
5584   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5585     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5586     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5587     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5588       return 0;
5589     if (CastSrcTy) {
5590       if (I->getOperand(0)->getType() != CastSrcTy)
5591         return 0;  // Cast operation must match.
5592     } else if (I->getOperand(1) != ConstantOp) {
5593       return 0;
5594     }
5595   }
5596
5597   // Okay, they are all the same operation.  Create a new PHI node of the
5598   // correct type, and PHI together all of the LHS's of the instructions.
5599   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5600                                PN.getName()+".in");
5601   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5602
5603   Value *InVal = FirstInst->getOperand(0);
5604   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5605
5606   // Add all operands to the new PHI.
5607   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5608     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5609     if (NewInVal != InVal)
5610       InVal = 0;
5611     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5612   }
5613
5614   Value *PhiVal;
5615   if (InVal) {
5616     // The new PHI unions all of the same values together.  This is really
5617     // common, so we handle it intelligently here for compile-time speed.
5618     PhiVal = InVal;
5619     delete NewPN;
5620   } else {
5621     InsertNewInstBefore(NewPN, PN);
5622     PhiVal = NewPN;
5623   }
5624
5625   // Insert and return the new operation.
5626   if (isa<CastInst>(FirstInst))
5627     return new CastInst(PhiVal, PN.getType());
5628   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5629     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5630   else
5631     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5632                          PhiVal, ConstantOp);
5633 }
5634
5635 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5636 /// that is dead.
5637 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5638   if (PN->use_empty()) return true;
5639   if (!PN->hasOneUse()) return false;
5640
5641   // Remember this node, and if we find the cycle, return.
5642   if (!PotentiallyDeadPHIs.insert(PN).second)
5643     return true;
5644
5645   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5646     return DeadPHICycle(PU, PotentiallyDeadPHIs);
5647
5648   return false;
5649 }
5650
5651 // PHINode simplification
5652 //
5653 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5654   if (Value *V = PN.hasConstantValue())
5655     return ReplaceInstUsesWith(PN, V);
5656
5657   // If the only user of this instruction is a cast instruction, and all of the
5658   // incoming values are constants, change this PHI to merge together the casted
5659   // constants.
5660   if (PN.hasOneUse())
5661     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5662       if (CI->getType() != PN.getType()) {  // noop casts will be folded
5663         bool AllConstant = true;
5664         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5665           if (!isa<Constant>(PN.getIncomingValue(i))) {
5666             AllConstant = false;
5667             break;
5668           }
5669         if (AllConstant) {
5670           // Make a new PHI with all casted values.
5671           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5672           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5673             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5674             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5675                              PN.getIncomingBlock(i));
5676           }
5677
5678           // Update the cast instruction.
5679           CI->setOperand(0, New);
5680           WorkList.push_back(CI);    // revisit the cast instruction to fold.
5681           WorkList.push_back(New);   // Make sure to revisit the new Phi
5682           return &PN;                // PN is now dead!
5683         }
5684       }
5685
5686   // If all PHI operands are the same operation, pull them through the PHI,
5687   // reducing code size.
5688   if (isa<Instruction>(PN.getIncomingValue(0)) &&
5689       PN.getIncomingValue(0)->hasOneUse())
5690     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5691       return Result;
5692
5693   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
5694   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5695   // PHI)... break the cycle.
5696   if (PN.hasOneUse())
5697     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5698       std::set<PHINode*> PotentiallyDeadPHIs;
5699       PotentiallyDeadPHIs.insert(&PN);
5700       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5701         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5702     }
5703
5704   return 0;
5705 }
5706
5707 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5708                                       Instruction *InsertPoint,
5709                                       InstCombiner *IC) {
5710   unsigned PS = IC->getTargetData().getPointerSize();
5711   const Type *VTy = V->getType();
5712   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5713     // We must insert a cast to ensure we sign-extend.
5714     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5715                                              V->getName()), *InsertPoint);
5716   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5717                                  *InsertPoint);
5718 }
5719
5720
5721 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5722   Value *PtrOp = GEP.getOperand(0);
5723   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
5724   // If so, eliminate the noop.
5725   if (GEP.getNumOperands() == 1)
5726     return ReplaceInstUsesWith(GEP, PtrOp);
5727
5728   if (isa<UndefValue>(GEP.getOperand(0)))
5729     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5730
5731   bool HasZeroPointerIndex = false;
5732   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5733     HasZeroPointerIndex = C->isNullValue();
5734
5735   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5736     return ReplaceInstUsesWith(GEP, PtrOp);
5737
5738   // Eliminate unneeded casts for indices.
5739   bool MadeChange = false;
5740   gep_type_iterator GTI = gep_type_begin(GEP);
5741   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5742     if (isa<SequentialType>(*GTI)) {
5743       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5744         Value *Src = CI->getOperand(0);
5745         const Type *SrcTy = Src->getType();
5746         const Type *DestTy = CI->getType();
5747         if (Src->getType()->isInteger()) {
5748           if (SrcTy->getPrimitiveSizeInBits() ==
5749                        DestTy->getPrimitiveSizeInBits()) {
5750             // We can always eliminate a cast from ulong or long to the other.
5751             // We can always eliminate a cast from uint to int or the other on
5752             // 32-bit pointer platforms.
5753             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5754               MadeChange = true;
5755               GEP.setOperand(i, Src);
5756             }
5757           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5758                      SrcTy->getPrimitiveSize() == 4) {
5759             // We can always eliminate a cast from int to [u]long.  We can
5760             // eliminate a cast from uint to [u]long iff the target is a 32-bit
5761             // pointer target.
5762             if (SrcTy->isSigned() ||
5763                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5764               MadeChange = true;
5765               GEP.setOperand(i, Src);
5766             }
5767           }
5768         }
5769       }
5770       // If we are using a wider index than needed for this platform, shrink it
5771       // to what we need.  If the incoming value needs a cast instruction,
5772       // insert it.  This explicit cast can make subsequent optimizations more
5773       // obvious.
5774       Value *Op = GEP.getOperand(i);
5775       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5776         if (Constant *C = dyn_cast<Constant>(Op)) {
5777           GEP.setOperand(i, ConstantExpr::getCast(C,
5778                                      TD->getIntPtrType()->getSignedVersion()));
5779           MadeChange = true;
5780         } else {
5781           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5782                                                 Op->getName()), GEP);
5783           GEP.setOperand(i, Op);
5784           MadeChange = true;
5785         }
5786
5787       // If this is a constant idx, make sure to canonicalize it to be a signed
5788       // operand, otherwise CSE and other optimizations are pessimized.
5789       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5790         GEP.setOperand(i, ConstantExpr::getCast(CUI,
5791                                           CUI->getType()->getSignedVersion()));
5792         MadeChange = true;
5793       }
5794     }
5795   if (MadeChange) return &GEP;
5796
5797   // Combine Indices - If the source pointer to this getelementptr instruction
5798   // is a getelementptr instruction, combine the indices of the two
5799   // getelementptr instructions into a single instruction.
5800   //
5801   std::vector<Value*> SrcGEPOperands;
5802   if (User *Src = dyn_castGetElementPtr(PtrOp))
5803     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5804
5805   if (!SrcGEPOperands.empty()) {
5806     // Note that if our source is a gep chain itself that we wait for that
5807     // chain to be resolved before we perform this transformation.  This
5808     // avoids us creating a TON of code in some cases.
5809     //
5810     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5811         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5812       return 0;   // Wait until our source is folded to completion.
5813
5814     std::vector<Value *> Indices;
5815
5816     // Find out whether the last index in the source GEP is a sequential idx.
5817     bool EndsWithSequential = false;
5818     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5819            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5820       EndsWithSequential = !isa<StructType>(*I);
5821
5822     // Can we combine the two pointer arithmetics offsets?
5823     if (EndsWithSequential) {
5824       // Replace: gep (gep %P, long B), long A, ...
5825       // With:    T = long A+B; gep %P, T, ...
5826       //
5827       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5828       if (SO1 == Constant::getNullValue(SO1->getType())) {
5829         Sum = GO1;
5830       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5831         Sum = SO1;
5832       } else {
5833         // If they aren't the same type, convert both to an integer of the
5834         // target's pointer size.
5835         if (SO1->getType() != GO1->getType()) {
5836           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5837             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5838           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5839             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5840           } else {
5841             unsigned PS = TD->getPointerSize();
5842             if (SO1->getType()->getPrimitiveSize() == PS) {
5843               // Convert GO1 to SO1's type.
5844               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5845
5846             } else if (GO1->getType()->getPrimitiveSize() == PS) {
5847               // Convert SO1 to GO1's type.
5848               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5849             } else {
5850               const Type *PT = TD->getIntPtrType();
5851               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5852               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5853             }
5854           }
5855         }
5856         if (isa<Constant>(SO1) && isa<Constant>(GO1))
5857           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5858         else {
5859           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5860           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5861         }
5862       }
5863
5864       // Recycle the GEP we already have if possible.
5865       if (SrcGEPOperands.size() == 2) {
5866         GEP.setOperand(0, SrcGEPOperands[0]);
5867         GEP.setOperand(1, Sum);
5868         return &GEP;
5869       } else {
5870         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5871                        SrcGEPOperands.end()-1);
5872         Indices.push_back(Sum);
5873         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5874       }
5875     } else if (isa<Constant>(*GEP.idx_begin()) &&
5876                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5877                SrcGEPOperands.size() != 1) {
5878       // Otherwise we can do the fold if the first index of the GEP is a zero
5879       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5880                      SrcGEPOperands.end());
5881       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5882     }
5883
5884     if (!Indices.empty())
5885       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5886
5887   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5888     // GEP of global variable.  If all of the indices for this GEP are
5889     // constants, we can promote this to a constexpr instead of an instruction.
5890
5891     // Scan for nonconstants...
5892     std::vector<Constant*> Indices;
5893     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5894     for (; I != E && isa<Constant>(*I); ++I)
5895       Indices.push_back(cast<Constant>(*I));
5896
5897     if (I == E) {  // If they are all constants...
5898       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5899
5900       // Replace all uses of the GEP with the new constexpr...
5901       return ReplaceInstUsesWith(GEP, CE);
5902     }
5903   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
5904     if (!isa<PointerType>(X->getType())) {
5905       // Not interesting.  Source pointer must be a cast from pointer.
5906     } else if (HasZeroPointerIndex) {
5907       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5908       // into     : GEP [10 x ubyte]* X, long 0, ...
5909       //
5910       // This occurs when the program declares an array extern like "int X[];"
5911       //
5912       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5913       const PointerType *XTy = cast<PointerType>(X->getType());
5914       if (const ArrayType *XATy =
5915           dyn_cast<ArrayType>(XTy->getElementType()))
5916         if (const ArrayType *CATy =
5917             dyn_cast<ArrayType>(CPTy->getElementType()))
5918           if (CATy->getElementType() == XATy->getElementType()) {
5919             // At this point, we know that the cast source type is a pointer
5920             // to an array of the same type as the destination pointer
5921             // array.  Because the array type is never stepped over (there
5922             // is a leading zero) we can fold the cast into this GEP.
5923             GEP.setOperand(0, X);
5924             return &GEP;
5925           }
5926     } else if (GEP.getNumOperands() == 2) {
5927       // Transform things like:
5928       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5929       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5930       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5931       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5932       if (isa<ArrayType>(SrcElTy) &&
5933           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5934           TD->getTypeSize(ResElTy)) {
5935         Value *V = InsertNewInstBefore(
5936                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5937                                      GEP.getOperand(1), GEP.getName()), GEP);
5938         return new CastInst(V, GEP.getType());
5939       }
5940       
5941       // Transform things like:
5942       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5943       //   (where tmp = 8*tmp2) into:
5944       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5945       
5946       if (isa<ArrayType>(SrcElTy) &&
5947           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5948         uint64_t ArrayEltSize =
5949             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5950         
5951         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
5952         // allow either a mul, shift, or constant here.
5953         Value *NewIdx = 0;
5954         ConstantInt *Scale = 0;
5955         if (ArrayEltSize == 1) {
5956           NewIdx = GEP.getOperand(1);
5957           Scale = ConstantInt::get(NewIdx->getType(), 1);
5958         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5959           NewIdx = ConstantInt::get(CI->getType(), 1);
5960           Scale = CI;
5961         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5962           if (Inst->getOpcode() == Instruction::Shl &&
5963               isa<ConstantInt>(Inst->getOperand(1))) {
5964             unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5965             if (Inst->getType()->isSigned())
5966               Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5967             else
5968               Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5969             NewIdx = Inst->getOperand(0);
5970           } else if (Inst->getOpcode() == Instruction::Mul &&
5971                      isa<ConstantInt>(Inst->getOperand(1))) {
5972             Scale = cast<ConstantInt>(Inst->getOperand(1));
5973             NewIdx = Inst->getOperand(0);
5974           }
5975         }
5976
5977         // If the index will be to exactly the right offset with the scale taken
5978         // out, perform the transformation.
5979         if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5980           if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5981             Scale = ConstantSInt::get(C->getType(),
5982                                       (int64_t)C->getRawValue() / 
5983                                       (int64_t)ArrayEltSize);
5984           else
5985             Scale = ConstantUInt::get(Scale->getType(),
5986                                       Scale->getRawValue() / ArrayEltSize);
5987           if (Scale->getRawValue() != 1) {
5988             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5989             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5990             NewIdx = InsertNewInstBefore(Sc, GEP);
5991           }
5992
5993           // Insert the new GEP instruction.
5994           Instruction *Idx =
5995             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5996                                   NewIdx, GEP.getName());
5997           Idx = InsertNewInstBefore(Idx, GEP);
5998           return new CastInst(Idx, GEP.getType());
5999         }
6000       }
6001     }
6002   }
6003
6004   return 0;
6005 }
6006
6007 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6008   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6009   if (AI.isArrayAllocation())    // Check C != 1
6010     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6011       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6012       AllocationInst *New = 0;
6013
6014       // Create and insert the replacement instruction...
6015       if (isa<MallocInst>(AI))
6016         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6017       else {
6018         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6019         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6020       }
6021
6022       InsertNewInstBefore(New, AI);
6023
6024       // Scan to the end of the allocation instructions, to skip over a block of
6025       // allocas if possible...
6026       //
6027       BasicBlock::iterator It = New;
6028       while (isa<AllocationInst>(*It)) ++It;
6029
6030       // Now that I is pointing to the first non-allocation-inst in the block,
6031       // insert our getelementptr instruction...
6032       //
6033       Value *NullIdx = Constant::getNullValue(Type::IntTy);
6034       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6035                                        New->getName()+".sub", It);
6036
6037       // Now make everything use the getelementptr instead of the original
6038       // allocation.
6039       return ReplaceInstUsesWith(AI, V);
6040     } else if (isa<UndefValue>(AI.getArraySize())) {
6041       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6042     }
6043
6044   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6045   // Note that we only do this for alloca's, because malloc should allocate and
6046   // return a unique pointer, even for a zero byte allocation.
6047   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6048       TD->getTypeSize(AI.getAllocatedType()) == 0)
6049     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6050
6051   return 0;
6052 }
6053
6054 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6055   Value *Op = FI.getOperand(0);
6056
6057   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6058   if (CastInst *CI = dyn_cast<CastInst>(Op))
6059     if (isa<PointerType>(CI->getOperand(0)->getType())) {
6060       FI.setOperand(0, CI->getOperand(0));
6061       return &FI;
6062     }
6063
6064   // free undef -> unreachable.
6065   if (isa<UndefValue>(Op)) {
6066     // Insert a new store to null because we cannot modify the CFG here.
6067     new StoreInst(ConstantBool::True,
6068                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6069     return EraseInstFromFunction(FI);
6070   }
6071
6072   // If we have 'free null' delete the instruction.  This can happen in stl code
6073   // when lots of inlining happens.
6074   if (isa<ConstantPointerNull>(Op))
6075     return EraseInstFromFunction(FI);
6076
6077   return 0;
6078 }
6079
6080
6081 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6082 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6083   User *CI = cast<User>(LI.getOperand(0));
6084   Value *CastOp = CI->getOperand(0);
6085
6086   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6087   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6088     const Type *SrcPTy = SrcTy->getElementType();
6089
6090     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6091       // If the source is an array, the code below will not succeed.  Check to
6092       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
6093       // constants.
6094       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6095         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6096           if (ASrcTy->getNumElements() != 0) {
6097             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6098             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6099             SrcTy = cast<PointerType>(CastOp->getType());
6100             SrcPTy = SrcTy->getElementType();
6101           }
6102
6103       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6104           // Do not allow turning this into a load of an integer, which is then
6105           // casted to a pointer, this pessimizes pointer analysis a lot.
6106           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6107           IC.getTargetData().getTypeSize(SrcPTy) ==
6108                IC.getTargetData().getTypeSize(DestPTy)) {
6109
6110         // Okay, we are casting from one integer or pointer type to another of
6111         // the same size.  Instead of casting the pointer before the load, cast
6112         // the result of the loaded value.
6113         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6114                                                              CI->getName(),
6115                                                          LI.isVolatile()),LI);
6116         // Now cast the result of the load.
6117         return new CastInst(NewLoad, LI.getType());
6118       }
6119     }
6120   }
6121   return 0;
6122 }
6123
6124 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6125 /// from this value cannot trap.  If it is not obviously safe to load from the
6126 /// specified pointer, we do a quick local scan of the basic block containing
6127 /// ScanFrom, to determine if the address is already accessed.
6128 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6129   // If it is an alloca or global variable, it is always safe to load from.
6130   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6131
6132   // Otherwise, be a little bit agressive by scanning the local block where we
6133   // want to check to see if the pointer is already being loaded or stored
6134   // from/to.  If so, the previous load or store would have already trapped,
6135   // so there is no harm doing an extra load (also, CSE will later eliminate
6136   // the load entirely).
6137   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6138
6139   while (BBI != E) {
6140     --BBI;
6141
6142     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6143       if (LI->getOperand(0) == V) return true;
6144     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6145       if (SI->getOperand(1) == V) return true;
6146
6147   }
6148   return false;
6149 }
6150
6151 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6152   Value *Op = LI.getOperand(0);
6153
6154   // load (cast X) --> cast (load X) iff safe
6155   if (CastInst *CI = dyn_cast<CastInst>(Op))
6156     if (Instruction *Res = InstCombineLoadCast(*this, LI))
6157       return Res;
6158
6159   // None of the following transforms are legal for volatile loads.
6160   if (LI.isVolatile()) return 0;
6161   
6162   if (&LI.getParent()->front() != &LI) {
6163     BasicBlock::iterator BBI = &LI; --BBI;
6164     // If the instruction immediately before this is a store to the same
6165     // address, do a simple form of store->load forwarding.
6166     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6167       if (SI->getOperand(1) == LI.getOperand(0))
6168         return ReplaceInstUsesWith(LI, SI->getOperand(0));
6169     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6170       if (LIB->getOperand(0) == LI.getOperand(0))
6171         return ReplaceInstUsesWith(LI, LIB);
6172   }
6173
6174   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6175     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6176         isa<UndefValue>(GEPI->getOperand(0))) {
6177       // Insert a new store to null instruction before the load to indicate
6178       // that this code is not reachable.  We do this instead of inserting
6179       // an unreachable instruction directly because we cannot modify the
6180       // CFG.
6181       new StoreInst(UndefValue::get(LI.getType()),
6182                     Constant::getNullValue(Op->getType()), &LI);
6183       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6184     }
6185
6186   if (Constant *C = dyn_cast<Constant>(Op)) {
6187     // load null/undef -> undef
6188     if ((C->isNullValue() || isa<UndefValue>(C))) {
6189       // Insert a new store to null instruction before the load to indicate that
6190       // this code is not reachable.  We do this instead of inserting an
6191       // unreachable instruction directly because we cannot modify the CFG.
6192       new StoreInst(UndefValue::get(LI.getType()),
6193                     Constant::getNullValue(Op->getType()), &LI);
6194       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6195     }
6196
6197     // Instcombine load (constant global) into the value loaded.
6198     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6199       if (GV->isConstant() && !GV->isExternal())
6200         return ReplaceInstUsesWith(LI, GV->getInitializer());
6201
6202     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6203     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6204       if (CE->getOpcode() == Instruction::GetElementPtr) {
6205         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6206           if (GV->isConstant() && !GV->isExternal())
6207             if (Constant *V = 
6208                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6209               return ReplaceInstUsesWith(LI, V);
6210         if (CE->getOperand(0)->isNullValue()) {
6211           // Insert a new store to null instruction before the load to indicate
6212           // that this code is not reachable.  We do this instead of inserting
6213           // an unreachable instruction directly because we cannot modify the
6214           // CFG.
6215           new StoreInst(UndefValue::get(LI.getType()),
6216                         Constant::getNullValue(Op->getType()), &LI);
6217           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6218         }
6219
6220       } else if (CE->getOpcode() == Instruction::Cast) {
6221         if (Instruction *Res = InstCombineLoadCast(*this, LI))
6222           return Res;
6223       }
6224   }
6225
6226   if (Op->hasOneUse()) {
6227     // Change select and PHI nodes to select values instead of addresses: this
6228     // helps alias analysis out a lot, allows many others simplifications, and
6229     // exposes redundancy in the code.
6230     //
6231     // Note that we cannot do the transformation unless we know that the
6232     // introduced loads cannot trap!  Something like this is valid as long as
6233     // the condition is always false: load (select bool %C, int* null, int* %G),
6234     // but it would not be valid if we transformed it to load from null
6235     // unconditionally.
6236     //
6237     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6238       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
6239       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6240           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6241         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6242                                      SI->getOperand(1)->getName()+".val"), LI);
6243         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6244                                      SI->getOperand(2)->getName()+".val"), LI);
6245         return new SelectInst(SI->getCondition(), V1, V2);
6246       }
6247
6248       // load (select (cond, null, P)) -> load P
6249       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6250         if (C->isNullValue()) {
6251           LI.setOperand(0, SI->getOperand(2));
6252           return &LI;
6253         }
6254
6255       // load (select (cond, P, null)) -> load P
6256       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6257         if (C->isNullValue()) {
6258           LI.setOperand(0, SI->getOperand(1));
6259           return &LI;
6260         }
6261
6262     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6263       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
6264       bool Safe = PN->getParent() == LI.getParent();
6265
6266       // Scan all of the instructions between the PHI and the load to make
6267       // sure there are no instructions that might possibly alter the value
6268       // loaded from the PHI.
6269       if (Safe) {
6270         BasicBlock::iterator I = &LI;
6271         for (--I; !isa<PHINode>(I); --I)
6272           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6273             Safe = false;
6274             break;
6275           }
6276       }
6277
6278       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6279         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6280                                     PN->getIncomingBlock(i)->getTerminator()))
6281           Safe = false;
6282
6283       if (Safe) {
6284         // Create the PHI.
6285         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6286         InsertNewInstBefore(NewPN, *PN);
6287         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
6288
6289         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6290           BasicBlock *BB = PN->getIncomingBlock(i);
6291           Value *&TheLoad = LoadMap[BB];
6292           if (TheLoad == 0) {
6293             Value *InVal = PN->getIncomingValue(i);
6294             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6295                                                        InVal->getName()+".val"),
6296                                           *BB->getTerminator());
6297           }
6298           NewPN->addIncoming(TheLoad, BB);
6299         }
6300         return ReplaceInstUsesWith(LI, NewPN);
6301       }
6302     }
6303   }
6304   return 0;
6305 }
6306
6307 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6308 /// when possible.
6309 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6310   User *CI = cast<User>(SI.getOperand(1));
6311   Value *CastOp = CI->getOperand(0);
6312
6313   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6314   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6315     const Type *SrcPTy = SrcTy->getElementType();
6316
6317     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6318       // If the source is an array, the code below will not succeed.  Check to
6319       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
6320       // constants.
6321       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6322         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6323           if (ASrcTy->getNumElements() != 0) {
6324             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6325             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6326             SrcTy = cast<PointerType>(CastOp->getType());
6327             SrcPTy = SrcTy->getElementType();
6328           }
6329
6330       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6331           IC.getTargetData().getTypeSize(SrcPTy) ==
6332                IC.getTargetData().getTypeSize(DestPTy)) {
6333
6334         // Okay, we are casting from one integer or pointer type to another of
6335         // the same size.  Instead of casting the pointer before the store, cast
6336         // the value to be stored.
6337         Value *NewCast;
6338         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6339           NewCast = ConstantExpr::getCast(C, SrcPTy);
6340         else
6341           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6342                                                         SrcPTy,
6343                                          SI.getOperand(0)->getName()+".c"), SI);
6344
6345         return new StoreInst(NewCast, CastOp);
6346       }
6347     }
6348   }
6349   return 0;
6350 }
6351
6352 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6353   Value *Val = SI.getOperand(0);
6354   Value *Ptr = SI.getOperand(1);
6355
6356   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
6357     EraseInstFromFunction(SI);
6358     ++NumCombined;
6359     return 0;
6360   }
6361
6362   // Do really simple DSE, to catch cases where there are several consequtive
6363   // stores to the same location, separated by a few arithmetic operations. This
6364   // situation often occurs with bitfield accesses.
6365   BasicBlock::iterator BBI = &SI;
6366   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6367        --ScanInsts) {
6368     --BBI;
6369     
6370     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6371       // Prev store isn't volatile, and stores to the same location?
6372       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6373         ++NumDeadStore;
6374         ++BBI;
6375         EraseInstFromFunction(*PrevSI);
6376         continue;
6377       }
6378       break;
6379     }
6380     
6381     // Don't skip over loads or things that can modify memory.
6382     if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6383       break;
6384   }
6385   
6386   
6387   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
6388
6389   // store X, null    -> turns into 'unreachable' in SimplifyCFG
6390   if (isa<ConstantPointerNull>(Ptr)) {
6391     if (!isa<UndefValue>(Val)) {
6392       SI.setOperand(0, UndefValue::get(Val->getType()));
6393       if (Instruction *U = dyn_cast<Instruction>(Val))
6394         WorkList.push_back(U);  // Dropped a use.
6395       ++NumCombined;
6396     }
6397     return 0;  // Do not modify these!
6398   }
6399
6400   // store undef, Ptr -> noop
6401   if (isa<UndefValue>(Val)) {
6402     EraseInstFromFunction(SI);
6403     ++NumCombined;
6404     return 0;
6405   }
6406
6407   // If the pointer destination is a cast, see if we can fold the cast into the
6408   // source instead.
6409   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6410     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6411       return Res;
6412   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6413     if (CE->getOpcode() == Instruction::Cast)
6414       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6415         return Res;
6416
6417   
6418   // If this store is the last instruction in the basic block, and if the block
6419   // ends with an unconditional branch, try to move it to the successor block.
6420   BBI = &SI; ++BBI;
6421   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6422     if (BI->isUnconditional()) {
6423       // Check to see if the successor block has exactly two incoming edges.  If
6424       // so, see if the other predecessor contains a store to the same location.
6425       // if so, insert a PHI node (if needed) and move the stores down.
6426       BasicBlock *Dest = BI->getSuccessor(0);
6427
6428       pred_iterator PI = pred_begin(Dest);
6429       BasicBlock *Other = 0;
6430       if (*PI != BI->getParent())
6431         Other = *PI;
6432       ++PI;
6433       if (PI != pred_end(Dest)) {
6434         if (*PI != BI->getParent())
6435           if (Other)
6436             Other = 0;
6437           else
6438             Other = *PI;
6439         if (++PI != pred_end(Dest))
6440           Other = 0;
6441       }
6442       if (Other) {  // If only one other pred...
6443         BBI = Other->getTerminator();
6444         // Make sure this other block ends in an unconditional branch and that
6445         // there is an instruction before the branch.
6446         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6447             BBI != Other->begin()) {
6448           --BBI;
6449           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6450           
6451           // If this instruction is a store to the same location.
6452           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6453             // Okay, we know we can perform this transformation.  Insert a PHI
6454             // node now if we need it.
6455             Value *MergedVal = OtherStore->getOperand(0);
6456             if (MergedVal != SI.getOperand(0)) {
6457               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6458               PN->reserveOperandSpace(2);
6459               PN->addIncoming(SI.getOperand(0), SI.getParent());
6460               PN->addIncoming(OtherStore->getOperand(0), Other);
6461               MergedVal = InsertNewInstBefore(PN, Dest->front());
6462             }
6463             
6464             // Advance to a place where it is safe to insert the new store and
6465             // insert it.
6466             BBI = Dest->begin();
6467             while (isa<PHINode>(BBI)) ++BBI;
6468             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6469                                               OtherStore->isVolatile()), *BBI);
6470
6471             // Nuke the old stores.
6472             EraseInstFromFunction(SI);
6473             EraseInstFromFunction(*OtherStore);
6474             ++NumCombined;
6475             return 0;
6476           }
6477         }
6478       }
6479     }
6480   
6481   return 0;
6482 }
6483
6484
6485 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6486   // Change br (not X), label True, label False to: br X, label False, True
6487   Value *X = 0;
6488   BasicBlock *TrueDest;
6489   BasicBlock *FalseDest;
6490   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6491       !isa<Constant>(X)) {
6492     // Swap Destinations and condition...
6493     BI.setCondition(X);
6494     BI.setSuccessor(0, FalseDest);
6495     BI.setSuccessor(1, TrueDest);
6496     return &BI;
6497   }
6498
6499   // Cannonicalize setne -> seteq
6500   Instruction::BinaryOps Op; Value *Y;
6501   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6502                       TrueDest, FalseDest)))
6503     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6504          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6505       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6506       std::string Name = I->getName(); I->setName("");
6507       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6508       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
6509       // Swap Destinations and condition...
6510       BI.setCondition(NewSCC);
6511       BI.setSuccessor(0, FalseDest);
6512       BI.setSuccessor(1, TrueDest);
6513       removeFromWorkList(I);
6514       I->getParent()->getInstList().erase(I);
6515       WorkList.push_back(cast<Instruction>(NewSCC));
6516       return &BI;
6517     }
6518
6519   return 0;
6520 }
6521
6522 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6523   Value *Cond = SI.getCondition();
6524   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6525     if (I->getOpcode() == Instruction::Add)
6526       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6527         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6528         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6529           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6530                                                 AddRHS));
6531         SI.setOperand(0, I->getOperand(0));
6532         WorkList.push_back(I);
6533         return &SI;
6534       }
6535   }
6536   return 0;
6537 }
6538
6539 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6540   if (ConstantAggregateZero *C = 
6541       dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6542     // If packed val is constant 0, replace extract with scalar 0
6543     const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6544     EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6545     return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6546   }
6547   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6548     // If packed val is constant with uniform operands, replace EI
6549     // with that operand
6550     Constant *op0 = cast<Constant>(C->getOperand(0));
6551     for (unsigned i = 1; i < C->getNumOperands(); ++i)
6552       if (C->getOperand(i) != op0) return 0;
6553     return ReplaceInstUsesWith(EI, op0);
6554   }
6555   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6556     if (I->hasOneUse()) {
6557       // Push extractelement into predecessor operation if legal and
6558       // profitable to do so
6559       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6560         if (!isa<Constant>(BO->getOperand(0)) &&
6561             !isa<Constant>(BO->getOperand(1)))
6562           return 0;
6563         ExtractElementInst *newEI0 = 
6564           new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6565                                  EI.getName());
6566         ExtractElementInst *newEI1 =
6567           new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6568                                  EI.getName());
6569         InsertNewInstBefore(newEI0, EI);
6570         InsertNewInstBefore(newEI1, EI);
6571         return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6572       }
6573       switch(I->getOpcode()) {
6574       case Instruction::Load: {
6575         Value *Ptr = InsertCastBefore(I->getOperand(0),
6576                                       PointerType::get(EI.getType()), EI);
6577         GetElementPtrInst *GEP = 
6578           new GetElementPtrInst(Ptr, EI.getOperand(1),
6579                                 I->getName() + ".gep");
6580         InsertNewInstBefore(GEP, EI);
6581         return new LoadInst(GEP);
6582       }
6583       default:
6584         return 0;
6585       }
6586     }
6587   return 0;
6588 }
6589
6590
6591 void InstCombiner::removeFromWorkList(Instruction *I) {
6592   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6593                  WorkList.end());
6594 }
6595
6596
6597 /// TryToSinkInstruction - Try to move the specified instruction from its
6598 /// current block into the beginning of DestBlock, which can only happen if it's
6599 /// safe to move the instruction past all of the instructions between it and the
6600 /// end of its block.
6601 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6602   assert(I->hasOneUse() && "Invariants didn't hold!");
6603
6604   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6605   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6606
6607   // Do not sink alloca instructions out of the entry block.
6608   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6609     return false;
6610
6611   // We can only sink load instructions if there is nothing between the load and
6612   // the end of block that could change the value.
6613   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6614     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6615          Scan != E; ++Scan)
6616       if (Scan->mayWriteToMemory())
6617         return false;
6618   }
6619
6620   BasicBlock::iterator InsertPos = DestBlock->begin();
6621   while (isa<PHINode>(InsertPos)) ++InsertPos;
6622
6623   I->moveBefore(InsertPos);
6624   ++NumSunkInst;
6625   return true;
6626 }
6627
6628 bool InstCombiner::runOnFunction(Function &F) {
6629   bool Changed = false;
6630   TD = &getAnalysis<TargetData>();
6631
6632   {
6633     // Populate the worklist with the reachable instructions.
6634     std::set<BasicBlock*> Visited;
6635     for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6636            E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6637       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6638         WorkList.push_back(I);
6639
6640     // Do a quick scan over the function.  If we find any blocks that are
6641     // unreachable, remove any instructions inside of them.  This prevents
6642     // the instcombine code from having to deal with some bad special cases.
6643     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6644       if (!Visited.count(BB)) {
6645         Instruction *Term = BB->getTerminator();
6646         while (Term != BB->begin()) {   // Remove instrs bottom-up
6647           BasicBlock::iterator I = Term; --I;
6648
6649           DEBUG(std::cerr << "IC: DCE: " << *I);
6650           ++NumDeadInst;
6651
6652           if (!I->use_empty())
6653             I->replaceAllUsesWith(UndefValue::get(I->getType()));
6654           I->eraseFromParent();
6655         }
6656       }
6657   }
6658
6659   while (!WorkList.empty()) {
6660     Instruction *I = WorkList.back();  // Get an instruction from the worklist
6661     WorkList.pop_back();
6662
6663     // Check to see if we can DCE or ConstantPropagate the instruction...
6664     // Check to see if we can DIE the instruction...
6665     if (isInstructionTriviallyDead(I)) {
6666       // Add operands to the worklist...
6667       if (I->getNumOperands() < 4)
6668         AddUsesToWorkList(*I);
6669       ++NumDeadInst;
6670
6671       DEBUG(std::cerr << "IC: DCE: " << *I);
6672
6673       I->eraseFromParent();
6674       removeFromWorkList(I);
6675       continue;
6676     }
6677
6678     // Instruction isn't dead, see if we can constant propagate it...
6679     if (Constant *C = ConstantFoldInstruction(I)) {
6680       Value* Ptr = I->getOperand(0);
6681       if (isa<GetElementPtrInst>(I) &&
6682           cast<Constant>(Ptr)->isNullValue() &&
6683           !isa<ConstantPointerNull>(C) &&
6684           cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6685         // If this is a constant expr gep that is effectively computing an
6686         // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6687         bool isFoldableGEP = true;
6688         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6689           if (!isa<ConstantInt>(I->getOperand(i)))
6690             isFoldableGEP = false;
6691         if (isFoldableGEP) {
6692           uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6693                              std::vector<Value*>(I->op_begin()+1, I->op_end()));
6694           C = ConstantUInt::get(Type::ULongTy, Offset);
6695           C = ConstantExpr::getCast(C, TD->getIntPtrType());
6696           C = ConstantExpr::getCast(C, I->getType());
6697         }
6698       }
6699
6700       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6701
6702       // Add operands to the worklist...
6703       AddUsesToWorkList(*I);
6704       ReplaceInstUsesWith(*I, C);
6705
6706       ++NumConstProp;
6707       I->getParent()->getInstList().erase(I);
6708       removeFromWorkList(I);
6709       continue;
6710     }
6711
6712     // See if we can trivially sink this instruction to a successor basic block.
6713     if (I->hasOneUse()) {
6714       BasicBlock *BB = I->getParent();
6715       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6716       if (UserParent != BB) {
6717         bool UserIsSuccessor = false;
6718         // See if the user is one of our successors.
6719         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6720           if (*SI == UserParent) {
6721             UserIsSuccessor = true;
6722             break;
6723           }
6724
6725         // If the user is one of our immediate successors, and if that successor
6726         // only has us as a predecessors (we'd have to split the critical edge
6727         // otherwise), we can keep going.
6728         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6729             next(pred_begin(UserParent)) == pred_end(UserParent))
6730           // Okay, the CFG is simple enough, try to sink this instruction.
6731           Changed |= TryToSinkInstruction(I, UserParent);
6732       }
6733     }
6734
6735     // Now that we have an instruction, try combining it to simplify it...
6736     if (Instruction *Result = visit(*I)) {
6737       ++NumCombined;
6738       // Should we replace the old instruction with a new one?
6739       if (Result != I) {
6740         DEBUG(std::cerr << "IC: Old = " << *I
6741                         << "    New = " << *Result);
6742
6743         // Everything uses the new instruction now.
6744         I->replaceAllUsesWith(Result);
6745
6746         // Push the new instruction and any users onto the worklist.
6747         WorkList.push_back(Result);
6748         AddUsersToWorkList(*Result);
6749
6750         // Move the name to the new instruction first...
6751         std::string OldName = I->getName(); I->setName("");
6752         Result->setName(OldName);
6753
6754         // Insert the new instruction into the basic block...
6755         BasicBlock *InstParent = I->getParent();
6756         BasicBlock::iterator InsertPos = I;
6757
6758         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
6759           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6760             ++InsertPos;
6761
6762         InstParent->getInstList().insert(InsertPos, Result);
6763
6764         // Make sure that we reprocess all operands now that we reduced their
6765         // use counts.
6766         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6767           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6768             WorkList.push_back(OpI);
6769
6770         // Instructions can end up on the worklist more than once.  Make sure
6771         // we do not process an instruction that has been deleted.
6772         removeFromWorkList(I);
6773
6774         // Erase the old instruction.
6775         InstParent->getInstList().erase(I);
6776       } else {
6777         DEBUG(std::cerr << "IC: MOD = " << *I);
6778
6779         // If the instruction was modified, it's possible that it is now dead.
6780         // if so, remove it.
6781         if (isInstructionTriviallyDead(I)) {
6782           // Make sure we process all operands now that we are reducing their
6783           // use counts.
6784           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6785             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6786               WorkList.push_back(OpI);
6787
6788           // Instructions may end up in the worklist more than once.  Erase all
6789           // occurrences of this instruction.
6790           removeFromWorkList(I);
6791           I->eraseFromParent();
6792         } else {
6793           WorkList.push_back(Result);
6794           AddUsersToWorkList(*Result);
6795         }
6796       }
6797       Changed = true;
6798     }
6799   }
6800
6801   return Changed;
6802 }
6803
6804 FunctionPass *llvm::createInstructionCombiningPass() {
6805   return new InstCombiner();
6806 }
6807