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