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