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