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