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