Merge two almost-identical pieces of code.
[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 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1816   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1817   if (I.getType()->isSigned()) {
1818     if (Value *RHSNeg = dyn_castNegVal(Op1))
1819       if (!isa<ConstantSInt>(RHSNeg) ||
1820           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1821         // X % -Y -> X % Y
1822         AddUsesToWorkList(I);
1823         I.setOperand(1, RHSNeg);
1824         return &I;
1825       }
1826    
1827     // If the top bits of both operands are zero (i.e. we can prove they are
1828     // unsigned inputs), turn this into a urem.
1829     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1830     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1831       const Type *NTy = Op0->getType()->getUnsignedVersion();
1832       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1833       InsertNewInstBefore(LHS, I);
1834       Value *RHS;
1835       if (Constant *R = dyn_cast<Constant>(Op1))
1836         RHS = ConstantExpr::getCast(R, NTy);
1837       else
1838         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1839       Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1840       InsertNewInstBefore(Rem, I);
1841       return new CastInst(Rem, I.getType());
1842     }
1843   }
1844
1845   if (isa<UndefValue>(Op0))              // undef % X -> 0
1846     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1847   if (isa<UndefValue>(Op1))
1848     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
1849
1850   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1851     if (RHS->equalsInt(1))  // X % 1 == 0
1852       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1853
1854     // Check to see if this is an unsigned remainder with an exact power of 2,
1855     // if so, convert to a bitwise and.
1856     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1857       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
1858         if (!(Val & (Val-1)))              // Power of 2
1859           return BinaryOperator::createAnd(Op0,
1860                                          ConstantUInt::get(I.getType(), Val-1));
1861
1862     if (!RHS->isNullValue()) {
1863       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1864         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1865           return R;
1866       if (isa<PHINode>(Op0))
1867         if (Instruction *NV = FoldOpIntoPhi(I))
1868           return NV;
1869     }
1870   }
1871
1872   // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1873   // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1874   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1875     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1876       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1877         if (STO->getValue() == 0) { // Couldn't be this argument.
1878           I.setOperand(1, SFO);
1879           return &I;
1880         } else if (SFO->getValue() == 0) {
1881           I.setOperand(1, STO);
1882           return &I;
1883         }
1884
1885         if (!(STO->getValue() & (STO->getValue()-1)) &&
1886             !(SFO->getValue() & (SFO->getValue()-1))) {
1887           Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1888                                          SubOne(STO), SI->getName()+".t"), I);
1889           Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1890                                          SubOne(SFO), SI->getName()+".f"), I);
1891           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1892         }
1893       }
1894
1895   // 0 % X == 0, we don't need to preserve faults!
1896   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1897     if (LHS->equalsInt(0))
1898       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1899
1900   
1901   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1902     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1903     if (I.getType()->isUnsigned() && 
1904         RHSI->getOpcode() == Instruction::Shl &&
1905         isa<ConstantUInt>(RHSI->getOperand(0))) {
1906       unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1907       if (isPowerOf2_64(C1)) {
1908         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1909         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1910                                                                    "tmp"), I);
1911         return BinaryOperator::createAnd(Op0, Add);
1912       }
1913     }
1914   }
1915   
1916   return 0;
1917 }
1918
1919 // isMaxValueMinusOne - return true if this is Max-1
1920 static bool isMaxValueMinusOne(const ConstantInt *C) {
1921   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1922     return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1923
1924   const ConstantSInt *CS = cast<ConstantSInt>(C);
1925
1926   // Calculate 0111111111..11111
1927   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1928   int64_t Val = INT64_MAX;             // All ones
1929   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1930   return CS->getValue() == Val-1;
1931 }
1932
1933 // isMinValuePlusOne - return true if this is Min+1
1934 static bool isMinValuePlusOne(const ConstantInt *C) {
1935   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1936     return CU->getValue() == 1;
1937
1938   const ConstantSInt *CS = cast<ConstantSInt>(C);
1939
1940   // Calculate 1111111111000000000000
1941   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1942   int64_t Val = -1;                    // All ones
1943   Val <<= TypeBits-1;                  // Shift over to the right spot
1944   return CS->getValue() == Val+1;
1945 }
1946
1947 // isOneBitSet - Return true if there is exactly one bit set in the specified
1948 // constant.
1949 static bool isOneBitSet(const ConstantInt *CI) {
1950   uint64_t V = CI->getRawValue();
1951   return V && (V & (V-1)) == 0;
1952 }
1953
1954 #if 0   // Currently unused
1955 // isLowOnes - Return true if the constant is of the form 0+1+.
1956 static bool isLowOnes(const ConstantInt *CI) {
1957   uint64_t V = CI->getRawValue();
1958
1959   // There won't be bits set in parts that the type doesn't contain.
1960   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1961
1962   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1963   return U && V && (U & V) == 0;
1964 }
1965 #endif
1966
1967 // isHighOnes - Return true if the constant is of the form 1+0+.
1968 // This is the same as lowones(~X).
1969 static bool isHighOnes(const ConstantInt *CI) {
1970   uint64_t V = ~CI->getRawValue();
1971   if (~V == 0) return false;  // 0's does not match "1+"
1972
1973   // There won't be bits set in parts that the type doesn't contain.
1974   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1975
1976   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1977   return U && V && (U & V) == 0;
1978 }
1979
1980
1981 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1982 /// are carefully arranged to allow folding of expressions such as:
1983 ///
1984 ///      (A < B) | (A > B) --> (A != B)
1985 ///
1986 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1987 /// represents that the comparison is true if A == B, and bit value '1' is true
1988 /// if A < B.
1989 ///
1990 static unsigned getSetCondCode(const SetCondInst *SCI) {
1991   switch (SCI->getOpcode()) {
1992     // False -> 0
1993   case Instruction::SetGT: return 1;
1994   case Instruction::SetEQ: return 2;
1995   case Instruction::SetGE: return 3;
1996   case Instruction::SetLT: return 4;
1997   case Instruction::SetNE: return 5;
1998   case Instruction::SetLE: return 6;
1999     // True -> 7
2000   default:
2001     assert(0 && "Invalid SetCC opcode!");
2002     return 0;
2003   }
2004 }
2005
2006 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2007 /// opcode and two operands into either a constant true or false, or a brand new
2008 /// SetCC instruction.
2009 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2010   switch (Opcode) {
2011   case 0: return ConstantBool::False;
2012   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2013   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2014   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2015   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2016   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2017   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2018   case 7: return ConstantBool::True;
2019   default: assert(0 && "Illegal SetCCCode!"); return 0;
2020   }
2021 }
2022
2023 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2024 struct FoldSetCCLogical {
2025   InstCombiner &IC;
2026   Value *LHS, *RHS;
2027   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2028     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2029   bool shouldApply(Value *V) const {
2030     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2031       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2032               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2033     return false;
2034   }
2035   Instruction *apply(BinaryOperator &Log) const {
2036     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2037     if (SCI->getOperand(0) != LHS) {
2038       assert(SCI->getOperand(1) == LHS);
2039       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2040     }
2041
2042     unsigned LHSCode = getSetCondCode(SCI);
2043     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2044     unsigned Code;
2045     switch (Log.getOpcode()) {
2046     case Instruction::And: Code = LHSCode & RHSCode; break;
2047     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2048     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2049     default: assert(0 && "Illegal logical opcode!"); return 0;
2050     }
2051
2052     Value *RV = getSetCCValue(Code, LHS, RHS);
2053     if (Instruction *I = dyn_cast<Instruction>(RV))
2054       return I;
2055     // Otherwise, it's a constant boolean value...
2056     return IC.ReplaceInstUsesWith(Log, RV);
2057   }
2058 };
2059
2060 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2061 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2062 // guaranteed to be either a shift instruction or a binary operator.
2063 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2064                                     ConstantIntegral *OpRHS,
2065                                     ConstantIntegral *AndRHS,
2066                                     BinaryOperator &TheAnd) {
2067   Value *X = Op->getOperand(0);
2068   Constant *Together = 0;
2069   if (!isa<ShiftInst>(Op))
2070     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2071
2072   switch (Op->getOpcode()) {
2073   case Instruction::Xor:
2074     if (Op->hasOneUse()) {
2075       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2076       std::string OpName = Op->getName(); Op->setName("");
2077       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2078       InsertNewInstBefore(And, TheAnd);
2079       return BinaryOperator::createXor(And, Together);
2080     }
2081     break;
2082   case Instruction::Or:
2083     if (Together == AndRHS) // (X | C) & C --> C
2084       return ReplaceInstUsesWith(TheAnd, AndRHS);
2085
2086     if (Op->hasOneUse() && Together != OpRHS) {
2087       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2088       std::string Op0Name = Op->getName(); Op->setName("");
2089       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2090       InsertNewInstBefore(Or, TheAnd);
2091       return BinaryOperator::createAnd(Or, AndRHS);
2092     }
2093     break;
2094   case Instruction::Add:
2095     if (Op->hasOneUse()) {
2096       // Adding a one to a single bit bit-field should be turned into an XOR
2097       // of the bit.  First thing to check is to see if this AND is with a
2098       // single bit constant.
2099       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2100
2101       // Clear bits that are not part of the constant.
2102       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2103
2104       // If there is only one bit set...
2105       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2106         // Ok, at this point, we know that we are masking the result of the
2107         // ADD down to exactly one bit.  If the constant we are adding has
2108         // no bits set below this bit, then we can eliminate the ADD.
2109         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2110
2111         // Check to see if any bits below the one bit set in AndRHSV are set.
2112         if ((AddRHS & (AndRHSV-1)) == 0) {
2113           // If not, the only thing that can effect the output of the AND is
2114           // the bit specified by AndRHSV.  If that bit is set, the effect of
2115           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2116           // no effect.
2117           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2118             TheAnd.setOperand(0, X);
2119             return &TheAnd;
2120           } else {
2121             std::string Name = Op->getName(); Op->setName("");
2122             // Pull the XOR out of the AND.
2123             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2124             InsertNewInstBefore(NewAnd, TheAnd);
2125             return BinaryOperator::createXor(NewAnd, AndRHS);
2126           }
2127         }
2128       }
2129     }
2130     break;
2131
2132   case Instruction::Shl: {
2133     // We know that the AND will not produce any of the bits shifted in, so if
2134     // the anded constant includes them, clear them now!
2135     //
2136     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2137     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2138     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2139
2140     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2141       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2142     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2143       TheAnd.setOperand(1, CI);
2144       return &TheAnd;
2145     }
2146     break;
2147   }
2148   case Instruction::Shr:
2149     // We know that the AND will not produce any of the bits shifted in, so if
2150     // the anded constant includes them, clear them now!  This only applies to
2151     // unsigned shifts, because a signed shr may bring in set bits!
2152     //
2153     if (AndRHS->getType()->isUnsigned()) {
2154       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2155       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2156       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2157
2158       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2159         return ReplaceInstUsesWith(TheAnd, Op);
2160       } else if (CI != AndRHS) {
2161         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2162         return &TheAnd;
2163       }
2164     } else {   // Signed shr.
2165       // See if this is shifting in some sign extension, then masking it out
2166       // with an and.
2167       if (Op->hasOneUse()) {
2168         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2169         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2170         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2171         if (CI == AndRHS) {          // Masking out bits shifted in.
2172           // Make the argument unsigned.
2173           Value *ShVal = Op->getOperand(0);
2174           ShVal = InsertCastBefore(ShVal,
2175                                    ShVal->getType()->getUnsignedVersion(),
2176                                    TheAnd);
2177           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2178                                                     OpRHS, Op->getName()),
2179                                       TheAnd);
2180           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2181           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2182                                                              TheAnd.getName()),
2183                                       TheAnd);
2184           return new CastInst(ShVal, Op->getType());
2185         }
2186       }
2187     }
2188     break;
2189   }
2190   return 0;
2191 }
2192
2193
2194 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2195 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2196 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2197 /// insert new instructions.
2198 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2199                                            bool Inside, Instruction &IB) {
2200   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2201          "Lo is not <= Hi in range emission code!");
2202   if (Inside) {
2203     if (Lo == Hi)  // Trivially false.
2204       return new SetCondInst(Instruction::SetNE, V, V);
2205     if (cast<ConstantIntegral>(Lo)->isMinValue())
2206       return new SetCondInst(Instruction::SetLT, V, Hi);
2207
2208     Constant *AddCST = ConstantExpr::getNeg(Lo);
2209     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2210     InsertNewInstBefore(Add, IB);
2211     // Convert to unsigned for the comparison.
2212     const Type *UnsType = Add->getType()->getUnsignedVersion();
2213     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2214     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2215     AddCST = ConstantExpr::getCast(AddCST, UnsType);
2216     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2217   }
2218
2219   if (Lo == Hi)  // Trivially true.
2220     return new SetCondInst(Instruction::SetEQ, V, V);
2221
2222   Hi = SubOne(cast<ConstantInt>(Hi));
2223   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2224     return new SetCondInst(Instruction::SetGT, V, Hi);
2225
2226   // Emit X-Lo > Hi-Lo-1
2227   Constant *AddCST = ConstantExpr::getNeg(Lo);
2228   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2229   InsertNewInstBefore(Add, IB);
2230   // Convert to unsigned for the comparison.
2231   const Type *UnsType = Add->getType()->getUnsignedVersion();
2232   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2233   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2234   AddCST = ConstantExpr::getCast(AddCST, UnsType);
2235   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2236 }
2237
2238 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2239 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2240 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2241 // not, since all 1s are not contiguous.
2242 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2243   uint64_t V = Val->getRawValue();
2244   if (!isShiftedMask_64(V)) return false;
2245
2246   // look for the first zero bit after the run of ones
2247   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2248   // look for the first non-zero bit
2249   ME = 64-CountLeadingZeros_64(V);
2250   return true;
2251 }
2252
2253
2254
2255 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2256 /// where isSub determines whether the operator is a sub.  If we can fold one of
2257 /// the following xforms:
2258 /// 
2259 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2260 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2261 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2262 ///
2263 /// return (A +/- B).
2264 ///
2265 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2266                                         ConstantIntegral *Mask, bool isSub,
2267                                         Instruction &I) {
2268   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2269   if (!LHSI || LHSI->getNumOperands() != 2 ||
2270       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2271
2272   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2273
2274   switch (LHSI->getOpcode()) {
2275   default: return 0;
2276   case Instruction::And:
2277     if (ConstantExpr::getAnd(N, Mask) == Mask) {
2278       // If the AndRHS is a power of two minus one (0+1+), this is simple.
2279       if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2280         break;
2281
2282       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2283       // part, we don't need any explicit masks to take them out of A.  If that
2284       // is all N is, ignore it.
2285       unsigned MB, ME;
2286       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
2287         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2288         Mask >>= 64-MB+1;
2289         if (MaskedValueIsZero(RHS, Mask))
2290           break;
2291       }
2292     }
2293     return 0;
2294   case Instruction::Or:
2295   case Instruction::Xor:
2296     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2297     if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2298         ConstantExpr::getAnd(N, Mask)->isNullValue())
2299       break;
2300     return 0;
2301   }
2302   
2303   Instruction *New;
2304   if (isSub)
2305     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2306   else
2307     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2308   return InsertNewInstBefore(New, I);
2309 }
2310
2311 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2312   bool Changed = SimplifyCommutative(I);
2313   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2314
2315   if (isa<UndefValue>(Op1))                         // X & undef -> 0
2316     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2317
2318   // and X, X = X
2319   if (Op0 == Op1)
2320     return ReplaceInstUsesWith(I, Op1);
2321
2322   // See if we can simplify any instructions used by the instruction whose sole 
2323   // purpose is to compute bits we don't care about.
2324   uint64_t KnownZero, KnownOne;
2325   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2326                            KnownZero, KnownOne))
2327     return &I;
2328   
2329   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2330     uint64_t AndRHSMask = AndRHS->getZExtValue();
2331     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2332     uint64_t NotAndRHS = AndRHSMask^TypeMask;
2333
2334     // Optimize a variety of ((val OP C1) & C2) combinations...
2335     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2336       Instruction *Op0I = cast<Instruction>(Op0);
2337       Value *Op0LHS = Op0I->getOperand(0);
2338       Value *Op0RHS = Op0I->getOperand(1);
2339       switch (Op0I->getOpcode()) {
2340       case Instruction::Xor:
2341       case Instruction::Or:
2342         // If the mask is only needed on one incoming arm, push it up.
2343         if (Op0I->hasOneUse()) {
2344           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2345             // Not masking anything out for the LHS, move to RHS.
2346             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2347                                                    Op0RHS->getName()+".masked");
2348             InsertNewInstBefore(NewRHS, I);
2349             return BinaryOperator::create(
2350                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2351           }
2352           if (!isa<Constant>(Op0RHS) &&
2353               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2354             // Not masking anything out for the RHS, move to LHS.
2355             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2356                                                    Op0LHS->getName()+".masked");
2357             InsertNewInstBefore(NewLHS, I);
2358             return BinaryOperator::create(
2359                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2360           }
2361         }
2362
2363         break;
2364       case Instruction::Add:
2365         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2366         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2367         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2368         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2369           return BinaryOperator::createAnd(V, AndRHS);
2370         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2371           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
2372         break;
2373
2374       case Instruction::Sub:
2375         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2376         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2377         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2378         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2379           return BinaryOperator::createAnd(V, AndRHS);
2380         break;
2381       }
2382
2383       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2384         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2385           return Res;
2386     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2387       const Type *SrcTy = CI->getOperand(0)->getType();
2388
2389       // If this is an integer truncation or change from signed-to-unsigned, and
2390       // if the source is an and/or with immediate, transform it.  This
2391       // frequently occurs for bitfield accesses.
2392       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2393         if (SrcTy->getPrimitiveSizeInBits() >= 
2394               I.getType()->getPrimitiveSizeInBits() &&
2395             CastOp->getNumOperands() == 2)
2396           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2397             if (CastOp->getOpcode() == Instruction::And) {
2398               // Change: and (cast (and X, C1) to T), C2
2399               // into  : and (cast X to T), trunc(C1)&C2
2400               // This will folds the two ands together, which may allow other
2401               // simplifications.
2402               Instruction *NewCast =
2403                 new CastInst(CastOp->getOperand(0), I.getType(),
2404                              CastOp->getName()+".shrunk");
2405               NewCast = InsertNewInstBefore(NewCast, I);
2406               
2407               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2408               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
2409               return BinaryOperator::createAnd(NewCast, C3);
2410             } else if (CastOp->getOpcode() == Instruction::Or) {
2411               // Change: and (cast (or X, C1) to T), C2
2412               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2413               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2414               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
2415                 return ReplaceInstUsesWith(I, AndRHS);
2416             }
2417       }
2418     }
2419
2420     // Try to fold constant and into select arguments.
2421     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2422       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2423         return R;
2424     if (isa<PHINode>(Op0))
2425       if (Instruction *NV = FoldOpIntoPhi(I))
2426         return NV;
2427   }
2428
2429   Value *Op0NotVal = dyn_castNotVal(Op0);
2430   Value *Op1NotVal = dyn_castNotVal(Op1);
2431
2432   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
2433     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2434
2435   // (~A & ~B) == (~(A | B)) - De Morgan's Law
2436   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2437     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2438                                                I.getName()+".demorgan");
2439     InsertNewInstBefore(Or, I);
2440     return BinaryOperator::createNot(Or);
2441   }
2442   
2443   {
2444     Value *A = 0, *B = 0;
2445     ConstantInt *C1 = 0, *C2 = 0;
2446     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2447       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
2448         return ReplaceInstUsesWith(I, Op1);
2449     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2450       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
2451         return ReplaceInstUsesWith(I, Op0);
2452   }
2453   
2454
2455   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2456     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2457     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2458       return R;
2459
2460     Value *LHSVal, *RHSVal;
2461     ConstantInt *LHSCst, *RHSCst;
2462     Instruction::BinaryOps LHSCC, RHSCC;
2463     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2464       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2465         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
2466             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2467             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2468             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2469           // Ensure that the larger constant is on the RHS.
2470           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2471           SetCondInst *LHS = cast<SetCondInst>(Op0);
2472           if (cast<ConstantBool>(Cmp)->getValue()) {
2473             std::swap(LHS, RHS);
2474             std::swap(LHSCst, RHSCst);
2475             std::swap(LHSCC, RHSCC);
2476           }
2477
2478           // At this point, we know we have have two setcc instructions
2479           // comparing a value against two constants and and'ing the result
2480           // together.  Because of the above check, we know that we only have
2481           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2482           // FoldSetCCLogical check above), that the two constants are not
2483           // equal.
2484           assert(LHSCst != RHSCst && "Compares not folded above?");
2485
2486           switch (LHSCC) {
2487           default: assert(0 && "Unknown integer condition code!");
2488           case Instruction::SetEQ:
2489             switch (RHSCC) {
2490             default: assert(0 && "Unknown integer condition code!");
2491             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
2492             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
2493               return ReplaceInstUsesWith(I, ConstantBool::False);
2494             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
2495             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
2496               return ReplaceInstUsesWith(I, LHS);
2497             }
2498           case Instruction::SetNE:
2499             switch (RHSCC) {
2500             default: assert(0 && "Unknown integer condition code!");
2501             case Instruction::SetLT:
2502               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2503                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2504               break;                        // (X != 13 & X < 15) -> no change
2505             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
2506             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
2507               return ReplaceInstUsesWith(I, RHS);
2508             case Instruction::SetNE:
2509               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2510                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2511                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2512                                                       LHSVal->getName()+".off");
2513                 InsertNewInstBefore(Add, I);
2514                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2515                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2516                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2517                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2518                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2519               }
2520               break;                        // (X != 13 & X != 15) -> no change
2521             }
2522             break;
2523           case Instruction::SetLT:
2524             switch (RHSCC) {
2525             default: assert(0 && "Unknown integer condition code!");
2526             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
2527             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
2528               return ReplaceInstUsesWith(I, ConstantBool::False);
2529             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
2530             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
2531               return ReplaceInstUsesWith(I, LHS);
2532             }
2533           case Instruction::SetGT:
2534             switch (RHSCC) {
2535             default: assert(0 && "Unknown integer condition code!");
2536             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
2537               return ReplaceInstUsesWith(I, LHS);
2538             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
2539               return ReplaceInstUsesWith(I, RHS);
2540             case Instruction::SetNE:
2541               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2542                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2543               break;                        // (X > 13 & X != 15) -> no change
2544             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
2545               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2546             }
2547           }
2548         }
2549   }
2550
2551   return Changed ? &I : 0;
2552 }
2553
2554 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2555   bool Changed = SimplifyCommutative(I);
2556   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2557
2558   if (isa<UndefValue>(Op1))
2559     return ReplaceInstUsesWith(I,                         // X | undef -> -1
2560                                ConstantIntegral::getAllOnesValue(I.getType()));
2561
2562   // or X, X = X
2563   if (Op0 == Op1)
2564     return ReplaceInstUsesWith(I, Op0);
2565
2566   // See if we can simplify any instructions used by the instruction whose sole 
2567   // purpose is to compute bits we don't care about.
2568   uint64_t KnownZero, KnownOne;
2569   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2570                            KnownZero, KnownOne))
2571     return &I;
2572   
2573   // or X, -1 == -1
2574   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2575     ConstantInt *C1 = 0; Value *X = 0;
2576     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2577     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2578       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2579       Op0->setName("");
2580       InsertNewInstBefore(Or, I);
2581       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2582     }
2583
2584     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2585     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2586       std::string Op0Name = Op0->getName(); Op0->setName("");
2587       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2588       InsertNewInstBefore(Or, I);
2589       return BinaryOperator::createXor(Or,
2590                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2591     }
2592
2593     // Try to fold constant and into select arguments.
2594     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2595       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2596         return R;
2597     if (isa<PHINode>(Op0))
2598       if (Instruction *NV = FoldOpIntoPhi(I))
2599         return NV;
2600   }
2601
2602   Value *A = 0, *B = 0;
2603   ConstantInt *C1 = 0, *C2 = 0;
2604
2605   if (match(Op0, m_And(m_Value(A), m_Value(B))))
2606     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
2607       return ReplaceInstUsesWith(I, Op1);
2608   if (match(Op1, m_And(m_Value(A), m_Value(B))))
2609     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
2610       return ReplaceInstUsesWith(I, Op0);
2611
2612   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2613   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2614       MaskedValueIsZero(Op1, C1->getZExtValue())) {
2615     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2616     Op0->setName("");
2617     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2618   }
2619
2620   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2621   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2622       MaskedValueIsZero(Op0, C1->getZExtValue())) {
2623     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2624     Op0->setName("");
2625     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2626   }
2627
2628   // (A & C1)|(B & C2)
2629   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2630       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2631
2632     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
2633       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2634
2635
2636     // If we have: ((V + N) & C1) | (V & C2)
2637     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2638     // replace with V+N.
2639     if (C1 == ConstantExpr::getNot(C2)) {
2640       Value *V1 = 0, *V2 = 0;
2641       if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2642           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2643         // Add commutes, try both ways.
2644         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2645           return ReplaceInstUsesWith(I, A);
2646         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2647           return ReplaceInstUsesWith(I, A);
2648       }
2649       // Or commutes, try both ways.
2650       if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2651           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2652         // Add commutes, try both ways.
2653         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2654           return ReplaceInstUsesWith(I, B);
2655         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2656           return ReplaceInstUsesWith(I, B);
2657       }
2658     }
2659   }
2660
2661   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
2662     if (A == Op1)   // ~A | A == -1
2663       return ReplaceInstUsesWith(I,
2664                                 ConstantIntegral::getAllOnesValue(I.getType()));
2665   } else {
2666     A = 0;
2667   }
2668   // Note, A is still live here!
2669   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
2670     if (Op0 == B)
2671       return ReplaceInstUsesWith(I,
2672                                 ConstantIntegral::getAllOnesValue(I.getType()));
2673
2674     // (~A | ~B) == (~(A & B)) - De Morgan's Law
2675     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2676       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2677                                               I.getName()+".demorgan"), I);
2678       return BinaryOperator::createNot(And);
2679     }
2680   }
2681
2682   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2683   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2684     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2685       return R;
2686
2687     Value *LHSVal, *RHSVal;
2688     ConstantInt *LHSCst, *RHSCst;
2689     Instruction::BinaryOps LHSCC, RHSCC;
2690     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2691       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2692         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
2693             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2694             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2695             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2696           // Ensure that the larger constant is on the RHS.
2697           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2698           SetCondInst *LHS = cast<SetCondInst>(Op0);
2699           if (cast<ConstantBool>(Cmp)->getValue()) {
2700             std::swap(LHS, RHS);
2701             std::swap(LHSCst, RHSCst);
2702             std::swap(LHSCC, RHSCC);
2703           }
2704
2705           // At this point, we know we have have two setcc instructions
2706           // comparing a value against two constants and or'ing the result
2707           // together.  Because of the above check, we know that we only have
2708           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2709           // FoldSetCCLogical check above), that the two constants are not
2710           // equal.
2711           assert(LHSCst != RHSCst && "Compares not folded above?");
2712
2713           switch (LHSCC) {
2714           default: assert(0 && "Unknown integer condition code!");
2715           case Instruction::SetEQ:
2716             switch (RHSCC) {
2717             default: assert(0 && "Unknown integer condition code!");
2718             case Instruction::SetEQ:
2719               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2720                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2721                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2722                                                       LHSVal->getName()+".off");
2723                 InsertNewInstBefore(Add, I);
2724                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2725                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2726                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2727                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2728                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2729               }
2730               break;                  // (X == 13 | X == 15) -> no change
2731
2732             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
2733               break;
2734             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
2735             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
2736               return ReplaceInstUsesWith(I, RHS);
2737             }
2738             break;
2739           case Instruction::SetNE:
2740             switch (RHSCC) {
2741             default: assert(0 && "Unknown integer condition code!");
2742             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
2743             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
2744               return ReplaceInstUsesWith(I, LHS);
2745             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
2746             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
2747               return ReplaceInstUsesWith(I, ConstantBool::True);
2748             }
2749             break;
2750           case Instruction::SetLT:
2751             switch (RHSCC) {
2752             default: assert(0 && "Unknown integer condition code!");
2753             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
2754               break;
2755             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
2756               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2757             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
2758             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
2759               return ReplaceInstUsesWith(I, RHS);
2760             }
2761             break;
2762           case Instruction::SetGT:
2763             switch (RHSCC) {
2764             default: assert(0 && "Unknown integer condition code!");
2765             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
2766             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
2767               return ReplaceInstUsesWith(I, LHS);
2768             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
2769             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
2770               return ReplaceInstUsesWith(I, ConstantBool::True);
2771             }
2772           }
2773         }
2774   }
2775
2776   return Changed ? &I : 0;
2777 }
2778
2779 // XorSelf - Implements: X ^ X --> 0
2780 struct XorSelf {
2781   Value *RHS;
2782   XorSelf(Value *rhs) : RHS(rhs) {}
2783   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2784   Instruction *apply(BinaryOperator &Xor) const {
2785     return &Xor;
2786   }
2787 };
2788
2789
2790 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2791   bool Changed = SimplifyCommutative(I);
2792   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2793
2794   if (isa<UndefValue>(Op1))
2795     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
2796
2797   // xor X, X = 0, even if X is nested in a sequence of Xor's.
2798   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2799     assert(Result == &I && "AssociativeOpt didn't work?");
2800     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2801   }
2802   
2803   // See if we can simplify any instructions used by the instruction whose sole 
2804   // purpose is to compute bits we don't care about.
2805   uint64_t KnownZero, KnownOne;
2806   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2807                            KnownZero, KnownOne))
2808     return &I;
2809
2810   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2811     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2812       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2813       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2814         if (RHS == ConstantBool::True && SCI->hasOneUse())
2815           return new SetCondInst(SCI->getInverseCondition(),
2816                                  SCI->getOperand(0), SCI->getOperand(1));
2817
2818       // ~(c-X) == X-c-1 == X+(-c-1)
2819       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2820         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2821           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2822           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2823                                               ConstantInt::get(I.getType(), 1));
2824           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2825         }
2826
2827       // ~(~X & Y) --> (X | ~Y)
2828       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2829         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2830         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2831           Instruction *NotY =
2832             BinaryOperator::createNot(Op0I->getOperand(1),
2833                                       Op0I->getOperand(1)->getName()+".not");
2834           InsertNewInstBefore(NotY, I);
2835           return BinaryOperator::createOr(Op0NotVal, NotY);
2836         }
2837       }
2838
2839       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2840         if (Op0I->getOpcode() == Instruction::Add) {
2841           // ~(X-c) --> (-c-1)-X
2842           if (RHS->isAllOnesValue()) {
2843             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2844             return BinaryOperator::createSub(
2845                            ConstantExpr::getSub(NegOp0CI,
2846                                              ConstantInt::get(I.getType(), 1)),
2847                                           Op0I->getOperand(0));
2848           }
2849         } else if (Op0I->getOpcode() == Instruction::Or) {
2850           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2851           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2852             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2853             // Anything in both C1 and C2 is known to be zero, remove it from
2854             // NewRHS.
2855             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2856             NewRHS = ConstantExpr::getAnd(NewRHS, 
2857                                           ConstantExpr::getNot(CommonBits));
2858             WorkList.push_back(Op0I);
2859             I.setOperand(0, Op0I->getOperand(0));
2860             I.setOperand(1, NewRHS);
2861             return &I;
2862           }
2863         }
2864     }
2865
2866     // Try to fold constant and into select arguments.
2867     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2868       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2869         return R;
2870     if (isa<PHINode>(Op0))
2871       if (Instruction *NV = FoldOpIntoPhi(I))
2872         return NV;
2873   }
2874
2875   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
2876     if (X == Op1)
2877       return ReplaceInstUsesWith(I,
2878                                 ConstantIntegral::getAllOnesValue(I.getType()));
2879
2880   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
2881     if (X == Op0)
2882       return ReplaceInstUsesWith(I,
2883                                 ConstantIntegral::getAllOnesValue(I.getType()));
2884
2885   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2886     if (Op1I->getOpcode() == Instruction::Or) {
2887       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
2888         cast<BinaryOperator>(Op1I)->swapOperands();
2889         I.swapOperands();
2890         std::swap(Op0, Op1);
2891       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
2892         I.swapOperands();
2893         std::swap(Op0, Op1);
2894       }
2895     } else if (Op1I->getOpcode() == Instruction::Xor) {
2896       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
2897         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2898       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
2899         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2900     }
2901
2902   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2903     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2904       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
2905         cast<BinaryOperator>(Op0I)->swapOperands();
2906       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
2907         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2908                                                      Op1->getName()+".not"), I);
2909         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2910       }
2911     } else if (Op0I->getOpcode() == Instruction::Xor) {
2912       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
2913         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2914       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
2915         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2916     }
2917
2918   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2919   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2920     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2921       return R;
2922
2923   return Changed ? &I : 0;
2924 }
2925
2926 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2927 /// overflowed for this type.
2928 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2929                             ConstantInt *In2) {
2930   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2931   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2932 }
2933
2934 static bool isPositive(ConstantInt *C) {
2935   return cast<ConstantSInt>(C)->getValue() >= 0;
2936 }
2937
2938 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2939 /// overflowed for this type.
2940 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2941                             ConstantInt *In2) {
2942   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2943
2944   if (In1->getType()->isUnsigned())
2945     return cast<ConstantUInt>(Result)->getValue() <
2946            cast<ConstantUInt>(In1)->getValue();
2947   if (isPositive(In1) != isPositive(In2))
2948     return false;
2949   if (isPositive(In1))
2950     return cast<ConstantSInt>(Result)->getValue() <
2951            cast<ConstantSInt>(In1)->getValue();
2952   return cast<ConstantSInt>(Result)->getValue() >
2953          cast<ConstantSInt>(In1)->getValue();
2954 }
2955
2956 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2957 /// code necessary to compute the offset from the base pointer (without adding
2958 /// in the base pointer).  Return the result as a signed integer of intptr size.
2959 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2960   TargetData &TD = IC.getTargetData();
2961   gep_type_iterator GTI = gep_type_begin(GEP);
2962   const Type *UIntPtrTy = TD.getIntPtrType();
2963   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2964   Value *Result = Constant::getNullValue(SIntPtrTy);
2965
2966   // Build a mask for high order bits.
2967   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
2968
2969   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2970     Value *Op = GEP->getOperand(i);
2971     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2972     Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2973                                             SIntPtrTy);
2974     if (Constant *OpC = dyn_cast<Constant>(Op)) {
2975       if (!OpC->isNullValue()) {
2976         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2977         Scale = ConstantExpr::getMul(OpC, Scale);
2978         if (Constant *RC = dyn_cast<Constant>(Result))
2979           Result = ConstantExpr::getAdd(RC, Scale);
2980         else {
2981           // Emit an add instruction.
2982           Result = IC.InsertNewInstBefore(
2983              BinaryOperator::createAdd(Result, Scale,
2984                                        GEP->getName()+".offs"), I);
2985         }
2986       }
2987     } else {
2988       // Convert to correct type.
2989       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2990                                                Op->getName()+".c"), I);
2991       if (Size != 1)
2992         // We'll let instcombine(mul) convert this to a shl if possible.
2993         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2994                                                     GEP->getName()+".idx"), I);
2995
2996       // Emit an add instruction.
2997       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2998                                                     GEP->getName()+".offs"), I);
2999     }
3000   }
3001   return Result;
3002 }
3003
3004 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3005 /// else.  At this point we know that the GEP is on the LHS of the comparison.
3006 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3007                                         Instruction::BinaryOps Cond,
3008                                         Instruction &I) {
3009   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3010
3011   if (CastInst *CI = dyn_cast<CastInst>(RHS))
3012     if (isa<PointerType>(CI->getOperand(0)->getType()))
3013       RHS = CI->getOperand(0);
3014
3015   Value *PtrBase = GEPLHS->getOperand(0);
3016   if (PtrBase == RHS) {
3017     // As an optimization, we don't actually have to compute the actual value of
3018     // OFFSET if this is a seteq or setne comparison, just return whether each
3019     // index is zero or not.
3020     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3021       Instruction *InVal = 0;
3022       gep_type_iterator GTI = gep_type_begin(GEPLHS);
3023       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3024         bool EmitIt = true;
3025         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3026           if (isa<UndefValue>(C))  // undef index -> undef.
3027             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3028           if (C->isNullValue())
3029             EmitIt = false;
3030           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3031             EmitIt = false;  // This is indexing into a zero sized array?
3032           } else if (isa<ConstantInt>(C))
3033             return ReplaceInstUsesWith(I, // No comparison is needed here.
3034                                  ConstantBool::get(Cond == Instruction::SetNE));
3035         }
3036
3037         if (EmitIt) {
3038           Instruction *Comp =
3039             new SetCondInst(Cond, GEPLHS->getOperand(i),
3040                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3041           if (InVal == 0)
3042             InVal = Comp;
3043           else {
3044             InVal = InsertNewInstBefore(InVal, I);
3045             InsertNewInstBefore(Comp, I);
3046             if (Cond == Instruction::SetNE)   // True if any are unequal
3047               InVal = BinaryOperator::createOr(InVal, Comp);
3048             else                              // True if all are equal
3049               InVal = BinaryOperator::createAnd(InVal, Comp);
3050           }
3051         }
3052       }
3053
3054       if (InVal)
3055         return InVal;
3056       else
3057         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3058                             ConstantBool::get(Cond == Instruction::SetEQ));
3059     }
3060
3061     // Only lower this if the setcc is the only user of the GEP or if we expect
3062     // the result to fold to a constant!
3063     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3064       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
3065       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3066       return new SetCondInst(Cond, Offset,
3067                              Constant::getNullValue(Offset->getType()));
3068     }
3069   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3070     // If the base pointers are different, but the indices are the same, just
3071     // compare the base pointer.
3072     if (PtrBase != GEPRHS->getOperand(0)) {
3073       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3074       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3075                         GEPRHS->getOperand(0)->getType();
3076       if (IndicesTheSame)
3077         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3078           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3079             IndicesTheSame = false;
3080             break;
3081           }
3082
3083       // If all indices are the same, just compare the base pointers.
3084       if (IndicesTheSame)
3085         return new SetCondInst(Cond, GEPLHS->getOperand(0),
3086                                GEPRHS->getOperand(0));
3087
3088       // Otherwise, the base pointers are different and the indices are
3089       // different, bail out.
3090       return 0;
3091     }
3092
3093     // If one of the GEPs has all zero indices, recurse.
3094     bool AllZeros = true;
3095     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3096       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3097           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3098         AllZeros = false;
3099         break;
3100       }
3101     if (AllZeros)
3102       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3103                           SetCondInst::getSwappedCondition(Cond), I);
3104
3105     // If the other GEP has all zero indices, recurse.
3106     AllZeros = true;
3107     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3108       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3109           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3110         AllZeros = false;
3111         break;
3112       }
3113     if (AllZeros)
3114       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3115
3116     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3117       // If the GEPs only differ by one index, compare it.
3118       unsigned NumDifferences = 0;  // Keep track of # differences.
3119       unsigned DiffOperand = 0;     // The operand that differs.
3120       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3121         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3122           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3123                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3124             // Irreconcilable differences.
3125             NumDifferences = 2;
3126             break;
3127           } else {
3128             if (NumDifferences++) break;
3129             DiffOperand = i;
3130           }
3131         }
3132
3133       if (NumDifferences == 0)   // SAME GEP?
3134         return ReplaceInstUsesWith(I, // No comparison is needed here.
3135                                  ConstantBool::get(Cond == Instruction::SetEQ));
3136       else if (NumDifferences == 1) {
3137         Value *LHSV = GEPLHS->getOperand(DiffOperand);
3138         Value *RHSV = GEPRHS->getOperand(DiffOperand);
3139
3140         // Convert the operands to signed values to make sure to perform a
3141         // signed comparison.
3142         const Type *NewTy = LHSV->getType()->getSignedVersion();
3143         if (LHSV->getType() != NewTy)
3144           LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3145                                                   LHSV->getName()), I);
3146         if (RHSV->getType() != NewTy)
3147           RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3148                                                   RHSV->getName()), I);
3149         return new SetCondInst(Cond, LHSV, RHSV);
3150       }
3151     }
3152
3153     // Only lower this if the setcc is the only user of the GEP or if we expect
3154     // the result to fold to a constant!
3155     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3156         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3157       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
3158       Value *L = EmitGEPOffset(GEPLHS, I, *this);
3159       Value *R = EmitGEPOffset(GEPRHS, I, *this);
3160       return new SetCondInst(Cond, L, R);
3161     }
3162   }
3163   return 0;
3164 }
3165
3166
3167 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3168   bool Changed = SimplifyCommutative(I);
3169   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3170   const Type *Ty = Op0->getType();
3171
3172   // setcc X, X
3173   if (Op0 == Op1)
3174     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3175
3176   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
3177     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3178
3179   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3180   // addresses never equal each other!  We already know that Op0 != Op1.
3181   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3182        isa<ConstantPointerNull>(Op0)) &&
3183       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3184        isa<ConstantPointerNull>(Op1)))
3185     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3186
3187   // setcc's with boolean values can always be turned into bitwise operations
3188   if (Ty == Type::BoolTy) {
3189     switch (I.getOpcode()) {
3190     default: assert(0 && "Invalid setcc instruction!");
3191     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
3192       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3193       InsertNewInstBefore(Xor, I);
3194       return BinaryOperator::createNot(Xor);
3195     }
3196     case Instruction::SetNE:
3197       return BinaryOperator::createXor(Op0, Op1);
3198
3199     case Instruction::SetGT:
3200       std::swap(Op0, Op1);                   // Change setgt -> setlt
3201       // FALL THROUGH
3202     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
3203       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3204       InsertNewInstBefore(Not, I);
3205       return BinaryOperator::createAnd(Not, Op1);
3206     }
3207     case Instruction::SetGE:
3208       std::swap(Op0, Op1);                   // Change setge -> setle
3209       // FALL THROUGH
3210     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
3211       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3212       InsertNewInstBefore(Not, I);
3213       return BinaryOperator::createOr(Not, Op1);
3214     }
3215     }
3216   }
3217
3218   // See if we are doing a comparison between a constant and an instruction that
3219   // can be folded into the comparison.
3220   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3221     // Check to see if we are comparing against the minimum or maximum value...
3222     if (CI->isMinValue()) {
3223       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
3224         return ReplaceInstUsesWith(I, ConstantBool::False);
3225       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
3226         return ReplaceInstUsesWith(I, ConstantBool::True);
3227       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
3228         return BinaryOperator::createSetEQ(Op0, Op1);
3229       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
3230         return BinaryOperator::createSetNE(Op0, Op1);
3231
3232     } else if (CI->isMaxValue()) {
3233       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
3234         return ReplaceInstUsesWith(I, ConstantBool::False);
3235       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
3236         return ReplaceInstUsesWith(I, ConstantBool::True);
3237       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
3238         return BinaryOperator::createSetEQ(Op0, Op1);
3239       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
3240         return BinaryOperator::createSetNE(Op0, Op1);
3241
3242       // Comparing against a value really close to min or max?
3243     } else if (isMinValuePlusOne(CI)) {
3244       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
3245         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3246       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
3247         return BinaryOperator::createSetNE(Op0, SubOne(CI));
3248
3249     } else if (isMaxValueMinusOne(CI)) {
3250       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
3251         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3252       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
3253         return BinaryOperator::createSetNE(Op0, AddOne(CI));
3254     }
3255
3256     // If we still have a setle or setge instruction, turn it into the
3257     // appropriate setlt or setgt instruction.  Since the border cases have
3258     // already been handled above, this requires little checking.
3259     //
3260     if (I.getOpcode() == Instruction::SetLE)
3261       return BinaryOperator::createSetLT(Op0, AddOne(CI));
3262     if (I.getOpcode() == Instruction::SetGE)
3263       return BinaryOperator::createSetGT(Op0, SubOne(CI));
3264
3265     
3266     // See if we can fold the comparison based on bits known to be zero or one
3267     // in the input.
3268     uint64_t KnownZero, KnownOne;
3269     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3270                              KnownZero, KnownOne, 0))
3271       return &I;
3272         
3273     // Given the known and unknown bits, compute a range that the LHS could be
3274     // in.
3275     if (KnownOne | KnownZero) {
3276       if (Ty->isUnsigned()) {   // Unsigned comparison.
3277         uint64_t Min, Max;
3278         uint64_t RHSVal = CI->getZExtValue();
3279         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3280                                                  Min, Max);
3281         switch (I.getOpcode()) {  // LE/GE have been folded already.
3282         default: assert(0 && "Unknown setcc opcode!");
3283         case Instruction::SetEQ:
3284           if (Max < RHSVal || Min > RHSVal)
3285             return ReplaceInstUsesWith(I, ConstantBool::False);
3286           break;
3287         case Instruction::SetNE:
3288           if (Max < RHSVal || Min > RHSVal)
3289             return ReplaceInstUsesWith(I, ConstantBool::True);
3290           break;
3291         case Instruction::SetLT:
3292           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3293           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3294           break;
3295         case Instruction::SetGT:
3296           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3297           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3298           break;
3299         }
3300       } else {              // Signed comparison.
3301         int64_t Min, Max;
3302         int64_t RHSVal = CI->getSExtValue();
3303         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3304                                                Min, Max);
3305         switch (I.getOpcode()) {  // LE/GE have been folded already.
3306         default: assert(0 && "Unknown setcc opcode!");
3307         case Instruction::SetEQ:
3308           if (Max < RHSVal || Min > RHSVal)
3309             return ReplaceInstUsesWith(I, ConstantBool::False);
3310           break;
3311         case Instruction::SetNE:
3312           if (Max < RHSVal || Min > RHSVal)
3313             return ReplaceInstUsesWith(I, ConstantBool::True);
3314           break;
3315         case Instruction::SetLT:
3316           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3317           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3318           break;
3319         case Instruction::SetGT:
3320           if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3321           if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3322           break;
3323         }
3324       }
3325     }
3326           
3327     
3328     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3329       switch (LHSI->getOpcode()) {
3330       case Instruction::And:
3331         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3332             LHSI->getOperand(0)->hasOneUse()) {
3333           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3334           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
3335           // happens a LOT in code produced by the C front-end, for bitfield
3336           // access.
3337           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3338           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3339
3340           // Check to see if there is a noop-cast between the shift and the and.
3341           if (!Shift) {
3342             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3343               if (CI->getOperand(0)->getType()->isIntegral() &&
3344                   CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3345                      CI->getType()->getPrimitiveSizeInBits())
3346                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3347           }
3348           
3349           ConstantUInt *ShAmt;
3350           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3351           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
3352           const Type *AndTy = AndCST->getType();          // Type of the and.
3353
3354           // We can fold this as long as we can't shift unknown bits
3355           // into the mask.  This can only happen with signed shift
3356           // rights, as they sign-extend.
3357           if (ShAmt) {
3358             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3359                            Ty->isUnsigned();
3360             if (!CanFold) {
3361               // To test for the bad case of the signed shr, see if any
3362               // of the bits shifted in could be tested after the mask.
3363               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3364               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3365
3366               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3367               Constant *ShVal =
3368                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
3369                                      OShAmt);
3370               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3371                 CanFold = true;
3372             }
3373
3374             if (CanFold) {
3375               Constant *NewCst;
3376               if (Shift->getOpcode() == Instruction::Shl)
3377                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3378               else
3379                 NewCst = ConstantExpr::getShl(CI, ShAmt);
3380
3381               // Check to see if we are shifting out any of the bits being
3382               // compared.
3383               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3384                 // If we shifted bits out, the fold is not going to work out.
3385                 // As a special case, check to see if this means that the
3386                 // result is always true or false now.
3387                 if (I.getOpcode() == Instruction::SetEQ)
3388                   return ReplaceInstUsesWith(I, ConstantBool::False);
3389                 if (I.getOpcode() == Instruction::SetNE)
3390                   return ReplaceInstUsesWith(I, ConstantBool::True);
3391               } else {
3392                 I.setOperand(1, NewCst);
3393                 Constant *NewAndCST;
3394                 if (Shift->getOpcode() == Instruction::Shl)
3395                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3396                 else
3397                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3398                 LHSI->setOperand(1, NewAndCST);
3399                 if (AndTy == Ty) 
3400                   LHSI->setOperand(0, Shift->getOperand(0));
3401                 else {
3402                   Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3403                                                     *Shift);
3404                   LHSI->setOperand(0, NewCast);
3405                 }
3406                 WorkList.push_back(Shift); // Shift is dead.
3407                 AddUsesToWorkList(I);
3408                 return &I;
3409               }
3410             }
3411           }
3412         }
3413         break;
3414
3415       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
3416         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3417           switch (I.getOpcode()) {
3418           default: break;
3419           case Instruction::SetEQ:
3420           case Instruction::SetNE: {
3421             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3422
3423             // Check that the shift amount is in range.  If not, don't perform
3424             // undefined shifts.  When the shift is visited it will be
3425             // simplified.
3426             if (ShAmt->getValue() >= TypeBits)
3427               break;
3428
3429             // If we are comparing against bits always shifted out, the
3430             // comparison cannot succeed.
3431             Constant *Comp =
3432               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3433             if (Comp != CI) {// Comparing against a bit that we know is zero.
3434               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3435               Constant *Cst = ConstantBool::get(IsSetNE);
3436               return ReplaceInstUsesWith(I, Cst);
3437             }
3438
3439             if (LHSI->hasOneUse()) {
3440               // Otherwise strength reduce the shift into an and.
3441               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3442               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3443
3444               Constant *Mask;
3445               if (CI->getType()->isUnsigned()) {
3446                 Mask = ConstantUInt::get(CI->getType(), Val);
3447               } else if (ShAmtVal != 0) {
3448                 Mask = ConstantSInt::get(CI->getType(), Val);
3449               } else {
3450                 Mask = ConstantInt::getAllOnesValue(CI->getType());
3451               }
3452
3453               Instruction *AndI =
3454                 BinaryOperator::createAnd(LHSI->getOperand(0),
3455                                           Mask, LHSI->getName()+".mask");
3456               Value *And = InsertNewInstBefore(AndI, I);
3457               return new SetCondInst(I.getOpcode(), And,
3458                                      ConstantExpr::getUShr(CI, ShAmt));
3459             }
3460           }
3461           }
3462         }
3463         break;
3464
3465       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
3466         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3467           switch (I.getOpcode()) {
3468           default: break;
3469           case Instruction::SetEQ:
3470           case Instruction::SetNE: {
3471
3472             // Check that the shift amount is in range.  If not, don't perform
3473             // undefined shifts.  When the shift is visited it will be
3474             // simplified.
3475             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3476             if (ShAmt->getValue() >= TypeBits)
3477               break;
3478
3479             // If we are comparing against bits always shifted out, the
3480             // comparison cannot succeed.
3481             Constant *Comp =
3482               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3483
3484             if (Comp != CI) {// Comparing against a bit that we know is zero.
3485               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3486               Constant *Cst = ConstantBool::get(IsSetNE);
3487               return ReplaceInstUsesWith(I, Cst);
3488             }
3489
3490             if (LHSI->hasOneUse() || CI->isNullValue()) {
3491               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3492
3493               // Otherwise strength reduce the shift into an and.
3494               uint64_t Val = ~0ULL;          // All ones.
3495               Val <<= ShAmtVal;              // Shift over to the right spot.
3496
3497               Constant *Mask;
3498               if (CI->getType()->isUnsigned()) {
3499                 Val &= ~0ULL >> (64-TypeBits);
3500                 Mask = ConstantUInt::get(CI->getType(), Val);
3501               } else {
3502                 Mask = ConstantSInt::get(CI->getType(), Val);
3503               }
3504
3505               Instruction *AndI =
3506                 BinaryOperator::createAnd(LHSI->getOperand(0),
3507                                           Mask, LHSI->getName()+".mask");
3508               Value *And = InsertNewInstBefore(AndI, I);
3509               return new SetCondInst(I.getOpcode(), And,
3510                                      ConstantExpr::getShl(CI, ShAmt));
3511             }
3512             break;
3513           }
3514           }
3515         }
3516         break;
3517
3518       case Instruction::Div:
3519         // Fold: (div X, C1) op C2 -> range check
3520         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3521           // Fold this div into the comparison, producing a range check.
3522           // Determine, based on the divide type, what the range is being
3523           // checked.  If there is an overflow on the low or high side, remember
3524           // it, otherwise compute the range [low, hi) bounding the new value.
3525           bool LoOverflow = false, HiOverflow = 0;
3526           ConstantInt *LoBound = 0, *HiBound = 0;
3527
3528           ConstantInt *Prod;
3529           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3530
3531           Instruction::BinaryOps Opcode = I.getOpcode();
3532
3533           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
3534           } else if (LHSI->getType()->isUnsigned()) {  // udiv
3535             LoBound = Prod;
3536             LoOverflow = ProdOV;
3537             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3538           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
3539             if (CI->isNullValue()) {       // (X / pos) op 0
3540               // Can't overflow.
3541               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3542               HiBound = DivRHS;
3543             } else if (isPositive(CI)) {   // (X / pos) op pos
3544               LoBound = Prod;
3545               LoOverflow = ProdOV;
3546               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3547             } else {                       // (X / pos) op neg
3548               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3549               LoOverflow = AddWithOverflow(LoBound, Prod,
3550                                            cast<ConstantInt>(DivRHSH));
3551               HiBound = Prod;
3552               HiOverflow = ProdOV;
3553             }
3554           } else {                                     // Divisor is < 0.
3555             if (CI->isNullValue()) {       // (X / neg) op 0
3556               LoBound = AddOne(DivRHS);
3557               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3558               if (HiBound == DivRHS)
3559                 LoBound = 0;  // - INTMIN = INTMIN
3560             } else if (isPositive(CI)) {   // (X / neg) op pos
3561               HiOverflow = LoOverflow = ProdOV;
3562               if (!LoOverflow)
3563                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3564               HiBound = AddOne(Prod);
3565             } else {                       // (X / neg) op neg
3566               LoBound = Prod;
3567               LoOverflow = HiOverflow = ProdOV;
3568               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3569             }
3570
3571             // Dividing by a negate swaps the condition.
3572             Opcode = SetCondInst::getSwappedCondition(Opcode);
3573           }
3574
3575           if (LoBound) {
3576             Value *X = LHSI->getOperand(0);
3577             switch (Opcode) {
3578             default: assert(0 && "Unhandled setcc opcode!");
3579             case Instruction::SetEQ:
3580               if (LoOverflow && HiOverflow)
3581                 return ReplaceInstUsesWith(I, ConstantBool::False);
3582               else if (HiOverflow)
3583                 return new SetCondInst(Instruction::SetGE, X, LoBound);
3584               else if (LoOverflow)
3585                 return new SetCondInst(Instruction::SetLT, X, HiBound);
3586               else
3587                 return InsertRangeTest(X, LoBound, HiBound, true, I);
3588             case Instruction::SetNE:
3589               if (LoOverflow && HiOverflow)
3590                 return ReplaceInstUsesWith(I, ConstantBool::True);
3591               else if (HiOverflow)
3592                 return new SetCondInst(Instruction::SetLT, X, LoBound);
3593               else if (LoOverflow)
3594                 return new SetCondInst(Instruction::SetGE, X, HiBound);
3595               else
3596                 return InsertRangeTest(X, LoBound, HiBound, false, I);
3597             case Instruction::SetLT:
3598               if (LoOverflow)
3599                 return ReplaceInstUsesWith(I, ConstantBool::False);
3600               return new SetCondInst(Instruction::SetLT, X, LoBound);
3601             case Instruction::SetGT:
3602               if (HiOverflow)
3603                 return ReplaceInstUsesWith(I, ConstantBool::False);
3604               return new SetCondInst(Instruction::SetGE, X, HiBound);
3605             }
3606           }
3607         }
3608         break;
3609       }
3610
3611     // Simplify seteq and setne instructions...
3612     if (I.getOpcode() == Instruction::SetEQ ||
3613         I.getOpcode() == Instruction::SetNE) {
3614       bool isSetNE = I.getOpcode() == Instruction::SetNE;
3615
3616       // If the first operand is (and|or|xor) with a constant, and the second
3617       // operand is a constant, simplify a bit.
3618       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3619         switch (BO->getOpcode()) {
3620         case Instruction::Rem:
3621           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3622           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3623               BO->hasOneUse() &&
3624               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3625             int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3626             if (isPowerOf2_64(V)) {
3627               unsigned L2 = Log2_64(V);
3628               const Type *UTy = BO->getType()->getUnsignedVersion();
3629               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3630                                                              UTy, "tmp"), I);
3631               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3632               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3633                                                     RHSCst, BO->getName()), I);
3634               return BinaryOperator::create(I.getOpcode(), NewRem,
3635                                             Constant::getNullValue(UTy));
3636             }
3637           }
3638           break;
3639
3640         case Instruction::Add:
3641           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3642           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3643             if (BO->hasOneUse())
3644               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3645                                      ConstantExpr::getSub(CI, BOp1C));
3646           } else if (CI->isNullValue()) {
3647             // Replace ((add A, B) != 0) with (A != -B) if A or B is
3648             // efficiently invertible, or if the add has just this one use.
3649             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3650
3651             if (Value *NegVal = dyn_castNegVal(BOp1))
3652               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3653             else if (Value *NegVal = dyn_castNegVal(BOp0))
3654               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3655             else if (BO->hasOneUse()) {
3656               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3657               BO->setName("");
3658               InsertNewInstBefore(Neg, I);
3659               return new SetCondInst(I.getOpcode(), BOp0, Neg);
3660             }
3661           }
3662           break;
3663         case Instruction::Xor:
3664           // For the xor case, we can xor two constants together, eliminating
3665           // the explicit xor.
3666           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3667             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3668                                   ConstantExpr::getXor(CI, BOC));
3669
3670           // FALLTHROUGH
3671         case Instruction::Sub:
3672           // Replace (([sub|xor] A, B) != 0) with (A != B)
3673           if (CI->isNullValue())
3674             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3675                                    BO->getOperand(1));
3676           break;
3677
3678         case Instruction::Or:
3679           // If bits are being or'd in that are not present in the constant we
3680           // are comparing against, then the comparison could never succeed!
3681           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3682             Constant *NotCI = ConstantExpr::getNot(CI);
3683             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3684               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3685           }
3686           break;
3687
3688         case Instruction::And:
3689           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3690             // If bits are being compared against that are and'd out, then the
3691             // comparison can never succeed!
3692             if (!ConstantExpr::getAnd(CI,
3693                                       ConstantExpr::getNot(BOC))->isNullValue())
3694               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3695
3696             // If we have ((X & C) == C), turn it into ((X & C) != 0).
3697             if (CI == BOC && isOneBitSet(CI))
3698               return new SetCondInst(isSetNE ? Instruction::SetEQ :
3699                                      Instruction::SetNE, Op0,
3700                                      Constant::getNullValue(CI->getType()));
3701
3702             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3703             // to be a signed value as appropriate.
3704             if (isSignBit(BOC)) {
3705               Value *X = BO->getOperand(0);
3706               // If 'X' is not signed, insert a cast now...
3707               if (!BOC->getType()->isSigned()) {
3708                 const Type *DestTy = BOC->getType()->getSignedVersion();
3709                 X = InsertCastBefore(X, DestTy, I);
3710               }
3711               return new SetCondInst(isSetNE ? Instruction::SetLT :
3712                                          Instruction::SetGE, X,
3713                                      Constant::getNullValue(X->getType()));
3714             }
3715
3716             // ((X & ~7) == 0) --> X < 8
3717             if (CI->isNullValue() && isHighOnes(BOC)) {
3718               Value *X = BO->getOperand(0);
3719               Constant *NegX = ConstantExpr::getNeg(BOC);
3720
3721               // If 'X' is signed, insert a cast now.
3722               if (NegX->getType()->isSigned()) {
3723                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3724                 X = InsertCastBefore(X, DestTy, I);
3725                 NegX = ConstantExpr::getCast(NegX, DestTy);
3726               }
3727
3728               return new SetCondInst(isSetNE ? Instruction::SetGE :
3729                                      Instruction::SetLT, X, NegX);
3730             }
3731
3732           }
3733         default: break;
3734         }
3735       }
3736     } else {  // Not a SetEQ/SetNE
3737       // If the LHS is a cast from an integral value of the same size,
3738       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3739         Value *CastOp = Cast->getOperand(0);
3740         const Type *SrcTy = CastOp->getType();
3741         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3742         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3743             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3744           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3745                  "Source and destination signednesses should differ!");
3746           if (Cast->getType()->isSigned()) {
3747             // If this is a signed comparison, check for comparisons in the
3748             // vicinity of zero.
3749             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3750               // X < 0  => x > 127
3751               return BinaryOperator::createSetGT(CastOp,
3752                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3753             else if (I.getOpcode() == Instruction::SetGT &&
3754                      cast<ConstantSInt>(CI)->getValue() == -1)
3755               // X > -1  => x < 128
3756               return BinaryOperator::createSetLT(CastOp,
3757                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3758           } else {
3759             ConstantUInt *CUI = cast<ConstantUInt>(CI);
3760             if (I.getOpcode() == Instruction::SetLT &&
3761                 CUI->getValue() == 1ULL << (SrcTySize-1))
3762               // X < 128 => X > -1
3763               return BinaryOperator::createSetGT(CastOp,
3764                                                  ConstantSInt::get(SrcTy, -1));
3765             else if (I.getOpcode() == Instruction::SetGT &&
3766                      CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3767               // X > 127 => X < 0
3768               return BinaryOperator::createSetLT(CastOp,
3769                                                  Constant::getNullValue(SrcTy));
3770           }
3771         }
3772       }
3773     }
3774   }
3775
3776   // Handle setcc with constant RHS's that can be integer, FP or pointer.
3777   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3778     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3779       switch (LHSI->getOpcode()) {
3780       case Instruction::GetElementPtr:
3781         if (RHSC->isNullValue()) {
3782           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3783           bool isAllZeros = true;
3784           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3785             if (!isa<Constant>(LHSI->getOperand(i)) ||
3786                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3787               isAllZeros = false;
3788               break;
3789             }
3790           if (isAllZeros)
3791             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3792                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
3793         }
3794         break;
3795
3796       case Instruction::PHI:
3797         if (Instruction *NV = FoldOpIntoPhi(I))
3798           return NV;
3799         break;
3800       case Instruction::Select:
3801         // If either operand of the select is a constant, we can fold the
3802         // comparison into the select arms, which will cause one to be
3803         // constant folded and the select turned into a bitwise or.
3804         Value *Op1 = 0, *Op2 = 0;
3805         if (LHSI->hasOneUse()) {
3806           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3807             // Fold the known value into the constant operand.
3808             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3809             // Insert a new SetCC of the other select operand.
3810             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3811                                                       LHSI->getOperand(2), RHSC,
3812                                                       I.getName()), I);
3813           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3814             // Fold the known value into the constant operand.
3815             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3816             // Insert a new SetCC of the other select operand.
3817             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3818                                                       LHSI->getOperand(1), RHSC,
3819                                                       I.getName()), I);
3820           }
3821         }
3822
3823         if (Op1)
3824           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3825         break;
3826       }
3827   }
3828
3829   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3830   if (User *GEP = dyn_castGetElementPtr(Op0))
3831     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3832       return NI;
3833   if (User *GEP = dyn_castGetElementPtr(Op1))
3834     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3835                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
3836       return NI;
3837
3838   // Test to see if the operands of the setcc are casted versions of other
3839   // values.  If the cast can be stripped off both arguments, we do so now.
3840   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3841     Value *CastOp0 = CI->getOperand(0);
3842     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3843         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3844         (I.getOpcode() == Instruction::SetEQ ||
3845          I.getOpcode() == Instruction::SetNE)) {
3846       // We keep moving the cast from the left operand over to the right
3847       // operand, where it can often be eliminated completely.
3848       Op0 = CastOp0;
3849
3850       // If operand #1 is a cast instruction, see if we can eliminate it as
3851       // well.
3852       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3853         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3854                                                                Op0->getType()))
3855           Op1 = CI2->getOperand(0);
3856
3857       // If Op1 is a constant, we can fold the cast into the constant.
3858       if (Op1->getType() != Op0->getType())
3859         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3860           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3861         } else {
3862           // Otherwise, cast the RHS right before the setcc
3863           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3864           InsertNewInstBefore(cast<Instruction>(Op1), I);
3865         }
3866       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3867     }
3868
3869     // Handle the special case of: setcc (cast bool to X), <cst>
3870     // This comes up when you have code like
3871     //   int X = A < B;
3872     //   if (X) ...
3873     // For generality, we handle any zero-extension of any operand comparison
3874     // with a constant or another cast from the same type.
3875     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3876       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3877         return R;
3878   }
3879   
3880   if (I.getOpcode() == Instruction::SetNE ||
3881       I.getOpcode() == Instruction::SetEQ) {
3882     Value *A, *B;
3883     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3884         (A == Op1 || B == Op1)) {
3885       // (A^B) == A  ->  B == 0
3886       Value *OtherVal = A == Op1 ? B : A;
3887       return BinaryOperator::create(I.getOpcode(), OtherVal,
3888                                     Constant::getNullValue(A->getType()));
3889     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3890                (A == Op0 || B == Op0)) {
3891       // A == (A^B)  ->  B == 0
3892       Value *OtherVal = A == Op0 ? B : A;
3893       return BinaryOperator::create(I.getOpcode(), OtherVal,
3894                                     Constant::getNullValue(A->getType()));
3895     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
3896       // (A-B) == A  ->  B == 0
3897       return BinaryOperator::create(I.getOpcode(), B,
3898                                     Constant::getNullValue(B->getType()));
3899     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
3900       // A == (A-B)  ->  B == 0
3901       return BinaryOperator::create(I.getOpcode(), B,
3902                                     Constant::getNullValue(B->getType()));
3903     }
3904   }
3905   return Changed ? &I : 0;
3906 }
3907
3908 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3909 // We only handle extending casts so far.
3910 //
3911 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3912   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3913   const Type *SrcTy = LHSCIOp->getType();
3914   const Type *DestTy = SCI.getOperand(0)->getType();
3915   Value *RHSCIOp;
3916
3917   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3918     return 0;
3919
3920   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
3921   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3922   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
3923
3924   // Is this a sign or zero extension?
3925   bool isSignSrc  = SrcTy->isSigned();
3926   bool isSignDest = DestTy->isSigned();
3927
3928   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3929     // Not an extension from the same type?
3930     RHSCIOp = CI->getOperand(0);
3931     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3932   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3933     // Compute the constant that would happen if we truncated to SrcTy then
3934     // reextended to DestTy.
3935     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3936
3937     if (ConstantExpr::getCast(Res, DestTy) == CI) {
3938       RHSCIOp = Res;
3939     } else {
3940       // If the value cannot be represented in the shorter type, we cannot emit
3941       // a simple comparison.
3942       if (SCI.getOpcode() == Instruction::SetEQ)
3943         return ReplaceInstUsesWith(SCI, ConstantBool::False);
3944       if (SCI.getOpcode() == Instruction::SetNE)
3945         return ReplaceInstUsesWith(SCI, ConstantBool::True);
3946
3947       // Evaluate the comparison for LT.
3948       Value *Result;
3949       if (DestTy->isSigned()) {
3950         // We're performing a signed comparison.
3951         if (isSignSrc) {
3952           // Signed extend and signed comparison.
3953           if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3954             Result = ConstantBool::False;
3955           else
3956             Result = ConstantBool::True;              // X < (large) --> true
3957         } else {
3958           // Unsigned extend and signed comparison.
3959           if (cast<ConstantSInt>(CI)->getValue() < 0)
3960             Result = ConstantBool::False;
3961           else
3962             Result = ConstantBool::True;
3963         }
3964       } else {
3965         // We're performing an unsigned comparison.
3966         if (!isSignSrc) {
3967           // Unsigned extend & compare -> always true.
3968           Result = ConstantBool::True;
3969         } else {
3970           // We're performing an unsigned comp with a sign extended value.
3971           // This is true if the input is >= 0. [aka >s -1]
3972           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3973           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3974                                                   NegOne, SCI.getName()), SCI);
3975         }
3976       }
3977
3978       // Finally, return the value computed.
3979       if (SCI.getOpcode() == Instruction::SetLT) {
3980         return ReplaceInstUsesWith(SCI, Result);
3981       } else {
3982         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3983         if (Constant *CI = dyn_cast<Constant>(Result))
3984           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3985         else
3986           return BinaryOperator::createNot(Result);
3987       }
3988     }
3989   } else {
3990     return 0;
3991   }
3992
3993   // Okay, just insert a compare of the reduced operands now!
3994   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3995 }
3996
3997 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3998   assert(I.getOperand(1)->getType() == Type::UByteTy);
3999   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4000   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4001
4002   // shl X, 0 == X and shr X, 0 == X
4003   // shl 0, X == 0 and shr 0, X == 0
4004   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4005       Op0 == Constant::getNullValue(Op0->getType()))
4006     return ReplaceInstUsesWith(I, Op0);
4007   
4008   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
4009     if (!isLeftShift && I.getType()->isSigned())
4010       return ReplaceInstUsesWith(I, Op0);
4011     else                         // undef << X -> 0   AND  undef >>u X -> 0
4012       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4013   }
4014   if (isa<UndefValue>(Op1)) {
4015     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4016       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4017     else
4018       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
4019   }
4020
4021   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
4022   if (!isLeftShift)
4023     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4024       if (CSI->isAllOnesValue())
4025         return ReplaceInstUsesWith(I, CSI);
4026
4027   // Try to fold constant and into select arguments.
4028   if (isa<Constant>(Op0))
4029     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4030       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4031         return R;
4032
4033   // See if we can turn a signed shr into an unsigned shr.
4034   if (!isLeftShift && I.getType()->isSigned()) {
4035     if (MaskedValueIsZero(Op0,
4036                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4037       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4038       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4039                                             I.getName()), I);
4040       return new CastInst(V, I.getType());
4041     }
4042   }
4043
4044   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4045     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4046       return Res;
4047   return 0;
4048 }
4049
4050 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4051                                                ShiftInst &I) {
4052   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4053   bool isSignedShift = Op0->getType()->isSigned();
4054   bool isUnsignedShift = !isSignedShift;
4055
4056   // See if we can simplify any instructions used by the instruction whose sole 
4057   // purpose is to compute bits we don't care about.
4058   uint64_t KnownZero, KnownOne;
4059   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4060                            KnownZero, KnownOne))
4061     return &I;
4062   
4063   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4064   // of a signed value.
4065   //
4066   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4067   if (Op1->getValue() >= TypeBits) {
4068     if (isUnsignedShift || isLeftShift)
4069       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4070     else {
4071       I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4072       return &I;
4073     }
4074   }
4075   
4076   // ((X*C1) << C2) == (X * (C1 << C2))
4077   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4078     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4079       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4080         return BinaryOperator::createMul(BO->getOperand(0),
4081                                          ConstantExpr::getShl(BOOp, Op1));
4082   
4083   // Try to fold constant and into select arguments.
4084   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4085     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4086       return R;
4087   if (isa<PHINode>(Op0))
4088     if (Instruction *NV = FoldOpIntoPhi(I))
4089       return NV;
4090   
4091   if (Op0->hasOneUse()) {
4092     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4093       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
4094       Value *V1, *V2;
4095       ConstantInt *CC;
4096       switch (Op0BO->getOpcode()) {
4097         default: break;
4098         case Instruction::Add:
4099         case Instruction::And:
4100         case Instruction::Or:
4101         case Instruction::Xor:
4102           // These operators commute.
4103           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
4104           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4105               match(Op0BO->getOperand(1),
4106                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4107             Instruction *YS = new ShiftInst(Instruction::Shl, 
4108                                             Op0BO->getOperand(0), Op1,
4109                                             Op0BO->getName());
4110             InsertNewInstBefore(YS, I); // (Y << C)
4111             Instruction *X = 
4112               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4113                                      Op0BO->getOperand(1)->getName());
4114             InsertNewInstBefore(X, I);  // (X + (Y << C))
4115             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4116             C2 = ConstantExpr::getShl(C2, Op1);
4117             return BinaryOperator::createAnd(X, C2);
4118           }
4119           
4120           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
4121           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4122               match(Op0BO->getOperand(1),
4123                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
4124                           m_ConstantInt(CC))) && V2 == Op1 &&
4125       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4126             Instruction *YS = new ShiftInst(Instruction::Shl, 
4127                                             Op0BO->getOperand(0), Op1,
4128                                             Op0BO->getName());
4129             InsertNewInstBefore(YS, I); // (Y << C)
4130             Instruction *XM =
4131               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4132                                         V1->getName()+".mask");
4133             InsertNewInstBefore(XM, I); // X & (CC << C)
4134             
4135             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4136           }
4137           
4138           // FALL THROUGH.
4139         case Instruction::Sub:
4140           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
4141           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4142               match(Op0BO->getOperand(0),
4143                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4144             Instruction *YS = new ShiftInst(Instruction::Shl, 
4145                                             Op0BO->getOperand(1), Op1,
4146                                             Op0BO->getName());
4147             InsertNewInstBefore(YS, I); // (Y << C)
4148             Instruction *X =
4149               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4150                                      Op0BO->getOperand(0)->getName());
4151             InsertNewInstBefore(X, I);  // (X + (Y << C))
4152             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4153             C2 = ConstantExpr::getShl(C2, Op1);
4154             return BinaryOperator::createAnd(X, C2);
4155           }
4156           
4157           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4158               match(Op0BO->getOperand(0),
4159                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
4160                           m_ConstantInt(CC))) && V2 == Op1 &&
4161               cast<BinaryOperator>(Op0BO->getOperand(0))
4162                   ->getOperand(0)->hasOneUse()) {
4163             Instruction *YS = new ShiftInst(Instruction::Shl, 
4164                                             Op0BO->getOperand(1), Op1,
4165                                             Op0BO->getName());
4166             InsertNewInstBefore(YS, I); // (Y << C)
4167             Instruction *XM =
4168               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4169                                         V1->getName()+".mask");
4170             InsertNewInstBefore(XM, I); // X & (CC << C)
4171             
4172             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4173           }
4174           
4175           break;
4176       }
4177       
4178       
4179       // If the operand is an bitwise operator with a constant RHS, and the
4180       // shift is the only use, we can pull it out of the shift.
4181       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4182         bool isValid = true;     // Valid only for And, Or, Xor
4183         bool highBitSet = false; // Transform if high bit of constant set?
4184         
4185         switch (Op0BO->getOpcode()) {
4186           default: isValid = false; break;   // Do not perform transform!
4187           case Instruction::Add:
4188             isValid = isLeftShift;
4189             break;
4190           case Instruction::Or:
4191           case Instruction::Xor:
4192             highBitSet = false;
4193             break;
4194           case Instruction::And:
4195             highBitSet = true;
4196             break;
4197         }
4198         
4199         // If this is a signed shift right, and the high bit is modified
4200         // by the logical operation, do not perform the transformation.
4201         // The highBitSet boolean indicates the value of the high bit of
4202         // the constant which would cause it to be modified for this
4203         // operation.
4204         //
4205         if (isValid && !isLeftShift && isSignedShift) {
4206           uint64_t Val = Op0C->getRawValue();
4207           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4208         }
4209         
4210         if (isValid) {
4211           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4212           
4213           Instruction *NewShift =
4214             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4215                           Op0BO->getName());
4216           Op0BO->setName("");
4217           InsertNewInstBefore(NewShift, I);
4218           
4219           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4220                                         NewRHS);
4221         }
4222       }
4223     }
4224   }
4225   
4226   // Find out if this is a shift of a shift by a constant.
4227   ShiftInst *ShiftOp = 0;
4228   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4229     ShiftOp = Op0SI;
4230   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4231     // If this is a noop-integer case of a shift instruction, use the shift.
4232     if (CI->getOperand(0)->getType()->isInteger() &&
4233         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4234         CI->getType()->getPrimitiveSizeInBits() &&
4235         isa<ShiftInst>(CI->getOperand(0))) {
4236       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4237     }
4238   }
4239   
4240   if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4241     // Find the operands and properties of the input shift.  Note that the
4242     // signedness of the input shift may differ from the current shift if there
4243     // is a noop cast between the two.
4244     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4245     bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4246     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4247     
4248     ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4249
4250     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4251     unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4252     
4253     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
4254     if (isLeftShift == isShiftOfLeftShift) {
4255       // Do not fold these shifts if the first one is signed and the second one
4256       // is unsigned and this is a right shift.  Further, don't do any folding
4257       // on them.
4258       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4259         return 0;
4260       
4261       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
4262       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4263         Amt = Op0->getType()->getPrimitiveSizeInBits();
4264       
4265       Value *Op = ShiftOp->getOperand(0);
4266       if (isShiftOfSignedShift != isSignedShift)
4267         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4268       return new ShiftInst(I.getOpcode(), Op,
4269                            ConstantUInt::get(Type::UByteTy, Amt));
4270     }
4271     
4272     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
4273     // signed types, we can only support the (A >> c1) << c2 configuration,
4274     // because it can not turn an arbitrary bit of A into a sign bit.
4275     if (isUnsignedShift || isLeftShift) {
4276       // Calculate bitmask for what gets shifted off the edge.
4277       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4278       if (isLeftShift)
4279         C = ConstantExpr::getShl(C, ShiftAmt1C);
4280       else
4281         C = ConstantExpr::getUShr(C, ShiftAmt1C);
4282       
4283       Value *Op = ShiftOp->getOperand(0);
4284       if (isShiftOfSignedShift != isSignedShift)
4285         Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4286       
4287       Instruction *Mask =
4288         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4289       InsertNewInstBefore(Mask, I);
4290       
4291       // Figure out what flavor of shift we should use...
4292       if (ShiftAmt1 == ShiftAmt2) {
4293         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
4294       } else if (ShiftAmt1 < ShiftAmt2) {
4295         return new ShiftInst(I.getOpcode(), Mask,
4296                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4297       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4298         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4299           // Make sure to emit an unsigned shift right, not a signed one.
4300           Mask = InsertNewInstBefore(new CastInst(Mask, 
4301                                         Mask->getType()->getUnsignedVersion(),
4302                                                   Op->getName()), I);
4303           Mask = new ShiftInst(Instruction::Shr, Mask,
4304                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4305           InsertNewInstBefore(Mask, I);
4306           return new CastInst(Mask, I.getType());
4307         } else {
4308           return new ShiftInst(ShiftOp->getOpcode(), Mask,
4309                     ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4310         }
4311       } else {
4312         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
4313         Op = InsertNewInstBefore(new CastInst(Mask,
4314                                               I.getType()->getSignedVersion(),
4315                                               Mask->getName()), I);
4316         Instruction *Shift =
4317           new ShiftInst(ShiftOp->getOpcode(), Op,
4318                         ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4319         InsertNewInstBefore(Shift, I);
4320         
4321         C = ConstantIntegral::getAllOnesValue(Shift->getType());
4322         C = ConstantExpr::getShl(C, Op1);
4323         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4324         InsertNewInstBefore(Mask, I);
4325         return new CastInst(Mask, I.getType());
4326       }
4327     } else {
4328       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
4329       // this case, C1 == C2 and C1 is 8, 16, or 32.
4330       if (ShiftAmt1 == ShiftAmt2) {
4331         const Type *SExtType = 0;
4332         switch (ShiftAmt1) {
4333         case 8 : SExtType = Type::SByteTy; break;
4334         case 16: SExtType = Type::ShortTy; break;
4335         case 32: SExtType = Type::IntTy; break;
4336         }
4337         
4338         if (SExtType) {
4339           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4340                                                SExtType, "sext");
4341           InsertNewInstBefore(NewTrunc, I);
4342           return new CastInst(NewTrunc, I.getType());
4343         }
4344       }
4345     }
4346   }
4347   return 0;
4348 }
4349
4350 enum CastType {
4351   Noop     = 0,
4352   Truncate = 1,
4353   Signext  = 2,
4354   Zeroext  = 3
4355 };
4356
4357 /// getCastType - In the future, we will split the cast instruction into these
4358 /// various types.  Until then, we have to do the analysis here.
4359 static CastType getCastType(const Type *Src, const Type *Dest) {
4360   assert(Src->isIntegral() && Dest->isIntegral() &&
4361          "Only works on integral types!");
4362   unsigned SrcSize = Src->getPrimitiveSizeInBits();
4363   unsigned DestSize = Dest->getPrimitiveSizeInBits();
4364
4365   if (SrcSize == DestSize) return Noop;
4366   if (SrcSize > DestSize)  return Truncate;
4367   if (Src->isSigned()) return Signext;
4368   return Zeroext;
4369 }
4370
4371
4372 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4373 // instruction.
4374 //
4375 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4376                                    const Type *DstTy, TargetData *TD) {
4377
4378   // It is legal to eliminate the instruction if casting A->B->A if the sizes
4379   // are identical and the bits don't get reinterpreted (for example
4380   // int->float->int would not be allowed).
4381   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
4382     return true;
4383
4384   // If we are casting between pointer and integer types, treat pointers as
4385   // integers of the appropriate size for the code below.
4386   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4387   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4388   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
4389
4390   // Allow free casting and conversion of sizes as long as the sign doesn't
4391   // change...
4392   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
4393     CastType FirstCast = getCastType(SrcTy, MidTy);
4394     CastType SecondCast = getCastType(MidTy, DstTy);
4395
4396     // Capture the effect of these two casts.  If the result is a legal cast,
4397     // the CastType is stored here, otherwise a special code is used.
4398     static const unsigned CastResult[] = {
4399       // First cast is noop
4400       0, 1, 2, 3,
4401       // First cast is a truncate
4402       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
4403       // First cast is a sign ext
4404       2, 5, 2, 4,         // signext->zeroext never ok
4405       // First cast is a zero ext
4406       3, 5, 3, 3,
4407     };
4408
4409     unsigned Result = CastResult[FirstCast*4+SecondCast];
4410     switch (Result) {
4411     default: assert(0 && "Illegal table value!");
4412     case 0:
4413     case 1:
4414     case 2:
4415     case 3:
4416       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4417       // truncates, we could eliminate more casts.
4418       return (unsigned)getCastType(SrcTy, DstTy) == Result;
4419     case 4:
4420       return false;  // Not possible to eliminate this here.
4421     case 5:
4422       // Sign or zero extend followed by truncate is always ok if the result
4423       // is a truncate or noop.
4424       CastType ResultCast = getCastType(SrcTy, DstTy);
4425       if (ResultCast == Noop || ResultCast == Truncate)
4426         return true;
4427       // Otherwise we are still growing the value, we are only safe if the
4428       // result will match the sign/zeroextendness of the result.
4429       return ResultCast == FirstCast;
4430     }
4431   }
4432   
4433   // If this is a cast from 'float -> double -> integer', cast from
4434   // 'float -> integer' directly, as the value isn't changed by the 
4435   // float->double conversion.
4436   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4437       DstTy->isIntegral() && 
4438       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4439     return true;
4440   
4441   return false;
4442 }
4443
4444 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4445   if (V->getType() == Ty || isa<Constant>(V)) return false;
4446   if (const CastInst *CI = dyn_cast<CastInst>(V))
4447     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4448                                TD))
4449       return false;
4450   return true;
4451 }
4452
4453 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4454 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
4455 /// casts that are known to not do anything...
4456 ///
4457 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4458                                              Instruction *InsertBefore) {
4459   if (V->getType() == DestTy) return V;
4460   if (Constant *C = dyn_cast<Constant>(V))
4461     return ConstantExpr::getCast(C, DestTy);
4462
4463   CastInst *CI = new CastInst(V, DestTy, V->getName());
4464   InsertNewInstBefore(CI, *InsertBefore);
4465   return CI;
4466 }
4467
4468 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4469 /// expression.  If so, decompose it, returning some value X, such that Val is
4470 /// X*Scale+Offset.
4471 ///
4472 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4473                                         unsigned &Offset) {
4474   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4475   if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4476     Offset = CI->getValue();
4477     Scale  = 1;
4478     return ConstantUInt::get(Type::UIntTy, 0);
4479   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4480     if (I->getNumOperands() == 2) {
4481       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4482         if (I->getOpcode() == Instruction::Shl) {
4483           // This is a value scaled by '1 << the shift amt'.
4484           Scale = 1U << CUI->getValue();
4485           Offset = 0;
4486           return I->getOperand(0);
4487         } else if (I->getOpcode() == Instruction::Mul) {
4488           // This value is scaled by 'CUI'.
4489           Scale = CUI->getValue();
4490           Offset = 0;
4491           return I->getOperand(0);
4492         } else if (I->getOpcode() == Instruction::Add) {
4493           // We have X+C.  Check to see if we really have (X*C2)+C1, where C1 is
4494           // divisible by C2.
4495           unsigned SubScale;
4496           Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4497                                                     Offset);
4498           Offset += CUI->getValue();
4499           if (SubScale > 1 && (Offset % SubScale == 0)) {
4500             Scale = SubScale;
4501             return SubVal;
4502           }
4503         }
4504       }
4505     }
4506   }
4507
4508   // Otherwise, we can't look past this.
4509   Scale = 1;
4510   Offset = 0;
4511   return Val;
4512 }
4513
4514
4515 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4516 /// try to eliminate the cast by moving the type information into the alloc.
4517 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4518                                                    AllocationInst &AI) {
4519   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4520   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
4521   
4522   // Remove any uses of AI that are dead.
4523   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4524   std::vector<Instruction*> DeadUsers;
4525   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4526     Instruction *User = cast<Instruction>(*UI++);
4527     if (isInstructionTriviallyDead(User)) {
4528       while (UI != E && *UI == User)
4529         ++UI; // If this instruction uses AI more than once, don't break UI.
4530       
4531       // Add operands to the worklist.
4532       AddUsesToWorkList(*User);
4533       ++NumDeadInst;
4534       DEBUG(std::cerr << "IC: DCE: " << *User);
4535       
4536       User->eraseFromParent();
4537       removeFromWorkList(User);
4538     }
4539   }
4540   
4541   // Get the type really allocated and the type casted to.
4542   const Type *AllocElTy = AI.getAllocatedType();
4543   const Type *CastElTy = PTy->getElementType();
4544   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4545
4546   unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4547   unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4548   if (CastElTyAlign < AllocElTyAlign) return 0;
4549
4550   // If the allocation has multiple uses, only promote it if we are strictly
4551   // increasing the alignment of the resultant allocation.  If we keep it the
4552   // same, we open the door to infinite loops of various kinds.
4553   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4554
4555   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4556   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4557   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4558
4559   // See if we can satisfy the modulus by pulling a scale out of the array
4560   // size argument.
4561   unsigned ArraySizeScale, ArrayOffset;
4562   Value *NumElements = // See if the array size is a decomposable linear expr.
4563     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4564  
4565   // If we can now satisfy the modulus, by using a non-1 scale, we really can
4566   // do the xform.
4567   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4568       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
4569
4570   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4571   Value *Amt = 0;
4572   if (Scale == 1) {
4573     Amt = NumElements;
4574   } else {
4575     Amt = ConstantUInt::get(Type::UIntTy, Scale);
4576     if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4577       Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4578     else if (Scale != 1) {
4579       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4580       Amt = InsertNewInstBefore(Tmp, AI);
4581     }
4582   }
4583   
4584   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4585     Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4586     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4587     Amt = InsertNewInstBefore(Tmp, AI);
4588   }
4589   
4590   std::string Name = AI.getName(); AI.setName("");
4591   AllocationInst *New;
4592   if (isa<MallocInst>(AI))
4593     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4594   else
4595     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4596   InsertNewInstBefore(New, AI);
4597   
4598   // If the allocation has multiple uses, insert a cast and change all things
4599   // that used it to use the new cast.  This will also hack on CI, but it will
4600   // die soon.
4601   if (!AI.hasOneUse()) {
4602     AddUsesToWorkList(AI);
4603     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4604     InsertNewInstBefore(NewCast, AI);
4605     AI.replaceAllUsesWith(NewCast);
4606   }
4607   return ReplaceInstUsesWith(CI, New);
4608 }
4609
4610
4611 // CastInst simplification
4612 //
4613 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4614   Value *Src = CI.getOperand(0);
4615
4616   // If the user is casting a value to the same type, eliminate this cast
4617   // instruction...
4618   if (CI.getType() == Src->getType())
4619     return ReplaceInstUsesWith(CI, Src);
4620
4621   if (isa<UndefValue>(Src))   // cast undef -> undef
4622     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4623
4624   // If casting the result of another cast instruction, try to eliminate this
4625   // one!
4626   //
4627   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
4628     Value *A = CSrc->getOperand(0);
4629     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4630                                CI.getType(), TD)) {
4631       // This instruction now refers directly to the cast's src operand.  This
4632       // has a good chance of making CSrc dead.
4633       CI.setOperand(0, CSrc->getOperand(0));
4634       return &CI;
4635     }
4636
4637     // If this is an A->B->A cast, and we are dealing with integral types, try
4638     // to convert this into a logical 'and' instruction.
4639     //
4640     if (A->getType()->isInteger() &&
4641         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4642         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
4643         CSrc->getType()->getPrimitiveSizeInBits() <
4644                     CI.getType()->getPrimitiveSizeInBits()&&
4645         A->getType()->getPrimitiveSizeInBits() ==
4646               CI.getType()->getPrimitiveSizeInBits()) {
4647       assert(CSrc->getType() != Type::ULongTy &&
4648              "Cannot have type bigger than ulong!");
4649       uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4650       Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4651                                           AndValue);
4652       AndOp = ConstantExpr::getCast(AndOp, A->getType());
4653       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4654       if (And->getType() != CI.getType()) {
4655         And->setName(CSrc->getName()+".mask");
4656         InsertNewInstBefore(And, CI);
4657         And = new CastInst(And, CI.getType());
4658       }
4659       return And;
4660     }
4661   }
4662   
4663   // If this is a cast to bool, turn it into the appropriate setne instruction.
4664   if (CI.getType() == Type::BoolTy)
4665     return BinaryOperator::createSetNE(CI.getOperand(0),
4666                        Constant::getNullValue(CI.getOperand(0)->getType()));
4667
4668   // See if we can simplify any instructions used by the LHS whose sole 
4669   // purpose is to compute bits we don't care about.
4670   if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4671     uint64_t KnownZero, KnownOne;
4672     if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4673                              KnownZero, KnownOne))
4674       return &CI;
4675   }
4676   
4677   // If casting the result of a getelementptr instruction with no offset, turn
4678   // this into a cast of the original pointer!
4679   //
4680   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4681     bool AllZeroOperands = true;
4682     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4683       if (!isa<Constant>(GEP->getOperand(i)) ||
4684           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4685         AllZeroOperands = false;
4686         break;
4687       }
4688     if (AllZeroOperands) {
4689       CI.setOperand(0, GEP->getOperand(0));
4690       return &CI;
4691     }
4692   }
4693
4694   // If we are casting a malloc or alloca to a pointer to a type of the same
4695   // size, rewrite the allocation instruction to allocate the "right" type.
4696   //
4697   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4698     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4699       return V;
4700
4701   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4702     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4703       return NV;
4704   if (isa<PHINode>(Src))
4705     if (Instruction *NV = FoldOpIntoPhi(CI))
4706       return NV;
4707
4708   // If the source value is an instruction with only this use, we can attempt to
4709   // propagate the cast into the instruction.  Also, only handle integral types
4710   // for now.
4711   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4712     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4713         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
4714       const Type *DestTy = CI.getType();
4715       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4716       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4717
4718       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4719       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4720
4721       switch (SrcI->getOpcode()) {
4722       case Instruction::Add:
4723       case Instruction::Mul:
4724       case Instruction::And:
4725       case Instruction::Or:
4726       case Instruction::Xor:
4727         // If we are discarding information, or just changing the sign, rewrite.
4728         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4729           // Don't insert two casts if they cannot be eliminated.  We allow two
4730           // casts to be inserted if the sizes are the same.  This could only be
4731           // converting signedness, which is a noop.
4732           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4733               !ValueRequiresCast(Op0, DestTy, TD)) {
4734             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4735             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4736             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4737                              ->getOpcode(), Op0c, Op1c);
4738           }
4739         }
4740
4741         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
4742         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4743             Op1 == ConstantBool::True &&
4744             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4745           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4746           return BinaryOperator::createXor(New,
4747                                            ConstantInt::get(CI.getType(), 1));
4748         }
4749         break;
4750       case Instruction::Shl:
4751         // Allow changing the sign of the source operand.  Do not allow changing
4752         // the size of the shift, UNLESS the shift amount is a constant.  We
4753         // mush not change variable sized shifts to a smaller size, because it
4754         // is undefined to shift more bits out than exist in the value.
4755         if (DestBitSize == SrcBitSize ||
4756             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4757           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4758           return new ShiftInst(Instruction::Shl, Op0c, Op1);
4759         }
4760         break;
4761       case Instruction::Shr:
4762         // If this is a signed shr, and if all bits shifted in are about to be
4763         // truncated off, turn it into an unsigned shr to allow greater
4764         // simplifications.
4765         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4766             isa<ConstantInt>(Op1)) {
4767           unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4768           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4769             // Convert to unsigned.
4770             Value *N1 = InsertOperandCastBefore(Op0,
4771                                      Op0->getType()->getUnsignedVersion(), &CI);
4772             // Insert the new shift, which is now unsigned.
4773             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4774                                                    Op1, Src->getName()), CI);
4775             return new CastInst(N1, CI.getType());
4776           }
4777         }
4778         break;
4779
4780       case Instruction::SetEQ:
4781       case Instruction::SetNE:
4782         // We if we are just checking for a seteq of a single bit and casting it
4783         // to an integer.  If so, shift the bit to the appropriate place then
4784         // cast to integer to avoid the comparison.
4785         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4786           uint64_t Op1CV = Op1C->getZExtValue();
4787           // cast (X == 0) to int --> X^1        iff X has only the low bit set.
4788           // cast (X == 0) to int --> (X>>1)^1   iff X has only the 2nd bit set.
4789           // cast (X == 1) to int --> X          iff X has only the low bit set.
4790           // cast (X == 2) to int --> X>>1       iff X has only the 2nd bit set.
4791           // cast (X != 0) to int --> X          iff X has only the low bit set.
4792           // cast (X != 0) to int --> X>>1       iff X has only the 2nd bit set.
4793           // cast (X != 1) to int --> X^1        iff X has only the low bit set.
4794           // cast (X != 2) to int --> (X>>1)^1   iff X has only the 2nd bit set.
4795           if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4796             // If Op1C some other power of two, convert:
4797             uint64_t KnownZero, KnownOne;
4798             uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4799             ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4800             
4801             if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4802               bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4803               if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4804                 // (X&4) == 2 --> false
4805                 // (X&4) != 2 --> true
4806                 return ReplaceInstUsesWith(CI, ConstantBool::get(isSetNE));
4807               }
4808               
4809               unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4810               Value *In = Op0;
4811               if (ShiftAmt) {
4812                 // Perform an unsigned shr by shiftamt.  Convert input to
4813                 // unsigned if it is signed.
4814                 if (In->getType()->isSigned())
4815                   In = InsertNewInstBefore(new CastInst(In,
4816                         In->getType()->getUnsignedVersion(), In->getName()),CI);
4817                 // Insert the shift to put the result in the low bit.
4818                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4819                                      ConstantInt::get(Type::UByteTy, ShiftAmt),
4820                                      In->getName()+".lobit"), CI);
4821               }
4822               
4823               if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4824                 Constant *One = ConstantInt::get(In->getType(), 1);
4825                 In = BinaryOperator::createXor(In, One, "tmp");
4826                 InsertNewInstBefore(cast<Instruction>(In), CI);
4827               }
4828               
4829               if (CI.getType() == In->getType())
4830                 return ReplaceInstUsesWith(CI, In);
4831               else
4832                 return new CastInst(In, CI.getType());
4833             }
4834           }
4835         }
4836         break;
4837       }
4838     }
4839       
4840   return 0;
4841 }
4842
4843 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4844 ///   %C = or %A, %B
4845 ///   %D = select %cond, %C, %A
4846 /// into:
4847 ///   %C = select %cond, %B, 0
4848 ///   %D = or %A, %C
4849 ///
4850 /// Assuming that the specified instruction is an operand to the select, return
4851 /// a bitmask indicating which operands of this instruction are foldable if they
4852 /// equal the other incoming value of the select.
4853 ///
4854 static unsigned GetSelectFoldableOperands(Instruction *I) {
4855   switch (I->getOpcode()) {
4856   case Instruction::Add:
4857   case Instruction::Mul:
4858   case Instruction::And:
4859   case Instruction::Or:
4860   case Instruction::Xor:
4861     return 3;              // Can fold through either operand.
4862   case Instruction::Sub:   // Can only fold on the amount subtracted.
4863   case Instruction::Shl:   // Can only fold on the shift amount.
4864   case Instruction::Shr:
4865     return 1;
4866   default:
4867     return 0;              // Cannot fold
4868   }
4869 }
4870
4871 /// GetSelectFoldableConstant - For the same transformation as the previous
4872 /// function, return the identity constant that goes into the select.
4873 static Constant *GetSelectFoldableConstant(Instruction *I) {
4874   switch (I->getOpcode()) {
4875   default: assert(0 && "This cannot happen!"); abort();
4876   case Instruction::Add:
4877   case Instruction::Sub:
4878   case Instruction::Or:
4879   case Instruction::Xor:
4880     return Constant::getNullValue(I->getType());
4881   case Instruction::Shl:
4882   case Instruction::Shr:
4883     return Constant::getNullValue(Type::UByteTy);
4884   case Instruction::And:
4885     return ConstantInt::getAllOnesValue(I->getType());
4886   case Instruction::Mul:
4887     return ConstantInt::get(I->getType(), 1);
4888   }
4889 }
4890
4891 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4892 /// have the same opcode and only one use each.  Try to simplify this.
4893 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4894                                           Instruction *FI) {
4895   if (TI->getNumOperands() == 1) {
4896     // If this is a non-volatile load or a cast from the same type,
4897     // merge.
4898     if (TI->getOpcode() == Instruction::Cast) {
4899       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4900         return 0;
4901     } else {
4902       return 0;  // unknown unary op.
4903     }
4904
4905     // Fold this by inserting a select from the input values.
4906     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4907                                        FI->getOperand(0), SI.getName()+".v");
4908     InsertNewInstBefore(NewSI, SI);
4909     return new CastInst(NewSI, TI->getType());
4910   }
4911
4912   // Only handle binary operators here.
4913   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4914     return 0;
4915
4916   // Figure out if the operations have any operands in common.
4917   Value *MatchOp, *OtherOpT, *OtherOpF;
4918   bool MatchIsOpZero;
4919   if (TI->getOperand(0) == FI->getOperand(0)) {
4920     MatchOp  = TI->getOperand(0);
4921     OtherOpT = TI->getOperand(1);
4922     OtherOpF = FI->getOperand(1);
4923     MatchIsOpZero = true;
4924   } else if (TI->getOperand(1) == FI->getOperand(1)) {
4925     MatchOp  = TI->getOperand(1);
4926     OtherOpT = TI->getOperand(0);
4927     OtherOpF = FI->getOperand(0);
4928     MatchIsOpZero = false;
4929   } else if (!TI->isCommutative()) {
4930     return 0;
4931   } else if (TI->getOperand(0) == FI->getOperand(1)) {
4932     MatchOp  = TI->getOperand(0);
4933     OtherOpT = TI->getOperand(1);
4934     OtherOpF = FI->getOperand(0);
4935     MatchIsOpZero = true;
4936   } else if (TI->getOperand(1) == FI->getOperand(0)) {
4937     MatchOp  = TI->getOperand(1);
4938     OtherOpT = TI->getOperand(0);
4939     OtherOpF = FI->getOperand(1);
4940     MatchIsOpZero = true;
4941   } else {
4942     return 0;
4943   }
4944
4945   // If we reach here, they do have operations in common.
4946   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4947                                      OtherOpF, SI.getName()+".v");
4948   InsertNewInstBefore(NewSI, SI);
4949
4950   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4951     if (MatchIsOpZero)
4952       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4953     else
4954       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4955   } else {
4956     if (MatchIsOpZero)
4957       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4958     else
4959       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4960   }
4961 }
4962
4963 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4964   Value *CondVal = SI.getCondition();
4965   Value *TrueVal = SI.getTrueValue();
4966   Value *FalseVal = SI.getFalseValue();
4967
4968   // select true, X, Y  -> X
4969   // select false, X, Y -> Y
4970   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4971     if (C == ConstantBool::True)
4972       return ReplaceInstUsesWith(SI, TrueVal);
4973     else {
4974       assert(C == ConstantBool::False);
4975       return ReplaceInstUsesWith(SI, FalseVal);
4976     }
4977
4978   // select C, X, X -> X
4979   if (TrueVal == FalseVal)
4980     return ReplaceInstUsesWith(SI, TrueVal);
4981
4982   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
4983     return ReplaceInstUsesWith(SI, FalseVal);
4984   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
4985     return ReplaceInstUsesWith(SI, TrueVal);
4986   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
4987     if (isa<Constant>(TrueVal))
4988       return ReplaceInstUsesWith(SI, TrueVal);
4989     else
4990       return ReplaceInstUsesWith(SI, FalseVal);
4991   }
4992
4993   if (SI.getType() == Type::BoolTy)
4994     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4995       if (C == ConstantBool::True) {
4996         // Change: A = select B, true, C --> A = or B, C
4997         return BinaryOperator::createOr(CondVal, FalseVal);
4998       } else {
4999         // Change: A = select B, false, C --> A = and !B, C
5000         Value *NotCond =
5001           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5002                                              "not."+CondVal->getName()), SI);
5003         return BinaryOperator::createAnd(NotCond, FalseVal);
5004       }
5005     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5006       if (C == ConstantBool::False) {
5007         // Change: A = select B, C, false --> A = and B, C
5008         return BinaryOperator::createAnd(CondVal, TrueVal);
5009       } else {
5010         // Change: A = select B, C, true --> A = or !B, C
5011         Value *NotCond =
5012           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5013                                              "not."+CondVal->getName()), SI);
5014         return BinaryOperator::createOr(NotCond, TrueVal);
5015       }
5016     }
5017
5018   // Selecting between two integer constants?
5019   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5020     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5021       // select C, 1, 0 -> cast C to int
5022       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5023         return new CastInst(CondVal, SI.getType());
5024       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5025         // select C, 0, 1 -> cast !C to int
5026         Value *NotCond =
5027           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5028                                                "not."+CondVal->getName()), SI);
5029         return new CastInst(NotCond, SI.getType());
5030       }
5031
5032       // If one of the constants is zero (we know they can't both be) and we
5033       // have a setcc instruction with zero, and we have an 'and' with the
5034       // non-constant value, eliminate this whole mess.  This corresponds to
5035       // cases like this: ((X & 27) ? 27 : 0)
5036       if (TrueValC->isNullValue() || FalseValC->isNullValue())
5037         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5038           if ((IC->getOpcode() == Instruction::SetEQ ||
5039                IC->getOpcode() == Instruction::SetNE) &&
5040               isa<ConstantInt>(IC->getOperand(1)) &&
5041               cast<Constant>(IC->getOperand(1))->isNullValue())
5042             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5043               if (ICA->getOpcode() == Instruction::And &&
5044                   isa<ConstantInt>(ICA->getOperand(1)) &&
5045                   (ICA->getOperand(1) == TrueValC ||
5046                    ICA->getOperand(1) == FalseValC) &&
5047                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5048                 // Okay, now we know that everything is set up, we just don't
5049                 // know whether we have a setne or seteq and whether the true or
5050                 // false val is the zero.
5051                 bool ShouldNotVal = !TrueValC->isNullValue();
5052                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5053                 Value *V = ICA;
5054                 if (ShouldNotVal)
5055                   V = InsertNewInstBefore(BinaryOperator::create(
5056                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
5057                 return ReplaceInstUsesWith(SI, V);
5058               }
5059     }
5060
5061   // See if we are selecting two values based on a comparison of the two values.
5062   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5063     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5064       // Transform (X == Y) ? X : Y  -> Y
5065       if (SCI->getOpcode() == Instruction::SetEQ)
5066         return ReplaceInstUsesWith(SI, FalseVal);
5067       // Transform (X != Y) ? X : Y  -> X
5068       if (SCI->getOpcode() == Instruction::SetNE)
5069         return ReplaceInstUsesWith(SI, TrueVal);
5070       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5071
5072     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5073       // Transform (X == Y) ? Y : X  -> X
5074       if (SCI->getOpcode() == Instruction::SetEQ)
5075         return ReplaceInstUsesWith(SI, FalseVal);
5076       // Transform (X != Y) ? Y : X  -> Y
5077       if (SCI->getOpcode() == Instruction::SetNE)
5078         return ReplaceInstUsesWith(SI, TrueVal);
5079       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5080     }
5081   }
5082
5083   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5084     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5085       if (TI->hasOneUse() && FI->hasOneUse()) {
5086         bool isInverse = false;
5087         Instruction *AddOp = 0, *SubOp = 0;
5088
5089         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5090         if (TI->getOpcode() == FI->getOpcode())
5091           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5092             return IV;
5093
5094         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
5095         // even legal for FP.
5096         if (TI->getOpcode() == Instruction::Sub &&
5097             FI->getOpcode() == Instruction::Add) {
5098           AddOp = FI; SubOp = TI;
5099         } else if (FI->getOpcode() == Instruction::Sub &&
5100                    TI->getOpcode() == Instruction::Add) {
5101           AddOp = TI; SubOp = FI;
5102         }
5103
5104         if (AddOp) {
5105           Value *OtherAddOp = 0;
5106           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5107             OtherAddOp = AddOp->getOperand(1);
5108           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5109             OtherAddOp = AddOp->getOperand(0);
5110           }
5111
5112           if (OtherAddOp) {
5113             // So at this point we know we have (Y -> OtherAddOp):
5114             //        select C, (add X, Y), (sub X, Z)
5115             Value *NegVal;  // Compute -Z
5116             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5117               NegVal = ConstantExpr::getNeg(C);
5118             } else {
5119               NegVal = InsertNewInstBefore(
5120                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5121             }
5122
5123             Value *NewTrueOp = OtherAddOp;
5124             Value *NewFalseOp = NegVal;
5125             if (AddOp != TI)
5126               std::swap(NewTrueOp, NewFalseOp);
5127             Instruction *NewSel =
5128               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5129
5130             NewSel = InsertNewInstBefore(NewSel, SI);
5131             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5132           }
5133         }
5134       }
5135
5136   // See if we can fold the select into one of our operands.
5137   if (SI.getType()->isInteger()) {
5138     // See the comment above GetSelectFoldableOperands for a description of the
5139     // transformation we are doing here.
5140     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5141       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5142           !isa<Constant>(FalseVal))
5143         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5144           unsigned OpToFold = 0;
5145           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5146             OpToFold = 1;
5147           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5148             OpToFold = 2;
5149           }
5150
5151           if (OpToFold) {
5152             Constant *C = GetSelectFoldableConstant(TVI);
5153             std::string Name = TVI->getName(); TVI->setName("");
5154             Instruction *NewSel =
5155               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5156                              Name);
5157             InsertNewInstBefore(NewSel, SI);
5158             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5159               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5160             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5161               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5162             else {
5163               assert(0 && "Unknown instruction!!");
5164             }
5165           }
5166         }
5167
5168     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5169       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5170           !isa<Constant>(TrueVal))
5171         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5172           unsigned OpToFold = 0;
5173           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5174             OpToFold = 1;
5175           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5176             OpToFold = 2;
5177           }
5178
5179           if (OpToFold) {
5180             Constant *C = GetSelectFoldableConstant(FVI);
5181             std::string Name = FVI->getName(); FVI->setName("");
5182             Instruction *NewSel =
5183               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5184                              Name);
5185             InsertNewInstBefore(NewSel, SI);
5186             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5187               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5188             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5189               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5190             else {
5191               assert(0 && "Unknown instruction!!");
5192             }
5193           }
5194         }
5195   }
5196
5197   if (BinaryOperator::isNot(CondVal)) {
5198     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5199     SI.setOperand(1, FalseVal);
5200     SI.setOperand(2, TrueVal);
5201     return &SI;
5202   }
5203
5204   return 0;
5205 }
5206
5207
5208 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
5209 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
5210 /// the heavy lifting.
5211 ///
5212 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5213   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5214   if (!II) return visitCallSite(&CI);
5215   
5216   // Intrinsics cannot occur in an invoke, so handle them here instead of in
5217   // visitCallSite.
5218   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5219     bool Changed = false;
5220
5221     // memmove/cpy/set of zero bytes is a noop.
5222     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5223       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5224
5225       // FIXME: Increase alignment here.
5226
5227       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5228         if (CI->getRawValue() == 1) {
5229           // Replace the instruction with just byte operations.  We would
5230           // transform other cases to loads/stores, but we don't know if
5231           // alignment is sufficient.
5232         }
5233     }
5234
5235     // If we have a memmove and the source operation is a constant global,
5236     // then the source and dest pointers can't alias, so we can change this
5237     // into a call to memcpy.
5238     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
5239       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5240         if (GVSrc->isConstant()) {
5241           Module *M = CI.getParent()->getParent()->getParent();
5242           Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
5243                                      CI.getCalledFunction()->getFunctionType());
5244           CI.setOperand(0, MemCpy);
5245           Changed = true;
5246         }
5247
5248     if (Changed) return II;
5249   } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
5250     // If this stoppoint is at the same source location as the previous
5251     // stoppoint in the chain, it is not needed.
5252     if (DbgStopPointInst *PrevSPI =
5253         dyn_cast<DbgStopPointInst>(SPI->getChain()))
5254       if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5255           SPI->getColNo() == PrevSPI->getColNo()) {
5256         SPI->replaceAllUsesWith(PrevSPI);
5257         return EraseInstFromFunction(CI);
5258       }
5259   } else {
5260     switch (II->getIntrinsicID()) {
5261     default: break;
5262     case Intrinsic::stackrestore: {
5263       // If the save is right next to the restore, remove the restore.  This can
5264       // happen when variable allocas are DCE'd.
5265       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5266         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5267           BasicBlock::iterator BI = SS;
5268           if (&*++BI == II)
5269             return EraseInstFromFunction(CI);
5270         }
5271       }
5272       
5273       // If the stack restore is in a return/unwind block and if there are no
5274       // allocas or calls between the restore and the return, nuke the restore.
5275       TerminatorInst *TI = II->getParent()->getTerminator();
5276       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5277         BasicBlock::iterator BI = II;
5278         bool CannotRemove = false;
5279         for (++BI; &*BI != TI; ++BI) {
5280           if (isa<AllocaInst>(BI) ||
5281               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5282             CannotRemove = true;
5283             break;
5284           }
5285         }
5286         if (!CannotRemove)
5287           return EraseInstFromFunction(CI);
5288       }
5289       break;
5290     }
5291     }
5292   }
5293
5294   return visitCallSite(II);
5295 }
5296
5297 // InvokeInst simplification
5298 //
5299 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5300   return visitCallSite(&II);
5301 }
5302
5303 // visitCallSite - Improvements for call and invoke instructions.
5304 //
5305 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5306   bool Changed = false;
5307
5308   // If the callee is a constexpr cast of a function, attempt to move the cast
5309   // to the arguments of the call/invoke.
5310   if (transformConstExprCastCall(CS)) return 0;
5311
5312   Value *Callee = CS.getCalledValue();
5313
5314   if (Function *CalleeF = dyn_cast<Function>(Callee))
5315     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5316       Instruction *OldCall = CS.getInstruction();
5317       // If the call and callee calling conventions don't match, this call must
5318       // be unreachable, as the call is undefined.
5319       new StoreInst(ConstantBool::True,
5320                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5321       if (!OldCall->use_empty())
5322         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5323       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
5324         return EraseInstFromFunction(*OldCall);
5325       return 0;
5326     }
5327
5328   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5329     // This instruction is not reachable, just remove it.  We insert a store to
5330     // undef so that we know that this code is not reachable, despite the fact
5331     // that we can't modify the CFG here.
5332     new StoreInst(ConstantBool::True,
5333                   UndefValue::get(PointerType::get(Type::BoolTy)),
5334                   CS.getInstruction());
5335
5336     if (!CS.getInstruction()->use_empty())
5337       CS.getInstruction()->
5338         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5339
5340     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5341       // Don't break the CFG, insert a dummy cond branch.
5342       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5343                      ConstantBool::True, II);
5344     }
5345     return EraseInstFromFunction(*CS.getInstruction());
5346   }
5347
5348   const PointerType *PTy = cast<PointerType>(Callee->getType());
5349   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5350   if (FTy->isVarArg()) {
5351     // See if we can optimize any arguments passed through the varargs area of
5352     // the call.
5353     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5354            E = CS.arg_end(); I != E; ++I)
5355       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5356         // If this cast does not effect the value passed through the varargs
5357         // area, we can eliminate the use of the cast.
5358         Value *Op = CI->getOperand(0);
5359         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5360           *I = Op;
5361           Changed = true;
5362         }
5363       }
5364   }
5365
5366   return Changed ? CS.getInstruction() : 0;
5367 }
5368
5369 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5370 // attempt to move the cast to the arguments of the call/invoke.
5371 //
5372 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5373   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5374   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5375   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5376     return false;
5377   Function *Callee = cast<Function>(CE->getOperand(0));
5378   Instruction *Caller = CS.getInstruction();
5379
5380   // Okay, this is a cast from a function to a different type.  Unless doing so
5381   // would cause a type conversion of one of our arguments, change this call to
5382   // be a direct call with arguments casted to the appropriate types.
5383   //
5384   const FunctionType *FT = Callee->getFunctionType();
5385   const Type *OldRetTy = Caller->getType();
5386
5387   // Check to see if we are changing the return type...
5388   if (OldRetTy != FT->getReturnType()) {
5389     if (Callee->isExternal() &&
5390         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5391         !Caller->use_empty())
5392       return false;   // Cannot transform this return value...
5393
5394     // If the callsite is an invoke instruction, and the return value is used by
5395     // a PHI node in a successor, we cannot change the return type of the call
5396     // because there is no place to put the cast instruction (without breaking
5397     // the critical edge).  Bail out in this case.
5398     if (!Caller->use_empty())
5399       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5400         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5401              UI != E; ++UI)
5402           if (PHINode *PN = dyn_cast<PHINode>(*UI))
5403             if (PN->getParent() == II->getNormalDest() ||
5404                 PN->getParent() == II->getUnwindDest())
5405               return false;
5406   }
5407
5408   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5409   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5410
5411   CallSite::arg_iterator AI = CS.arg_begin();
5412   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5413     const Type *ParamTy = FT->getParamType(i);
5414     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5415     if (Callee->isExternal() && !isConvertible) return false;
5416   }
5417
5418   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5419       Callee->isExternal())
5420     return false;   // Do not delete arguments unless we have a function body...
5421
5422   // Okay, we decided that this is a safe thing to do: go ahead and start
5423   // inserting cast instructions as necessary...
5424   std::vector<Value*> Args;
5425   Args.reserve(NumActualArgs);
5426
5427   AI = CS.arg_begin();
5428   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5429     const Type *ParamTy = FT->getParamType(i);
5430     if ((*AI)->getType() == ParamTy) {
5431       Args.push_back(*AI);
5432     } else {
5433       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5434                                          *Caller));
5435     }
5436   }
5437
5438   // If the function takes more arguments than the call was taking, add them
5439   // now...
5440   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5441     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5442
5443   // If we are removing arguments to the function, emit an obnoxious warning...
5444   if (FT->getNumParams() < NumActualArgs)
5445     if (!FT->isVarArg()) {
5446       std::cerr << "WARNING: While resolving call to function '"
5447                 << Callee->getName() << "' arguments were dropped!\n";
5448     } else {
5449       // Add all of the arguments in their promoted form to the arg list...
5450       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5451         const Type *PTy = getPromotedType((*AI)->getType());
5452         if (PTy != (*AI)->getType()) {
5453           // Must promote to pass through va_arg area!
5454           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5455           InsertNewInstBefore(Cast, *Caller);
5456           Args.push_back(Cast);
5457         } else {
5458           Args.push_back(*AI);
5459         }
5460       }
5461     }
5462
5463   if (FT->getReturnType() == Type::VoidTy)
5464     Caller->setName("");   // Void type should not have a name...
5465
5466   Instruction *NC;
5467   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5468     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5469                         Args, Caller->getName(), Caller);
5470     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5471   } else {
5472     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5473     if (cast<CallInst>(Caller)->isTailCall())
5474       cast<CallInst>(NC)->setTailCall();
5475    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5476   }
5477
5478   // Insert a cast of the return type as necessary...
5479   Value *NV = NC;
5480   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5481     if (NV->getType() != Type::VoidTy) {
5482       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5483
5484       // If this is an invoke instruction, we should insert it after the first
5485       // non-phi, instruction in the normal successor block.
5486       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5487         BasicBlock::iterator I = II->getNormalDest()->begin();
5488         while (isa<PHINode>(I)) ++I;
5489         InsertNewInstBefore(NC, *I);
5490       } else {
5491         // Otherwise, it's a call, just insert cast right after the call instr
5492         InsertNewInstBefore(NC, *Caller);
5493       }
5494       AddUsersToWorkList(*Caller);
5495     } else {
5496       NV = UndefValue::get(Caller->getType());
5497     }
5498   }
5499
5500   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5501     Caller->replaceAllUsesWith(NV);
5502   Caller->getParent()->getInstList().erase(Caller);
5503   removeFromWorkList(Caller);
5504   return true;
5505 }
5506
5507
5508 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5509 // operator and they all are only used by the PHI, PHI together their
5510 // inputs, and do the operation once, to the result of the PHI.
5511 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5512   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5513
5514   // Scan the instruction, looking for input operations that can be folded away.
5515   // If all input operands to the phi are the same instruction (e.g. a cast from
5516   // the same type or "+42") we can pull the operation through the PHI, reducing
5517   // code size and simplifying code.
5518   Constant *ConstantOp = 0;
5519   const Type *CastSrcTy = 0;
5520   if (isa<CastInst>(FirstInst)) {
5521     CastSrcTy = FirstInst->getOperand(0)->getType();
5522   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5523     // Can fold binop or shift if the RHS is a constant.
5524     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5525     if (ConstantOp == 0) return 0;
5526   } else {
5527     return 0;  // Cannot fold this operation.
5528   }
5529
5530   // Check to see if all arguments are the same operation.
5531   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5532     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5533     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5534     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5535       return 0;
5536     if (CastSrcTy) {
5537       if (I->getOperand(0)->getType() != CastSrcTy)
5538         return 0;  // Cast operation must match.
5539     } else if (I->getOperand(1) != ConstantOp) {
5540       return 0;
5541     }
5542   }
5543
5544   // Okay, they are all the same operation.  Create a new PHI node of the
5545   // correct type, and PHI together all of the LHS's of the instructions.
5546   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5547                                PN.getName()+".in");
5548   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5549
5550   Value *InVal = FirstInst->getOperand(0);
5551   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5552
5553   // Add all operands to the new PHI.
5554   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5555     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5556     if (NewInVal != InVal)
5557       InVal = 0;
5558     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5559   }
5560
5561   Value *PhiVal;
5562   if (InVal) {
5563     // The new PHI unions all of the same values together.  This is really
5564     // common, so we handle it intelligently here for compile-time speed.
5565     PhiVal = InVal;
5566     delete NewPN;
5567   } else {
5568     InsertNewInstBefore(NewPN, PN);
5569     PhiVal = NewPN;
5570   }
5571
5572   // Insert and return the new operation.
5573   if (isa<CastInst>(FirstInst))
5574     return new CastInst(PhiVal, PN.getType());
5575   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5576     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5577   else
5578     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5579                          PhiVal, ConstantOp);
5580 }
5581
5582 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5583 /// that is dead.
5584 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5585   if (PN->use_empty()) return true;
5586   if (!PN->hasOneUse()) return false;
5587
5588   // Remember this node, and if we find the cycle, return.
5589   if (!PotentiallyDeadPHIs.insert(PN).second)
5590     return true;
5591
5592   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5593     return DeadPHICycle(PU, PotentiallyDeadPHIs);
5594
5595   return false;
5596 }
5597
5598 // PHINode simplification
5599 //
5600 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5601   if (Value *V = PN.hasConstantValue())
5602     return ReplaceInstUsesWith(PN, V);
5603
5604   // If the only user of this instruction is a cast instruction, and all of the
5605   // incoming values are constants, change this PHI to merge together the casted
5606   // constants.
5607   if (PN.hasOneUse())
5608     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5609       if (CI->getType() != PN.getType()) {  // noop casts will be folded
5610         bool AllConstant = true;
5611         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5612           if (!isa<Constant>(PN.getIncomingValue(i))) {
5613             AllConstant = false;
5614             break;
5615           }
5616         if (AllConstant) {
5617           // Make a new PHI with all casted values.
5618           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5619           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5620             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5621             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5622                              PN.getIncomingBlock(i));
5623           }
5624
5625           // Update the cast instruction.
5626           CI->setOperand(0, New);
5627           WorkList.push_back(CI);    // revisit the cast instruction to fold.
5628           WorkList.push_back(New);   // Make sure to revisit the new Phi
5629           return &PN;                // PN is now dead!
5630         }
5631       }
5632
5633   // If all PHI operands are the same operation, pull them through the PHI,
5634   // reducing code size.
5635   if (isa<Instruction>(PN.getIncomingValue(0)) &&
5636       PN.getIncomingValue(0)->hasOneUse())
5637     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5638       return Result;
5639
5640   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
5641   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5642   // PHI)... break the cycle.
5643   if (PN.hasOneUse())
5644     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5645       std::set<PHINode*> PotentiallyDeadPHIs;
5646       PotentiallyDeadPHIs.insert(&PN);
5647       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5648         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5649     }
5650
5651   return 0;
5652 }
5653
5654 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5655                                       Instruction *InsertPoint,
5656                                       InstCombiner *IC) {
5657   unsigned PS = IC->getTargetData().getPointerSize();
5658   const Type *VTy = V->getType();
5659   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5660     // We must insert a cast to ensure we sign-extend.
5661     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5662                                              V->getName()), *InsertPoint);
5663   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5664                                  *InsertPoint);
5665 }
5666
5667
5668 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5669   Value *PtrOp = GEP.getOperand(0);
5670   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
5671   // If so, eliminate the noop.
5672   if (GEP.getNumOperands() == 1)
5673     return ReplaceInstUsesWith(GEP, PtrOp);
5674
5675   if (isa<UndefValue>(GEP.getOperand(0)))
5676     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5677
5678   bool HasZeroPointerIndex = false;
5679   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5680     HasZeroPointerIndex = C->isNullValue();
5681
5682   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5683     return ReplaceInstUsesWith(GEP, PtrOp);
5684
5685   // Eliminate unneeded casts for indices.
5686   bool MadeChange = false;
5687   gep_type_iterator GTI = gep_type_begin(GEP);
5688   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5689     if (isa<SequentialType>(*GTI)) {
5690       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5691         Value *Src = CI->getOperand(0);
5692         const Type *SrcTy = Src->getType();
5693         const Type *DestTy = CI->getType();
5694         if (Src->getType()->isInteger()) {
5695           if (SrcTy->getPrimitiveSizeInBits() ==
5696                        DestTy->getPrimitiveSizeInBits()) {
5697             // We can always eliminate a cast from ulong or long to the other.
5698             // We can always eliminate a cast from uint to int or the other on
5699             // 32-bit pointer platforms.
5700             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5701               MadeChange = true;
5702               GEP.setOperand(i, Src);
5703             }
5704           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5705                      SrcTy->getPrimitiveSize() == 4) {
5706             // We can always eliminate a cast from int to [u]long.  We can
5707             // eliminate a cast from uint to [u]long iff the target is a 32-bit
5708             // pointer target.
5709             if (SrcTy->isSigned() ||
5710                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5711               MadeChange = true;
5712               GEP.setOperand(i, Src);
5713             }
5714           }
5715         }
5716       }
5717       // If we are using a wider index than needed for this platform, shrink it
5718       // to what we need.  If the incoming value needs a cast instruction,
5719       // insert it.  This explicit cast can make subsequent optimizations more
5720       // obvious.
5721       Value *Op = GEP.getOperand(i);
5722       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5723         if (Constant *C = dyn_cast<Constant>(Op)) {
5724           GEP.setOperand(i, ConstantExpr::getCast(C,
5725                                      TD->getIntPtrType()->getSignedVersion()));
5726           MadeChange = true;
5727         } else {
5728           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5729                                                 Op->getName()), GEP);
5730           GEP.setOperand(i, Op);
5731           MadeChange = true;
5732         }
5733
5734       // If this is a constant idx, make sure to canonicalize it to be a signed
5735       // operand, otherwise CSE and other optimizations are pessimized.
5736       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5737         GEP.setOperand(i, ConstantExpr::getCast(CUI,
5738                                           CUI->getType()->getSignedVersion()));
5739         MadeChange = true;
5740       }
5741     }
5742   if (MadeChange) return &GEP;
5743
5744   // Combine Indices - If the source pointer to this getelementptr instruction
5745   // is a getelementptr instruction, combine the indices of the two
5746   // getelementptr instructions into a single instruction.
5747   //
5748   std::vector<Value*> SrcGEPOperands;
5749   if (User *Src = dyn_castGetElementPtr(PtrOp))
5750     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5751
5752   if (!SrcGEPOperands.empty()) {
5753     // Note that if our source is a gep chain itself that we wait for that
5754     // chain to be resolved before we perform this transformation.  This
5755     // avoids us creating a TON of code in some cases.
5756     //
5757     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5758         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5759       return 0;   // Wait until our source is folded to completion.
5760
5761     std::vector<Value *> Indices;
5762
5763     // Find out whether the last index in the source GEP is a sequential idx.
5764     bool EndsWithSequential = false;
5765     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5766            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5767       EndsWithSequential = !isa<StructType>(*I);
5768
5769     // Can we combine the two pointer arithmetics offsets?
5770     if (EndsWithSequential) {
5771       // Replace: gep (gep %P, long B), long A, ...
5772       // With:    T = long A+B; gep %P, T, ...
5773       //
5774       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5775       if (SO1 == Constant::getNullValue(SO1->getType())) {
5776         Sum = GO1;
5777       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5778         Sum = SO1;
5779       } else {
5780         // If they aren't the same type, convert both to an integer of the
5781         // target's pointer size.
5782         if (SO1->getType() != GO1->getType()) {
5783           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5784             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5785           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5786             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5787           } else {
5788             unsigned PS = TD->getPointerSize();
5789             if (SO1->getType()->getPrimitiveSize() == PS) {
5790               // Convert GO1 to SO1's type.
5791               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5792
5793             } else if (GO1->getType()->getPrimitiveSize() == PS) {
5794               // Convert SO1 to GO1's type.
5795               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5796             } else {
5797               const Type *PT = TD->getIntPtrType();
5798               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5799               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5800             }
5801           }
5802         }
5803         if (isa<Constant>(SO1) && isa<Constant>(GO1))
5804           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5805         else {
5806           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5807           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5808         }
5809       }
5810
5811       // Recycle the GEP we already have if possible.
5812       if (SrcGEPOperands.size() == 2) {
5813         GEP.setOperand(0, SrcGEPOperands[0]);
5814         GEP.setOperand(1, Sum);
5815         return &GEP;
5816       } else {
5817         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5818                        SrcGEPOperands.end()-1);
5819         Indices.push_back(Sum);
5820         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5821       }
5822     } else if (isa<Constant>(*GEP.idx_begin()) &&
5823                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5824                SrcGEPOperands.size() != 1) {
5825       // Otherwise we can do the fold if the first index of the GEP is a zero
5826       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5827                      SrcGEPOperands.end());
5828       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5829     }
5830
5831     if (!Indices.empty())
5832       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5833
5834   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5835     // GEP of global variable.  If all of the indices for this GEP are
5836     // constants, we can promote this to a constexpr instead of an instruction.
5837
5838     // Scan for nonconstants...
5839     std::vector<Constant*> Indices;
5840     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5841     for (; I != E && isa<Constant>(*I); ++I)
5842       Indices.push_back(cast<Constant>(*I));
5843
5844     if (I == E) {  // If they are all constants...
5845       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5846
5847       // Replace all uses of the GEP with the new constexpr...
5848       return ReplaceInstUsesWith(GEP, CE);
5849     }
5850   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
5851     if (!isa<PointerType>(X->getType())) {
5852       // Not interesting.  Source pointer must be a cast from pointer.
5853     } else if (HasZeroPointerIndex) {
5854       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5855       // into     : GEP [10 x ubyte]* X, long 0, ...
5856       //
5857       // This occurs when the program declares an array extern like "int X[];"
5858       //
5859       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5860       const PointerType *XTy = cast<PointerType>(X->getType());
5861       if (const ArrayType *XATy =
5862           dyn_cast<ArrayType>(XTy->getElementType()))
5863         if (const ArrayType *CATy =
5864             dyn_cast<ArrayType>(CPTy->getElementType()))
5865           if (CATy->getElementType() == XATy->getElementType()) {
5866             // At this point, we know that the cast source type is a pointer
5867             // to an array of the same type as the destination pointer
5868             // array.  Because the array type is never stepped over (there
5869             // is a leading zero) we can fold the cast into this GEP.
5870             GEP.setOperand(0, X);
5871             return &GEP;
5872           }
5873     } else if (GEP.getNumOperands() == 2) {
5874       // Transform things like:
5875       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5876       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5877       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5878       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5879       if (isa<ArrayType>(SrcElTy) &&
5880           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5881           TD->getTypeSize(ResElTy)) {
5882         Value *V = InsertNewInstBefore(
5883                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5884                                      GEP.getOperand(1), GEP.getName()), GEP);
5885         return new CastInst(V, GEP.getType());
5886       }
5887       
5888       // Transform things like:
5889       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5890       //   (where tmp = 8*tmp2) into:
5891       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5892       
5893       if (isa<ArrayType>(SrcElTy) &&
5894           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5895         uint64_t ArrayEltSize =
5896             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5897         
5898         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
5899         // allow either a mul, shift, or constant here.
5900         Value *NewIdx = 0;
5901         ConstantInt *Scale = 0;
5902         if (ArrayEltSize == 1) {
5903           NewIdx = GEP.getOperand(1);
5904           Scale = ConstantInt::get(NewIdx->getType(), 1);
5905         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5906           NewIdx = ConstantInt::get(CI->getType(), 1);
5907           Scale = CI;
5908         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5909           if (Inst->getOpcode() == Instruction::Shl &&
5910               isa<ConstantInt>(Inst->getOperand(1))) {
5911             unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5912             if (Inst->getType()->isSigned())
5913               Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5914             else
5915               Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5916             NewIdx = Inst->getOperand(0);
5917           } else if (Inst->getOpcode() == Instruction::Mul &&
5918                      isa<ConstantInt>(Inst->getOperand(1))) {
5919             Scale = cast<ConstantInt>(Inst->getOperand(1));
5920             NewIdx = Inst->getOperand(0);
5921           }
5922         }
5923
5924         // If the index will be to exactly the right offset with the scale taken
5925         // out, perform the transformation.
5926         if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5927           if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5928             Scale = ConstantSInt::get(C->getType(),
5929                                       (int64_t)C->getRawValue() / 
5930                                       (int64_t)ArrayEltSize);
5931           else
5932             Scale = ConstantUInt::get(Scale->getType(),
5933                                       Scale->getRawValue() / ArrayEltSize);
5934           if (Scale->getRawValue() != 1) {
5935             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5936             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5937             NewIdx = InsertNewInstBefore(Sc, GEP);
5938           }
5939
5940           // Insert the new GEP instruction.
5941           Instruction *Idx =
5942             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5943                                   NewIdx, GEP.getName());
5944           Idx = InsertNewInstBefore(Idx, GEP);
5945           return new CastInst(Idx, GEP.getType());
5946         }
5947       }
5948     }
5949   }
5950
5951   return 0;
5952 }
5953
5954 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5955   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5956   if (AI.isArrayAllocation())    // Check C != 1
5957     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5958       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5959       AllocationInst *New = 0;
5960
5961       // Create and insert the replacement instruction...
5962       if (isa<MallocInst>(AI))
5963         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
5964       else {
5965         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5966         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
5967       }
5968
5969       InsertNewInstBefore(New, AI);
5970
5971       // Scan to the end of the allocation instructions, to skip over a block of
5972       // allocas if possible...
5973       //
5974       BasicBlock::iterator It = New;
5975       while (isa<AllocationInst>(*It)) ++It;
5976
5977       // Now that I is pointing to the first non-allocation-inst in the block,
5978       // insert our getelementptr instruction...
5979       //
5980       Value *NullIdx = Constant::getNullValue(Type::IntTy);
5981       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5982                                        New->getName()+".sub", It);
5983
5984       // Now make everything use the getelementptr instead of the original
5985       // allocation.
5986       return ReplaceInstUsesWith(AI, V);
5987     } else if (isa<UndefValue>(AI.getArraySize())) {
5988       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5989     }
5990
5991   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5992   // Note that we only do this for alloca's, because malloc should allocate and
5993   // return a unique pointer, even for a zero byte allocation.
5994   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5995       TD->getTypeSize(AI.getAllocatedType()) == 0)
5996     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5997
5998   return 0;
5999 }
6000
6001 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6002   Value *Op = FI.getOperand(0);
6003
6004   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6005   if (CastInst *CI = dyn_cast<CastInst>(Op))
6006     if (isa<PointerType>(CI->getOperand(0)->getType())) {
6007       FI.setOperand(0, CI->getOperand(0));
6008       return &FI;
6009     }
6010
6011   // free undef -> unreachable.
6012   if (isa<UndefValue>(Op)) {
6013     // Insert a new store to null because we cannot modify the CFG here.
6014     new StoreInst(ConstantBool::True,
6015                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6016     return EraseInstFromFunction(FI);
6017   }
6018
6019   // If we have 'free null' delete the instruction.  This can happen in stl code
6020   // when lots of inlining happens.
6021   if (isa<ConstantPointerNull>(Op))
6022     return EraseInstFromFunction(FI);
6023
6024   return 0;
6025 }
6026
6027
6028 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6029 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6030   User *CI = cast<User>(LI.getOperand(0));
6031   Value *CastOp = CI->getOperand(0);
6032
6033   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6034   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6035     const Type *SrcPTy = SrcTy->getElementType();
6036
6037     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6038       // If the source is an array, the code below will not succeed.  Check to
6039       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
6040       // constants.
6041       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6042         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6043           if (ASrcTy->getNumElements() != 0) {
6044             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6045             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6046             SrcTy = cast<PointerType>(CastOp->getType());
6047             SrcPTy = SrcTy->getElementType();
6048           }
6049
6050       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6051           // Do not allow turning this into a load of an integer, which is then
6052           // casted to a pointer, this pessimizes pointer analysis a lot.
6053           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6054           IC.getTargetData().getTypeSize(SrcPTy) ==
6055                IC.getTargetData().getTypeSize(DestPTy)) {
6056
6057         // Okay, we are casting from one integer or pointer type to another of
6058         // the same size.  Instead of casting the pointer before the load, cast
6059         // the result of the loaded value.
6060         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6061                                                              CI->getName(),
6062                                                          LI.isVolatile()),LI);
6063         // Now cast the result of the load.
6064         return new CastInst(NewLoad, LI.getType());
6065       }
6066     }
6067   }
6068   return 0;
6069 }
6070
6071 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6072 /// from this value cannot trap.  If it is not obviously safe to load from the
6073 /// specified pointer, we do a quick local scan of the basic block containing
6074 /// ScanFrom, to determine if the address is already accessed.
6075 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6076   // If it is an alloca or global variable, it is always safe to load from.
6077   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6078
6079   // Otherwise, be a little bit agressive by scanning the local block where we
6080   // want to check to see if the pointer is already being loaded or stored
6081   // from/to.  If so, the previous load or store would have already trapped,
6082   // so there is no harm doing an extra load (also, CSE will later eliminate
6083   // the load entirely).
6084   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6085
6086   while (BBI != E) {
6087     --BBI;
6088
6089     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6090       if (LI->getOperand(0) == V) return true;
6091     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6092       if (SI->getOperand(1) == V) return true;
6093
6094   }
6095   return false;
6096 }
6097
6098 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6099   Value *Op = LI.getOperand(0);
6100
6101   // load (cast X) --> cast (load X) iff safe
6102   if (CastInst *CI = dyn_cast<CastInst>(Op))
6103     if (Instruction *Res = InstCombineLoadCast(*this, LI))
6104       return Res;
6105
6106   // None of the following transforms are legal for volatile loads.
6107   if (LI.isVolatile()) return 0;
6108   
6109   if (&LI.getParent()->front() != &LI) {
6110     BasicBlock::iterator BBI = &LI; --BBI;
6111     // If the instruction immediately before this is a store to the same
6112     // address, do a simple form of store->load forwarding.
6113     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6114       if (SI->getOperand(1) == LI.getOperand(0))
6115         return ReplaceInstUsesWith(LI, SI->getOperand(0));
6116     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6117       if (LIB->getOperand(0) == LI.getOperand(0))
6118         return ReplaceInstUsesWith(LI, LIB);
6119   }
6120
6121   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6122     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6123         isa<UndefValue>(GEPI->getOperand(0))) {
6124       // Insert a new store to null instruction before the load to indicate
6125       // that this code is not reachable.  We do this instead of inserting
6126       // an unreachable instruction directly because we cannot modify the
6127       // CFG.
6128       new StoreInst(UndefValue::get(LI.getType()),
6129                     Constant::getNullValue(Op->getType()), &LI);
6130       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6131     }
6132
6133   if (Constant *C = dyn_cast<Constant>(Op)) {
6134     // load null/undef -> undef
6135     if ((C->isNullValue() || isa<UndefValue>(C))) {
6136       // Insert a new store to null instruction before the load to indicate that
6137       // this code is not reachable.  We do this instead of inserting an
6138       // unreachable instruction directly because we cannot modify the CFG.
6139       new StoreInst(UndefValue::get(LI.getType()),
6140                     Constant::getNullValue(Op->getType()), &LI);
6141       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6142     }
6143
6144     // Instcombine load (constant global) into the value loaded.
6145     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6146       if (GV->isConstant() && !GV->isExternal())
6147         return ReplaceInstUsesWith(LI, GV->getInitializer());
6148
6149     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6150     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6151       if (CE->getOpcode() == Instruction::GetElementPtr) {
6152         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6153           if (GV->isConstant() && !GV->isExternal())
6154             if (Constant *V = 
6155                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6156               return ReplaceInstUsesWith(LI, V);
6157         if (CE->getOperand(0)->isNullValue()) {
6158           // Insert a new store to null instruction before the load to indicate
6159           // that this code is not reachable.  We do this instead of inserting
6160           // an unreachable instruction directly because we cannot modify the
6161           // CFG.
6162           new StoreInst(UndefValue::get(LI.getType()),
6163                         Constant::getNullValue(Op->getType()), &LI);
6164           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6165         }
6166
6167       } else if (CE->getOpcode() == Instruction::Cast) {
6168         if (Instruction *Res = InstCombineLoadCast(*this, LI))
6169           return Res;
6170       }
6171   }
6172
6173   if (Op->hasOneUse()) {
6174     // Change select and PHI nodes to select values instead of addresses: this
6175     // helps alias analysis out a lot, allows many others simplifications, and
6176     // exposes redundancy in the code.
6177     //
6178     // Note that we cannot do the transformation unless we know that the
6179     // introduced loads cannot trap!  Something like this is valid as long as
6180     // the condition is always false: load (select bool %C, int* null, int* %G),
6181     // but it would not be valid if we transformed it to load from null
6182     // unconditionally.
6183     //
6184     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6185       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
6186       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6187           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6188         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6189                                      SI->getOperand(1)->getName()+".val"), LI);
6190         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6191                                      SI->getOperand(2)->getName()+".val"), LI);
6192         return new SelectInst(SI->getCondition(), V1, V2);
6193       }
6194
6195       // load (select (cond, null, P)) -> load P
6196       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6197         if (C->isNullValue()) {
6198           LI.setOperand(0, SI->getOperand(2));
6199           return &LI;
6200         }
6201
6202       // load (select (cond, P, null)) -> load P
6203       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6204         if (C->isNullValue()) {
6205           LI.setOperand(0, SI->getOperand(1));
6206           return &LI;
6207         }
6208
6209     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6210       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
6211       bool Safe = PN->getParent() == LI.getParent();
6212
6213       // Scan all of the instructions between the PHI and the load to make
6214       // sure there are no instructions that might possibly alter the value
6215       // loaded from the PHI.
6216       if (Safe) {
6217         BasicBlock::iterator I = &LI;
6218         for (--I; !isa<PHINode>(I); --I)
6219           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6220             Safe = false;
6221             break;
6222           }
6223       }
6224
6225       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6226         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6227                                     PN->getIncomingBlock(i)->getTerminator()))
6228           Safe = false;
6229
6230       if (Safe) {
6231         // Create the PHI.
6232         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6233         InsertNewInstBefore(NewPN, *PN);
6234         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
6235
6236         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6237           BasicBlock *BB = PN->getIncomingBlock(i);
6238           Value *&TheLoad = LoadMap[BB];
6239           if (TheLoad == 0) {
6240             Value *InVal = PN->getIncomingValue(i);
6241             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6242                                                        InVal->getName()+".val"),
6243                                           *BB->getTerminator());
6244           }
6245           NewPN->addIncoming(TheLoad, BB);
6246         }
6247         return ReplaceInstUsesWith(LI, NewPN);
6248       }
6249     }
6250   }
6251   return 0;
6252 }
6253
6254 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6255 /// when possible.
6256 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6257   User *CI = cast<User>(SI.getOperand(1));
6258   Value *CastOp = CI->getOperand(0);
6259
6260   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6261   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6262     const Type *SrcPTy = SrcTy->getElementType();
6263
6264     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6265       // If the source is an array, the code below will not succeed.  Check to
6266       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
6267       // constants.
6268       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6269         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6270           if (ASrcTy->getNumElements() != 0) {
6271             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6272             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6273             SrcTy = cast<PointerType>(CastOp->getType());
6274             SrcPTy = SrcTy->getElementType();
6275           }
6276
6277       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6278           IC.getTargetData().getTypeSize(SrcPTy) ==
6279                IC.getTargetData().getTypeSize(DestPTy)) {
6280
6281         // Okay, we are casting from one integer or pointer type to another of
6282         // the same size.  Instead of casting the pointer before the store, cast
6283         // the value to be stored.
6284         Value *NewCast;
6285         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6286           NewCast = ConstantExpr::getCast(C, SrcPTy);
6287         else
6288           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6289                                                         SrcPTy,
6290                                          SI.getOperand(0)->getName()+".c"), SI);
6291
6292         return new StoreInst(NewCast, CastOp);
6293       }
6294     }
6295   }
6296   return 0;
6297 }
6298
6299 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6300   Value *Val = SI.getOperand(0);
6301   Value *Ptr = SI.getOperand(1);
6302
6303   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
6304     EraseInstFromFunction(SI);
6305     ++NumCombined;
6306     return 0;
6307   }
6308
6309   // Do really simple DSE, to catch cases where there are several consequtive
6310   // stores to the same location, separated by a few arithmetic operations. This
6311   // situation often occurs with bitfield accesses.
6312   BasicBlock::iterator BBI = &SI;
6313   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6314        --ScanInsts) {
6315     --BBI;
6316     
6317     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6318       // Prev store isn't volatile, and stores to the same location?
6319       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6320         ++NumDeadStore;
6321         ++BBI;
6322         EraseInstFromFunction(*PrevSI);
6323         continue;
6324       }
6325       break;
6326     }
6327     
6328     // Don't skip over loads or things that can modify memory.
6329     if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6330       break;
6331   }
6332   
6333   
6334   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
6335
6336   // store X, null    -> turns into 'unreachable' in SimplifyCFG
6337   if (isa<ConstantPointerNull>(Ptr)) {
6338     if (!isa<UndefValue>(Val)) {
6339       SI.setOperand(0, UndefValue::get(Val->getType()));
6340       if (Instruction *U = dyn_cast<Instruction>(Val))
6341         WorkList.push_back(U);  // Dropped a use.
6342       ++NumCombined;
6343     }
6344     return 0;  // Do not modify these!
6345   }
6346
6347   // store undef, Ptr -> noop
6348   if (isa<UndefValue>(Val)) {
6349     EraseInstFromFunction(SI);
6350     ++NumCombined;
6351     return 0;
6352   }
6353
6354   // If the pointer destination is a cast, see if we can fold the cast into the
6355   // source instead.
6356   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6357     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6358       return Res;
6359   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6360     if (CE->getOpcode() == Instruction::Cast)
6361       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6362         return Res;
6363
6364   
6365   // If this store is the last instruction in the basic block, and if the block
6366   // ends with an unconditional branch, try to move it to the successor block.
6367   BBI = &SI; ++BBI;
6368   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6369     if (BI->isUnconditional()) {
6370       // Check to see if the successor block has exactly two incoming edges.  If
6371       // so, see if the other predecessor contains a store to the same location.
6372       // if so, insert a PHI node (if needed) and move the stores down.
6373       BasicBlock *Dest = BI->getSuccessor(0);
6374
6375       pred_iterator PI = pred_begin(Dest);
6376       BasicBlock *Other = 0;
6377       if (*PI != BI->getParent())
6378         Other = *PI;
6379       ++PI;
6380       if (PI != pred_end(Dest)) {
6381         if (*PI != BI->getParent())
6382           if (Other)
6383             Other = 0;
6384           else
6385             Other = *PI;
6386         if (++PI != pred_end(Dest))
6387           Other = 0;
6388       }
6389       if (Other) {  // If only one other pred...
6390         BBI = Other->getTerminator();
6391         // Make sure this other block ends in an unconditional branch and that
6392         // there is an instruction before the branch.
6393         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6394             BBI != Other->begin()) {
6395           --BBI;
6396           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6397           
6398           // If this instruction is a store to the same location.
6399           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6400             // Okay, we know we can perform this transformation.  Insert a PHI
6401             // node now if we need it.
6402             Value *MergedVal = OtherStore->getOperand(0);
6403             if (MergedVal != SI.getOperand(0)) {
6404               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6405               PN->reserveOperandSpace(2);
6406               PN->addIncoming(SI.getOperand(0), SI.getParent());
6407               PN->addIncoming(OtherStore->getOperand(0), Other);
6408               MergedVal = InsertNewInstBefore(PN, Dest->front());
6409             }
6410             
6411             // Advance to a place where it is safe to insert the new store and
6412             // insert it.
6413             BBI = Dest->begin();
6414             while (isa<PHINode>(BBI)) ++BBI;
6415             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6416                                               OtherStore->isVolatile()), *BBI);
6417
6418             // Nuke the old stores.
6419             EraseInstFromFunction(SI);
6420             EraseInstFromFunction(*OtherStore);
6421             ++NumCombined;
6422             return 0;
6423           }
6424         }
6425       }
6426     }
6427   
6428   return 0;
6429 }
6430
6431
6432 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6433   // Change br (not X), label True, label False to: br X, label False, True
6434   Value *X = 0;
6435   BasicBlock *TrueDest;
6436   BasicBlock *FalseDest;
6437   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6438       !isa<Constant>(X)) {
6439     // Swap Destinations and condition...
6440     BI.setCondition(X);
6441     BI.setSuccessor(0, FalseDest);
6442     BI.setSuccessor(1, TrueDest);
6443     return &BI;
6444   }
6445
6446   // Cannonicalize setne -> seteq
6447   Instruction::BinaryOps Op; Value *Y;
6448   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6449                       TrueDest, FalseDest)))
6450     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6451          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6452       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6453       std::string Name = I->getName(); I->setName("");
6454       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6455       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
6456       // Swap Destinations and condition...
6457       BI.setCondition(NewSCC);
6458       BI.setSuccessor(0, FalseDest);
6459       BI.setSuccessor(1, TrueDest);
6460       removeFromWorkList(I);
6461       I->getParent()->getInstList().erase(I);
6462       WorkList.push_back(cast<Instruction>(NewSCC));
6463       return &BI;
6464     }
6465
6466   return 0;
6467 }
6468
6469 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6470   Value *Cond = SI.getCondition();
6471   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6472     if (I->getOpcode() == Instruction::Add)
6473       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6474         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6475         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6476           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6477                                                 AddRHS));
6478         SI.setOperand(0, I->getOperand(0));
6479         WorkList.push_back(I);
6480         return &SI;
6481       }
6482   }
6483   return 0;
6484 }
6485
6486 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6487   if (ConstantAggregateZero *C = 
6488       dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6489     // If packed val is constant 0, replace extract with scalar 0
6490     const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6491     EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6492     return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6493   }
6494   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6495     // If packed val is constant with uniform operands, replace EI
6496     // with that operand
6497     Constant *op0 = cast<Constant>(C->getOperand(0));
6498     for (unsigned i = 1; i < C->getNumOperands(); ++i)
6499       if (C->getOperand(i) != op0) return 0;
6500     return ReplaceInstUsesWith(EI, op0);
6501   }
6502   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6503     if (I->hasOneUse()) {
6504       // Push extractelement into predecessor operation if legal and
6505       // profitable to do so
6506       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6507         if (!isa<Constant>(BO->getOperand(0)) &&
6508             !isa<Constant>(BO->getOperand(1)))
6509           return 0;
6510         ExtractElementInst *newEI0 = 
6511           new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6512                                  EI.getName());
6513         ExtractElementInst *newEI1 =
6514           new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6515                                  EI.getName());
6516         InsertNewInstBefore(newEI0, EI);
6517         InsertNewInstBefore(newEI1, EI);
6518         return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6519       }
6520       switch(I->getOpcode()) {
6521       case Instruction::Load: {
6522         Value *Ptr = InsertCastBefore(I->getOperand(0),
6523                                       PointerType::get(EI.getType()), EI);
6524         GetElementPtrInst *GEP = 
6525           new GetElementPtrInst(Ptr, EI.getOperand(1),
6526                                 I->getName() + ".gep");
6527         InsertNewInstBefore(GEP, EI);
6528         return new LoadInst(GEP);
6529       }
6530       default:
6531         return 0;
6532       }
6533     }
6534   return 0;
6535 }
6536
6537
6538 void InstCombiner::removeFromWorkList(Instruction *I) {
6539   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6540                  WorkList.end());
6541 }
6542
6543
6544 /// TryToSinkInstruction - Try to move the specified instruction from its
6545 /// current block into the beginning of DestBlock, which can only happen if it's
6546 /// safe to move the instruction past all of the instructions between it and the
6547 /// end of its block.
6548 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6549   assert(I->hasOneUse() && "Invariants didn't hold!");
6550
6551   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6552   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6553
6554   // Do not sink alloca instructions out of the entry block.
6555   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6556     return false;
6557
6558   // We can only sink load instructions if there is nothing between the load and
6559   // the end of block that could change the value.
6560   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6561     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6562          Scan != E; ++Scan)
6563       if (Scan->mayWriteToMemory())
6564         return false;
6565   }
6566
6567   BasicBlock::iterator InsertPos = DestBlock->begin();
6568   while (isa<PHINode>(InsertPos)) ++InsertPos;
6569
6570   I->moveBefore(InsertPos);
6571   ++NumSunkInst;
6572   return true;
6573 }
6574
6575 bool InstCombiner::runOnFunction(Function &F) {
6576   bool Changed = false;
6577   TD = &getAnalysis<TargetData>();
6578
6579   {
6580     // Populate the worklist with the reachable instructions.
6581     std::set<BasicBlock*> Visited;
6582     for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6583            E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6584       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6585         WorkList.push_back(I);
6586
6587     // Do a quick scan over the function.  If we find any blocks that are
6588     // unreachable, remove any instructions inside of them.  This prevents
6589     // the instcombine code from having to deal with some bad special cases.
6590     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6591       if (!Visited.count(BB)) {
6592         Instruction *Term = BB->getTerminator();
6593         while (Term != BB->begin()) {   // Remove instrs bottom-up
6594           BasicBlock::iterator I = Term; --I;
6595
6596           DEBUG(std::cerr << "IC: DCE: " << *I);
6597           ++NumDeadInst;
6598
6599           if (!I->use_empty())
6600             I->replaceAllUsesWith(UndefValue::get(I->getType()));
6601           I->eraseFromParent();
6602         }
6603       }
6604   }
6605
6606   while (!WorkList.empty()) {
6607     Instruction *I = WorkList.back();  // Get an instruction from the worklist
6608     WorkList.pop_back();
6609
6610     // Check to see if we can DCE or ConstantPropagate the instruction...
6611     // Check to see if we can DIE the instruction...
6612     if (isInstructionTriviallyDead(I)) {
6613       // Add operands to the worklist...
6614       if (I->getNumOperands() < 4)
6615         AddUsesToWorkList(*I);
6616       ++NumDeadInst;
6617
6618       DEBUG(std::cerr << "IC: DCE: " << *I);
6619
6620       I->eraseFromParent();
6621       removeFromWorkList(I);
6622       continue;
6623     }
6624
6625     // Instruction isn't dead, see if we can constant propagate it...
6626     if (Constant *C = ConstantFoldInstruction(I)) {
6627       Value* Ptr = I->getOperand(0);
6628       if (isa<GetElementPtrInst>(I) &&
6629           cast<Constant>(Ptr)->isNullValue() &&
6630           !isa<ConstantPointerNull>(C) &&
6631           cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6632         // If this is a constant expr gep that is effectively computing an
6633         // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6634         bool isFoldableGEP = true;
6635         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6636           if (!isa<ConstantInt>(I->getOperand(i)))
6637             isFoldableGEP = false;
6638         if (isFoldableGEP) {
6639           uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6640                              std::vector<Value*>(I->op_begin()+1, I->op_end()));
6641           C = ConstantUInt::get(Type::ULongTy, Offset);
6642           C = ConstantExpr::getCast(C, TD->getIntPtrType());
6643           C = ConstantExpr::getCast(C, I->getType());
6644         }
6645       }
6646
6647       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6648
6649       // Add operands to the worklist...
6650       AddUsesToWorkList(*I);
6651       ReplaceInstUsesWith(*I, C);
6652
6653       ++NumConstProp;
6654       I->getParent()->getInstList().erase(I);
6655       removeFromWorkList(I);
6656       continue;
6657     }
6658
6659     // See if we can trivially sink this instruction to a successor basic block.
6660     if (I->hasOneUse()) {
6661       BasicBlock *BB = I->getParent();
6662       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6663       if (UserParent != BB) {
6664         bool UserIsSuccessor = false;
6665         // See if the user is one of our successors.
6666         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6667           if (*SI == UserParent) {
6668             UserIsSuccessor = true;
6669             break;
6670           }
6671
6672         // If the user is one of our immediate successors, and if that successor
6673         // only has us as a predecessors (we'd have to split the critical edge
6674         // otherwise), we can keep going.
6675         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6676             next(pred_begin(UserParent)) == pred_end(UserParent))
6677           // Okay, the CFG is simple enough, try to sink this instruction.
6678           Changed |= TryToSinkInstruction(I, UserParent);
6679       }
6680     }
6681
6682     // Now that we have an instruction, try combining it to simplify it...
6683     if (Instruction *Result = visit(*I)) {
6684       ++NumCombined;
6685       // Should we replace the old instruction with a new one?
6686       if (Result != I) {
6687         DEBUG(std::cerr << "IC: Old = " << *I
6688                         << "    New = " << *Result);
6689
6690         // Everything uses the new instruction now.
6691         I->replaceAllUsesWith(Result);
6692
6693         // Push the new instruction and any users onto the worklist.
6694         WorkList.push_back(Result);
6695         AddUsersToWorkList(*Result);
6696
6697         // Move the name to the new instruction first...
6698         std::string OldName = I->getName(); I->setName("");
6699         Result->setName(OldName);
6700
6701         // Insert the new instruction into the basic block...
6702         BasicBlock *InstParent = I->getParent();
6703         BasicBlock::iterator InsertPos = I;
6704
6705         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
6706           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6707             ++InsertPos;
6708
6709         InstParent->getInstList().insert(InsertPos, Result);
6710
6711         // Make sure that we reprocess all operands now that we reduced their
6712         // use counts.
6713         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6714           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6715             WorkList.push_back(OpI);
6716
6717         // Instructions can end up on the worklist more than once.  Make sure
6718         // we do not process an instruction that has been deleted.
6719         removeFromWorkList(I);
6720
6721         // Erase the old instruction.
6722         InstParent->getInstList().erase(I);
6723       } else {
6724         DEBUG(std::cerr << "IC: MOD = " << *I);
6725
6726         // If the instruction was modified, it's possible that it is now dead.
6727         // if so, remove it.
6728         if (isInstructionTriviallyDead(I)) {
6729           // Make sure we process all operands now that we are reducing their
6730           // use counts.
6731           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6732             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6733               WorkList.push_back(OpI);
6734
6735           // Instructions may end up in the worklist more than once.  Erase all
6736           // occurrences of this instruction.
6737           removeFromWorkList(I);
6738           I->eraseFromParent();
6739         } else {
6740           WorkList.push_back(Result);
6741           AddUsersToWorkList(*Result);
6742         }
6743       }
6744       Changed = true;
6745     }
6746   }
6747
6748   return Changed;
6749 }
6750
6751 FunctionPass *llvm::createInstructionCombiningPass() {
6752   return new InstCombiner();
6753 }
6754