Fix InstCombine/2007-01-18-VectorInfLoop.ll, a case where instcombine
[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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp 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/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : 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     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitFCmpInst(FCmpInst &I);
147     Instruction *visitICmpInst(ICmpInst &I);
148     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
149
150     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151                              ICmpInst::Predicate Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *commonCastTransforms(CastInst &CI);
156     Instruction *commonIntCastTransforms(CastInst &CI);
157     Instruction *visitTrunc(CastInst &CI);
158     Instruction *visitZExt(CastInst &CI);
159     Instruction *visitSExt(CastInst &CI);
160     Instruction *visitFPTrunc(CastInst &CI);
161     Instruction *visitFPExt(CastInst &CI);
162     Instruction *visitFPToUI(CastInst &CI);
163     Instruction *visitFPToSI(CastInst &CI);
164     Instruction *visitUIToFP(CastInst &CI);
165     Instruction *visitSIToFP(CastInst &CI);
166     Instruction *visitPtrToInt(CastInst &CI);
167     Instruction *visitIntToPtr(CastInst &CI);
168     Instruction *visitBitCast(CastInst &CI);
169     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170                                 Instruction *FI);
171     Instruction *visitSelectInst(SelectInst &CI);
172     Instruction *visitCallInst(CallInst &CI);
173     Instruction *visitInvokeInst(InvokeInst &II);
174     Instruction *visitPHINode(PHINode &PN);
175     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176     Instruction *visitAllocationInst(AllocationInst &AI);
177     Instruction *visitFreeInst(FreeInst &FI);
178     Instruction *visitLoadInst(LoadInst &LI);
179     Instruction *visitStoreInst(StoreInst &SI);
180     Instruction *visitBranchInst(BranchInst &BI);
181     Instruction *visitSwitchInst(SwitchInst &SI);
182     Instruction *visitInsertElementInst(InsertElementInst &IE);
183     Instruction *visitExtractElementInst(ExtractElementInst &EI);
184     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185
186     // visitInstruction - Specify what to return for unhandled instructions...
187     Instruction *visitInstruction(Instruction &I) { return 0; }
188
189   private:
190     Instruction *visitCallSite(CallSite CS);
191     bool transformConstExprCastCall(CallSite CS);
192
193   public:
194     // InsertNewInstBefore - insert an instruction New before instruction Old
195     // in the program.  Add the new instruction to the worklist.
196     //
197     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198       assert(New && New->getParent() == 0 &&
199              "New instruction already inserted into a basic block!");
200       BasicBlock *BB = Old.getParent();
201       BB->getInstList().insert(&Old, New);  // Insert inst
202       WorkList.push_back(New);              // Add to worklist
203       return New;
204     }
205
206     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207     /// This also adds the cast to the worklist.  Finally, this returns the
208     /// cast.
209     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210                             Instruction &Pos) {
211       if (V->getType() == Ty) return V;
212
213       if (Constant *CV = dyn_cast<Constant>(V))
214         return ConstantExpr::getCast(opc, CV, Ty);
215       
216       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217       WorkList.push_back(C);
218       return C;
219     }
220
221     // ReplaceInstUsesWith - This method is to be used when an instruction is
222     // found to be dead, replacable with another preexisting expression.  Here
223     // we add all uses of I to the worklist, replace all uses of I with the new
224     // value, then return I, so that the inst combiner will know that I was
225     // modified.
226     //
227     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228       AddUsersToWorkList(I);         // Add all modified instrs to worklist
229       if (&I != V) {
230         I.replaceAllUsesWith(V);
231         return &I;
232       } else {
233         // If we are replacing the instruction with itself, this must be in a
234         // segment of unreachable code, so just clobber the instruction.
235         I.replaceAllUsesWith(UndefValue::get(I.getType()));
236         return &I;
237       }
238     }
239
240     // UpdateValueUsesWith - This method is to be used when an value is
241     // found to be replacable with another preexisting expression or was
242     // updated.  Here we add all uses of I to the worklist, replace all uses of
243     // I with the new value (unless the instruction was just updated), then
244     // return true, so that the inst combiner will know that I was modified.
245     //
246     bool UpdateValueUsesWith(Value *Old, Value *New) {
247       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
248       if (Old != New)
249         Old->replaceAllUsesWith(New);
250       if (Instruction *I = dyn_cast<Instruction>(Old))
251         WorkList.push_back(I);
252       if (Instruction *I = dyn_cast<Instruction>(New))
253         WorkList.push_back(I);
254       return true;
255     }
256     
257     // EraseInstFromFunction - When dealing with an instruction that has side
258     // effects or produces a void value, we can't rely on DCE to delete the
259     // instruction.  Instead, visit methods should return the value returned by
260     // this function.
261     Instruction *EraseInstFromFunction(Instruction &I) {
262       assert(I.use_empty() && "Cannot erase instruction that is used!");
263       AddUsesToWorkList(I);
264       removeFromWorkList(&I);
265       I.eraseFromParent();
266       return 0;  // Don't do anything with FI
267     }
268
269   private:
270     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
272     /// casts that are known to not do anything...
273     ///
274     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275                                    Value *V, const Type *DestTy,
276                                    Instruction *InsertBefore);
277
278     /// SimplifyCommutative - This performs a few simplifications for 
279     /// commutative operators.
280     bool SimplifyCommutative(BinaryOperator &I);
281
282     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283     /// most-complex to least-complex order.
284     bool SimplifyCompare(CmpInst &I);
285
286     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
287                               uint64_t &KnownZero, uint64_t &KnownOne,
288                               unsigned Depth = 0);
289
290     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291                                       uint64_t &UndefElts, unsigned Depth = 0);
292       
293     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294     // PHI node as operand #0, see if we can fold the instruction into the PHI
295     // (which is only possible if all operands to the PHI are constants).
296     Instruction *FoldOpIntoPhi(Instruction &I);
297
298     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299     // operator and they all are only used by the PHI, PHI together their
300     // inputs, and do the operation once, to the result of the PHI.
301     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303     
304     
305     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
307     
308     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
309                               bool isSub, Instruction &I);
310     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311                                  bool isSigned, bool Inside, Instruction &IB);
312     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313     Instruction *MatchBSwap(BinaryOperator &I);
314
315     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
316   };
317
318   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
319 }
320
321 // getComplexity:  Assign a complexity or rank value to LLVM Values...
322 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324   if (isa<Instruction>(V)) {
325     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
326       return 3;
327     return 4;
328   }
329   if (isa<Argument>(V)) return 3;
330   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
331 }
332
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
334 // it.
335 static bool isOnlyUse(Value *V) {
336   return V->hasOneUse() || isa<Constant>(V);
337 }
338
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
343     if (ITy->getBitWidth() < 32)
344       return Type::Int32Ty;
345   } else if (Ty == Type::FloatTy)
346     return Type::DoubleTy;
347   return Ty;
348 }
349
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
351 /// expression bitcast,  return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354     return I->getOperand(0);
355   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356     if (CE->getOpcode() == Instruction::BitCast)
357       return CE->getOperand(0);
358   return 0;
359 }
360
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps 
365 isEliminableCastPair(
366   const CastInst *CI, ///< The first cast instruction
367   unsigned opcode,       ///< The opcode of the second cast instruction
368   const Type *DstTy,     ///< The target type for the second cast instruction
369   TargetData *TD         ///< The target data for pointer size
370 ) {
371   
372   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
373   const Type *MidTy = CI->getType();                  // B from above
374
375   // Get the opcodes of the two Cast instructions
376   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379   return Instruction::CastOps(
380       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381                                      DstTy, TD->getIntPtrType()));
382 }
383
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated.  It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
388                               const Type *Ty, TargetData *TD) {
389   if (V->getType() == Ty || isa<Constant>(V)) return false;
390   
391   // If this is another cast that can be eliminated, it isn't codegen either.
392   if (const CastInst *CI = dyn_cast<CastInst>(V))
393     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
394       return false;
395   return true;
396 }
397
398 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
400 /// casts that are known to not do anything...
401 ///
402 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403                                              Value *V, const Type *DestTy,
404                                              Instruction *InsertBefore) {
405   if (V->getType() == DestTy) return V;
406   if (Constant *C = dyn_cast<Constant>(V))
407     return ConstantExpr::getCast(opcode, C, DestTy);
408   
409   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
410 }
411
412 // SimplifyCommutative - This performs a few simplifications for commutative
413 // operators:
414 //
415 //  1. Order operands such that they are listed from right (least complex) to
416 //     left (most complex).  This puts constants before unary operators before
417 //     binary operators.
418 //
419 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
421 //
422 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
423   bool Changed = false;
424   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425     Changed = !I.swapOperands();
426
427   if (!I.isAssociative()) return Changed;
428   Instruction::BinaryOps Opcode = I.getOpcode();
429   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431       if (isa<Constant>(I.getOperand(1))) {
432         Constant *Folded = ConstantExpr::get(I.getOpcode(),
433                                              cast<Constant>(I.getOperand(1)),
434                                              cast<Constant>(Op->getOperand(1)));
435         I.setOperand(0, Op->getOperand(0));
436         I.setOperand(1, Folded);
437         return true;
438       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440             isOnlyUse(Op) && isOnlyUse(Op1)) {
441           Constant *C1 = cast<Constant>(Op->getOperand(1));
442           Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
445           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
446           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447                                                     Op1->getOperand(0),
448                                                     Op1->getName(), &I);
449           WorkList.push_back(New);
450           I.setOperand(0, New);
451           I.setOperand(1, Folded);
452           return true;
453         }
454     }
455   return Changed;
456 }
457
458 /// SimplifyCompare - For a CmpInst this function just orders the operands
459 /// so that theyare listed from right (least complex) to left (most complex).
460 /// This puts constants before unary operators before binary operators.
461 bool InstCombiner::SimplifyCompare(CmpInst &I) {
462   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463     return false;
464   I.swapOperands();
465   // Compare instructions are not associative so there's nothing else we can do.
466   return true;
467 }
468
469 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470 // if the LHS is a constant zero (which is the 'negate' form).
471 //
472 static inline Value *dyn_castNegVal(Value *V) {
473   if (BinaryOperator::isNeg(V))
474     return BinaryOperator::getNegArgument(V);
475
476   // Constants can be considered to be negated values if they can be folded.
477   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478     return ConstantExpr::getNeg(C);
479   return 0;
480 }
481
482 static inline Value *dyn_castNotVal(Value *V) {
483   if (BinaryOperator::isNot(V))
484     return BinaryOperator::getNotArgument(V);
485
486   // Constants can be considered to be not'ed values...
487   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
488     return ConstantExpr::getNot(C);
489   return 0;
490 }
491
492 // dyn_castFoldableMul - If this value is a multiply that can be folded into
493 // other computations (because it has a constant operand), return the
494 // non-constant operand of the multiply, and set CST to point to the multiplier.
495 // Otherwise, return null.
496 //
497 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
498   if (V->hasOneUse() && V->getType()->isInteger())
499     if (Instruction *I = dyn_cast<Instruction>(V)) {
500       if (I->getOpcode() == Instruction::Mul)
501         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
502           return I->getOperand(0);
503       if (I->getOpcode() == Instruction::Shl)
504         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
505           // The multiplier is really 1 << CST.
506           Constant *One = ConstantInt::get(V->getType(), 1);
507           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508           return I->getOperand(0);
509         }
510     }
511   return 0;
512 }
513
514 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515 /// expression, return it.
516 static User *dyn_castGetElementPtr(Value *V) {
517   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519     if (CE->getOpcode() == Instruction::GetElementPtr)
520       return cast<User>(V);
521   return false;
522 }
523
524 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
525 static ConstantInt *AddOne(ConstantInt *C) {
526   return cast<ConstantInt>(ConstantExpr::getAdd(C,
527                                          ConstantInt::get(C->getType(), 1)));
528 }
529 static ConstantInt *SubOne(ConstantInt *C) {
530   return cast<ConstantInt>(ConstantExpr::getSub(C,
531                                          ConstantInt::get(C->getType(), 1)));
532 }
533
534 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
535 /// known to be either zero or one and return them in the KnownZero/KnownOne
536 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
537 /// processing.
538 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539                               uint64_t &KnownOne, unsigned Depth = 0) {
540   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
541   // we cannot optimize based on the assumption that it is zero without changing
542   // it to be an explicit zero.  If we don't change it to zero, other code could
543   // optimized based on the contradictory assumption that it is non-zero.
544   // Because instcombine aggressively folds operations with undef args anyway,
545   // this won't lose us code quality.
546   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
547     // We know all of the bits for a constant!
548     KnownOne = CI->getZExtValue() & Mask;
549     KnownZero = ~KnownOne & Mask;
550     return;
551   }
552
553   KnownZero = KnownOne = 0;   // Don't know anything.
554   if (Depth == 6 || Mask == 0)
555     return;  // Limit search depth.
556
557   uint64_t KnownZero2, KnownOne2;
558   Instruction *I = dyn_cast<Instruction>(V);
559   if (!I) return;
560
561   Mask &= V->getType()->getIntegerTypeMask();
562   
563   switch (I->getOpcode()) {
564   case Instruction::And:
565     // If either the LHS or the RHS are Zero, the result is zero.
566     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567     Mask &= ~KnownZero;
568     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
570     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
571     
572     // Output known-1 bits are only known if set in both the LHS & RHS.
573     KnownOne &= KnownOne2;
574     // Output known-0 are known to be clear if zero in either the LHS | RHS.
575     KnownZero |= KnownZero2;
576     return;
577   case Instruction::Or:
578     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579     Mask &= ~KnownOne;
580     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
582     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
583     
584     // Output known-0 bits are only known if clear in both the LHS & RHS.
585     KnownZero &= KnownZero2;
586     // Output known-1 are known to be set if set in either the LHS | RHS.
587     KnownOne |= KnownOne2;
588     return;
589   case Instruction::Xor: {
590     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
593     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
594     
595     // Output known-0 bits are known if clear or set in both the LHS & RHS.
596     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597     // Output known-1 are known to be set if set in only one of the LHS, RHS.
598     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599     KnownZero = KnownZeroOut;
600     return;
601   }
602   case Instruction::Select:
603     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
606     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
607
608     // Only known if known in both the LHS and RHS.
609     KnownOne &= KnownOne2;
610     KnownZero &= KnownZero2;
611     return;
612   case Instruction::FPTrunc:
613   case Instruction::FPExt:
614   case Instruction::FPToUI:
615   case Instruction::FPToSI:
616   case Instruction::SIToFP:
617   case Instruction::PtrToInt:
618   case Instruction::UIToFP:
619   case Instruction::IntToPtr:
620     return; // Can't work with floating point or pointers
621   case Instruction::Trunc: 
622     // All these have integer operands
623     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624     return;
625   case Instruction::BitCast: {
626     const Type *SrcTy = I->getOperand(0)->getType();
627     if (SrcTy->isInteger()) {
628       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
629       return;
630     }
631     break;
632   }
633   case Instruction::ZExt:  {
634     // Compute the bits in the result that are not present in the input.
635     const Type *SrcTy = I->getOperand(0)->getType();
636     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
637     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
638       
639     Mask &= SrcTy->getIntegerTypeMask();
640     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
642     // The top bits are known to be zero.
643     KnownZero |= NewBits;
644     return;
645   }
646   case Instruction::SExt: {
647     // Compute the bits in the result that are not present in the input.
648     const Type *SrcTy = I->getOperand(0)->getType();
649     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
650     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
651       
652     Mask &= SrcTy->getIntegerTypeMask();
653     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
655
656     // If the sign bit of the input is known set or clear, then we know the
657     // top bits of the result.
658     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659     if (KnownZero & InSignBit) {          // Input sign bit known zero
660       KnownZero |= NewBits;
661       KnownOne &= ~NewBits;
662     } else if (KnownOne & InSignBit) {    // Input sign bit known set
663       KnownOne |= NewBits;
664       KnownZero &= ~NewBits;
665     } else {                              // Input sign bit unknown
666       KnownZero &= ~NewBits;
667       KnownOne &= ~NewBits;
668     }
669     return;
670   }
671   case Instruction::Shl:
672     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
673     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674       uint64_t ShiftAmt = SA->getZExtValue();
675       Mask >>= ShiftAmt;
676       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
678       KnownZero <<= ShiftAmt;
679       KnownOne  <<= ShiftAmt;
680       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
681       return;
682     }
683     break;
684   case Instruction::LShr:
685     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
686     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687       // Compute the new bits that are at the top now.
688       uint64_t ShiftAmt = SA->getZExtValue();
689       uint64_t HighBits = (1ULL << ShiftAmt)-1;
690       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
691       
692       // Unsigned shift right.
693       Mask <<= ShiftAmt;
694       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
696       KnownZero >>= ShiftAmt;
697       KnownOne  >>= ShiftAmt;
698       KnownZero |= HighBits;  // high bits known zero.
699       return;
700     }
701     break;
702   case Instruction::AShr:
703     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
704     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705       // Compute the new bits that are at the top now.
706       uint64_t ShiftAmt = SA->getZExtValue();
707       uint64_t HighBits = (1ULL << ShiftAmt)-1;
708       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709       
710       // Signed shift right.
711       Mask <<= ShiftAmt;
712       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
714       KnownZero >>= ShiftAmt;
715       KnownOne  >>= ShiftAmt;
716         
717       // Handle the sign bits.
718       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
720         
721       if (KnownZero & SignBit) {       // New bits are known zero.
722         KnownZero |= HighBits;
723       } else if (KnownOne & SignBit) { // New bits are known one.
724         KnownOne |= HighBits;
725       }
726       return;
727     }
728     break;
729   }
730 }
731
732 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
733 /// this predicate to simplify operations downstream.  Mask is known to be zero
734 /// for bits that V cannot have.
735 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
736   uint64_t KnownZero, KnownOne;
737   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
739   return (KnownZero & Mask) == Mask;
740 }
741
742 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
743 /// specified instruction is a constant integer.  If so, check to see if there
744 /// are any bits set in the constant that are not demanded.  If so, shrink the
745 /// constant and return true.
746 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
747                                    uint64_t Demanded) {
748   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749   if (!OpC) return false;
750
751   // If there are no bits set that aren't demanded, nothing to do.
752   if ((~Demanded & OpC->getZExtValue()) == 0)
753     return false;
754
755   // This is producing any bits that are not needed, shrink the RHS.
756   uint64_t Val = Demanded & OpC->getZExtValue();
757   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
758   return true;
759 }
760
761 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
762 // set of known zero and one bits, compute the maximum and minimum values that
763 // could have the specified known zero and known one bits, returning them in
764 // min/max.
765 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766                                                    uint64_t KnownZero,
767                                                    uint64_t KnownOne,
768                                                    int64_t &Min, int64_t &Max) {
769   uint64_t TypeBits = Ty->getIntegerTypeMask();
770   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773   
774   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775   // bit if it is unknown.
776   Min = KnownOne;
777   Max = KnownOne|UnknownBits;
778   
779   if (SignBit & UnknownBits) { // Sign bit is unknown
780     Min |= SignBit;
781     Max &= ~SignBit;
782   }
783   
784   // Sign extend the min/max values.
785   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786   Min = (Min << ShAmt) >> ShAmt;
787   Max = (Max << ShAmt) >> ShAmt;
788 }
789
790 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791 // a set of known zero and one bits, compute the maximum and minimum values that
792 // could have the specified known zero and known one bits, returning them in
793 // min/max.
794 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795                                                      uint64_t KnownZero,
796                                                      uint64_t KnownOne,
797                                                      uint64_t &Min,
798                                                      uint64_t &Max) {
799   uint64_t TypeBits = Ty->getIntegerTypeMask();
800   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801   
802   // The minimum value is when the unknown bits are all zeros.
803   Min = KnownOne;
804   // The maximum value is when the unknown bits are all ones.
805   Max = KnownOne|UnknownBits;
806 }
807
808
809 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
810 /// DemandedMask bits of the result of V are ever used downstream.  If we can
811 /// use this information to simplify V, do so and return true.  Otherwise,
812 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
813 /// the expression (used to simplify the caller).  The KnownZero/One bits may
814 /// only be accurate for those bits in the DemandedMask.
815 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816                                         uint64_t &KnownZero, uint64_t &KnownOne,
817                                         unsigned Depth) {
818   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
819     // We know all of the bits for a constant!
820     KnownOne = CI->getZExtValue() & DemandedMask;
821     KnownZero = ~KnownOne & DemandedMask;
822     return false;
823   }
824   
825   KnownZero = KnownOne = 0;
826   if (!V->hasOneUse()) {    // Other users may use these bits.
827     if (Depth != 0) {       // Not at the root.
828       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
830       return false;
831     }
832     // If this is the root being simplified, allow it to have multiple uses,
833     // just set the DemandedMask to all bits.
834     DemandedMask = V->getType()->getIntegerTypeMask();
835   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
836     if (V != UndefValue::get(V->getType()))
837       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838     return false;
839   } else if (Depth == 6) {        // Limit search depth.
840     return false;
841   }
842   
843   Instruction *I = dyn_cast<Instruction>(V);
844   if (!I) return false;        // Only analyze instructions.
845
846   DemandedMask &= V->getType()->getIntegerTypeMask();
847   
848   uint64_t KnownZero2 = 0, KnownOne2 = 0;
849   switch (I->getOpcode()) {
850   default: break;
851   case Instruction::And:
852     // If either the LHS or the RHS are Zero, the result is zero.
853     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854                              KnownZero, KnownOne, Depth+1))
855       return true;
856     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
857
858     // If something is known zero on the RHS, the bits aren't demanded on the
859     // LHS.
860     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861                              KnownZero2, KnownOne2, Depth+1))
862       return true;
863     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
864
865     // If all of the demanded bits are known 1 on one side, return the other.
866     // These bits cannot contribute to the result of the 'and'.
867     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868       return UpdateValueUsesWith(I, I->getOperand(0));
869     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871     
872     // If all of the demanded bits in the inputs are known zeros, return zero.
873     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875       
876     // If the RHS is a constant, see if we can simplify it.
877     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
878       return UpdateValueUsesWith(I, I);
879       
880     // Output known-1 bits are only known if set in both the LHS & RHS.
881     KnownOne &= KnownOne2;
882     // Output known-0 are known to be clear if zero in either the LHS | RHS.
883     KnownZero |= KnownZero2;
884     break;
885   case Instruction::Or:
886     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
887                              KnownZero, KnownOne, Depth+1))
888       return true;
889     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
890     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
891                              KnownZero2, KnownOne2, Depth+1))
892       return true;
893     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
894     
895     // If all of the demanded bits are known zero on one side, return the other.
896     // These bits cannot contribute to the result of the 'or'.
897     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
898       return UpdateValueUsesWith(I, I->getOperand(0));
899     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
900       return UpdateValueUsesWith(I, I->getOperand(1));
901
902     // If all of the potentially set bits on one side are known to be set on
903     // the other side, just use the 'other' side.
904     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
905         (DemandedMask & (~KnownZero)))
906       return UpdateValueUsesWith(I, I->getOperand(0));
907     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
908         (DemandedMask & (~KnownZero2)))
909       return UpdateValueUsesWith(I, I->getOperand(1));
910         
911     // If the RHS is a constant, see if we can simplify it.
912     if (ShrinkDemandedConstant(I, 1, DemandedMask))
913       return UpdateValueUsesWith(I, I);
914           
915     // Output known-0 bits are only known if clear in both the LHS & RHS.
916     KnownZero &= KnownZero2;
917     // Output known-1 are known to be set if set in either the LHS | RHS.
918     KnownOne |= KnownOne2;
919     break;
920   case Instruction::Xor: {
921     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922                              KnownZero, KnownOne, Depth+1))
923       return true;
924     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
925     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
926                              KnownZero2, KnownOne2, Depth+1))
927       return true;
928     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
929     
930     // If all of the demanded bits are known zero on one side, return the other.
931     // These bits cannot contribute to the result of the 'xor'.
932     if ((DemandedMask & KnownZero) == DemandedMask)
933       return UpdateValueUsesWith(I, I->getOperand(0));
934     if ((DemandedMask & KnownZero2) == DemandedMask)
935       return UpdateValueUsesWith(I, I->getOperand(1));
936     
937     // Output known-0 bits are known if clear or set in both the LHS & RHS.
938     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939     // Output known-1 are known to be set if set in only one of the LHS, RHS.
940     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941     
942     // If all of the demanded bits are known to be zero on one side or the
943     // other, turn this into an *inclusive* or.
944     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946       Instruction *Or =
947         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948                                  I->getName());
949       InsertNewInstBefore(Or, *I);
950       return UpdateValueUsesWith(I, Or);
951     }
952     
953     // If all of the demanded bits on one side are known, and all of the set
954     // bits on that side are also known to be set on the other side, turn this
955     // into an AND, as we know the bits will be cleared.
956     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958       if ((KnownOne & KnownOne2) == KnownOne) {
959         Constant *AndC = ConstantInt::get(I->getType(), 
960                                           ~KnownOne & DemandedMask);
961         Instruction *And = 
962           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963         InsertNewInstBefore(And, *I);
964         return UpdateValueUsesWith(I, And);
965       }
966     }
967     
968     // If the RHS is a constant, see if we can simplify it.
969     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return UpdateValueUsesWith(I, I);
972     
973     KnownZero = KnownZeroOut;
974     KnownOne  = KnownOneOut;
975     break;
976   }
977   case Instruction::Select:
978     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979                              KnownZero, KnownOne, Depth+1))
980       return true;
981     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
982                              KnownZero2, KnownOne2, Depth+1))
983       return true;
984     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
985     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
986     
987     // If the operands are constants, see if we can simplify them.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return UpdateValueUsesWith(I, I);
990     if (ShrinkDemandedConstant(I, 2, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     // Only known if known in both the LHS and RHS.
994     KnownOne &= KnownOne2;
995     KnownZero &= KnownZero2;
996     break;
997   case Instruction::Trunc:
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999                              KnownZero, KnownOne, Depth+1))
1000       return true;
1001     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1002     break;
1003   case Instruction::BitCast:
1004     if (!I->getOperand(0)->getType()->isInteger())
1005       return false;
1006       
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              KnownZero, KnownOne, Depth+1))
1009       return true;
1010     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1011     break;
1012   case Instruction::ZExt: {
1013     // Compute the bits in the result that are not present in the input.
1014     const Type *SrcTy = I->getOperand(0)->getType();
1015     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1016     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1017     
1018     DemandedMask &= SrcTy->getIntegerTypeMask();
1019     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020                              KnownZero, KnownOne, Depth+1))
1021       return true;
1022     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1023     // The top bits are known to be zero.
1024     KnownZero |= NewBits;
1025     break;
1026   }
1027   case Instruction::SExt: {
1028     // Compute the bits in the result that are not present in the input.
1029     const Type *SrcTy = I->getOperand(0)->getType();
1030     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1031     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1032     
1033     // Get the sign bit for the source type
1034     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegerTypeMask();
1036
1037     // If any of the sign extended bits are demanded, we know that the sign
1038     // bit is demanded.
1039     if (NewBits & DemandedMask)
1040       InputDemandedBits |= InSignBit;
1041       
1042     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043                              KnownZero, KnownOne, Depth+1))
1044       return true;
1045     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1046       
1047     // If the sign bit of the input is known set or clear, then we know the
1048     // top bits of the result.
1049
1050     // If the input sign bit is known zero, or if the NewBits are not demanded
1051     // convert this into a zero extension.
1052     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053       // Convert to ZExt cast
1054       CastInst *NewCast = CastInst::create(
1055         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056       return UpdateValueUsesWith(I, NewCast);
1057     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1058       KnownOne |= NewBits;
1059       KnownZero &= ~NewBits;
1060     } else {                              // Input sign bit unknown
1061       KnownZero &= ~NewBits;
1062       KnownOne &= ~NewBits;
1063     }
1064     break;
1065   }
1066   case Instruction::Add:
1067     // If there is a constant on the RHS, there are a variety of xformations
1068     // we can do.
1069     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070       // If null, this should be simplified elsewhere.  Some of the xforms here
1071       // won't work if the RHS is zero.
1072       if (RHS->isNullValue())
1073         break;
1074       
1075       // Figure out what the input bits are.  If the top bits of the and result
1076       // are not demanded, then the add doesn't demand them from its input
1077       // either.
1078       
1079       // Shift the demanded mask up so that it's at the top of the uint64_t.
1080       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1082       
1083       // If the top bit of the output is demanded, demand everything from the
1084       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1085       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1086
1087       // Find information about known zero/one bits in the input.
1088       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1089                                KnownZero2, KnownOne2, Depth+1))
1090         return true;
1091
1092       // If the RHS of the add has bits set that can't affect the input, reduce
1093       // the constant.
1094       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095         return UpdateValueUsesWith(I, I);
1096       
1097       // Avoid excess work.
1098       if (KnownZero2 == 0 && KnownOne2 == 0)
1099         break;
1100       
1101       // Turn it into OR if input bits are zero.
1102       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1103         Instruction *Or =
1104           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1105                                    I->getName());
1106         InsertNewInstBefore(Or, *I);
1107         return UpdateValueUsesWith(I, Or);
1108       }
1109       
1110       // We can say something about the output known-zero and known-one bits,
1111       // depending on potential carries from the input constant and the
1112       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1113       // bits set and the RHS constant is 0x01001, then we know we have a known
1114       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1115       
1116       // To compute this, we first compute the potential carry bits.  These are
1117       // the bits which may be modified.  I'm not aware of a better way to do
1118       // this scan.
1119       uint64_t RHSVal = RHS->getZExtValue();
1120       
1121       bool CarryIn = false;
1122       uint64_t CarryBits = 0;
1123       uint64_t CurBit = 1;
1124       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125         // Record the current carry in.
1126         if (CarryIn) CarryBits |= CurBit;
1127         
1128         bool CarryOut;
1129         
1130         // This bit has a carry out unless it is "zero + zero" or
1131         // "zero + anything" with no carry in.
1132         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1134         } else if (!CarryIn &&
1135                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1137         } else {
1138           // Otherwise, we have to assume we have a carry out.
1139           CarryOut = true;
1140         }
1141         
1142         // This stage's carry out becomes the next stage's carry-in.
1143         CarryIn = CarryOut;
1144       }
1145       
1146       // Now that we know which bits have carries, compute the known-1/0 sets.
1147       
1148       // Bits are known one if they are known zero in one operand and one in the
1149       // other, and there is no input carry.
1150       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1151       
1152       // Bits are known zero if they are known zero in both operands and there
1153       // is no input carry.
1154       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1155     }
1156     break;
1157   case Instruction::Shl:
1158     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       uint64_t ShiftAmt = SA->getZExtValue();
1160       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1161                                KnownZero, KnownOne, Depth+1))
1162         return true;
1163       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1164       KnownZero <<= ShiftAmt;
1165       KnownOne  <<= ShiftAmt;
1166       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1167     }
1168     break;
1169   case Instruction::LShr:
1170     // For a logical shift right
1171     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       unsigned ShiftAmt = SA->getZExtValue();
1173       
1174       // Compute the new bits that are at the top now.
1175       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1177       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1178       // Unsigned shift right.
1179       if (SimplifyDemandedBits(I->getOperand(0),
1180                               (DemandedMask << ShiftAmt) & TypeMask,
1181                                KnownZero, KnownOne, Depth+1))
1182         return true;
1183       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1184       KnownZero &= TypeMask;
1185       KnownOne  &= TypeMask;
1186       KnownZero >>= ShiftAmt;
1187       KnownOne  >>= ShiftAmt;
1188       KnownZero |= HighBits;  // high bits known zero.
1189     }
1190     break;
1191   case Instruction::AShr:
1192     // If this is an arithmetic shift right and only the low-bit is set, we can
1193     // always convert this into a logical shr, even if the shift amount is
1194     // variable.  The low bit of the shift cannot be an input sign bit unless
1195     // the shift amount is >= the size of the datatype, which is undefined.
1196     if (DemandedMask == 1) {
1197       // Perform the logical shift right.
1198       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1199                                     I->getOperand(1), I->getName());
1200       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1201       return UpdateValueUsesWith(I, NewVal);
1202     }    
1203     
1204     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205       unsigned ShiftAmt = SA->getZExtValue();
1206       
1207       // Compute the new bits that are at the top now.
1208       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1210       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1211       // Signed shift right.
1212       if (SimplifyDemandedBits(I->getOperand(0),
1213                                (DemandedMask << ShiftAmt) & TypeMask,
1214                                KnownZero, KnownOne, Depth+1))
1215         return true;
1216       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217       KnownZero &= TypeMask;
1218       KnownOne  &= TypeMask;
1219       KnownZero >>= ShiftAmt;
1220       KnownOne  >>= ShiftAmt;
1221         
1222       // Handle the sign bits.
1223       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1225         
1226       // If the input sign bit is known to be zero, or if none of the top bits
1227       // are demanded, turn this into an unsigned shift right.
1228       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229         // Perform the logical shift right.
1230         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1231                                       SA, I->getName());
1232         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233         return UpdateValueUsesWith(I, NewVal);
1234       } else if (KnownOne & SignBit) { // New bits are known one.
1235         KnownOne |= HighBits;
1236       }
1237     }
1238     break;
1239   }
1240   
1241   // If the client is only demanding bits that we know, return the known
1242   // constant.
1243   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1244     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1245   return false;
1246 }  
1247
1248
1249 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1251 /// actually used by the caller.  This method analyzes which elements of the
1252 /// operand are undef and returns that information in UndefElts.
1253 ///
1254 /// If the information about demanded elements can be used to simplify the
1255 /// operation, the operation is simplified, then the resultant value is
1256 /// returned.  This returns null if no change was made.
1257 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258                                                 uint64_t &UndefElts,
1259                                                 unsigned Depth) {
1260   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261   assert(VWidth <= 64 && "Vector too wide to analyze!");
1262   uint64_t EltMask = ~0ULL >> (64-VWidth);
1263   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264          "Invalid DemandedElts!");
1265
1266   if (isa<UndefValue>(V)) {
1267     // If the entire vector is undefined, just return this info.
1268     UndefElts = EltMask;
1269     return 0;
1270   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271     UndefElts = EltMask;
1272     return UndefValue::get(V->getType());
1273   }
1274   
1275   UndefElts = 0;
1276   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278     Constant *Undef = UndefValue::get(EltTy);
1279
1280     std::vector<Constant*> Elts;
1281     for (unsigned i = 0; i != VWidth; ++i)
1282       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1283         Elts.push_back(Undef);
1284         UndefElts |= (1ULL << i);
1285       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1286         Elts.push_back(Undef);
1287         UndefElts |= (1ULL << i);
1288       } else {                               // Otherwise, defined.
1289         Elts.push_back(CP->getOperand(i));
1290       }
1291         
1292     // If we changed the constant, return it.
1293     Constant *NewCP = ConstantPacked::get(Elts);
1294     return NewCP != CP ? NewCP : 0;
1295   } else if (isa<ConstantAggregateZero>(V)) {
1296     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297     // set to undef.
1298     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299     Constant *Zero = Constant::getNullValue(EltTy);
1300     Constant *Undef = UndefValue::get(EltTy);
1301     std::vector<Constant*> Elts;
1302     for (unsigned i = 0; i != VWidth; ++i)
1303       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304     UndefElts = DemandedElts ^ EltMask;
1305     return ConstantPacked::get(Elts);
1306   }
1307   
1308   if (!V->hasOneUse()) {    // Other users may use these bits.
1309     if (Depth != 0) {       // Not at the root.
1310       // TODO: Just compute the UndefElts information recursively.
1311       return false;
1312     }
1313     return false;
1314   } else if (Depth == 10) {        // Limit search depth.
1315     return false;
1316   }
1317   
1318   Instruction *I = dyn_cast<Instruction>(V);
1319   if (!I) return false;        // Only analyze instructions.
1320   
1321   bool MadeChange = false;
1322   uint64_t UndefElts2;
1323   Value *TmpV;
1324   switch (I->getOpcode()) {
1325   default: break;
1326     
1327   case Instruction::InsertElement: {
1328     // If this is a variable index, we don't know which element it overwrites.
1329     // demand exactly the same input as we produce.
1330     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1331     if (Idx == 0) {
1332       // Note that we can't propagate undef elt info, because we don't know
1333       // which elt is getting updated.
1334       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335                                         UndefElts2, Depth+1);
1336       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337       break;
1338     }
1339     
1340     // If this is inserting an element that isn't demanded, remove this
1341     // insertelement.
1342     unsigned IdxNo = Idx->getZExtValue();
1343     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344       return AddSoonDeadInstToWorklist(*I, 0);
1345     
1346     // Otherwise, the element inserted overwrites whatever was there, so the
1347     // input demanded set is simpler than the output set.
1348     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349                                       DemandedElts & ~(1ULL << IdxNo),
1350                                       UndefElts, Depth+1);
1351     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353     // The inserted element is defined.
1354     UndefElts |= 1ULL << IdxNo;
1355     break;
1356   }
1357     
1358   case Instruction::And:
1359   case Instruction::Or:
1360   case Instruction::Xor:
1361   case Instruction::Add:
1362   case Instruction::Sub:
1363   case Instruction::Mul:
1364     // div/rem demand all inputs, because they don't want divide by zero.
1365     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366                                       UndefElts, Depth+1);
1367     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369                                       UndefElts2, Depth+1);
1370     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371       
1372     // Output elements are undefined if both are undefined.  Consider things
1373     // like undef&0.  The result is known zero, not undef.
1374     UndefElts &= UndefElts2;
1375     break;
1376     
1377   case Instruction::Call: {
1378     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379     if (!II) break;
1380     switch (II->getIntrinsicID()) {
1381     default: break;
1382       
1383     // Binary vector operations that work column-wise.  A dest element is a
1384     // function of the corresponding input elements from the two inputs.
1385     case Intrinsic::x86_sse_sub_ss:
1386     case Intrinsic::x86_sse_mul_ss:
1387     case Intrinsic::x86_sse_min_ss:
1388     case Intrinsic::x86_sse_max_ss:
1389     case Intrinsic::x86_sse2_sub_sd:
1390     case Intrinsic::x86_sse2_mul_sd:
1391     case Intrinsic::x86_sse2_min_sd:
1392     case Intrinsic::x86_sse2_max_sd:
1393       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394                                         UndefElts, Depth+1);
1395       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397                                         UndefElts2, Depth+1);
1398       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400       // If only the low elt is demanded and this is a scalarizable intrinsic,
1401       // scalarize it now.
1402       if (DemandedElts == 1) {
1403         switch (II->getIntrinsicID()) {
1404         default: break;
1405         case Intrinsic::x86_sse_sub_ss:
1406         case Intrinsic::x86_sse_mul_ss:
1407         case Intrinsic::x86_sse2_sub_sd:
1408         case Intrinsic::x86_sse2_mul_sd:
1409           // TODO: Lower MIN/MAX/ABS/etc
1410           Value *LHS = II->getOperand(1);
1411           Value *RHS = II->getOperand(2);
1412           // Extract the element as scalars.
1413           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415           
1416           switch (II->getIntrinsicID()) {
1417           default: assert(0 && "Case stmts out of sync!");
1418           case Intrinsic::x86_sse_sub_ss:
1419           case Intrinsic::x86_sse2_sub_sd:
1420             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421                                                         II->getName()), *II);
1422             break;
1423           case Intrinsic::x86_sse_mul_ss:
1424           case Intrinsic::x86_sse2_mul_sd:
1425             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426                                                          II->getName()), *II);
1427             break;
1428           }
1429           
1430           Instruction *New =
1431             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432                                   II->getName());
1433           InsertNewInstBefore(New, *II);
1434           AddSoonDeadInstToWorklist(*II, 0);
1435           return New;
1436         }            
1437       }
1438         
1439       // Output elements are undefined if both are undefined.  Consider things
1440       // like undef&0.  The result is known zero, not undef.
1441       UndefElts &= UndefElts2;
1442       break;
1443     }
1444     break;
1445   }
1446   }
1447   return MadeChange ? I : 0;
1448 }
1449
1450 /// @returns true if the specified compare instruction is
1451 /// true when both operands are equal...
1452 /// @brief Determine if the ICmpInst returns true if both operands are equal
1453 static bool isTrueWhenEqual(ICmpInst &ICI) {
1454   ICmpInst::Predicate pred = ICI.getPredicate();
1455   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1456          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1457          pred == ICmpInst::ICMP_SLE;
1458 }
1459
1460 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1461 /// function is designed to check a chain of associative operators for a
1462 /// potential to apply a certain optimization.  Since the optimization may be
1463 /// applicable if the expression was reassociated, this checks the chain, then
1464 /// reassociates the expression as necessary to expose the optimization
1465 /// opportunity.  This makes use of a special Functor, which must define
1466 /// 'shouldApply' and 'apply' methods.
1467 ///
1468 template<typename Functor>
1469 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1470   unsigned Opcode = Root.getOpcode();
1471   Value *LHS = Root.getOperand(0);
1472
1473   // Quick check, see if the immediate LHS matches...
1474   if (F.shouldApply(LHS))
1475     return F.apply(Root);
1476
1477   // Otherwise, if the LHS is not of the same opcode as the root, return.
1478   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1479   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1480     // Should we apply this transform to the RHS?
1481     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482
1483     // If not to the RHS, check to see if we should apply to the LHS...
1484     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1485       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1486       ShouldApply = true;
1487     }
1488
1489     // If the functor wants to apply the optimization to the RHS of LHSI,
1490     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491     if (ShouldApply) {
1492       BasicBlock *BB = Root.getParent();
1493
1494       // Now all of the instructions are in the current basic block, go ahead
1495       // and perform the reassociation.
1496       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497
1498       // First move the selected RHS to the LHS of the root...
1499       Root.setOperand(0, LHSI->getOperand(1));
1500
1501       // Make what used to be the LHS of the root be the user of the root...
1502       Value *ExtraOperand = TmpLHSI->getOperand(1);
1503       if (&Root == TmpLHSI) {
1504         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1505         return 0;
1506       }
1507       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1508       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1509       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1510       BasicBlock::iterator ARI = &Root; ++ARI;
1511       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1512       ARI = Root;
1513
1514       // Now propagate the ExtraOperand down the chain of instructions until we
1515       // get to LHSI.
1516       while (TmpLHSI != LHSI) {
1517         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1518         // Move the instruction to immediately before the chain we are
1519         // constructing to avoid breaking dominance properties.
1520         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1521         BB->getInstList().insert(ARI, NextLHSI);
1522         ARI = NextLHSI;
1523
1524         Value *NextOp = NextLHSI->getOperand(1);
1525         NextLHSI->setOperand(1, ExtraOperand);
1526         TmpLHSI = NextLHSI;
1527         ExtraOperand = NextOp;
1528       }
1529
1530       // Now that the instructions are reassociated, have the functor perform
1531       // the transformation...
1532       return F.apply(Root);
1533     }
1534
1535     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1536   }
1537   return 0;
1538 }
1539
1540
1541 // AddRHS - Implements: X + X --> X << 1
1542 struct AddRHS {
1543   Value *RHS;
1544   AddRHS(Value *rhs) : RHS(rhs) {}
1545   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1546   Instruction *apply(BinaryOperator &Add) const {
1547     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1548                          ConstantInt::get(Type::Int8Ty, 1));
1549   }
1550 };
1551
1552 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553 //                 iff C1&C2 == 0
1554 struct AddMaskingAnd {
1555   Constant *C2;
1556   AddMaskingAnd(Constant *c) : C2(c) {}
1557   bool shouldApply(Value *LHS) const {
1558     ConstantInt *C1;
1559     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1560            ConstantExpr::getAnd(C1, C2)->isNullValue();
1561   }
1562   Instruction *apply(BinaryOperator &Add) const {
1563     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1564   }
1565 };
1566
1567 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1568                                              InstCombiner *IC) {
1569   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1570     if (Constant *SOC = dyn_cast<Constant>(SO))
1571       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1572
1573     return IC->InsertNewInstBefore(CastInst::create(
1574           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1575   }
1576
1577   // Figure out if the constant is the left or the right argument.
1578   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1579   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1580
1581   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582     if (ConstIsRHS)
1583       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1584     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1585   }
1586
1587   Value *Op0 = SO, *Op1 = ConstOperand;
1588   if (!ConstIsRHS)
1589     std::swap(Op0, Op1);
1590   Instruction *New;
1591   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1592     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1593   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1594     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1595                           SO->getName()+".cmp");
1596   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1598   else {
1599     assert(0 && "Unknown binary instruction type!");
1600     abort();
1601   }
1602   return IC->InsertNewInstBefore(New, I);
1603 }
1604
1605 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606 // constant as the other operand, try to fold the binary operator into the
1607 // select arguments.  This also works for Cast instructions, which obviously do
1608 // not have a second operand.
1609 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610                                      InstCombiner *IC) {
1611   // Don't modify shared select instructions
1612   if (!SI->hasOneUse()) return 0;
1613   Value *TV = SI->getOperand(1);
1614   Value *FV = SI->getOperand(2);
1615
1616   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1617     // Bool selects with constant operands can be folded to logical ops.
1618     if (SI->getType() == Type::Int1Ty) return 0;
1619
1620     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623     return new SelectInst(SI->getCondition(), SelectTrueVal,
1624                           SelectFalseVal);
1625   }
1626   return 0;
1627 }
1628
1629
1630 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631 /// node as operand #0, see if we can fold the instruction into the PHI (which
1632 /// is only possible if all operands to the PHI are constants).
1633 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634   PHINode *PN = cast<PHINode>(I.getOperand(0));
1635   unsigned NumPHIValues = PN->getNumIncomingValues();
1636   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1637
1638   // Check to see if all of the operands of the PHI are constants.  If there is
1639   // one non-constant value, remember the BB it is.  If there is more than one
1640   // bail out.
1641   BasicBlock *NonConstBB = 0;
1642   for (unsigned i = 0; i != NumPHIValues; ++i)
1643     if (!isa<Constant>(PN->getIncomingValue(i))) {
1644       if (NonConstBB) return 0;  // More than one non-const value.
1645       NonConstBB = PN->getIncomingBlock(i);
1646       
1647       // If the incoming non-constant value is in I's block, we have an infinite
1648       // loop.
1649       if (NonConstBB == I.getParent())
1650         return 0;
1651     }
1652   
1653   // If there is exactly one non-constant value, we can insert a copy of the
1654   // operation in that block.  However, if this is a critical edge, we would be
1655   // inserting the computation one some other paths (e.g. inside a loop).  Only
1656   // do this if the pred block is unconditionally branching into the phi block.
1657   if (NonConstBB) {
1658     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659     if (!BI || !BI->isUnconditional()) return 0;
1660   }
1661
1662   // Okay, we can do the transformation: create the new PHI node.
1663   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664   I.setName("");
1665   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1666   InsertNewInstBefore(NewPN, *PN);
1667
1668   // Next, add all of the operands to the PHI.
1669   if (I.getNumOperands() == 2) {
1670     Constant *C = cast<Constant>(I.getOperand(1));
1671     for (unsigned i = 0; i != NumPHIValues; ++i) {
1672       Value *InV;
1673       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1675           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1676         else
1677           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1678       } else {
1679         assert(PN->getIncomingBlock(i) == NonConstBB);
1680         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1681           InV = BinaryOperator::create(BO->getOpcode(),
1682                                        PN->getIncomingValue(i), C, "phitmp",
1683                                        NonConstBB->getTerminator());
1684         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685           InV = CmpInst::create(CI->getOpcode(), 
1686                                 CI->getPredicate(),
1687                                 PN->getIncomingValue(i), C, "phitmp",
1688                                 NonConstBB->getTerminator());
1689         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1690           InV = new ShiftInst(SI->getOpcode(),
1691                               PN->getIncomingValue(i), C, "phitmp",
1692                               NonConstBB->getTerminator());
1693         else
1694           assert(0 && "Unknown binop!");
1695         
1696         WorkList.push_back(cast<Instruction>(InV));
1697       }
1698       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1699     }
1700   } else { 
1701     CastInst *CI = cast<CastInst>(&I);
1702     const Type *RetTy = CI->getType();
1703     for (unsigned i = 0; i != NumPHIValues; ++i) {
1704       Value *InV;
1705       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1706         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1707       } else {
1708         assert(PN->getIncomingBlock(i) == NonConstBB);
1709         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1710                                I.getType(), "phitmp", 
1711                                NonConstBB->getTerminator());
1712         WorkList.push_back(cast<Instruction>(InV));
1713       }
1714       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1715     }
1716   }
1717   return ReplaceInstUsesWith(I, NewPN);
1718 }
1719
1720 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1721   bool Changed = SimplifyCommutative(I);
1722   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1723
1724   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1725     // X + undef -> undef
1726     if (isa<UndefValue>(RHS))
1727       return ReplaceInstUsesWith(I, RHS);
1728
1729     // X + 0 --> X
1730     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1731       if (RHSC->isNullValue())
1732         return ReplaceInstUsesWith(I, LHS);
1733     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734       if (CFP->isExactlyValue(-0.0))
1735         return ReplaceInstUsesWith(I, LHS);
1736     }
1737
1738     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1739       // X + (signbit) --> X ^ signbit
1740       uint64_t Val = CI->getZExtValue();
1741       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1742         return BinaryOperator::createXor(LHS, RHS);
1743       
1744       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1745       // (X & 254)+1 -> (X&254)|1
1746       uint64_t KnownZero, KnownOne;
1747       if (!isa<PackedType>(I.getType()) &&
1748           SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
1749                                KnownZero, KnownOne))
1750         return &I;
1751     }
1752
1753     if (isa<PHINode>(LHS))
1754       if (Instruction *NV = FoldOpIntoPhi(I))
1755         return NV;
1756     
1757     ConstantInt *XorRHS = 0;
1758     Value *XorLHS = 0;
1759     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1760       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763       
1764       uint64_t C0080Val = 1ULL << 31;
1765       int64_t CFF80Val = -C0080Val;
1766       unsigned Size = 32;
1767       do {
1768         if (TySizeBits > Size) {
1769           bool Found = false;
1770           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772           if (RHSSExt == CFF80Val) {
1773             if (XorRHS->getZExtValue() == C0080Val)
1774               Found = true;
1775           } else if (RHSZExt == C0080Val) {
1776             if (XorRHS->getSExtValue() == CFF80Val)
1777               Found = true;
1778           }
1779           if (Found) {
1780             // This is a sign extend if the top bits are known zero.
1781             uint64_t Mask = ~0ULL;
1782             Mask <<= 64-(TySizeBits-Size);
1783             Mask &= XorLHS->getType()->getIntegerTypeMask();
1784             if (!MaskedValueIsZero(XorLHS, Mask))
1785               Size = 0;  // Not a sign ext, but can't be any others either.
1786             goto FoundSExt;
1787           }
1788         }
1789         Size >>= 1;
1790         C0080Val >>= Size;
1791         CFF80Val >>= Size;
1792       } while (Size >= 8);
1793       
1794 FoundSExt:
1795       const Type *MiddleType = 0;
1796       switch (Size) {
1797       default: break;
1798       case 32: MiddleType = Type::Int32Ty; break;
1799       case 16: MiddleType = Type::Int16Ty; break;
1800       case 8:  MiddleType = Type::Int8Ty; break;
1801       }
1802       if (MiddleType) {
1803         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1804         InsertNewInstBefore(NewTrunc, I);
1805         return new SExtInst(NewTrunc, I.getType());
1806       }
1807     }
1808   }
1809
1810   // X + X --> X << 1
1811   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1812     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1813
1814     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815       if (RHSI->getOpcode() == Instruction::Sub)
1816         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1817           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818     }
1819     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820       if (LHSI->getOpcode() == Instruction::Sub)
1821         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1822           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823     }
1824   }
1825
1826   // -A + B  -->  B - A
1827   if (Value *V = dyn_castNegVal(LHS))
1828     return BinaryOperator::createSub(RHS, V);
1829
1830   // A + -B  -->  A - B
1831   if (!isa<Constant>(RHS))
1832     if (Value *V = dyn_castNegVal(RHS))
1833       return BinaryOperator::createSub(LHS, V);
1834
1835
1836   ConstantInt *C2;
1837   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838     if (X == RHS)   // X*C + X --> X * (C+1)
1839       return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841     // X*C1 + X*C2 --> X * (C1+C2)
1842     ConstantInt *C1;
1843     if (X == dyn_castFoldableMul(RHS, C1))
1844       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1845   }
1846
1847   // X + X*C --> X * (C+1)
1848   if (dyn_castFoldableMul(RHS, C2) == LHS)
1849     return BinaryOperator::createMul(LHS, AddOne(C2));
1850
1851   // X + ~X --> -1   since   ~X = -X-1
1852   if (dyn_castNotVal(LHS) == RHS ||
1853       dyn_castNotVal(RHS) == LHS)
1854     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855   
1856
1857   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1858   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1859     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860       return R;
1861
1862   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1863     Value *X = 0;
1864     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1865       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866       return BinaryOperator::createSub(C, X);
1867     }
1868
1869     // (X & FF00) + xx00  -> (X+xx00) & FF00
1870     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872       if (Anded == CRHS) {
1873         // See if all bits from the first bit set in the Add RHS up are included
1874         // in the mask.  First, get the rightmost bit.
1875         uint64_t AddRHSV = CRHS->getZExtValue();
1876
1877         // Form a mask of all bits from the lowest bit added through the top.
1878         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1879         AddRHSHighBits &= C2->getType()->getIntegerTypeMask();
1880
1881         // See if the and mask includes all of these bits.
1882         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1883
1884         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885           // Okay, the xform is safe.  Insert the new add pronto.
1886           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887                                                             LHS->getName()), I);
1888           return BinaryOperator::createAnd(NewAdd, C2);
1889         }
1890       }
1891     }
1892
1893     // Try to fold constant add into select arguments.
1894     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1895       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1896         return R;
1897   }
1898
1899   // add (cast *A to intptrtype) B -> 
1900   //   cast (GEP (cast *A to sbyte*) B) -> 
1901   //     intptrtype
1902   {
1903     CastInst *CI = dyn_cast<CastInst>(LHS);
1904     Value *Other = RHS;
1905     if (!CI) {
1906       CI = dyn_cast<CastInst>(RHS);
1907       Other = LHS;
1908     }
1909     if (CI && CI->getType()->isSized() && 
1910         (CI->getType()->getPrimitiveSizeInBits() == 
1911          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1912         && isa<PointerType>(CI->getOperand(0)->getType())) {
1913       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1914                                    PointerType::get(Type::Int8Ty), I);
1915       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1916       return new PtrToIntInst(I2, CI->getType());
1917     }
1918   }
1919
1920   return Changed ? &I : 0;
1921 }
1922
1923 // isSignBit - Return true if the value represented by the constant only has the
1924 // highest order bit set.
1925 static bool isSignBit(ConstantInt *CI) {
1926   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1927   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1928 }
1929
1930 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1931   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1932
1933   if (Op0 == Op1)         // sub X, X  -> 0
1934     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1935
1936   // If this is a 'B = x-(-A)', change to B = x+A...
1937   if (Value *V = dyn_castNegVal(Op1))
1938     return BinaryOperator::createAdd(Op0, V);
1939
1940   if (isa<UndefValue>(Op0))
1941     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1942   if (isa<UndefValue>(Op1))
1943     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1944
1945   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1946     // Replace (-1 - A) with (~A)...
1947     if (C->isAllOnesValue())
1948       return BinaryOperator::createNot(Op1);
1949
1950     // C - ~X == X + (1+C)
1951     Value *X = 0;
1952     if (match(Op1, m_Not(m_Value(X))))
1953       return BinaryOperator::createAdd(X,
1954                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1955     // -(X >>u 31) -> (X >>s 31)
1956     // -(X >>s 31) -> (X >>u 31)
1957     if (C->isNullValue()) {
1958       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
1959         if (SI->getOpcode() == Instruction::LShr) {
1960           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1961             // Check to see if we are shifting out everything but the sign bit.
1962             if (CU->getZExtValue() == 
1963                 SI->getType()->getPrimitiveSizeInBits()-1) {
1964               // Ok, the transformation is safe.  Insert AShr.
1965               return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
1966                                    SI->getName());
1967             }
1968           }
1969         }
1970         else if (SI->getOpcode() == Instruction::AShr) {
1971           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972             // Check to see if we are shifting out everything but the sign bit.
1973             if (CU->getZExtValue() == 
1974                 SI->getType()->getPrimitiveSizeInBits()-1) {
1975               // Ok, the transformation is safe.  Insert LShr. 
1976               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
1977                                    SI->getName());
1978             }
1979           }
1980         } 
1981     }
1982
1983     // Try to fold constant sub into select arguments.
1984     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1985       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1986         return R;
1987
1988     if (isa<PHINode>(Op0))
1989       if (Instruction *NV = FoldOpIntoPhi(I))
1990         return NV;
1991   }
1992
1993   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994     if (Op1I->getOpcode() == Instruction::Add &&
1995         !Op0->getType()->isFPOrFPVector()) {
1996       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1997         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1998       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
1999         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2000       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002           // C1-(X+C2) --> (C1-C2)-X
2003           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004                                            Op1I->getOperand(0));
2005       }
2006     }
2007
2008     if (Op1I->hasOneUse()) {
2009       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010       // is not used by anyone else...
2011       //
2012       if (Op1I->getOpcode() == Instruction::Sub &&
2013           !Op1I->getType()->isFPOrFPVector()) {
2014         // Swap the two operands of the subexpr...
2015         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016         Op1I->setOperand(0, IIOp1);
2017         Op1I->setOperand(1, IIOp0);
2018
2019         // Create the new top level add instruction...
2020         return BinaryOperator::createAdd(Op0, Op1);
2021       }
2022
2023       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024       //
2025       if (Op1I->getOpcode() == Instruction::And &&
2026           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
2029         Value *NewNot =
2030           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2031         return BinaryOperator::createAnd(Op0, NewNot);
2032       }
2033
2034       // 0 - (X sdiv C)  -> (X sdiv -C)
2035       if (Op1I->getOpcode() == Instruction::SDiv)
2036         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2037           if (CSI->isNullValue())
2038             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2039               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2040                                                ConstantExpr::getNeg(DivRHS));
2041
2042       // X - X*C --> X * (1-C)
2043       ConstantInt *C2 = 0;
2044       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2045         Constant *CP1 =
2046           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2047         return BinaryOperator::createMul(Op0, CP1);
2048       }
2049     }
2050   }
2051
2052   if (!Op0->getType()->isFPOrFPVector())
2053     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054       if (Op0I->getOpcode() == Instruction::Add) {
2055         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2056           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2058           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2059       } else if (Op0I->getOpcode() == Instruction::Sub) {
2060         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2061           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2062       }
2063
2064   ConstantInt *C1;
2065   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066     if (X == Op1) { // X*C - X --> X * (C-1)
2067       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068       return BinaryOperator::createMul(Op1, CP1);
2069     }
2070
2071     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2072     if (X == dyn_castFoldableMul(Op1, C2))
2073       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074   }
2075   return 0;
2076 }
2077
2078 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2079 /// really just returns true if the most significant (sign) bit is set.
2080 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2081   switch (pred) {
2082     case ICmpInst::ICMP_SLT: 
2083       // True if LHS s< RHS and RHS == 0
2084       return RHS->isNullValue();
2085     case ICmpInst::ICMP_SLE: 
2086       // True if LHS s<= RHS and RHS == -1
2087       return RHS->isAllOnesValue();
2088     case ICmpInst::ICMP_UGE: 
2089       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2090       return RHS->getZExtValue() == (1ULL << 
2091         (RHS->getType()->getPrimitiveSizeInBits()-1));
2092     case ICmpInst::ICMP_UGT:
2093       // True if LHS u> RHS and RHS == high-bit-mask - 1
2094       return RHS->getZExtValue() ==
2095         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2096     default:
2097       return false;
2098   }
2099 }
2100
2101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2102   bool Changed = SimplifyCommutative(I);
2103   Value *Op0 = I.getOperand(0);
2104
2105   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2106     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
2108   // Simplify mul instructions with a constant RHS...
2109   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2111
2112       // ((X << C1)*C2) == (X * (C2 << C1))
2113       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114         if (SI->getOpcode() == Instruction::Shl)
2115           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2116             return BinaryOperator::createMul(SI->getOperand(0),
2117                                              ConstantExpr::getShl(CI, ShOp));
2118
2119       if (CI->isNullValue())
2120         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2121       if (CI->equalsInt(1))                  // X * 1  == X
2122         return ReplaceInstUsesWith(I, Op0);
2123       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2124         return BinaryOperator::createNeg(Op0, I.getName());
2125
2126       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2127       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2128         uint64_t C = Log2_64(Val);
2129         return new ShiftInst(Instruction::Shl, Op0,
2130                              ConstantInt::get(Type::Int8Ty, C));
2131       }
2132     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2133       if (Op1F->isNullValue())
2134         return ReplaceInstUsesWith(I, Op1);
2135
2136       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2137       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138       if (Op1F->getValue() == 1.0)
2139         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2140     }
2141     
2142     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144           isa<ConstantInt>(Op0I->getOperand(1))) {
2145         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147                                                      Op1, "tmp");
2148         InsertNewInstBefore(Add, I);
2149         Value *C1C2 = ConstantExpr::getMul(Op1, 
2150                                            cast<Constant>(Op0I->getOperand(1)));
2151         return BinaryOperator::createAdd(Add, C1C2);
2152         
2153       }
2154
2155     // Try to fold constant mul into select arguments.
2156     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2157       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2158         return R;
2159
2160     if (isa<PHINode>(Op0))
2161       if (Instruction *NV = FoldOpIntoPhi(I))
2162         return NV;
2163   }
2164
2165   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2166     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2167       return BinaryOperator::createMul(Op0v, Op1v);
2168
2169   // If one of the operands of the multiply is a cast from a boolean value, then
2170   // we know the bool is either zero or one, so this is a 'masking' multiply.
2171   // See if we can simplify things based on how the boolean was originally
2172   // formed.
2173   CastInst *BoolCast = 0;
2174   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2175     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2176       BoolCast = CI;
2177   if (!BoolCast)
2178     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2179       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2180         BoolCast = CI;
2181   if (BoolCast) {
2182     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2183       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184       const Type *SCOpTy = SCIOp0->getType();
2185
2186       // If the icmp is true iff the sign bit of X is set, then convert this
2187       // multiply into a shift/and combination.
2188       if (isa<ConstantInt>(SCIOp1) &&
2189           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2190         // Shift the X value right to turn it into "all signbits".
2191         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2192                                           SCOpTy->getPrimitiveSizeInBits()-1);
2193         Value *V =
2194           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2195                                             BoolCast->getOperand(0)->getName()+
2196                                             ".mask"), I);
2197
2198         // If the multiply type is not the same as the source type, sign extend
2199         // or truncate to the multiply type.
2200         if (I.getType() != V->getType()) {
2201           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2202           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2203           Instruction::CastOps opcode = 
2204             (SrcBits == DstBits ? Instruction::BitCast : 
2205              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2206           V = InsertCastBefore(opcode, V, I.getType(), I);
2207         }
2208
2209         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2210         return BinaryOperator::createAnd(V, OtherOp);
2211       }
2212     }
2213   }
2214
2215   return Changed ? &I : 0;
2216 }
2217
2218 /// This function implements the transforms on div instructions that work
2219 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2220 /// used by the visitors to those instructions.
2221 /// @brief Transforms common to all three div instructions
2222 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2223   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2224
2225   // undef / X -> 0
2226   if (isa<UndefValue>(Op0))
2227     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2228
2229   // X / undef -> undef
2230   if (isa<UndefValue>(Op1))
2231     return ReplaceInstUsesWith(I, Op1);
2232
2233   // Handle cases involving: div X, (select Cond, Y, Z)
2234   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2235     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2236     // same basic block, then we replace the select with Y, and the condition 
2237     // of the select with false (if the cond value is in the same BB).  If the
2238     // select has uses other than the div, this allows them to be simplified
2239     // also. Note that div X, Y is just as good as div X, 0 (undef)
2240     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2241       if (ST->isNullValue()) {
2242         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2243         if (CondI && CondI->getParent() == I.getParent())
2244           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2245         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2246           I.setOperand(1, SI->getOperand(2));
2247         else
2248           UpdateValueUsesWith(SI, SI->getOperand(2));
2249         return &I;
2250       }
2251
2252     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2253     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2254       if (ST->isNullValue()) {
2255         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2256         if (CondI && CondI->getParent() == I.getParent())
2257           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2258         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2259           I.setOperand(1, SI->getOperand(1));
2260         else
2261           UpdateValueUsesWith(SI, SI->getOperand(1));
2262         return &I;
2263       }
2264   }
2265
2266   return 0;
2267 }
2268
2269 /// This function implements the transforms common to both integer division
2270 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2271 /// division instructions.
2272 /// @brief Common integer divide transforms
2273 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2274   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
2276   if (Instruction *Common = commonDivTransforms(I))
2277     return Common;
2278
2279   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2280     // div X, 1 == X
2281     if (RHS->equalsInt(1))
2282       return ReplaceInstUsesWith(I, Op0);
2283
2284     // (X / C1) / C2  -> X / (C1*C2)
2285     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2286       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2287         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2288           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2289                                         ConstantExpr::getMul(RHS, LHSRHS));
2290         }
2291
2292     if (!RHS->isNullValue()) { // avoid X udiv 0
2293       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2294         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2295           return R;
2296       if (isa<PHINode>(Op0))
2297         if (Instruction *NV = FoldOpIntoPhi(I))
2298           return NV;
2299     }
2300   }
2301
2302   // 0 / X == 0, we don't need to preserve faults!
2303   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2304     if (LHS->equalsInt(0))
2305       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306
2307   return 0;
2308 }
2309
2310 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2311   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2312
2313   // Handle the integer div common cases
2314   if (Instruction *Common = commonIDivTransforms(I))
2315     return Common;
2316
2317   // X udiv C^2 -> X >> C
2318   // Check to see if this is an unsigned division with an exact power of 2,
2319   // if so, convert to a right shift.
2320   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2321     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2322       if (isPowerOf2_64(Val)) {
2323         uint64_t ShiftAmt = Log2_64(Val);
2324         return new ShiftInst(Instruction::LShr, Op0, 
2325                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2326       }
2327   }
2328
2329   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2330   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2331     if (RHSI->getOpcode() == Instruction::Shl &&
2332         isa<ConstantInt>(RHSI->getOperand(0))) {
2333       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2334       if (isPowerOf2_64(C1)) {
2335         Value *N = RHSI->getOperand(1);
2336         const Type *NTy = N->getType();
2337         if (uint64_t C2 = Log2_64(C1)) {
2338           Constant *C2V = ConstantInt::get(NTy, C2);
2339           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2340         }
2341         return new ShiftInst(Instruction::LShr, Op0, N);
2342       }
2343     }
2344   }
2345   
2346   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2347   // where C1&C2 are powers of two.
2348   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2349     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2350       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2351         if (!STO->isNullValue() && !STO->isNullValue()) {
2352           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2353           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2354             // Compute the shift amounts
2355             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2356             // Construct the "on true" case of the select
2357             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2358             Instruction *TSI = 
2359               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2360             TSI = InsertNewInstBefore(TSI, I);
2361     
2362             // Construct the "on false" case of the select
2363             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2364             Instruction *FSI = 
2365               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2366             FSI = InsertNewInstBefore(FSI, I);
2367
2368             // construct the select instruction and return it.
2369             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2370           }
2371         }
2372   }
2373   return 0;
2374 }
2375
2376 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2377   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378
2379   // Handle the integer div common cases
2380   if (Instruction *Common = commonIDivTransforms(I))
2381     return Common;
2382
2383   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2384     // sdiv X, -1 == -X
2385     if (RHS->isAllOnesValue())
2386       return BinaryOperator::createNeg(Op0);
2387
2388     // -X/C -> X/-C
2389     if (Value *LHSNeg = dyn_castNegVal(Op0))
2390       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2391   }
2392
2393   // If the sign bits of both operands are zero (i.e. we can prove they are
2394   // unsigned inputs), turn this into a udiv.
2395   if (I.getType()->isInteger()) {
2396     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2397     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2398       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2399     }
2400   }      
2401   
2402   return 0;
2403 }
2404
2405 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2406   return commonDivTransforms(I);
2407 }
2408
2409 /// GetFactor - If we can prove that the specified value is at least a multiple
2410 /// of some factor, return that factor.
2411 static Constant *GetFactor(Value *V) {
2412   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2413     return CI;
2414   
2415   // Unless we can be tricky, we know this is a multiple of 1.
2416   Constant *Result = ConstantInt::get(V->getType(), 1);
2417   
2418   Instruction *I = dyn_cast<Instruction>(V);
2419   if (!I) return Result;
2420   
2421   if (I->getOpcode() == Instruction::Mul) {
2422     // Handle multiplies by a constant, etc.
2423     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2424                                 GetFactor(I->getOperand(1)));
2425   } else if (I->getOpcode() == Instruction::Shl) {
2426     // (X<<C) -> X * (1 << C)
2427     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2428       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2429       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2430     }
2431   } else if (I->getOpcode() == Instruction::And) {
2432     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2433       // X & 0xFFF0 is known to be a multiple of 16.
2434       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2435       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2436         return ConstantExpr::getShl(Result, 
2437                                     ConstantInt::get(Type::Int8Ty, Zeros));
2438     }
2439   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2440     // Only handle int->int casts.
2441     if (!CI->isIntegerCast())
2442       return Result;
2443     Value *Op = CI->getOperand(0);
2444     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2445   }    
2446   return Result;
2447 }
2448
2449 /// This function implements the transforms on rem instructions that work
2450 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2451 /// is used by the visitors to those instructions.
2452 /// @brief Transforms common to all three rem instructions
2453 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2454   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455
2456   // 0 % X == 0, we don't need to preserve faults!
2457   if (Constant *LHS = dyn_cast<Constant>(Op0))
2458     if (LHS->isNullValue())
2459       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461   if (isa<UndefValue>(Op0))              // undef % X -> 0
2462     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463   if (isa<UndefValue>(Op1))
2464     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2465
2466   // Handle cases involving: rem X, (select Cond, Y, Z)
2467   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2468     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2469     // the same basic block, then we replace the select with Y, and the
2470     // condition of the select with false (if the cond value is in the same
2471     // BB).  If the select has uses other than the div, this allows them to be
2472     // simplified also.
2473     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2474       if (ST->isNullValue()) {
2475         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476         if (CondI && CondI->getParent() == I.getParent())
2477           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2478         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479           I.setOperand(1, SI->getOperand(2));
2480         else
2481           UpdateValueUsesWith(SI, SI->getOperand(2));
2482         return &I;
2483       }
2484     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2485     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486       if (ST->isNullValue()) {
2487         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488         if (CondI && CondI->getParent() == I.getParent())
2489           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2490         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491           I.setOperand(1, SI->getOperand(1));
2492         else
2493           UpdateValueUsesWith(SI, SI->getOperand(1));
2494         return &I;
2495       }
2496   }
2497
2498   return 0;
2499 }
2500
2501 /// This function implements the transforms common to both integer remainder
2502 /// instructions (urem and srem). It is called by the visitors to those integer
2503 /// remainder instructions.
2504 /// @brief Common integer remainder transforms
2505 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2506   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508   if (Instruction *common = commonRemTransforms(I))
2509     return common;
2510
2511   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2512     // X % 0 == undef, we don't need to preserve faults!
2513     if (RHS->equalsInt(0))
2514       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2515     
2516     if (RHS->equalsInt(1))  // X % 1 == 0
2517       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
2519     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2520       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2521         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2522           return R;
2523       } else if (isa<PHINode>(Op0I)) {
2524         if (Instruction *NV = FoldOpIntoPhi(I))
2525           return NV;
2526       }
2527       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2528       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2529         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2530     }
2531   }
2532
2533   return 0;
2534 }
2535
2536 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539   if (Instruction *common = commonIRemTransforms(I))
2540     return common;
2541   
2542   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543     // X urem C^2 -> X and C
2544     // Check to see if this is an unsigned remainder with an exact power of 2,
2545     // if so, convert to a bitwise and.
2546     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2547       if (isPowerOf2_64(C->getZExtValue()))
2548         return BinaryOperator::createAnd(Op0, SubOne(C));
2549   }
2550
2551   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2552     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2553     if (RHSI->getOpcode() == Instruction::Shl &&
2554         isa<ConstantInt>(RHSI->getOperand(0))) {
2555       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2556       if (isPowerOf2_64(C1)) {
2557         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2558         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2559                                                                    "tmp"), I);
2560         return BinaryOperator::createAnd(Op0, Add);
2561       }
2562     }
2563   }
2564
2565   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2566   // where C1&C2 are powers of two.
2567   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2568     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2569       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2570         // STO == 0 and SFO == 0 handled above.
2571         if (isPowerOf2_64(STO->getZExtValue()) && 
2572             isPowerOf2_64(SFO->getZExtValue())) {
2573           Value *TrueAnd = InsertNewInstBefore(
2574             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2575           Value *FalseAnd = InsertNewInstBefore(
2576             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2577           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2578         }
2579       }
2580   }
2581   
2582   return 0;
2583 }
2584
2585 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   if (Instruction *common = commonIRemTransforms(I))
2589     return common;
2590   
2591   if (Value *RHSNeg = dyn_castNegVal(Op1))
2592     if (!isa<ConstantInt>(RHSNeg) || 
2593         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2594       // X % -Y -> X % Y
2595       AddUsesToWorkList(I);
2596       I.setOperand(1, RHSNeg);
2597       return &I;
2598     }
2599  
2600   // If the top bits of both operands are zero (i.e. we can prove they are
2601   // unsigned inputs), turn this into a urem.
2602   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2603   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2605     return BinaryOperator::createURem(Op0, Op1, I.getName());
2606   }
2607
2608   return 0;
2609 }
2610
2611 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2612   return commonRemTransforms(I);
2613 }
2614
2615 // isMaxValueMinusOne - return true if this is Max-1
2616 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2617   if (isSigned) {
2618     // Calculate 0111111111..11111
2619     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2620     int64_t Val = INT64_MAX;             // All ones
2621     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2622     return C->getSExtValue() == Val-1;
2623   }
2624   return C->getZExtValue() == C->getType()->getIntegerTypeMask()-1;
2625 }
2626
2627 // isMinValuePlusOne - return true if this is Min+1
2628 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2629   if (isSigned) {
2630     // Calculate 1111111111000000000000
2631     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2632     int64_t Val = -1;                    // All ones
2633     Val <<= TypeBits-1;                  // Shift over to the right spot
2634     return C->getSExtValue() == Val+1;
2635   }
2636   return C->getZExtValue() == 1; // unsigned
2637 }
2638
2639 // isOneBitSet - Return true if there is exactly one bit set in the specified
2640 // constant.
2641 static bool isOneBitSet(const ConstantInt *CI) {
2642   uint64_t V = CI->getZExtValue();
2643   return V && (V & (V-1)) == 0;
2644 }
2645
2646 #if 0   // Currently unused
2647 // isLowOnes - Return true if the constant is of the form 0+1+.
2648 static bool isLowOnes(const ConstantInt *CI) {
2649   uint64_t V = CI->getZExtValue();
2650
2651   // There won't be bits set in parts that the type doesn't contain.
2652   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2653
2654   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2655   return U && V && (U & V) == 0;
2656 }
2657 #endif
2658
2659 // isHighOnes - Return true if the constant is of the form 1+0+.
2660 // This is the same as lowones(~X).
2661 static bool isHighOnes(const ConstantInt *CI) {
2662   uint64_t V = ~CI->getZExtValue();
2663   if (~V == 0) return false;  // 0's does not match "1+"
2664
2665   // There won't be bits set in parts that the type doesn't contain.
2666   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2667
2668   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2669   return U && V && (U & V) == 0;
2670 }
2671
2672 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2673 /// are carefully arranged to allow folding of expressions such as:
2674 ///
2675 ///      (A < B) | (A > B) --> (A != B)
2676 ///
2677 /// Note that this is only valid if the first and second predicates have the
2678 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2679 ///
2680 /// Three bits are used to represent the condition, as follows:
2681 ///   0  A > B
2682 ///   1  A == B
2683 ///   2  A < B
2684 ///
2685 /// <=>  Value  Definition
2686 /// 000     0   Always false
2687 /// 001     1   A >  B
2688 /// 010     2   A == B
2689 /// 011     3   A >= B
2690 /// 100     4   A <  B
2691 /// 101     5   A != B
2692 /// 110     6   A <= B
2693 /// 111     7   Always true
2694 ///  
2695 static unsigned getICmpCode(const ICmpInst *ICI) {
2696   switch (ICI->getPredicate()) {
2697     // False -> 0
2698   case ICmpInst::ICMP_UGT: return 1;  // 001
2699   case ICmpInst::ICMP_SGT: return 1;  // 001
2700   case ICmpInst::ICMP_EQ:  return 2;  // 010
2701   case ICmpInst::ICMP_UGE: return 3;  // 011
2702   case ICmpInst::ICMP_SGE: return 3;  // 011
2703   case ICmpInst::ICMP_ULT: return 4;  // 100
2704   case ICmpInst::ICMP_SLT: return 4;  // 100
2705   case ICmpInst::ICMP_NE:  return 5;  // 101
2706   case ICmpInst::ICMP_ULE: return 6;  // 110
2707   case ICmpInst::ICMP_SLE: return 6;  // 110
2708     // True -> 7
2709   default:
2710     assert(0 && "Invalid ICmp predicate!");
2711     return 0;
2712   }
2713 }
2714
2715 /// getICmpValue - This is the complement of getICmpCode, which turns an
2716 /// opcode and two operands into either a constant true or false, or a brand 
2717 /// new /// ICmp instruction. The sign is passed in to determine which kind
2718 /// of predicate to use in new icmp instructions.
2719 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2720   switch (code) {
2721   default: assert(0 && "Illegal ICmp code!");
2722   case  0: return ConstantInt::getFalse();
2723   case  1: 
2724     if (sign)
2725       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2726     else
2727       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2728   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2729   case  3: 
2730     if (sign)
2731       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2732     else
2733       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2734   case  4: 
2735     if (sign)
2736       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2737     else
2738       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2739   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2740   case  6: 
2741     if (sign)
2742       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2743     else
2744       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2745   case  7: return ConstantInt::getTrue();
2746   }
2747 }
2748
2749 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2750   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2751     (ICmpInst::isSignedPredicate(p1) && 
2752      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2753     (ICmpInst::isSignedPredicate(p2) && 
2754      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2755 }
2756
2757 namespace { 
2758 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2759 struct FoldICmpLogical {
2760   InstCombiner &IC;
2761   Value *LHS, *RHS;
2762   ICmpInst::Predicate pred;
2763   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2764     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2765       pred(ICI->getPredicate()) {}
2766   bool shouldApply(Value *V) const {
2767     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2768       if (PredicatesFoldable(pred, ICI->getPredicate()))
2769         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2770                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2771     return false;
2772   }
2773   Instruction *apply(Instruction &Log) const {
2774     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2775     if (ICI->getOperand(0) != LHS) {
2776       assert(ICI->getOperand(1) == LHS);
2777       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2778     }
2779
2780     unsigned LHSCode = getICmpCode(ICI);
2781     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2782     unsigned Code;
2783     switch (Log.getOpcode()) {
2784     case Instruction::And: Code = LHSCode & RHSCode; break;
2785     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2786     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2787     default: assert(0 && "Illegal logical opcode!"); return 0;
2788     }
2789
2790     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2791     if (Instruction *I = dyn_cast<Instruction>(RV))
2792       return I;
2793     // Otherwise, it's a constant boolean value...
2794     return IC.ReplaceInstUsesWith(Log, RV);
2795   }
2796 };
2797 } // end anonymous namespace
2798
2799 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2800 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2801 // guaranteed to be either a shift instruction or a binary operator.
2802 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2803                                     ConstantInt *OpRHS,
2804                                     ConstantInt *AndRHS,
2805                                     BinaryOperator &TheAnd) {
2806   Value *X = Op->getOperand(0);
2807   Constant *Together = 0;
2808   if (!isa<ShiftInst>(Op))
2809     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2810
2811   switch (Op->getOpcode()) {
2812   case Instruction::Xor:
2813     if (Op->hasOneUse()) {
2814       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815       std::string OpName = Op->getName(); Op->setName("");
2816       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2817       InsertNewInstBefore(And, TheAnd);
2818       return BinaryOperator::createXor(And, Together);
2819     }
2820     break;
2821   case Instruction::Or:
2822     if (Together == AndRHS) // (X | C) & C --> C
2823       return ReplaceInstUsesWith(TheAnd, AndRHS);
2824
2825     if (Op->hasOneUse() && Together != OpRHS) {
2826       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827       std::string Op0Name = Op->getName(); Op->setName("");
2828       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829       InsertNewInstBefore(Or, TheAnd);
2830       return BinaryOperator::createAnd(Or, AndRHS);
2831     }
2832     break;
2833   case Instruction::Add:
2834     if (Op->hasOneUse()) {
2835       // Adding a one to a single bit bit-field should be turned into an XOR
2836       // of the bit.  First thing to check is to see if this AND is with a
2837       // single bit constant.
2838       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2839
2840       // Clear bits that are not part of the constant.
2841       AndRHSV &= AndRHS->getType()->getIntegerTypeMask();
2842
2843       // If there is only one bit set...
2844       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2845         // Ok, at this point, we know that we are masking the result of the
2846         // ADD down to exactly one bit.  If the constant we are adding has
2847         // no bits set below this bit, then we can eliminate the ADD.
2848         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2849
2850         // Check to see if any bits below the one bit set in AndRHSV are set.
2851         if ((AddRHS & (AndRHSV-1)) == 0) {
2852           // If not, the only thing that can effect the output of the AND is
2853           // the bit specified by AndRHSV.  If that bit is set, the effect of
2854           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2855           // no effect.
2856           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857             TheAnd.setOperand(0, X);
2858             return &TheAnd;
2859           } else {
2860             std::string Name = Op->getName(); Op->setName("");
2861             // Pull the XOR out of the AND.
2862             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2863             InsertNewInstBefore(NewAnd, TheAnd);
2864             return BinaryOperator::createXor(NewAnd, AndRHS);
2865           }
2866         }
2867       }
2868     }
2869     break;
2870
2871   case Instruction::Shl: {
2872     // We know that the AND will not produce any of the bits shifted in, so if
2873     // the anded constant includes them, clear them now!
2874     //
2875     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2876     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2878
2879     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2880       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2881     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2882       TheAnd.setOperand(1, CI);
2883       return &TheAnd;
2884     }
2885     break;
2886   }
2887   case Instruction::LShr:
2888   {
2889     // We know that the AND will not produce any of the bits shifted in, so if
2890     // the anded constant includes them, clear them now!  This only applies to
2891     // unsigned shifts, because a signed shr may bring in set bits!
2892     //
2893     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2894     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2896
2897     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2898       return ReplaceInstUsesWith(TheAnd, Op);
2899     } else if (CI != AndRHS) {
2900       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2901       return &TheAnd;
2902     }
2903     break;
2904   }
2905   case Instruction::AShr:
2906     // Signed shr.
2907     // See if this is shifting in some sign extension, then masking it out
2908     // with an and.
2909     if (Op->hasOneUse()) {
2910       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2911       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2912       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2913       if (C == AndRHS) {          // Masking out bits shifted in.
2914         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2915         // Make the argument unsigned.
2916         Value *ShVal = Op->getOperand(0);
2917         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2918                                     OpRHS, Op->getName()), TheAnd);
2919         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2920       }
2921     }
2922     break;
2923   }
2924   return 0;
2925 }
2926
2927
2928 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2929 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2930 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2931 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2932 /// insert new instructions.
2933 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2934                                            bool isSigned, bool Inside, 
2935                                            Instruction &IB) {
2936   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2937             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2938          "Lo is not <= Hi in range emission code!");
2939     
2940   if (Inside) {
2941     if (Lo == Hi)  // Trivially false.
2942       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2943
2944     // V >= Min && V < Hi --> V < Hi
2945     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2946     ICmpInst::Predicate pred = (isSigned ? 
2947         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2948       return new ICmpInst(pred, V, Hi);
2949     }
2950
2951     // Emit V-Lo <u Hi-Lo
2952     Constant *NegLo = ConstantExpr::getNeg(Lo);
2953     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2954     InsertNewInstBefore(Add, IB);
2955     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2956     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2957   }
2958
2959   if (Lo == Hi)  // Trivially true.
2960     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2961
2962   // V < Min || V >= Hi ->'V > Hi-1'
2963   Hi = SubOne(cast<ConstantInt>(Hi));
2964   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2965     ICmpInst::Predicate pred = (isSigned ? 
2966         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2967     return new ICmpInst(pred, V, Hi);
2968   }
2969
2970   // Emit V-Lo > Hi-1-Lo
2971   Constant *NegLo = ConstantExpr::getNeg(Lo);
2972   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2973   InsertNewInstBefore(Add, IB);
2974   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2975   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2976 }
2977
2978 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2979 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2980 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2981 // not, since all 1s are not contiguous.
2982 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
2983   uint64_t V = Val->getZExtValue();
2984   if (!isShiftedMask_64(V)) return false;
2985
2986   // look for the first zero bit after the run of ones
2987   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2988   // look for the first non-zero bit
2989   ME = 64-CountLeadingZeros_64(V);
2990   return true;
2991 }
2992
2993
2994
2995 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2996 /// where isSub determines whether the operator is a sub.  If we can fold one of
2997 /// the following xforms:
2998 /// 
2999 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3000 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3001 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3002 ///
3003 /// return (A +/- B).
3004 ///
3005 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3006                                         ConstantInt *Mask, bool isSub,
3007                                         Instruction &I) {
3008   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3009   if (!LHSI || LHSI->getNumOperands() != 2 ||
3010       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3011
3012   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3013
3014   switch (LHSI->getOpcode()) {
3015   default: return 0;
3016   case Instruction::And:
3017     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3018       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3019       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3020         break;
3021
3022       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3023       // part, we don't need any explicit masks to take them out of A.  If that
3024       // is all N is, ignore it.
3025       unsigned MB, ME;
3026       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3027         uint64_t Mask = RHS->getType()->getIntegerTypeMask();
3028         Mask >>= 64-MB+1;
3029         if (MaskedValueIsZero(RHS, Mask))
3030           break;
3031       }
3032     }
3033     return 0;
3034   case Instruction::Or:
3035   case Instruction::Xor:
3036     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3037     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3038         ConstantExpr::getAnd(N, Mask)->isNullValue())
3039       break;
3040     return 0;
3041   }
3042   
3043   Instruction *New;
3044   if (isSub)
3045     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3046   else
3047     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3048   return InsertNewInstBefore(New, I);
3049 }
3050
3051 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3052   bool Changed = SimplifyCommutative(I);
3053   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3056     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3057
3058   // and X, X = X
3059   if (Op0 == Op1)
3060     return ReplaceInstUsesWith(I, Op1);
3061
3062   // See if we can simplify any instructions used by the instruction whose sole 
3063   // purpose is to compute bits we don't care about.
3064   uint64_t KnownZero, KnownOne;
3065   if (!isa<PackedType>(I.getType())) {
3066     if (SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3067                              KnownZero, KnownOne))
3068     return &I;
3069   } else {
3070     if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3071       if (CP->isAllOnesValue())
3072         return ReplaceInstUsesWith(I, I.getOperand(0));
3073     }
3074   }
3075   
3076   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3077     uint64_t AndRHSMask = AndRHS->getZExtValue();
3078     uint64_t TypeMask = Op0->getType()->getIntegerTypeMask();
3079     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3080
3081     // Optimize a variety of ((val OP C1) & C2) combinations...
3082     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3083       Instruction *Op0I = cast<Instruction>(Op0);
3084       Value *Op0LHS = Op0I->getOperand(0);
3085       Value *Op0RHS = Op0I->getOperand(1);
3086       switch (Op0I->getOpcode()) {
3087       case Instruction::Xor:
3088       case Instruction::Or:
3089         // If the mask is only needed on one incoming arm, push it up.
3090         if (Op0I->hasOneUse()) {
3091           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3092             // Not masking anything out for the LHS, move to RHS.
3093             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3094                                                    Op0RHS->getName()+".masked");
3095             InsertNewInstBefore(NewRHS, I);
3096             return BinaryOperator::create(
3097                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3098           }
3099           if (!isa<Constant>(Op0RHS) &&
3100               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3101             // Not masking anything out for the RHS, move to LHS.
3102             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3103                                                    Op0LHS->getName()+".masked");
3104             InsertNewInstBefore(NewLHS, I);
3105             return BinaryOperator::create(
3106                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3107           }
3108         }
3109
3110         break;
3111       case Instruction::Add:
3112         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3113         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3114         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3115         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3116           return BinaryOperator::createAnd(V, AndRHS);
3117         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3118           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3119         break;
3120
3121       case Instruction::Sub:
3122         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3123         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3124         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3125         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3126           return BinaryOperator::createAnd(V, AndRHS);
3127         break;
3128       }
3129
3130       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3131         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3132           return Res;
3133     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3134       // If this is an integer truncation or change from signed-to-unsigned, and
3135       // if the source is an and/or with immediate, transform it.  This
3136       // frequently occurs for bitfield accesses.
3137       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3138         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3139             CastOp->getNumOperands() == 2)
3140           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3141             if (CastOp->getOpcode() == Instruction::And) {
3142               // Change: and (cast (and X, C1) to T), C2
3143               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3144               // This will fold the two constants together, which may allow 
3145               // other simplifications.
3146               Instruction *NewCast = CastInst::createTruncOrBitCast(
3147                 CastOp->getOperand(0), I.getType(), 
3148                 CastOp->getName()+".shrunk");
3149               NewCast = InsertNewInstBefore(NewCast, I);
3150               // trunc_or_bitcast(C1)&C2
3151               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3152               C3 = ConstantExpr::getAnd(C3, AndRHS);
3153               return BinaryOperator::createAnd(NewCast, C3);
3154             } else if (CastOp->getOpcode() == Instruction::Or) {
3155               // Change: and (cast (or X, C1) to T), C2
3156               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3157               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3158               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3159                 return ReplaceInstUsesWith(I, AndRHS);
3160             }
3161       }
3162     }
3163
3164     // Try to fold constant and into select arguments.
3165     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3166       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3167         return R;
3168     if (isa<PHINode>(Op0))
3169       if (Instruction *NV = FoldOpIntoPhi(I))
3170         return NV;
3171   }
3172
3173   Value *Op0NotVal = dyn_castNotVal(Op0);
3174   Value *Op1NotVal = dyn_castNotVal(Op1);
3175
3176   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3177     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3178
3179   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3180   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3181     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3182                                                I.getName()+".demorgan");
3183     InsertNewInstBefore(Or, I);
3184     return BinaryOperator::createNot(Or);
3185   }
3186   
3187   {
3188     Value *A = 0, *B = 0;
3189     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3190       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3191         return ReplaceInstUsesWith(I, Op1);
3192     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3193       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3194         return ReplaceInstUsesWith(I, Op0);
3195     
3196     if (Op0->hasOneUse() &&
3197         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3198       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3199         I.swapOperands();     // Simplify below
3200         std::swap(Op0, Op1);
3201       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3202         cast<BinaryOperator>(Op0)->swapOperands();
3203         I.swapOperands();     // Simplify below
3204         std::swap(Op0, Op1);
3205       }
3206     }
3207     if (Op1->hasOneUse() &&
3208         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3209       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3210         cast<BinaryOperator>(Op1)->swapOperands();
3211         std::swap(A, B);
3212       }
3213       if (A == Op0) {                                // A&(A^B) -> A & ~B
3214         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3215         InsertNewInstBefore(NotB, I);
3216         return BinaryOperator::createAnd(A, NotB);
3217       }
3218     }
3219   }
3220   
3221   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3222     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3223     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3224       return R;
3225
3226     Value *LHSVal, *RHSVal;
3227     ConstantInt *LHSCst, *RHSCst;
3228     ICmpInst::Predicate LHSCC, RHSCC;
3229     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3230       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3231         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3232             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3233             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3234             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3235             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3236             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3237           // Ensure that the larger constant is on the RHS.
3238           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3239             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3240           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3241           ICmpInst *LHS = cast<ICmpInst>(Op0);
3242           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3243             std::swap(LHS, RHS);
3244             std::swap(LHSCst, RHSCst);
3245             std::swap(LHSCC, RHSCC);
3246           }
3247
3248           // At this point, we know we have have two icmp instructions
3249           // comparing a value against two constants and and'ing the result
3250           // together.  Because of the above check, we know that we only have
3251           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3252           // (from the FoldICmpLogical check above), that the two constants 
3253           // are not equal and that the larger constant is on the RHS
3254           assert(LHSCst != RHSCst && "Compares not folded above?");
3255
3256           switch (LHSCC) {
3257           default: assert(0 && "Unknown integer condition code!");
3258           case ICmpInst::ICMP_EQ:
3259             switch (RHSCC) {
3260             default: assert(0 && "Unknown integer condition code!");
3261             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3262             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3263             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3264               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3265             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3266             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3267             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3268               return ReplaceInstUsesWith(I, LHS);
3269             }
3270           case ICmpInst::ICMP_NE:
3271             switch (RHSCC) {
3272             default: assert(0 && "Unknown integer condition code!");
3273             case ICmpInst::ICMP_ULT:
3274               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3275                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3276               break;                        // (X != 13 & X u< 15) -> no change
3277             case ICmpInst::ICMP_SLT:
3278               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3279                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3280               break;                        // (X != 13 & X s< 15) -> no change
3281             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3282             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3283             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3284               return ReplaceInstUsesWith(I, RHS);
3285             case ICmpInst::ICMP_NE:
3286               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3287                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3288                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3289                                                       LHSVal->getName()+".off");
3290                 InsertNewInstBefore(Add, I);
3291                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3292               }
3293               break;                        // (X != 13 & X != 15) -> no change
3294             }
3295             break;
3296           case ICmpInst::ICMP_ULT:
3297             switch (RHSCC) {
3298             default: assert(0 && "Unknown integer condition code!");
3299             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3300             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3301               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3302             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3303               break;
3304             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3305             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3306               return ReplaceInstUsesWith(I, LHS);
3307             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3308               break;
3309             }
3310             break;
3311           case ICmpInst::ICMP_SLT:
3312             switch (RHSCC) {
3313             default: assert(0 && "Unknown integer condition code!");
3314             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3315             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3316               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3317             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3318               break;
3319             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3320             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3321               return ReplaceInstUsesWith(I, LHS);
3322             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3323               break;
3324             }
3325             break;
3326           case ICmpInst::ICMP_UGT:
3327             switch (RHSCC) {
3328             default: assert(0 && "Unknown integer condition code!");
3329             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3330               return ReplaceInstUsesWith(I, LHS);
3331             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3332               return ReplaceInstUsesWith(I, RHS);
3333             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3334               break;
3335             case ICmpInst::ICMP_NE:
3336               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3337                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3338               break;                        // (X u> 13 & X != 15) -> no change
3339             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3340               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3341                                      true, I);
3342             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3343               break;
3344             }
3345             break;
3346           case ICmpInst::ICMP_SGT:
3347             switch (RHSCC) {
3348             default: assert(0 && "Unknown integer condition code!");
3349             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3350               return ReplaceInstUsesWith(I, LHS);
3351             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3352               return ReplaceInstUsesWith(I, RHS);
3353             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3354               break;
3355             case ICmpInst::ICMP_NE:
3356               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3357                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3358               break;                        // (X s> 13 & X != 15) -> no change
3359             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3360               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3361                                      true, I);
3362             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3363               break;
3364             }
3365             break;
3366           }
3367         }
3368   }
3369
3370   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3371   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3372     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3373       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3374         const Type *SrcTy = Op0C->getOperand(0)->getType();
3375         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3376             // Only do this if the casts both really cause code to be generated.
3377             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3378                               I.getType(), TD) &&
3379             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3380                               I.getType(), TD)) {
3381           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3382                                                          Op1C->getOperand(0),
3383                                                          I.getName());
3384           InsertNewInstBefore(NewOp, I);
3385           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3386         }
3387       }
3388     
3389   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3390   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3391     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3392       if (SI0->getOpcode() == SI1->getOpcode() && 
3393           SI0->getOperand(1) == SI1->getOperand(1) &&
3394           (SI0->hasOneUse() || SI1->hasOneUse())) {
3395         Instruction *NewOp =
3396           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3397                                                         SI1->getOperand(0),
3398                                                         SI0->getName()), I);
3399         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3400       }
3401   }
3402
3403   return Changed ? &I : 0;
3404 }
3405
3406 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3407 /// in the result.  If it does, and if the specified byte hasn't been filled in
3408 /// yet, fill it in and return false.
3409 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3410   Instruction *I = dyn_cast<Instruction>(V);
3411   if (I == 0) return true;
3412
3413   // If this is an or instruction, it is an inner node of the bswap.
3414   if (I->getOpcode() == Instruction::Or)
3415     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3416            CollectBSwapParts(I->getOperand(1), ByteValues);
3417   
3418   // If this is a shift by a constant int, and it is "24", then its operand
3419   // defines a byte.  We only handle unsigned types here.
3420   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3421     // Not shifting the entire input by N-1 bytes?
3422     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3423         8*(ByteValues.size()-1))
3424       return true;
3425     
3426     unsigned DestNo;
3427     if (I->getOpcode() == Instruction::Shl) {
3428       // X << 24 defines the top byte with the lowest of the input bytes.
3429       DestNo = ByteValues.size()-1;
3430     } else {
3431       // X >>u 24 defines the low byte with the highest of the input bytes.
3432       DestNo = 0;
3433     }
3434     
3435     // If the destination byte value is already defined, the values are or'd
3436     // together, which isn't a bswap (unless it's an or of the same bits).
3437     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3438       return true;
3439     ByteValues[DestNo] = I->getOperand(0);
3440     return false;
3441   }
3442   
3443   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3444   // don't have this.
3445   Value *Shift = 0, *ShiftLHS = 0;
3446   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3447   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3448       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3449     return true;
3450   Instruction *SI = cast<Instruction>(Shift);
3451
3452   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3453   if (ShiftAmt->getZExtValue() & 7 ||
3454       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3455     return true;
3456   
3457   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3458   unsigned DestByte;
3459   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3460     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3461       break;
3462   // Unknown mask for bswap.
3463   if (DestByte == ByteValues.size()) return true;
3464   
3465   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3466   unsigned SrcByte;
3467   if (SI->getOpcode() == Instruction::Shl)
3468     SrcByte = DestByte - ShiftBytes;
3469   else
3470     SrcByte = DestByte + ShiftBytes;
3471   
3472   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3473   if (SrcByte != ByteValues.size()-DestByte-1)
3474     return true;
3475   
3476   // If the destination byte value is already defined, the values are or'd
3477   // together, which isn't a bswap (unless it's an or of the same bits).
3478   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3479     return true;
3480   ByteValues[DestByte] = SI->getOperand(0);
3481   return false;
3482 }
3483
3484 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3485 /// If so, insert the new bswap intrinsic and return it.
3486 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3487   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3488   if (I.getType() == Type::Int8Ty)
3489     return 0;
3490   
3491   /// ByteValues - For each byte of the result, we keep track of which value
3492   /// defines each byte.
3493   std::vector<Value*> ByteValues;
3494   ByteValues.resize(TD->getTypeSize(I.getType()));
3495     
3496   // Try to find all the pieces corresponding to the bswap.
3497   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3498       CollectBSwapParts(I.getOperand(1), ByteValues))
3499     return 0;
3500   
3501   // Check to see if all of the bytes come from the same value.
3502   Value *V = ByteValues[0];
3503   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3504   
3505   // Check to make sure that all of the bytes come from the same value.
3506   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3507     if (ByteValues[i] != V)
3508       return 0;
3509     
3510   // If they do then *success* we can turn this into a bswap.  Figure out what
3511   // bswap to make it into.
3512   Module *M = I.getParent()->getParent()->getParent();
3513   const char *FnName = 0;
3514   if (I.getType() == Type::Int16Ty)
3515     FnName = "llvm.bswap.i16";
3516   else if (I.getType() == Type::Int32Ty)
3517     FnName = "llvm.bswap.i32";
3518   else if (I.getType() == Type::Int64Ty)
3519     FnName = "llvm.bswap.i64";
3520   else
3521     assert(0 && "Unknown integer type!");
3522   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3523   return new CallInst(F, V);
3524 }
3525
3526
3527 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3528   bool Changed = SimplifyCommutative(I);
3529   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3530
3531   if (isa<UndefValue>(Op1))
3532     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3533                                ConstantInt::getAllOnesValue(I.getType()));
3534
3535   // or X, X = X
3536   if (Op0 == Op1)
3537     return ReplaceInstUsesWith(I, Op0);
3538
3539   // See if we can simplify any instructions used by the instruction whose sole 
3540   // purpose is to compute bits we don't care about.
3541   uint64_t KnownZero, KnownOne;
3542   if (!isa<PackedType>(I.getType()) &&
3543       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3544                            KnownZero, KnownOne))
3545     return &I;
3546   
3547   // or X, -1 == -1
3548   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3549     ConstantInt *C1 = 0; Value *X = 0;
3550     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3551     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3552       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3553       Op0->setName("");
3554       InsertNewInstBefore(Or, I);
3555       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3556     }
3557
3558     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3559     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3560       std::string Op0Name = Op0->getName(); Op0->setName("");
3561       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3562       InsertNewInstBefore(Or, I);
3563       return BinaryOperator::createXor(Or,
3564                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3565     }
3566
3567     // Try to fold constant and into select arguments.
3568     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3569       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3570         return R;
3571     if (isa<PHINode>(Op0))
3572       if (Instruction *NV = FoldOpIntoPhi(I))
3573         return NV;
3574   }
3575
3576   Value *A = 0, *B = 0;
3577   ConstantInt *C1 = 0, *C2 = 0;
3578
3579   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3580     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3581       return ReplaceInstUsesWith(I, Op1);
3582   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3583     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3584       return ReplaceInstUsesWith(I, Op0);
3585
3586   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3587   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3588   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3589       match(Op1, m_Or(m_Value(), m_Value())) ||
3590       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3591        match(Op1, m_Shift(m_Value(), m_Value())))) {
3592     if (Instruction *BSwap = MatchBSwap(I))
3593       return BSwap;
3594   }
3595   
3596   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3597   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3598       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3599     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3600     Op0->setName("");
3601     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3602   }
3603
3604   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3605   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3606       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3607     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3608     Op0->setName("");
3609     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3610   }
3611
3612   // (A & C1)|(B & C2)
3613   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3614       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3615
3616     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3617       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3618
3619
3620     // If we have: ((V + N) & C1) | (V & C2)
3621     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3622     // replace with V+N.
3623     if (C1 == ConstantExpr::getNot(C2)) {
3624       Value *V1 = 0, *V2 = 0;
3625       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3626           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3627         // Add commutes, try both ways.
3628         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3629           return ReplaceInstUsesWith(I, A);
3630         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3631           return ReplaceInstUsesWith(I, A);
3632       }
3633       // Or commutes, try both ways.
3634       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3635           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3636         // Add commutes, try both ways.
3637         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3638           return ReplaceInstUsesWith(I, B);
3639         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3640           return ReplaceInstUsesWith(I, B);
3641       }
3642     }
3643   }
3644   
3645   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3646   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3647     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3648       if (SI0->getOpcode() == SI1->getOpcode() && 
3649           SI0->getOperand(1) == SI1->getOperand(1) &&
3650           (SI0->hasOneUse() || SI1->hasOneUse())) {
3651         Instruction *NewOp =
3652         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3653                                                      SI1->getOperand(0),
3654                                                      SI0->getName()), I);
3655         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3656       }
3657   }
3658
3659   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3660     if (A == Op1)   // ~A | A == -1
3661       return ReplaceInstUsesWith(I,
3662                                 ConstantInt::getAllOnesValue(I.getType()));
3663   } else {
3664     A = 0;
3665   }
3666   // Note, A is still live here!
3667   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3668     if (Op0 == B)
3669       return ReplaceInstUsesWith(I,
3670                                 ConstantInt::getAllOnesValue(I.getType()));
3671
3672     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3673     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3674       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3675                                               I.getName()+".demorgan"), I);
3676       return BinaryOperator::createNot(And);
3677     }
3678   }
3679
3680   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3681   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3682     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3683       return R;
3684
3685     Value *LHSVal, *RHSVal;
3686     ConstantInt *LHSCst, *RHSCst;
3687     ICmpInst::Predicate LHSCC, RHSCC;
3688     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3689       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3690         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3691             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3692             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3693             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3694             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3695             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3696           // Ensure that the larger constant is on the RHS.
3697           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3698             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3699           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3700           ICmpInst *LHS = cast<ICmpInst>(Op0);
3701           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3702             std::swap(LHS, RHS);
3703             std::swap(LHSCst, RHSCst);
3704             std::swap(LHSCC, RHSCC);
3705           }
3706
3707           // At this point, we know we have have two icmp instructions
3708           // comparing a value against two constants and or'ing the result
3709           // together.  Because of the above check, we know that we only have
3710           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3711           // FoldICmpLogical check above), that the two constants are not
3712           // equal.
3713           assert(LHSCst != RHSCst && "Compares not folded above?");
3714
3715           switch (LHSCC) {
3716           default: assert(0 && "Unknown integer condition code!");
3717           case ICmpInst::ICMP_EQ:
3718             switch (RHSCC) {
3719             default: assert(0 && "Unknown integer condition code!");
3720             case ICmpInst::ICMP_EQ:
3721               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3722                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3723                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3724                                                       LHSVal->getName()+".off");
3725                 InsertNewInstBefore(Add, I);
3726                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3727                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3728               }
3729               break;                         // (X == 13 | X == 15) -> no change
3730             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3731             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3732               break;
3733             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3734             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3735             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3736               return ReplaceInstUsesWith(I, RHS);
3737             }
3738             break;
3739           case ICmpInst::ICMP_NE:
3740             switch (RHSCC) {
3741             default: assert(0 && "Unknown integer condition code!");
3742             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3743             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3744             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3745               return ReplaceInstUsesWith(I, LHS);
3746             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3747             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3748             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3749               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3750             }
3751             break;
3752           case ICmpInst::ICMP_ULT:
3753             switch (RHSCC) {
3754             default: assert(0 && "Unknown integer condition code!");
3755             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3756               break;
3757             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3758               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3759                                      false, I);
3760             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3761               break;
3762             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3763             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3764               return ReplaceInstUsesWith(I, RHS);
3765             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3766               break;
3767             }
3768             break;
3769           case ICmpInst::ICMP_SLT:
3770             switch (RHSCC) {
3771             default: assert(0 && "Unknown integer condition code!");
3772             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3773               break;
3774             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3775               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3776                                      false, I);
3777             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3778               break;
3779             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3780             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3781               return ReplaceInstUsesWith(I, RHS);
3782             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3783               break;
3784             }
3785             break;
3786           case ICmpInst::ICMP_UGT:
3787             switch (RHSCC) {
3788             default: assert(0 && "Unknown integer condition code!");
3789             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3790             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3791               return ReplaceInstUsesWith(I, LHS);
3792             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3793               break;
3794             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3795             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3796               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3797             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3798               break;
3799             }
3800             break;
3801           case ICmpInst::ICMP_SGT:
3802             switch (RHSCC) {
3803             default: assert(0 && "Unknown integer condition code!");
3804             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3805             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3806               return ReplaceInstUsesWith(I, LHS);
3807             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3808               break;
3809             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3810             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3811               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3812             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3813               break;
3814             }
3815             break;
3816           }
3817         }
3818   }
3819     
3820   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3821   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3822     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3823       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3824         const Type *SrcTy = Op0C->getOperand(0)->getType();
3825         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3826             // Only do this if the casts both really cause code to be generated.
3827             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3828                               I.getType(), TD) &&
3829             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3830                               I.getType(), TD)) {
3831           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3832                                                         Op1C->getOperand(0),
3833                                                         I.getName());
3834           InsertNewInstBefore(NewOp, I);
3835           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3836         }
3837       }
3838       
3839
3840   return Changed ? &I : 0;
3841 }
3842
3843 // XorSelf - Implements: X ^ X --> 0
3844 struct XorSelf {
3845   Value *RHS;
3846   XorSelf(Value *rhs) : RHS(rhs) {}
3847   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3848   Instruction *apply(BinaryOperator &Xor) const {
3849     return &Xor;
3850   }
3851 };
3852
3853
3854 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3855   bool Changed = SimplifyCommutative(I);
3856   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3857
3858   if (isa<UndefValue>(Op1))
3859     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3860
3861   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3862   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3863     assert(Result == &I && "AssociativeOpt didn't work?");
3864     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3865   }
3866   
3867   // See if we can simplify any instructions used by the instruction whose sole 
3868   // purpose is to compute bits we don't care about.
3869   uint64_t KnownZero, KnownOne;
3870   if (!isa<PackedType>(I.getType()) &&
3871       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3872                            KnownZero, KnownOne))
3873     return &I;
3874
3875   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3876     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3877     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3878       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3879         return new ICmpInst(ICI->getInversePredicate(),
3880                             ICI->getOperand(0), ICI->getOperand(1));
3881
3882     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3883       // ~(c-X) == X-c-1 == X+(-c-1)
3884       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3885         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3886           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3887           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3888                                               ConstantInt::get(I.getType(), 1));
3889           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3890         }
3891
3892       // ~(~X & Y) --> (X | ~Y)
3893       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3894         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3895         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3896           Instruction *NotY =
3897             BinaryOperator::createNot(Op0I->getOperand(1),
3898                                       Op0I->getOperand(1)->getName()+".not");
3899           InsertNewInstBefore(NotY, I);
3900           return BinaryOperator::createOr(Op0NotVal, NotY);
3901         }
3902       }
3903
3904       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3905         if (Op0I->getOpcode() == Instruction::Add) {
3906           // ~(X-c) --> (-c-1)-X
3907           if (RHS->isAllOnesValue()) {
3908             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3909             return BinaryOperator::createSub(
3910                            ConstantExpr::getSub(NegOp0CI,
3911                                              ConstantInt::get(I.getType(), 1)),
3912                                           Op0I->getOperand(0));
3913           }
3914         } else if (Op0I->getOpcode() == Instruction::Or) {
3915           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3916           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3917             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3918             // Anything in both C1 and C2 is known to be zero, remove it from
3919             // NewRHS.
3920             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3921             NewRHS = ConstantExpr::getAnd(NewRHS, 
3922                                           ConstantExpr::getNot(CommonBits));
3923             WorkList.push_back(Op0I);
3924             I.setOperand(0, Op0I->getOperand(0));
3925             I.setOperand(1, NewRHS);
3926             return &I;
3927           }
3928         }
3929     }
3930
3931     // Try to fold constant and into select arguments.
3932     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3933       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3934         return R;
3935     if (isa<PHINode>(Op0))
3936       if (Instruction *NV = FoldOpIntoPhi(I))
3937         return NV;
3938   }
3939
3940   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3941     if (X == Op1)
3942       return ReplaceInstUsesWith(I,
3943                                 ConstantInt::getAllOnesValue(I.getType()));
3944
3945   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3946     if (X == Op0)
3947       return ReplaceInstUsesWith(I,
3948                                 ConstantInt::getAllOnesValue(I.getType()));
3949
3950   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3951     if (Op1I->getOpcode() == Instruction::Or) {
3952       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3953         Op1I->swapOperands();
3954         I.swapOperands();
3955         std::swap(Op0, Op1);
3956       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3957         I.swapOperands();     // Simplified below.
3958         std::swap(Op0, Op1);
3959       }
3960     } else if (Op1I->getOpcode() == Instruction::Xor) {
3961       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3962         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3963       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3964         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3965     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3966       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3967         Op1I->swapOperands();
3968       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3969         I.swapOperands();     // Simplified below.
3970         std::swap(Op0, Op1);
3971       }
3972     }
3973
3974   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3975     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3976       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3977         Op0I->swapOperands();
3978       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3979         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3980         InsertNewInstBefore(NotB, I);
3981         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3982       }
3983     } else if (Op0I->getOpcode() == Instruction::Xor) {
3984       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3985         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3986       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3987         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3988     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3989       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3990         Op0I->swapOperands();
3991       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3992           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3993         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3994         InsertNewInstBefore(N, I);
3995         return BinaryOperator::createAnd(N, Op1);
3996       }
3997     }
3998
3999   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4000   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4001     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4002       return R;
4003
4004   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4005   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4006     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4007       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4008         const Type *SrcTy = Op0C->getOperand(0)->getType();
4009         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4010             // Only do this if the casts both really cause code to be generated.
4011             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4012                               I.getType(), TD) &&
4013             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4014                               I.getType(), TD)) {
4015           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4016                                                          Op1C->getOperand(0),
4017                                                          I.getName());
4018           InsertNewInstBefore(NewOp, I);
4019           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4020         }
4021       }
4022
4023   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4024   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4025     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4026       if (SI0->getOpcode() == SI1->getOpcode() && 
4027           SI0->getOperand(1) == SI1->getOperand(1) &&
4028           (SI0->hasOneUse() || SI1->hasOneUse())) {
4029         Instruction *NewOp =
4030         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4031                                                       SI1->getOperand(0),
4032                                                       SI0->getName()), I);
4033         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4034       }
4035   }
4036     
4037   return Changed ? &I : 0;
4038 }
4039
4040 static bool isPositive(ConstantInt *C) {
4041   return C->getSExtValue() >= 0;
4042 }
4043
4044 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4045 /// overflowed for this type.
4046 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4047                             ConstantInt *In2) {
4048   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4049
4050   return cast<ConstantInt>(Result)->getZExtValue() <
4051          cast<ConstantInt>(In1)->getZExtValue();
4052 }
4053
4054 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4055 /// code necessary to compute the offset from the base pointer (without adding
4056 /// in the base pointer).  Return the result as a signed integer of intptr size.
4057 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4058   TargetData &TD = IC.getTargetData();
4059   gep_type_iterator GTI = gep_type_begin(GEP);
4060   const Type *IntPtrTy = TD.getIntPtrType();
4061   Value *Result = Constant::getNullValue(IntPtrTy);
4062
4063   // Build a mask for high order bits.
4064   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4065
4066   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4067     Value *Op = GEP->getOperand(i);
4068     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4069     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4070     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4071       if (!OpC->isNullValue()) {
4072         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4073         Scale = ConstantExpr::getMul(OpC, Scale);
4074         if (Constant *RC = dyn_cast<Constant>(Result))
4075           Result = ConstantExpr::getAdd(RC, Scale);
4076         else {
4077           // Emit an add instruction.
4078           Result = IC.InsertNewInstBefore(
4079              BinaryOperator::createAdd(Result, Scale,
4080                                        GEP->getName()+".offs"), I);
4081         }
4082       }
4083     } else {
4084       // Convert to correct type.
4085       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4086                                                Op->getName()+".c"), I);
4087       if (Size != 1)
4088         // We'll let instcombine(mul) convert this to a shl if possible.
4089         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4090                                                     GEP->getName()+".idx"), I);
4091
4092       // Emit an add instruction.
4093       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4094                                                     GEP->getName()+".offs"), I);
4095     }
4096   }
4097   return Result;
4098 }
4099
4100 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4101 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4102 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4103                                        ICmpInst::Predicate Cond,
4104                                        Instruction &I) {
4105   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4106
4107   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4108     if (isa<PointerType>(CI->getOperand(0)->getType()))
4109       RHS = CI->getOperand(0);
4110
4111   Value *PtrBase = GEPLHS->getOperand(0);
4112   if (PtrBase == RHS) {
4113     // As an optimization, we don't actually have to compute the actual value of
4114     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4115     // each index is zero or not.
4116     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4117       Instruction *InVal = 0;
4118       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4119       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4120         bool EmitIt = true;
4121         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4122           if (isa<UndefValue>(C))  // undef index -> undef.
4123             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4124           if (C->isNullValue())
4125             EmitIt = false;
4126           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4127             EmitIt = false;  // This is indexing into a zero sized array?
4128           } else if (isa<ConstantInt>(C))
4129             return ReplaceInstUsesWith(I, // No comparison is needed here.
4130                                  ConstantInt::get(Type::Int1Ty, 
4131                                                   Cond == ICmpInst::ICMP_NE));
4132         }
4133
4134         if (EmitIt) {
4135           Instruction *Comp =
4136             new ICmpInst(Cond, GEPLHS->getOperand(i),
4137                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4138           if (InVal == 0)
4139             InVal = Comp;
4140           else {
4141             InVal = InsertNewInstBefore(InVal, I);
4142             InsertNewInstBefore(Comp, I);
4143             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4144               InVal = BinaryOperator::createOr(InVal, Comp);
4145             else                              // True if all are equal
4146               InVal = BinaryOperator::createAnd(InVal, Comp);
4147           }
4148         }
4149       }
4150
4151       if (InVal)
4152         return InVal;
4153       else
4154         // No comparison is needed here, all indexes = 0
4155         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4156                                                 Cond == ICmpInst::ICMP_EQ));
4157     }
4158
4159     // Only lower this if the icmp is the only user of the GEP or if we expect
4160     // the result to fold to a constant!
4161     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4162       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4163       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4164       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4165                           Constant::getNullValue(Offset->getType()));
4166     }
4167   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4168     // If the base pointers are different, but the indices are the same, just
4169     // compare the base pointer.
4170     if (PtrBase != GEPRHS->getOperand(0)) {
4171       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4172       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4173                         GEPRHS->getOperand(0)->getType();
4174       if (IndicesTheSame)
4175         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4176           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4177             IndicesTheSame = false;
4178             break;
4179           }
4180
4181       // If all indices are the same, just compare the base pointers.
4182       if (IndicesTheSame)
4183         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4184                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4185
4186       // Otherwise, the base pointers are different and the indices are
4187       // different, bail out.
4188       return 0;
4189     }
4190
4191     // If one of the GEPs has all zero indices, recurse.
4192     bool AllZeros = true;
4193     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4194       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4195           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4196         AllZeros = false;
4197         break;
4198       }
4199     if (AllZeros)
4200       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4201                           ICmpInst::getSwappedPredicate(Cond), I);
4202
4203     // If the other GEP has all zero indices, recurse.
4204     AllZeros = true;
4205     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4206       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4207           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4208         AllZeros = false;
4209         break;
4210       }
4211     if (AllZeros)
4212       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4213
4214     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4215       // If the GEPs only differ by one index, compare it.
4216       unsigned NumDifferences = 0;  // Keep track of # differences.
4217       unsigned DiffOperand = 0;     // The operand that differs.
4218       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4219         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4220           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4221                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4222             // Irreconcilable differences.
4223             NumDifferences = 2;
4224             break;
4225           } else {
4226             if (NumDifferences++) break;
4227             DiffOperand = i;
4228           }
4229         }
4230
4231       if (NumDifferences == 0)   // SAME GEP?
4232         return ReplaceInstUsesWith(I, // No comparison is needed here.
4233                                    ConstantInt::get(Type::Int1Ty, 
4234                                                     Cond == ICmpInst::ICMP_EQ));
4235       else if (NumDifferences == 1) {
4236         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4237         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4238         // Make sure we do a signed comparison here.
4239         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4240       }
4241     }
4242
4243     // Only lower this if the icmp is the only user of the GEP or if we expect
4244     // the result to fold to a constant!
4245     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4246         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4247       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4248       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4249       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4250       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4251     }
4252   }
4253   return 0;
4254 }
4255
4256 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4257   bool Changed = SimplifyCompare(I);
4258   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4259
4260   // Fold trivial predicates.
4261   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4262     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4263   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4264     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4265   
4266   // Simplify 'fcmp pred X, X'
4267   if (Op0 == Op1) {
4268     switch (I.getPredicate()) {
4269     default: assert(0 && "Unknown predicate!");
4270     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4271     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4272     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4273       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4274     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4275     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4276     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4277       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4278       
4279     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4280     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4281     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4282     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4283       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4284       I.setPredicate(FCmpInst::FCMP_UNO);
4285       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4286       return &I;
4287       
4288     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4289     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4290     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4291     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4292       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4293       I.setPredicate(FCmpInst::FCMP_ORD);
4294       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4295       return &I;
4296     }
4297   }
4298     
4299   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4300     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4301
4302   // Handle fcmp with constant RHS
4303   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4304     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4305       switch (LHSI->getOpcode()) {
4306       case Instruction::PHI:
4307         if (Instruction *NV = FoldOpIntoPhi(I))
4308           return NV;
4309         break;
4310       case Instruction::Select:
4311         // If either operand of the select is a constant, we can fold the
4312         // comparison into the select arms, which will cause one to be
4313         // constant folded and the select turned into a bitwise or.
4314         Value *Op1 = 0, *Op2 = 0;
4315         if (LHSI->hasOneUse()) {
4316           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4317             // Fold the known value into the constant operand.
4318             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4319             // Insert a new FCmp of the other select operand.
4320             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4321                                                       LHSI->getOperand(2), RHSC,
4322                                                       I.getName()), I);
4323           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4324             // Fold the known value into the constant operand.
4325             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4326             // Insert a new FCmp of the other select operand.
4327             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4328                                                       LHSI->getOperand(1), RHSC,
4329                                                       I.getName()), I);
4330           }
4331         }
4332
4333         if (Op1)
4334           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4335         break;
4336       }
4337   }
4338
4339   return Changed ? &I : 0;
4340 }
4341
4342 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4343   bool Changed = SimplifyCompare(I);
4344   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4345   const Type *Ty = Op0->getType();
4346
4347   // icmp X, X
4348   if (Op0 == Op1)
4349     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4350                                                    isTrueWhenEqual(I)));
4351
4352   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4353     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4354
4355   // icmp of GlobalValues can never equal each other as long as they aren't
4356   // external weak linkage type.
4357   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4358     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4359       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4360         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4361                                                        !isTrueWhenEqual(I)));
4362
4363   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4364   // addresses never equal each other!  We already know that Op0 != Op1.
4365   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4366        isa<ConstantPointerNull>(Op0)) &&
4367       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4368        isa<ConstantPointerNull>(Op1)))
4369     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4370                                                    !isTrueWhenEqual(I)));
4371
4372   // icmp's with boolean values can always be turned into bitwise operations
4373   if (Ty == Type::Int1Ty) {
4374     switch (I.getPredicate()) {
4375     default: assert(0 && "Invalid icmp instruction!");
4376     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4377       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4378       InsertNewInstBefore(Xor, I);
4379       return BinaryOperator::createNot(Xor);
4380     }
4381     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4382       return BinaryOperator::createXor(Op0, Op1);
4383
4384     case ICmpInst::ICMP_UGT:
4385     case ICmpInst::ICMP_SGT:
4386       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4387       // FALL THROUGH
4388     case ICmpInst::ICMP_ULT:
4389     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4390       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4391       InsertNewInstBefore(Not, I);
4392       return BinaryOperator::createAnd(Not, Op1);
4393     }
4394     case ICmpInst::ICMP_UGE:
4395     case ICmpInst::ICMP_SGE:
4396       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4397       // FALL THROUGH
4398     case ICmpInst::ICMP_ULE:
4399     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4400       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4401       InsertNewInstBefore(Not, I);
4402       return BinaryOperator::createOr(Not, Op1);
4403     }
4404     }
4405   }
4406
4407   // See if we are doing a comparison between a constant and an instruction that
4408   // can be folded into the comparison.
4409   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4410     switch (I.getPredicate()) {
4411     default: break;
4412     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4413       if (CI->isMinValue(false))
4414         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4415       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4416         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4417       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4418         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4419       break;
4420
4421     case ICmpInst::ICMP_SLT:
4422       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4423         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4424       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4425         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4426       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4427         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4428       break;
4429
4430     case ICmpInst::ICMP_UGT:
4431       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4432         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4433       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4434         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4435       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4436         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4437       break;
4438
4439     case ICmpInst::ICMP_SGT:
4440       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4441         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4442       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4443         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4444       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4445         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4446       break;
4447
4448     case ICmpInst::ICMP_ULE:
4449       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4450         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4451       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4452         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4453       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4454         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4455       break;
4456
4457     case ICmpInst::ICMP_SLE:
4458       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4459         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4460       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4461         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4462       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4463         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4464       break;
4465
4466     case ICmpInst::ICMP_UGE:
4467       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4468         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4469       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4470         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4471       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4472         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4473       break;
4474
4475     case ICmpInst::ICMP_SGE:
4476       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4477         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4478       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4479         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4480       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4481         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4482       break;
4483     }
4484
4485     // If we still have a icmp le or icmp ge instruction, turn it into the
4486     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4487     // already been handled above, this requires little checking.
4488     //
4489     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4490       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4491     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4492       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4493     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4494       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4495     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4496       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4497     
4498     // See if we can fold the comparison based on bits known to be zero or one
4499     // in the input.
4500     uint64_t KnownZero, KnownOne;
4501     if (SimplifyDemandedBits(Op0, Ty->getIntegerTypeMask(),
4502                              KnownZero, KnownOne, 0))
4503       return &I;
4504         
4505     // Given the known and unknown bits, compute a range that the LHS could be
4506     // in.
4507     if (KnownOne | KnownZero) {
4508       // Compute the Min, Max and RHS values based on the known bits. For the
4509       // EQ and NE we use unsigned values.
4510       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4511       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4512       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4513         SRHSVal = CI->getSExtValue();
4514         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4515                                                SMax);
4516       } else {
4517         URHSVal = CI->getZExtValue();
4518         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4519                                                  UMax);
4520       }
4521       switch (I.getPredicate()) {  // LE/GE have been folded already.
4522       default: assert(0 && "Unknown icmp opcode!");
4523       case ICmpInst::ICMP_EQ:
4524         if (UMax < URHSVal || UMin > URHSVal)
4525           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4526         break;
4527       case ICmpInst::ICMP_NE:
4528         if (UMax < URHSVal || UMin > URHSVal)
4529           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4530         break;
4531       case ICmpInst::ICMP_ULT:
4532         if (UMax < URHSVal)
4533           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4534         if (UMin > URHSVal)
4535           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4536         break;
4537       case ICmpInst::ICMP_UGT:
4538         if (UMin > URHSVal)
4539           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4540         if (UMax < URHSVal)
4541           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4542         break;
4543       case ICmpInst::ICMP_SLT:
4544         if (SMax < SRHSVal)
4545           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4546         if (SMin > SRHSVal)
4547           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4548         break;
4549       case ICmpInst::ICMP_SGT: 
4550         if (SMin > SRHSVal)
4551           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4552         if (SMax < SRHSVal)
4553           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4554         break;
4555       }
4556     }
4557           
4558     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4559     // instruction, see if that instruction also has constants so that the 
4560     // instruction can be folded into the icmp 
4561     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4562       switch (LHSI->getOpcode()) {
4563       case Instruction::And:
4564         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4565             LHSI->getOperand(0)->hasOneUse()) {
4566           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4567
4568           // If the LHS is an AND of a truncating cast, we can widen the
4569           // and/compare to be the input width without changing the value
4570           // produced, eliminating a cast.
4571           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4572             // We can do this transformation if either the AND constant does not
4573             // have its sign bit set or if it is an equality comparison. 
4574             // Extending a relational comparison when we're checking the sign
4575             // bit would not work.
4576             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4577                 (I.isEquality() ||
4578                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4579                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4580               ConstantInt *NewCST;
4581               ConstantInt *NewCI;
4582               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4583                                          AndCST->getZExtValue());
4584               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4585                                         CI->getZExtValue());
4586               Instruction *NewAnd = 
4587                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4588                                           LHSI->getName());
4589               InsertNewInstBefore(NewAnd, I);
4590               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4591             }
4592           }
4593           
4594           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4595           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4596           // happens a LOT in code produced by the C front-end, for bitfield
4597           // access.
4598           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4599
4600           // Check to see if there is a noop-cast between the shift and the and.
4601           if (!Shift) {
4602             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4603               if (CI->getOpcode() == Instruction::BitCast)
4604                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4605           }
4606
4607           ConstantInt *ShAmt;
4608           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4609           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4610           const Type *AndTy = AndCST->getType();          // Type of the and.
4611
4612           // We can fold this as long as we can't shift unknown bits
4613           // into the mask.  This can only happen with signed shift
4614           // rights, as they sign-extend.
4615           if (ShAmt) {
4616             bool CanFold = Shift->isLogicalShift();
4617             if (!CanFold) {
4618               // To test for the bad case of the signed shr, see if any
4619               // of the bits shifted in could be tested after the mask.
4620               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4621               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4622
4623               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4624               Constant *ShVal =
4625                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4626                                      OShAmt);
4627               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4628                 CanFold = true;
4629             }
4630
4631             if (CanFold) {
4632               Constant *NewCst;
4633               if (Shift->getOpcode() == Instruction::Shl)
4634                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4635               else
4636                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4637
4638               // Check to see if we are shifting out any of the bits being
4639               // compared.
4640               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4641                 // If we shifted bits out, the fold is not going to work out.
4642                 // As a special case, check to see if this means that the
4643                 // result is always true or false now.
4644                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4645                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4646                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4647                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4648               } else {
4649                 I.setOperand(1, NewCst);
4650                 Constant *NewAndCST;
4651                 if (Shift->getOpcode() == Instruction::Shl)
4652                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4653                 else
4654                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4655                 LHSI->setOperand(1, NewAndCST);
4656                 LHSI->setOperand(0, Shift->getOperand(0));
4657                 WorkList.push_back(Shift); // Shift is dead.
4658                 AddUsesToWorkList(I);
4659                 return &I;
4660               }
4661             }
4662           }
4663           
4664           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4665           // preferable because it allows the C<<Y expression to be hoisted out
4666           // of a loop if Y is invariant and X is not.
4667           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4668               I.isEquality() && !Shift->isArithmeticShift() &&
4669               isa<Instruction>(Shift->getOperand(0))) {
4670             // Compute C << Y.
4671             Value *NS;
4672             if (Shift->getOpcode() == Instruction::LShr) {
4673               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4674                                  "tmp");
4675             } else {
4676               // Insert a logical shift.
4677               NS = new ShiftInst(Instruction::LShr, AndCST,
4678                                  Shift->getOperand(1), "tmp");
4679             }
4680             InsertNewInstBefore(cast<Instruction>(NS), I);
4681
4682             // Compute X & (C << Y).
4683             Instruction *NewAnd = BinaryOperator::createAnd(
4684                 Shift->getOperand(0), NS, LHSI->getName());
4685             InsertNewInstBefore(NewAnd, I);
4686             
4687             I.setOperand(0, NewAnd);
4688             return &I;
4689           }
4690         }
4691         break;
4692
4693       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4694         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4695           if (I.isEquality()) {
4696             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4697
4698             // Check that the shift amount is in range.  If not, don't perform
4699             // undefined shifts.  When the shift is visited it will be
4700             // simplified.
4701             if (ShAmt->getZExtValue() >= TypeBits)
4702               break;
4703
4704             // If we are comparing against bits always shifted out, the
4705             // comparison cannot succeed.
4706             Constant *Comp =
4707               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4708             if (Comp != CI) {// Comparing against a bit that we know is zero.
4709               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4710               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4711               return ReplaceInstUsesWith(I, Cst);
4712             }
4713
4714             if (LHSI->hasOneUse()) {
4715               // Otherwise strength reduce the shift into an and.
4716               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4717               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4718               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4719
4720               Instruction *AndI =
4721                 BinaryOperator::createAnd(LHSI->getOperand(0),
4722                                           Mask, LHSI->getName()+".mask");
4723               Value *And = InsertNewInstBefore(AndI, I);
4724               return new ICmpInst(I.getPredicate(), And,
4725                                      ConstantExpr::getLShr(CI, ShAmt));
4726             }
4727           }
4728         }
4729         break;
4730
4731       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4732       case Instruction::AShr:
4733         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4734           if (I.isEquality()) {
4735             // Check that the shift amount is in range.  If not, don't perform
4736             // undefined shifts.  When the shift is visited it will be
4737             // simplified.
4738             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4739             if (ShAmt->getZExtValue() >= TypeBits)
4740               break;
4741
4742             // If we are comparing against bits always shifted out, the
4743             // comparison cannot succeed.
4744             Constant *Comp;
4745             if (LHSI->getOpcode() == Instruction::LShr) 
4746               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4747                                            ShAmt);
4748             else
4749               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4750                                            ShAmt);
4751
4752             if (Comp != CI) {// Comparing against a bit that we know is zero.
4753               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4754               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4755               return ReplaceInstUsesWith(I, Cst);
4756             }
4757
4758             if (LHSI->hasOneUse() || CI->isNullValue()) {
4759               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4760
4761               // Otherwise strength reduce the shift into an and.
4762               uint64_t Val = ~0ULL;          // All ones.
4763               Val <<= ShAmtVal;              // Shift over to the right spot.
4764               Val &= ~0ULL >> (64-TypeBits);
4765               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4766
4767               Instruction *AndI =
4768                 BinaryOperator::createAnd(LHSI->getOperand(0),
4769                                           Mask, LHSI->getName()+".mask");
4770               Value *And = InsertNewInstBefore(AndI, I);
4771               return new ICmpInst(I.getPredicate(), And,
4772                                      ConstantExpr::getShl(CI, ShAmt));
4773             }
4774           }
4775         }
4776         break;
4777
4778       case Instruction::SDiv:
4779       case Instruction::UDiv:
4780         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4781         // Fold this div into the comparison, producing a range check. 
4782         // Determine, based on the divide type, what the range is being 
4783         // checked.  If there is an overflow on the low or high side, remember 
4784         // it, otherwise compute the range [low, hi) bounding the new value.
4785         // See: InsertRangeTest above for the kinds of replacements possible.
4786         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4787           // FIXME: If the operand types don't match the type of the divide 
4788           // then don't attempt this transform. The code below doesn't have the
4789           // logic to deal with a signed divide and an unsigned compare (and
4790           // vice versa). This is because (x /s C1) <s C2  produces different 
4791           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4792           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4793           // work. :(  The if statement below tests that condition and bails 
4794           // if it finds it. 
4795           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4796           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4797             break;
4798
4799           // Initialize the variables that will indicate the nature of the
4800           // range check.
4801           bool LoOverflow = false, HiOverflow = false;
4802           ConstantInt *LoBound = 0, *HiBound = 0;
4803
4804           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4805           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4806           // C2 (CI). By solving for X we can turn this into a range check 
4807           // instead of computing a divide. 
4808           ConstantInt *Prod = 
4809             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4810
4811           // Determine if the product overflows by seeing if the product is
4812           // not equal to the divide. Make sure we do the same kind of divide
4813           // as in the LHS instruction that we're folding. 
4814           bool ProdOV = !DivRHS->isNullValue() && 
4815             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4816               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4817
4818           // Get the ICmp opcode
4819           ICmpInst::Predicate predicate = I.getPredicate();
4820
4821           if (DivRHS->isNullValue()) {  
4822             // Don't hack on divide by zeros!
4823           } else if (!DivIsSigned) {  // udiv
4824             LoBound = Prod;
4825             LoOverflow = ProdOV;
4826             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4827           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4828             if (CI->isNullValue()) {       // (X / pos) op 0
4829               // Can't overflow.
4830               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4831               HiBound = DivRHS;
4832             } else if (isPositive(CI)) {   // (X / pos) op pos
4833               LoBound = Prod;
4834               LoOverflow = ProdOV;
4835               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4836             } else {                       // (X / pos) op neg
4837               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4838               LoOverflow = AddWithOverflow(LoBound, Prod,
4839                                            cast<ConstantInt>(DivRHSH));
4840               HiBound = Prod;
4841               HiOverflow = ProdOV;
4842             }
4843           } else {                         // Divisor is < 0.
4844             if (CI->isNullValue()) {       // (X / neg) op 0
4845               LoBound = AddOne(DivRHS);
4846               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4847               if (HiBound == DivRHS)
4848                 LoBound = 0;               // - INTMIN = INTMIN
4849             } else if (isPositive(CI)) {   // (X / neg) op pos
4850               HiOverflow = LoOverflow = ProdOV;
4851               if (!LoOverflow)
4852                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4853               HiBound = AddOne(Prod);
4854             } else {                       // (X / neg) op neg
4855               LoBound = Prod;
4856               LoOverflow = HiOverflow = ProdOV;
4857               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4858             }
4859
4860             // Dividing by a negate swaps the condition.
4861             predicate = ICmpInst::getSwappedPredicate(predicate);
4862           }
4863
4864           if (LoBound) {
4865             Value *X = LHSI->getOperand(0);
4866             switch (predicate) {
4867             default: assert(0 && "Unhandled icmp opcode!");
4868             case ICmpInst::ICMP_EQ:
4869               if (LoOverflow && HiOverflow)
4870                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4871               else if (HiOverflow)
4872                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4873                                     ICmpInst::ICMP_UGE, X, LoBound);
4874               else if (LoOverflow)
4875                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4876                                     ICmpInst::ICMP_ULT, X, HiBound);
4877               else
4878                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4879                                        true, I);
4880             case ICmpInst::ICMP_NE:
4881               if (LoOverflow && HiOverflow)
4882                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4883               else if (HiOverflow)
4884                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4885                                     ICmpInst::ICMP_ULT, X, LoBound);
4886               else if (LoOverflow)
4887                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4888                                     ICmpInst::ICMP_UGE, X, HiBound);
4889               else
4890                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4891                                        false, I);
4892             case ICmpInst::ICMP_ULT:
4893             case ICmpInst::ICMP_SLT:
4894               if (LoOverflow)
4895                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4896               return new ICmpInst(predicate, X, LoBound);
4897             case ICmpInst::ICMP_UGT:
4898             case ICmpInst::ICMP_SGT:
4899               if (HiOverflow)
4900                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4901               if (predicate == ICmpInst::ICMP_UGT)
4902                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4903               else
4904                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4905             }
4906           }
4907         }
4908         break;
4909       }
4910
4911     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4912     if (I.isEquality()) {
4913       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4914
4915       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4916       // the second operand is a constant, simplify a bit.
4917       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4918         switch (BO->getOpcode()) {
4919         case Instruction::SRem:
4920           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4921           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4922               BO->hasOneUse()) {
4923             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4924             if (V > 1 && isPowerOf2_64(V)) {
4925               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4926                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4927               return new ICmpInst(I.getPredicate(), NewRem, 
4928                                   Constant::getNullValue(BO->getType()));
4929             }
4930           }
4931           break;
4932         case Instruction::Add:
4933           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4934           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4935             if (BO->hasOneUse())
4936               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4937                                   ConstantExpr::getSub(CI, BOp1C));
4938           } else if (CI->isNullValue()) {
4939             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4940             // efficiently invertible, or if the add has just this one use.
4941             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4942
4943             if (Value *NegVal = dyn_castNegVal(BOp1))
4944               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4945             else if (Value *NegVal = dyn_castNegVal(BOp0))
4946               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4947             else if (BO->hasOneUse()) {
4948               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4949               BO->setName("");
4950               InsertNewInstBefore(Neg, I);
4951               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4952             }
4953           }
4954           break;
4955         case Instruction::Xor:
4956           // For the xor case, we can xor two constants together, eliminating
4957           // the explicit xor.
4958           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4959             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4960                                 ConstantExpr::getXor(CI, BOC));
4961
4962           // FALLTHROUGH
4963         case Instruction::Sub:
4964           // Replace (([sub|xor] A, B) != 0) with (A != B)
4965           if (CI->isNullValue())
4966             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4967                                 BO->getOperand(1));
4968           break;
4969
4970         case Instruction::Or:
4971           // If bits are being or'd in that are not present in the constant we
4972           // are comparing against, then the comparison could never succeed!
4973           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4974             Constant *NotCI = ConstantExpr::getNot(CI);
4975             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4976               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4977                                                              isICMP_NE));
4978           }
4979           break;
4980
4981         case Instruction::And:
4982           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4983             // If bits are being compared against that are and'd out, then the
4984             // comparison can never succeed!
4985             if (!ConstantExpr::getAnd(CI,
4986                                       ConstantExpr::getNot(BOC))->isNullValue())
4987               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4988                                                              isICMP_NE));
4989
4990             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4991             if (CI == BOC && isOneBitSet(CI))
4992               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4993                                   ICmpInst::ICMP_NE, Op0,
4994                                   Constant::getNullValue(CI->getType()));
4995
4996             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4997             if (isSignBit(BOC)) {
4998               Value *X = BO->getOperand(0);
4999               Constant *Zero = Constant::getNullValue(X->getType());
5000               ICmpInst::Predicate pred = isICMP_NE ? 
5001                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5002               return new ICmpInst(pred, X, Zero);
5003             }
5004
5005             // ((X & ~7) == 0) --> X < 8
5006             if (CI->isNullValue() && isHighOnes(BOC)) {
5007               Value *X = BO->getOperand(0);
5008               Constant *NegX = ConstantExpr::getNeg(BOC);
5009               ICmpInst::Predicate pred = isICMP_NE ? 
5010                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5011               return new ICmpInst(pred, X, NegX);
5012             }
5013
5014           }
5015         default: break;
5016         }
5017       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5018         // Handle set{eq|ne} <intrinsic>, intcst.
5019         switch (II->getIntrinsicID()) {
5020         default: break;
5021         case Intrinsic::bswap_i16: 
5022           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5023           WorkList.push_back(II);  // Dead?
5024           I.setOperand(0, II->getOperand(1));
5025           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5026                                            ByteSwap_16(CI->getZExtValue())));
5027           return &I;
5028         case Intrinsic::bswap_i32:   
5029           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5030           WorkList.push_back(II);  // Dead?
5031           I.setOperand(0, II->getOperand(1));
5032           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5033                                            ByteSwap_32(CI->getZExtValue())));
5034           return &I;
5035         case Intrinsic::bswap_i64:   
5036           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5037           WorkList.push_back(II);  // Dead?
5038           I.setOperand(0, II->getOperand(1));
5039           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5040                                            ByteSwap_64(CI->getZExtValue())));
5041           return &I;
5042         }
5043       }
5044     } else {  // Not a ICMP_EQ/ICMP_NE
5045       // If the LHS is a cast from an integral value of the same size, then 
5046       // since we know the RHS is a constant, try to simlify.
5047       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5048         Value *CastOp = Cast->getOperand(0);
5049         const Type *SrcTy = CastOp->getType();
5050         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5051         if (SrcTy->isInteger() && 
5052             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5053           // If this is an unsigned comparison, try to make the comparison use
5054           // smaller constant values.
5055           switch (I.getPredicate()) {
5056             default: break;
5057             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5058               ConstantInt *CUI = cast<ConstantInt>(CI);
5059               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5060                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5061                                     ConstantInt::get(SrcTy, -1));
5062               break;
5063             }
5064             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5065               ConstantInt *CUI = cast<ConstantInt>(CI);
5066               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5067                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5068                                     Constant::getNullValue(SrcTy));
5069               break;
5070             }
5071           }
5072
5073         }
5074       }
5075     }
5076   }
5077
5078   // Handle icmp with constant RHS
5079   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5080     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5081       switch (LHSI->getOpcode()) {
5082       case Instruction::GetElementPtr:
5083         if (RHSC->isNullValue()) {
5084           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5085           bool isAllZeros = true;
5086           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5087             if (!isa<Constant>(LHSI->getOperand(i)) ||
5088                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5089               isAllZeros = false;
5090               break;
5091             }
5092           if (isAllZeros)
5093             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5094                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5095         }
5096         break;
5097
5098       case Instruction::PHI:
5099         if (Instruction *NV = FoldOpIntoPhi(I))
5100           return NV;
5101         break;
5102       case Instruction::Select:
5103         // If either operand of the select is a constant, we can fold the
5104         // comparison into the select arms, which will cause one to be
5105         // constant folded and the select turned into a bitwise or.
5106         Value *Op1 = 0, *Op2 = 0;
5107         if (LHSI->hasOneUse()) {
5108           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5109             // Fold the known value into the constant operand.
5110             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5111             // Insert a new ICmp of the other select operand.
5112             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5113                                                    LHSI->getOperand(2), RHSC,
5114                                                    I.getName()), I);
5115           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5116             // Fold the known value into the constant operand.
5117             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5118             // Insert a new ICmp of the other select operand.
5119             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5120                                                    LHSI->getOperand(1), RHSC,
5121                                                    I.getName()), I);
5122           }
5123         }
5124
5125         if (Op1)
5126           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5127         break;
5128       }
5129   }
5130
5131   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5132   if (User *GEP = dyn_castGetElementPtr(Op0))
5133     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5134       return NI;
5135   if (User *GEP = dyn_castGetElementPtr(Op1))
5136     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5137                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5138       return NI;
5139
5140   // Test to see if the operands of the icmp are casted versions of other
5141   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5142   // now.
5143   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5144     if (isa<PointerType>(Op0->getType()) && 
5145         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5146       // We keep moving the cast from the left operand over to the right
5147       // operand, where it can often be eliminated completely.
5148       Op0 = CI->getOperand(0);
5149
5150       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5151       // so eliminate it as well.
5152       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5153         Op1 = CI2->getOperand(0);
5154
5155       // If Op1 is a constant, we can fold the cast into the constant.
5156       if (Op0->getType() != Op1->getType())
5157         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5158           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5159         } else {
5160           // Otherwise, cast the RHS right before the icmp
5161           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5162         }
5163       return new ICmpInst(I.getPredicate(), Op0, Op1);
5164     }
5165   }
5166   
5167   if (isa<CastInst>(Op0)) {
5168     // Handle the special case of: icmp (cast bool to X), <cst>
5169     // This comes up when you have code like
5170     //   int X = A < B;
5171     //   if (X) ...
5172     // For generality, we handle any zero-extension of any operand comparison
5173     // with a constant or another cast from the same type.
5174     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5175       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5176         return R;
5177   }
5178   
5179   if (I.isEquality()) {
5180     Value *A, *B, *C, *D;
5181     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5182       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5183         Value *OtherVal = A == Op1 ? B : A;
5184         return new ICmpInst(I.getPredicate(), OtherVal,
5185                             Constant::getNullValue(A->getType()));
5186       }
5187
5188       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5189         // A^c1 == C^c2 --> A == C^(c1^c2)
5190         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5191           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5192             if (Op1->hasOneUse()) {
5193               Constant *NC = ConstantExpr::getXor(C1, C2);
5194               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5195               return new ICmpInst(I.getPredicate(), A,
5196                                   InsertNewInstBefore(Xor, I));
5197             }
5198         
5199         // A^B == A^D -> B == D
5200         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5201         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5202         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5203         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5204       }
5205     }
5206     
5207     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5208         (A == Op0 || B == Op0)) {
5209       // A == (A^B)  ->  B == 0
5210       Value *OtherVal = A == Op0 ? B : A;
5211       return new ICmpInst(I.getPredicate(), OtherVal,
5212                           Constant::getNullValue(A->getType()));
5213     }
5214     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5215       // (A-B) == A  ->  B == 0
5216       return new ICmpInst(I.getPredicate(), B,
5217                           Constant::getNullValue(B->getType()));
5218     }
5219     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5220       // A == (A-B)  ->  B == 0
5221       return new ICmpInst(I.getPredicate(), B,
5222                           Constant::getNullValue(B->getType()));
5223     }
5224     
5225     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5226     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5227         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5228         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5229       Value *X = 0, *Y = 0, *Z = 0;
5230       
5231       if (A == C) {
5232         X = B; Y = D; Z = A;
5233       } else if (A == D) {
5234         X = B; Y = C; Z = A;
5235       } else if (B == C) {
5236         X = A; Y = D; Z = B;
5237       } else if (B == D) {
5238         X = A; Y = C; Z = B;
5239       }
5240       
5241       if (X) {   // Build (X^Y) & Z
5242         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5243         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5244         I.setOperand(0, Op1);
5245         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5246         return &I;
5247       }
5248     }
5249   }
5250   return Changed ? &I : 0;
5251 }
5252
5253 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5254 // We only handle extending casts so far.
5255 //
5256 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5257   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5258   Value *LHSCIOp        = LHSCI->getOperand(0);
5259   const Type *SrcTy     = LHSCIOp->getType();
5260   const Type *DestTy    = LHSCI->getType();
5261   Value *RHSCIOp;
5262
5263   // We only handle extension cast instructions, so far. Enforce this.
5264   if (LHSCI->getOpcode() != Instruction::ZExt &&
5265       LHSCI->getOpcode() != Instruction::SExt)
5266     return 0;
5267
5268   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5269   bool isSignedCmp = ICI.isSignedPredicate();
5270
5271   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5272     // Not an extension from the same type?
5273     RHSCIOp = CI->getOperand(0);
5274     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5275       return 0;
5276     
5277     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5278     // and the other is a zext), then we can't handle this.
5279     if (CI->getOpcode() != LHSCI->getOpcode())
5280       return 0;
5281
5282     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5283     // then we can't handle this.
5284     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5285       return 0;
5286     
5287     // Okay, just insert a compare of the reduced operands now!
5288     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5289   }
5290
5291   // If we aren't dealing with a constant on the RHS, exit early
5292   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5293   if (!CI)
5294     return 0;
5295
5296   // Compute the constant that would happen if we truncated to SrcTy then
5297   // reextended to DestTy.
5298   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5299   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5300
5301   // If the re-extended constant didn't change...
5302   if (Res2 == CI) {
5303     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5304     // For example, we might have:
5305     //    %A = sext short %X to uint
5306     //    %B = icmp ugt uint %A, 1330
5307     // It is incorrect to transform this into 
5308     //    %B = icmp ugt short %X, 1330 
5309     // because %A may have negative value. 
5310     //
5311     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5312     // OR operation is EQ/NE.
5313     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5314       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5315     else
5316       return 0;
5317   }
5318
5319   // The re-extended constant changed so the constant cannot be represented 
5320   // in the shorter type. Consequently, we cannot emit a simple comparison.
5321
5322   // First, handle some easy cases. We know the result cannot be equal at this
5323   // point so handle the ICI.isEquality() cases
5324   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5325     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5326   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5327     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5328
5329   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5330   // should have been folded away previously and not enter in here.
5331   Value *Result;
5332   if (isSignedCmp) {
5333     // We're performing a signed comparison.
5334     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5335       Result = ConstantInt::getFalse();          // X < (small) --> false
5336     else
5337       Result = ConstantInt::getTrue();           // X < (large) --> true
5338   } else {
5339     // We're performing an unsigned comparison.
5340     if (isSignedExt) {
5341       // We're performing an unsigned comp with a sign extended value.
5342       // This is true if the input is >= 0. [aka >s -1]
5343       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5344       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5345                                    NegOne, ICI.getName()), ICI);
5346     } else {
5347       // Unsigned extend & unsigned compare -> always true.
5348       Result = ConstantInt::getTrue();
5349     }
5350   }
5351
5352   // Finally, return the value computed.
5353   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5354       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5355     return ReplaceInstUsesWith(ICI, Result);
5356   } else {
5357     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5358             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5359            "ICmp should be folded!");
5360     if (Constant *CI = dyn_cast<Constant>(Result))
5361       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5362     else
5363       return BinaryOperator::createNot(Result);
5364   }
5365 }
5366
5367 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5368   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5369   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5370
5371   // shl X, 0 == X and shr X, 0 == X
5372   // shl 0, X == 0 and shr 0, X == 0
5373   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5374       Op0 == Constant::getNullValue(Op0->getType()))
5375     return ReplaceInstUsesWith(I, Op0);
5376   
5377   if (isa<UndefValue>(Op0)) {            
5378     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5379       return ReplaceInstUsesWith(I, Op0);
5380     else                                    // undef << X -> 0, undef >>u X -> 0
5381       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5382   }
5383   if (isa<UndefValue>(Op1)) {
5384     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5385       return ReplaceInstUsesWith(I, Op0);          
5386     else                                     // X << undef, X >>u undef -> 0
5387       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5388   }
5389
5390   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5391   if (I.getOpcode() == Instruction::AShr)
5392     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5393       if (CSI->isAllOnesValue())
5394         return ReplaceInstUsesWith(I, CSI);
5395
5396   // Try to fold constant and into select arguments.
5397   if (isa<Constant>(Op0))
5398     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5399       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5400         return R;
5401
5402   // See if we can turn a signed shr into an unsigned shr.
5403   if (I.isArithmeticShift()) {
5404     if (MaskedValueIsZero(Op0,
5405                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5406       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5407     }
5408   }
5409
5410   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5411     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5412       return Res;
5413   return 0;
5414 }
5415
5416 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5417                                                ShiftInst &I) {
5418   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5419   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5420   bool isUnsignedShift = !isSignedShift;
5421
5422   // See if we can simplify any instructions used by the instruction whose sole 
5423   // purpose is to compute bits we don't care about.
5424   uint64_t KnownZero, KnownOne;
5425   if (SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
5426                            KnownZero, KnownOne))
5427     return &I;
5428   
5429   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5430   // of a signed value.
5431   //
5432   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5433   if (Op1->getZExtValue() >= TypeBits) {
5434     if (isUnsignedShift || isLeftShift)
5435       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5436     else {
5437       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5438       return &I;
5439     }
5440   }
5441   
5442   // ((X*C1) << C2) == (X * (C1 << C2))
5443   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5444     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5445       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5446         return BinaryOperator::createMul(BO->getOperand(0),
5447                                          ConstantExpr::getShl(BOOp, Op1));
5448   
5449   // Try to fold constant and into select arguments.
5450   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5451     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5452       return R;
5453   if (isa<PHINode>(Op0))
5454     if (Instruction *NV = FoldOpIntoPhi(I))
5455       return NV;
5456   
5457   if (Op0->hasOneUse()) {
5458     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5459       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5460       Value *V1, *V2;
5461       ConstantInt *CC;
5462       switch (Op0BO->getOpcode()) {
5463         default: break;
5464         case Instruction::Add:
5465         case Instruction::And:
5466         case Instruction::Or:
5467         case Instruction::Xor:
5468           // These operators commute.
5469           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5470           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5471               match(Op0BO->getOperand(1),
5472                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5473             Instruction *YS = new ShiftInst(Instruction::Shl, 
5474                                             Op0BO->getOperand(0), Op1,
5475                                             Op0BO->getName());
5476             InsertNewInstBefore(YS, I); // (Y << C)
5477             Instruction *X = 
5478               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5479                                      Op0BO->getOperand(1)->getName());
5480             InsertNewInstBefore(X, I);  // (X + (Y << C))
5481             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5482             C2 = ConstantExpr::getShl(C2, Op1);
5483             return BinaryOperator::createAnd(X, C2);
5484           }
5485           
5486           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5487           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5488               match(Op0BO->getOperand(1),
5489                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5490                           m_ConstantInt(CC))) && V2 == Op1 &&
5491       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5492             Instruction *YS = new ShiftInst(Instruction::Shl, 
5493                                             Op0BO->getOperand(0), Op1,
5494                                             Op0BO->getName());
5495             InsertNewInstBefore(YS, I); // (Y << C)
5496             Instruction *XM =
5497               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5498                                         V1->getName()+".mask");
5499             InsertNewInstBefore(XM, I); // X & (CC << C)
5500             
5501             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5502           }
5503           
5504           // FALL THROUGH.
5505         case Instruction::Sub:
5506           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5507           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5508               match(Op0BO->getOperand(0),
5509                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5510             Instruction *YS = new ShiftInst(Instruction::Shl, 
5511                                             Op0BO->getOperand(1), Op1,
5512                                             Op0BO->getName());
5513             InsertNewInstBefore(YS, I); // (Y << C)
5514             Instruction *X =
5515               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5516                                      Op0BO->getOperand(0)->getName());
5517             InsertNewInstBefore(X, I);  // (X + (Y << C))
5518             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5519             C2 = ConstantExpr::getShl(C2, Op1);
5520             return BinaryOperator::createAnd(X, C2);
5521           }
5522           
5523           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5524           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5525               match(Op0BO->getOperand(0),
5526                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5527                           m_ConstantInt(CC))) && V2 == Op1 &&
5528               cast<BinaryOperator>(Op0BO->getOperand(0))
5529                   ->getOperand(0)->hasOneUse()) {
5530             Instruction *YS = new ShiftInst(Instruction::Shl, 
5531                                             Op0BO->getOperand(1), Op1,
5532                                             Op0BO->getName());
5533             InsertNewInstBefore(YS, I); // (Y << C)
5534             Instruction *XM =
5535               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5536                                         V1->getName()+".mask");
5537             InsertNewInstBefore(XM, I); // X & (CC << C)
5538             
5539             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5540           }
5541           
5542           break;
5543       }
5544       
5545       
5546       // If the operand is an bitwise operator with a constant RHS, and the
5547       // shift is the only use, we can pull it out of the shift.
5548       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5549         bool isValid = true;     // Valid only for And, Or, Xor
5550         bool highBitSet = false; // Transform if high bit of constant set?
5551         
5552         switch (Op0BO->getOpcode()) {
5553           default: isValid = false; break;   // Do not perform transform!
5554           case Instruction::Add:
5555             isValid = isLeftShift;
5556             break;
5557           case Instruction::Or:
5558           case Instruction::Xor:
5559             highBitSet = false;
5560             break;
5561           case Instruction::And:
5562             highBitSet = true;
5563             break;
5564         }
5565         
5566         // If this is a signed shift right, and the high bit is modified
5567         // by the logical operation, do not perform the transformation.
5568         // The highBitSet boolean indicates the value of the high bit of
5569         // the constant which would cause it to be modified for this
5570         // operation.
5571         //
5572         if (isValid && !isLeftShift && isSignedShift) {
5573           uint64_t Val = Op0C->getZExtValue();
5574           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5575         }
5576         
5577         if (isValid) {
5578           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5579           
5580           Instruction *NewShift =
5581             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5582                           Op0BO->getName());
5583           Op0BO->setName("");
5584           InsertNewInstBefore(NewShift, I);
5585           
5586           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5587                                         NewRHS);
5588         }
5589       }
5590     }
5591   }
5592   
5593   // Find out if this is a shift of a shift by a constant.
5594   ShiftInst *ShiftOp = 0;
5595   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5596     ShiftOp = Op0SI;
5597   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5598     // If this is a noop-integer cast of a shift instruction, use the shift.
5599     if (isa<ShiftInst>(CI->getOperand(0))) {
5600       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5601     }
5602   }
5603   
5604   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5605     // Find the operands and properties of the input shift.  Note that the
5606     // signedness of the input shift may differ from the current shift if there
5607     // is a noop cast between the two.
5608     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5609     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5610     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5611     
5612     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5613
5614     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5615     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5616     
5617     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5618     if (isLeftShift == isShiftOfLeftShift) {
5619       // Do not fold these shifts if the first one is signed and the second one
5620       // is unsigned and this is a right shift.  Further, don't do any folding
5621       // on them.
5622       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5623         return 0;
5624       
5625       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5626       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5627         Amt = Op0->getType()->getPrimitiveSizeInBits();
5628       
5629       Value *Op = ShiftOp->getOperand(0);
5630       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5631                                           ConstantInt::get(Type::Int8Ty, Amt));
5632       if (I.getType() == ShiftResult->getType())
5633         return ShiftResult;
5634       InsertNewInstBefore(ShiftResult, I);
5635       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5636     }
5637     
5638     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5639     // signed types, we can only support the (A >> c1) << c2 configuration,
5640     // because it can not turn an arbitrary bit of A into a sign bit.
5641     if (isUnsignedShift || isLeftShift) {
5642       // Calculate bitmask for what gets shifted off the edge.
5643       Constant *C = ConstantInt::getAllOnesValue(I.getType());
5644       if (isLeftShift)
5645         C = ConstantExpr::getShl(C, ShiftAmt1C);
5646       else
5647         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5648       
5649       Value *Op = ShiftOp->getOperand(0);
5650       
5651       Instruction *Mask =
5652         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5653       InsertNewInstBefore(Mask, I);
5654       
5655       // Figure out what flavor of shift we should use...
5656       if (ShiftAmt1 == ShiftAmt2) {
5657         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5658       } else if (ShiftAmt1 < ShiftAmt2) {
5659         return new ShiftInst(I.getOpcode(), Mask,
5660                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5661       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5662         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5663           return new ShiftInst(Instruction::LShr, Mask, 
5664             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5665         } else {
5666           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5667                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5668         }
5669       } else {
5670         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5671         Instruction *Shift =
5672           new ShiftInst(ShiftOp->getOpcode(), Mask,
5673                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5674         InsertNewInstBefore(Shift, I);
5675         
5676         C = ConstantInt::getAllOnesValue(Shift->getType());
5677         C = ConstantExpr::getShl(C, Op1);
5678         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5679       }
5680     } else {
5681       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5682       // this case, C1 == C2 and C1 is 8, 16, or 32.
5683       if (ShiftAmt1 == ShiftAmt2) {
5684         const Type *SExtType = 0;
5685         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5686         case 8 : SExtType = Type::Int8Ty; break;
5687         case 16: SExtType = Type::Int16Ty; break;
5688         case 32: SExtType = Type::Int32Ty; break;
5689         }
5690         
5691         if (SExtType) {
5692           Instruction *NewTrunc = 
5693             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5694           InsertNewInstBefore(NewTrunc, I);
5695           return new SExtInst(NewTrunc, I.getType());
5696         }
5697       }
5698     }
5699   }
5700   return 0;
5701 }
5702
5703
5704 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5705 /// expression.  If so, decompose it, returning some value X, such that Val is
5706 /// X*Scale+Offset.
5707 ///
5708 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5709                                         unsigned &Offset) {
5710   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5711   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5712     Offset = CI->getZExtValue();
5713     Scale  = 1;
5714     return ConstantInt::get(Type::Int32Ty, 0);
5715   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5716     if (I->getNumOperands() == 2) {
5717       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5718         if (I->getOpcode() == Instruction::Shl) {
5719           // This is a value scaled by '1 << the shift amt'.
5720           Scale = 1U << CUI->getZExtValue();
5721           Offset = 0;
5722           return I->getOperand(0);
5723         } else if (I->getOpcode() == Instruction::Mul) {
5724           // This value is scaled by 'CUI'.
5725           Scale = CUI->getZExtValue();
5726           Offset = 0;
5727           return I->getOperand(0);
5728         } else if (I->getOpcode() == Instruction::Add) {
5729           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5730           // where C1 is divisible by C2.
5731           unsigned SubScale;
5732           Value *SubVal = 
5733             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5734           Offset += CUI->getZExtValue();
5735           if (SubScale > 1 && (Offset % SubScale == 0)) {
5736             Scale = SubScale;
5737             return SubVal;
5738           }
5739         }
5740       }
5741     }
5742   }
5743
5744   // Otherwise, we can't look past this.
5745   Scale = 1;
5746   Offset = 0;
5747   return Val;
5748 }
5749
5750
5751 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5752 /// try to eliminate the cast by moving the type information into the alloc.
5753 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5754                                                    AllocationInst &AI) {
5755   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5756   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5757   
5758   // Remove any uses of AI that are dead.
5759   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5760   std::vector<Instruction*> DeadUsers;
5761   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5762     Instruction *User = cast<Instruction>(*UI++);
5763     if (isInstructionTriviallyDead(User)) {
5764       while (UI != E && *UI == User)
5765         ++UI; // If this instruction uses AI more than once, don't break UI.
5766       
5767       // Add operands to the worklist.
5768       AddUsesToWorkList(*User);
5769       ++NumDeadInst;
5770       DOUT << "IC: DCE: " << *User;
5771       
5772       User->eraseFromParent();
5773       removeFromWorkList(User);
5774     }
5775   }
5776   
5777   // Get the type really allocated and the type casted to.
5778   const Type *AllocElTy = AI.getAllocatedType();
5779   const Type *CastElTy = PTy->getElementType();
5780   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5781
5782   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5783   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5784   if (CastElTyAlign < AllocElTyAlign) return 0;
5785
5786   // If the allocation has multiple uses, only promote it if we are strictly
5787   // increasing the alignment of the resultant allocation.  If we keep it the
5788   // same, we open the door to infinite loops of various kinds.
5789   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5790
5791   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5792   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5793   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5794
5795   // See if we can satisfy the modulus by pulling a scale out of the array
5796   // size argument.
5797   unsigned ArraySizeScale, ArrayOffset;
5798   Value *NumElements = // See if the array size is a decomposable linear expr.
5799     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5800  
5801   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5802   // do the xform.
5803   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5804       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5805
5806   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5807   Value *Amt = 0;
5808   if (Scale == 1) {
5809     Amt = NumElements;
5810   } else {
5811     // If the allocation size is constant, form a constant mul expression
5812     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5813     if (isa<ConstantInt>(NumElements))
5814       Amt = ConstantExpr::getMul(
5815               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5816     // otherwise multiply the amount and the number of elements
5817     else if (Scale != 1) {
5818       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5819       Amt = InsertNewInstBefore(Tmp, AI);
5820     }
5821   }
5822   
5823   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5824     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5825     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5826     Amt = InsertNewInstBefore(Tmp, AI);
5827   }
5828   
5829   std::string Name = AI.getName(); AI.setName("");
5830   AllocationInst *New;
5831   if (isa<MallocInst>(AI))
5832     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5833   else
5834     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5835   InsertNewInstBefore(New, AI);
5836   
5837   // If the allocation has multiple uses, insert a cast and change all things
5838   // that used it to use the new cast.  This will also hack on CI, but it will
5839   // die soon.
5840   if (!AI.hasOneUse()) {
5841     AddUsesToWorkList(AI);
5842     // New is the allocation instruction, pointer typed. AI is the original
5843     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5844     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5845     InsertNewInstBefore(NewCast, AI);
5846     AI.replaceAllUsesWith(NewCast);
5847   }
5848   return ReplaceInstUsesWith(CI, New);
5849 }
5850
5851 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5852 /// and return it without inserting any new casts.  This is used by code that
5853 /// tries to decide whether promoting or shrinking integer operations to wider
5854 /// or smaller types will allow us to eliminate a truncate or extend.
5855 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5856                                        int &NumCastsRemoved) {
5857   if (isa<Constant>(V)) return true;
5858   
5859   Instruction *I = dyn_cast<Instruction>(V);
5860   if (!I || !I->hasOneUse()) return false;
5861   
5862   switch (I->getOpcode()) {
5863   case Instruction::And:
5864   case Instruction::Or:
5865   case Instruction::Xor:
5866     // These operators can all arbitrarily be extended or truncated.
5867     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5868            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5869   case Instruction::AShr:
5870   case Instruction::LShr:
5871   case Instruction::Shl:
5872     // If this is just a bitcast changing the sign of the operation, we can
5873     // convert if the operand can be converted.
5874     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5875       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5876     break;
5877   case Instruction::Trunc:
5878   case Instruction::ZExt:
5879   case Instruction::SExt:
5880   case Instruction::BitCast:
5881     // If this is a cast from the destination type, we can trivially eliminate
5882     // it, and this will remove a cast overall.
5883     if (I->getOperand(0)->getType() == Ty) {
5884       // If the first operand is itself a cast, and is eliminable, do not count
5885       // this as an eliminable cast.  We would prefer to eliminate those two
5886       // casts first.
5887       if (isa<CastInst>(I->getOperand(0)))
5888         return true;
5889       
5890       ++NumCastsRemoved;
5891       return true;
5892     }
5893     break;
5894   default:
5895     // TODO: Can handle more cases here.
5896     break;
5897   }
5898   
5899   return false;
5900 }
5901
5902 /// EvaluateInDifferentType - Given an expression that 
5903 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5904 /// evaluate the expression.
5905 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5906                                              bool isSigned ) {
5907   if (Constant *C = dyn_cast<Constant>(V))
5908     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5909
5910   // Otherwise, it must be an instruction.
5911   Instruction *I = cast<Instruction>(V);
5912   Instruction *Res = 0;
5913   switch (I->getOpcode()) {
5914   case Instruction::And:
5915   case Instruction::Or:
5916   case Instruction::Xor: {
5917     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5918     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5919     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5920                                  LHS, RHS, I->getName());
5921     break;
5922   }
5923   case Instruction::AShr:
5924   case Instruction::LShr:
5925   case Instruction::Shl: {
5926     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5927     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5928                         I->getOperand(1), I->getName());
5929     break;
5930   }    
5931   case Instruction::Trunc:
5932   case Instruction::ZExt:
5933   case Instruction::SExt:
5934   case Instruction::BitCast:
5935     // If the source type of the cast is the type we're trying for then we can
5936     // just return the source. There's no need to insert it because its not new.
5937     if (I->getOperand(0)->getType() == Ty)
5938       return I->getOperand(0);
5939     
5940     // Some other kind of cast, which shouldn't happen, so just ..
5941     // FALL THROUGH
5942   default: 
5943     // TODO: Can handle more cases here.
5944     assert(0 && "Unreachable!");
5945     break;
5946   }
5947   
5948   return InsertNewInstBefore(Res, *I);
5949 }
5950
5951 /// @brief Implement the transforms common to all CastInst visitors.
5952 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5953   Value *Src = CI.getOperand(0);
5954
5955   // Casting undef to anything results in undef so might as just replace it and
5956   // get rid of the cast.
5957   if (isa<UndefValue>(Src))   // cast undef -> undef
5958     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5959
5960   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5961   // eliminate it now.
5962   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5963     if (Instruction::CastOps opc = 
5964         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5965       // The first cast (CSrc) is eliminable so we need to fix up or replace
5966       // the second cast (CI). CSrc will then have a good chance of being dead.
5967       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5968     }
5969   }
5970
5971   // If casting the result of a getelementptr instruction with no offset, turn
5972   // this into a cast of the original pointer!
5973   //
5974   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5975     bool AllZeroOperands = true;
5976     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5977       if (!isa<Constant>(GEP->getOperand(i)) ||
5978           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5979         AllZeroOperands = false;
5980         break;
5981       }
5982     if (AllZeroOperands) {
5983       // Changing the cast operand is usually not a good idea but it is safe
5984       // here because the pointer operand is being replaced with another 
5985       // pointer operand so the opcode doesn't need to change.
5986       CI.setOperand(0, GEP->getOperand(0));
5987       return &CI;
5988     }
5989   }
5990     
5991   // If we are casting a malloc or alloca to a pointer to a type of the same
5992   // size, rewrite the allocation instruction to allocate the "right" type.
5993   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5994     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5995       return V;
5996
5997   // If we are casting a select then fold the cast into the select
5998   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5999     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6000       return NV;
6001
6002   // If we are casting a PHI then fold the cast into the PHI
6003   if (isa<PHINode>(Src))
6004     if (Instruction *NV = FoldOpIntoPhi(CI))
6005       return NV;
6006   
6007   return 0;
6008 }
6009
6010 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6011 /// integers. This function implements the common transforms for all those
6012 /// cases.
6013 /// @brief Implement the transforms common to CastInst with integer operands
6014 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6015   if (Instruction *Result = commonCastTransforms(CI))
6016     return Result;
6017
6018   Value *Src = CI.getOperand(0);
6019   const Type *SrcTy = Src->getType();
6020   const Type *DestTy = CI.getType();
6021   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6022   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6023
6024   // See if we can simplify any instructions used by the LHS whose sole 
6025   // purpose is to compute bits we don't care about.
6026   uint64_t KnownZero = 0, KnownOne = 0;
6027   if (SimplifyDemandedBits(&CI, DestTy->getIntegerTypeMask(),
6028                            KnownZero, KnownOne))
6029     return &CI;
6030
6031   // If the source isn't an instruction or has more than one use then we
6032   // can't do anything more. 
6033   Instruction *SrcI = dyn_cast<Instruction>(Src);
6034   if (!SrcI || !Src->hasOneUse())
6035     return 0;
6036
6037   // Attempt to propagate the cast into the instruction.
6038   int NumCastsRemoved = 0;
6039   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6040     // If this cast is a truncate, evaluting in a different type always
6041     // eliminates the cast, so it is always a win.  If this is a noop-cast
6042     // this just removes a noop cast which isn't pointful, but simplifies
6043     // the code.  If this is a zero-extension, we need to do an AND to
6044     // maintain the clear top-part of the computation, so we require that
6045     // the input have eliminated at least one cast.  If this is a sign
6046     // extension, we insert two new casts (to do the extension) so we
6047     // require that two casts have been eliminated.
6048     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6049     if (!DoXForm) {
6050       switch (CI.getOpcode()) {
6051         case Instruction::Trunc:
6052           DoXForm = true;
6053           break;
6054         case Instruction::ZExt:
6055           DoXForm = NumCastsRemoved >= 1;
6056           break;
6057         case Instruction::SExt:
6058           DoXForm = NumCastsRemoved >= 2;
6059           break;
6060         case Instruction::BitCast:
6061           DoXForm = false;
6062           break;
6063         default:
6064           // All the others use floating point so we shouldn't actually 
6065           // get here because of the check above.
6066           assert(!"Unknown cast type .. unreachable");
6067           break;
6068       }
6069     }
6070     
6071     if (DoXForm) {
6072       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6073                                            CI.getOpcode() == Instruction::SExt);
6074       assert(Res->getType() == DestTy);
6075       switch (CI.getOpcode()) {
6076       default: assert(0 && "Unknown cast type!");
6077       case Instruction::Trunc:
6078       case Instruction::BitCast:
6079         // Just replace this cast with the result.
6080         return ReplaceInstUsesWith(CI, Res);
6081       case Instruction::ZExt: {
6082         // We need to emit an AND to clear the high bits.
6083         assert(SrcBitSize < DestBitSize && "Not a zext?");
6084         Constant *C = 
6085           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6086         if (DestBitSize < 64)
6087           C = ConstantExpr::getTrunc(C, DestTy);
6088         return BinaryOperator::createAnd(Res, C);
6089       }
6090       case Instruction::SExt:
6091         // We need to emit a cast to truncate, then a cast to sext.
6092         return CastInst::create(Instruction::SExt,
6093             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6094                              CI), DestTy);
6095       }
6096     }
6097   }
6098   
6099   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6100   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6101
6102   switch (SrcI->getOpcode()) {
6103   case Instruction::Add:
6104   case Instruction::Mul:
6105   case Instruction::And:
6106   case Instruction::Or:
6107   case Instruction::Xor:
6108     // If we are discarding information, or just changing the sign, 
6109     // rewrite.
6110     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6111       // Don't insert two casts if they cannot be eliminated.  We allow 
6112       // two casts to be inserted if the sizes are the same.  This could 
6113       // only be converting signedness, which is a noop.
6114       if (DestBitSize == SrcBitSize || 
6115           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6116           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6117         Instruction::CastOps opcode = CI.getOpcode();
6118         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6119         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6120         return BinaryOperator::create(
6121             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6122       }
6123     }
6124
6125     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6126     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6127         SrcI->getOpcode() == Instruction::Xor &&
6128         Op1 == ConstantInt::getTrue() &&
6129         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6130       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6131       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6132     }
6133     break;
6134   case Instruction::SDiv:
6135   case Instruction::UDiv:
6136   case Instruction::SRem:
6137   case Instruction::URem:
6138     // If we are just changing the sign, rewrite.
6139     if (DestBitSize == SrcBitSize) {
6140       // Don't insert two casts if they cannot be eliminated.  We allow 
6141       // two casts to be inserted if the sizes are the same.  This could 
6142       // only be converting signedness, which is a noop.
6143       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6144           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6145         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6146                                               Op0, DestTy, SrcI);
6147         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6148                                               Op1, DestTy, SrcI);
6149         return BinaryOperator::create(
6150           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6151       }
6152     }
6153     break;
6154
6155   case Instruction::Shl:
6156     // Allow changing the sign of the source operand.  Do not allow 
6157     // changing the size of the shift, UNLESS the shift amount is a 
6158     // constant.  We must not change variable sized shifts to a smaller 
6159     // size, because it is undefined to shift more bits out than exist 
6160     // in the value.
6161     if (DestBitSize == SrcBitSize ||
6162         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6163       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6164           Instruction::BitCast : Instruction::Trunc);
6165       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6166       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6167     }
6168     break;
6169   case Instruction::AShr:
6170     // If this is a signed shr, and if all bits shifted in are about to be
6171     // truncated off, turn it into an unsigned shr to allow greater
6172     // simplifications.
6173     if (DestBitSize < SrcBitSize &&
6174         isa<ConstantInt>(Op1)) {
6175       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6176       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6177         // Insert the new logical shift right.
6178         return new ShiftInst(Instruction::LShr, Op0, Op1);
6179       }
6180     }
6181     break;
6182
6183   case Instruction::ICmp:
6184     // If we are just checking for a icmp eq of a single bit and casting it
6185     // to an integer, then shift the bit to the appropriate place and then
6186     // cast to integer to avoid the comparison.
6187     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6188       uint64_t Op1CV = Op1C->getZExtValue();
6189       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6190       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6191       // cast (X == 1) to int --> X        iff X has only the low bit set.
6192       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6193       // cast (X != 0) to int --> X        iff X has only the low bit set.
6194       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6195       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6196       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6197       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6198         // If Op1C some other power of two, convert:
6199         uint64_t KnownZero, KnownOne;
6200         uint64_t TypeMask = Op1->getType()->getIntegerTypeMask();
6201         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6202
6203         // This only works for EQ and NE
6204         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6205         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6206           break;
6207         
6208         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6209           bool isNE = pred == ICmpInst::ICMP_NE;
6210           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6211             // (X&4) == 2 --> false
6212             // (X&4) != 2 --> true
6213             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6214             Res = ConstantExpr::getZExt(Res, CI.getType());
6215             return ReplaceInstUsesWith(CI, Res);
6216           }
6217           
6218           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6219           Value *In = Op0;
6220           if (ShiftAmt) {
6221             // Perform a logical shr by shiftamt.
6222             // Insert the shift to put the result in the low bit.
6223             In = InsertNewInstBefore(
6224               new ShiftInst(Instruction::LShr, In,
6225                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6226                             In->getName()+".lobit"), CI);
6227           }
6228           
6229           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6230             Constant *One = ConstantInt::get(In->getType(), 1);
6231             In = BinaryOperator::createXor(In, One, "tmp");
6232             InsertNewInstBefore(cast<Instruction>(In), CI);
6233           }
6234           
6235           if (CI.getType() == In->getType())
6236             return ReplaceInstUsesWith(CI, In);
6237           else
6238             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6239         }
6240       }
6241     }
6242     break;
6243   }
6244   return 0;
6245 }
6246
6247 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6248   if (Instruction *Result = commonIntCastTransforms(CI))
6249     return Result;
6250   
6251   Value *Src = CI.getOperand(0);
6252   const Type *Ty = CI.getType();
6253   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6254   
6255   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6256     switch (SrcI->getOpcode()) {
6257     default: break;
6258     case Instruction::LShr:
6259       // We can shrink lshr to something smaller if we know the bits shifted in
6260       // are already zeros.
6261       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6262         unsigned ShAmt = ShAmtV->getZExtValue();
6263         
6264         // Get a mask for the bits shifting in.
6265         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6266         Value* SrcIOp0 = SrcI->getOperand(0);
6267         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6268           if (ShAmt >= DestBitWidth)        // All zeros.
6269             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6270
6271           // Okay, we can shrink this.  Truncate the input, then return a new
6272           // shift.
6273           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6274           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6275         }
6276       } else {     // This is a variable shr.
6277         
6278         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6279         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6280         // loop-invariant and CSE'd.
6281         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6282           Value *One = ConstantInt::get(SrcI->getType(), 1);
6283
6284           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6285                                                        SrcI->getOperand(1),
6286                                                        "tmp"), CI);
6287           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6288                                                             SrcI->getOperand(0),
6289                                                             "tmp"), CI);
6290           Value *Zero = Constant::getNullValue(V->getType());
6291           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6292         }
6293       }
6294       break;
6295     }
6296   }
6297   
6298   return 0;
6299 }
6300
6301 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6302   // If one of the common conversion will work ..
6303   if (Instruction *Result = commonIntCastTransforms(CI))
6304     return Result;
6305
6306   Value *Src = CI.getOperand(0);
6307
6308   // If this is a cast of a cast
6309   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6310     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6311     // types and if the sizes are just right we can convert this into a logical
6312     // 'and' which will be much cheaper than the pair of casts.
6313     if (isa<TruncInst>(CSrc)) {
6314       // Get the sizes of the types involved
6315       Value *A = CSrc->getOperand(0);
6316       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6317       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6318       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6319       // If we're actually extending zero bits and the trunc is a no-op
6320       if (MidSize < DstSize && SrcSize == DstSize) {
6321         // Replace both of the casts with an And of the type mask.
6322         uint64_t AndValue = CSrc->getType()->getIntegerTypeMask();
6323         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6324         Instruction *And = 
6325           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6326         // Unfortunately, if the type changed, we need to cast it back.
6327         if (And->getType() != CI.getType()) {
6328           And->setName(CSrc->getName()+".mask");
6329           InsertNewInstBefore(And, CI);
6330           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6331         }
6332         return And;
6333       }
6334     }
6335   }
6336
6337   return 0;
6338 }
6339
6340 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6341   return commonIntCastTransforms(CI);
6342 }
6343
6344 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6345   return commonCastTransforms(CI);
6346 }
6347
6348 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6349   return commonCastTransforms(CI);
6350 }
6351
6352 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6353   return commonCastTransforms(CI);
6354 }
6355
6356 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6357   return commonCastTransforms(CI);
6358 }
6359
6360 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6361   return commonCastTransforms(CI);
6362 }
6363
6364 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6365   return commonCastTransforms(CI);
6366 }
6367
6368 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6369   return commonCastTransforms(CI);
6370 }
6371
6372 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6373   return commonCastTransforms(CI);
6374 }
6375
6376 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6377
6378   // If the operands are integer typed then apply the integer transforms,
6379   // otherwise just apply the common ones.
6380   Value *Src = CI.getOperand(0);
6381   const Type *SrcTy = Src->getType();
6382   const Type *DestTy = CI.getType();
6383
6384   if (SrcTy->isInteger() && DestTy->isInteger()) {
6385     if (Instruction *Result = commonIntCastTransforms(CI))
6386       return Result;
6387   } else {
6388     if (Instruction *Result = commonCastTransforms(CI))
6389       return Result;
6390   }
6391
6392
6393   // Get rid of casts from one type to the same type. These are useless and can
6394   // be replaced by the operand.
6395   if (DestTy == Src->getType())
6396     return ReplaceInstUsesWith(CI, Src);
6397
6398   // If the source and destination are pointers, and this cast is equivalent to
6399   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6400   // This can enhance SROA and other transforms that want type-safe pointers.
6401   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6402     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6403       const Type *DstElTy = DstPTy->getElementType();
6404       const Type *SrcElTy = SrcPTy->getElementType();
6405       
6406       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6407       unsigned NumZeros = 0;
6408       while (SrcElTy != DstElTy && 
6409              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6410              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6411         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6412         ++NumZeros;
6413       }
6414
6415       // If we found a path from the src to dest, create the getelementptr now.
6416       if (SrcElTy == DstElTy) {
6417         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6418         return new GetElementPtrInst(Src, Idxs);
6419       }
6420     }
6421   }
6422
6423   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6424     if (SVI->hasOneUse()) {
6425       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6426       // a bitconvert to a vector with the same # elts.
6427       if (isa<PackedType>(DestTy) && 
6428           cast<PackedType>(DestTy)->getNumElements() == 
6429                 SVI->getType()->getNumElements()) {
6430         CastInst *Tmp;
6431         // If either of the operands is a cast from CI.getType(), then
6432         // evaluating the shuffle in the casted destination's type will allow
6433         // us to eliminate at least one cast.
6434         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6435              Tmp->getOperand(0)->getType() == DestTy) ||
6436             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6437              Tmp->getOperand(0)->getType() == DestTy)) {
6438           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6439                                                SVI->getOperand(0), DestTy, &CI);
6440           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6441                                                SVI->getOperand(1), DestTy, &CI);
6442           // Return a new shuffle vector.  Use the same element ID's, as we
6443           // know the vector types match #elts.
6444           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6445         }
6446       }
6447     }
6448   }
6449   return 0;
6450 }
6451
6452 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6453 ///   %C = or %A, %B
6454 ///   %D = select %cond, %C, %A
6455 /// into:
6456 ///   %C = select %cond, %B, 0
6457 ///   %D = or %A, %C
6458 ///
6459 /// Assuming that the specified instruction is an operand to the select, return
6460 /// a bitmask indicating which operands of this instruction are foldable if they
6461 /// equal the other incoming value of the select.
6462 ///
6463 static unsigned GetSelectFoldableOperands(Instruction *I) {
6464   switch (I->getOpcode()) {
6465   case Instruction::Add:
6466   case Instruction::Mul:
6467   case Instruction::And:
6468   case Instruction::Or:
6469   case Instruction::Xor:
6470     return 3;              // Can fold through either operand.
6471   case Instruction::Sub:   // Can only fold on the amount subtracted.
6472   case Instruction::Shl:   // Can only fold on the shift amount.
6473   case Instruction::LShr:
6474   case Instruction::AShr:
6475     return 1;
6476   default:
6477     return 0;              // Cannot fold
6478   }
6479 }
6480
6481 /// GetSelectFoldableConstant - For the same transformation as the previous
6482 /// function, return the identity constant that goes into the select.
6483 static Constant *GetSelectFoldableConstant(Instruction *I) {
6484   switch (I->getOpcode()) {
6485   default: assert(0 && "This cannot happen!"); abort();
6486   case Instruction::Add:
6487   case Instruction::Sub:
6488   case Instruction::Or:
6489   case Instruction::Xor:
6490     return Constant::getNullValue(I->getType());
6491   case Instruction::Shl:
6492   case Instruction::LShr:
6493   case Instruction::AShr:
6494     return Constant::getNullValue(Type::Int8Ty);
6495   case Instruction::And:
6496     return ConstantInt::getAllOnesValue(I->getType());
6497   case Instruction::Mul:
6498     return ConstantInt::get(I->getType(), 1);
6499   }
6500 }
6501
6502 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6503 /// have the same opcode and only one use each.  Try to simplify this.
6504 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6505                                           Instruction *FI) {
6506   if (TI->getNumOperands() == 1) {
6507     // If this is a non-volatile load or a cast from the same type,
6508     // merge.
6509     if (TI->isCast()) {
6510       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6511         return 0;
6512     } else {
6513       return 0;  // unknown unary op.
6514     }
6515
6516     // Fold this by inserting a select from the input values.
6517     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6518                                        FI->getOperand(0), SI.getName()+".v");
6519     InsertNewInstBefore(NewSI, SI);
6520     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6521                             TI->getType());
6522   }
6523
6524   // Only handle binary, compare and shift operators here.
6525   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6526     return 0;
6527
6528   // Figure out if the operations have any operands in common.
6529   Value *MatchOp, *OtherOpT, *OtherOpF;
6530   bool MatchIsOpZero;
6531   if (TI->getOperand(0) == FI->getOperand(0)) {
6532     MatchOp  = TI->getOperand(0);
6533     OtherOpT = TI->getOperand(1);
6534     OtherOpF = FI->getOperand(1);
6535     MatchIsOpZero = true;
6536   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6537     MatchOp  = TI->getOperand(1);
6538     OtherOpT = TI->getOperand(0);
6539     OtherOpF = FI->getOperand(0);
6540     MatchIsOpZero = false;
6541   } else if (!TI->isCommutative()) {
6542     return 0;
6543   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6544     MatchOp  = TI->getOperand(0);
6545     OtherOpT = TI->getOperand(1);
6546     OtherOpF = FI->getOperand(0);
6547     MatchIsOpZero = true;
6548   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6549     MatchOp  = TI->getOperand(1);
6550     OtherOpT = TI->getOperand(0);
6551     OtherOpF = FI->getOperand(1);
6552     MatchIsOpZero = true;
6553   } else {
6554     return 0;
6555   }
6556
6557   // If we reach here, they do have operations in common.
6558   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6559                                      OtherOpF, SI.getName()+".v");
6560   InsertNewInstBefore(NewSI, SI);
6561
6562   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6563     if (MatchIsOpZero)
6564       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6565     else
6566       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6567   }
6568
6569   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6570   if (MatchIsOpZero)
6571     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6572   else
6573     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6574 }
6575
6576 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6577   Value *CondVal = SI.getCondition();
6578   Value *TrueVal = SI.getTrueValue();
6579   Value *FalseVal = SI.getFalseValue();
6580
6581   // select true, X, Y  -> X
6582   // select false, X, Y -> Y
6583   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6584     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6585
6586   // select C, X, X -> X
6587   if (TrueVal == FalseVal)
6588     return ReplaceInstUsesWith(SI, TrueVal);
6589
6590   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6591     return ReplaceInstUsesWith(SI, FalseVal);
6592   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6593     return ReplaceInstUsesWith(SI, TrueVal);
6594   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6595     if (isa<Constant>(TrueVal))
6596       return ReplaceInstUsesWith(SI, TrueVal);
6597     else
6598       return ReplaceInstUsesWith(SI, FalseVal);
6599   }
6600
6601   if (SI.getType() == Type::Int1Ty) {
6602     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6603       if (C->getZExtValue()) {
6604         // Change: A = select B, true, C --> A = or B, C
6605         return BinaryOperator::createOr(CondVal, FalseVal);
6606       } else {
6607         // Change: A = select B, false, C --> A = and !B, C
6608         Value *NotCond =
6609           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6610                                              "not."+CondVal->getName()), SI);
6611         return BinaryOperator::createAnd(NotCond, FalseVal);
6612       }
6613     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6614       if (C->getZExtValue() == false) {
6615         // Change: A = select B, C, false --> A = and B, C
6616         return BinaryOperator::createAnd(CondVal, TrueVal);
6617       } else {
6618         // Change: A = select B, C, true --> A = or !B, C
6619         Value *NotCond =
6620           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6621                                              "not."+CondVal->getName()), SI);
6622         return BinaryOperator::createOr(NotCond, TrueVal);
6623       }
6624     }
6625   }
6626
6627   // Selecting between two integer constants?
6628   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6629     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6630       // select C, 1, 0 -> cast C to int
6631       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6632         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6633       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6634         // select C, 0, 1 -> cast !C to int
6635         Value *NotCond =
6636           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6637                                                "not."+CondVal->getName()), SI);
6638         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6639       }
6640
6641       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6642
6643         // (x <s 0) ? -1 : 0 -> ashr x, 31
6644         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6645         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6646           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6647             bool CanXForm = false;
6648             if (IC->isSignedPredicate())
6649               CanXForm = CmpCst->isNullValue() && 
6650                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6651             else {
6652               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6653               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6654                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6655             }
6656             
6657             if (CanXForm) {
6658               // The comparison constant and the result are not neccessarily the
6659               // same width. Make an all-ones value by inserting a AShr.
6660               Value *X = IC->getOperand(0);
6661               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6662               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6663               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6664                                                ShAmt, "ones");
6665               InsertNewInstBefore(SRA, SI);
6666               
6667               // Finally, convert to the type of the select RHS.  We figure out
6668               // if this requires a SExt, Trunc or BitCast based on the sizes.
6669               Instruction::CastOps opc = Instruction::BitCast;
6670               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6671               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6672               if (SRASize < SISize)
6673                 opc = Instruction::SExt;
6674               else if (SRASize > SISize)
6675                 opc = Instruction::Trunc;
6676               return CastInst::create(opc, SRA, SI.getType());
6677             }
6678           }
6679
6680
6681         // If one of the constants is zero (we know they can't both be) and we
6682         // have a fcmp instruction with zero, and we have an 'and' with the
6683         // non-constant value, eliminate this whole mess.  This corresponds to
6684         // cases like this: ((X & 27) ? 27 : 0)
6685         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6686           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6687               cast<Constant>(IC->getOperand(1))->isNullValue())
6688             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6689               if (ICA->getOpcode() == Instruction::And &&
6690                   isa<ConstantInt>(ICA->getOperand(1)) &&
6691                   (ICA->getOperand(1) == TrueValC ||
6692                    ICA->getOperand(1) == FalseValC) &&
6693                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6694                 // Okay, now we know that everything is set up, we just don't
6695                 // know whether we have a icmp_ne or icmp_eq and whether the 
6696                 // true or false val is the zero.
6697                 bool ShouldNotVal = !TrueValC->isNullValue();
6698                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6699                 Value *V = ICA;
6700                 if (ShouldNotVal)
6701                   V = InsertNewInstBefore(BinaryOperator::create(
6702                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6703                 return ReplaceInstUsesWith(SI, V);
6704               }
6705       }
6706     }
6707
6708   // See if we are selecting two values based on a comparison of the two values.
6709   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6710     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6711       // Transform (X == Y) ? X : Y  -> Y
6712       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6713         return ReplaceInstUsesWith(SI, FalseVal);
6714       // Transform (X != Y) ? X : Y  -> X
6715       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6716         return ReplaceInstUsesWith(SI, TrueVal);
6717       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6718
6719     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6720       // Transform (X == Y) ? Y : X  -> X
6721       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6722         return ReplaceInstUsesWith(SI, FalseVal);
6723       // Transform (X != Y) ? Y : X  -> Y
6724       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6725         return ReplaceInstUsesWith(SI, TrueVal);
6726       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6727     }
6728   }
6729
6730   // See if we are selecting two values based on a comparison of the two values.
6731   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6732     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6733       // Transform (X == Y) ? X : Y  -> Y
6734       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6735         return ReplaceInstUsesWith(SI, FalseVal);
6736       // Transform (X != Y) ? X : Y  -> X
6737       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6738         return ReplaceInstUsesWith(SI, TrueVal);
6739       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6740
6741     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6742       // Transform (X == Y) ? Y : X  -> X
6743       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6744         return ReplaceInstUsesWith(SI, FalseVal);
6745       // Transform (X != Y) ? Y : X  -> Y
6746       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6747         return ReplaceInstUsesWith(SI, TrueVal);
6748       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6749     }
6750   }
6751
6752   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6753     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6754       if (TI->hasOneUse() && FI->hasOneUse()) {
6755         Instruction *AddOp = 0, *SubOp = 0;
6756
6757         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6758         if (TI->getOpcode() == FI->getOpcode())
6759           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6760             return IV;
6761
6762         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6763         // even legal for FP.
6764         if (TI->getOpcode() == Instruction::Sub &&
6765             FI->getOpcode() == Instruction::Add) {
6766           AddOp = FI; SubOp = TI;
6767         } else if (FI->getOpcode() == Instruction::Sub &&
6768                    TI->getOpcode() == Instruction::Add) {
6769           AddOp = TI; SubOp = FI;
6770         }
6771
6772         if (AddOp) {
6773           Value *OtherAddOp = 0;
6774           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6775             OtherAddOp = AddOp->getOperand(1);
6776           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6777             OtherAddOp = AddOp->getOperand(0);
6778           }
6779
6780           if (OtherAddOp) {
6781             // So at this point we know we have (Y -> OtherAddOp):
6782             //        select C, (add X, Y), (sub X, Z)
6783             Value *NegVal;  // Compute -Z
6784             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6785               NegVal = ConstantExpr::getNeg(C);
6786             } else {
6787               NegVal = InsertNewInstBefore(
6788                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6789             }
6790
6791             Value *NewTrueOp = OtherAddOp;
6792             Value *NewFalseOp = NegVal;
6793             if (AddOp != TI)
6794               std::swap(NewTrueOp, NewFalseOp);
6795             Instruction *NewSel =
6796               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6797
6798             NewSel = InsertNewInstBefore(NewSel, SI);
6799             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6800           }
6801         }
6802       }
6803
6804   // See if we can fold the select into one of our operands.
6805   if (SI.getType()->isInteger()) {
6806     // See the comment above GetSelectFoldableOperands for a description of the
6807     // transformation we are doing here.
6808     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6809       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6810           !isa<Constant>(FalseVal))
6811         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6812           unsigned OpToFold = 0;
6813           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6814             OpToFold = 1;
6815           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6816             OpToFold = 2;
6817           }
6818
6819           if (OpToFold) {
6820             Constant *C = GetSelectFoldableConstant(TVI);
6821             std::string Name = TVI->getName(); TVI->setName("");
6822             Instruction *NewSel =
6823               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6824                              Name);
6825             InsertNewInstBefore(NewSel, SI);
6826             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6827               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6828             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6829               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6830             else {
6831               assert(0 && "Unknown instruction!!");
6832             }
6833           }
6834         }
6835
6836     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6837       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6838           !isa<Constant>(TrueVal))
6839         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6840           unsigned OpToFold = 0;
6841           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6842             OpToFold = 1;
6843           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6844             OpToFold = 2;
6845           }
6846
6847           if (OpToFold) {
6848             Constant *C = GetSelectFoldableConstant(FVI);
6849             std::string Name = FVI->getName(); FVI->setName("");
6850             Instruction *NewSel =
6851               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6852                              Name);
6853             InsertNewInstBefore(NewSel, SI);
6854             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6855               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6856             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6857               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6858             else {
6859               assert(0 && "Unknown instruction!!");
6860             }
6861           }
6862         }
6863   }
6864
6865   if (BinaryOperator::isNot(CondVal)) {
6866     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6867     SI.setOperand(1, FalseVal);
6868     SI.setOperand(2, TrueVal);
6869     return &SI;
6870   }
6871
6872   return 0;
6873 }
6874
6875 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6876 /// determine, return it, otherwise return 0.
6877 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6878   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6879     unsigned Align = GV->getAlignment();
6880     if (Align == 0 && TD) 
6881       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6882     return Align;
6883   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6884     unsigned Align = AI->getAlignment();
6885     if (Align == 0 && TD) {
6886       if (isa<AllocaInst>(AI))
6887         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6888       else if (isa<MallocInst>(AI)) {
6889         // Malloc returns maximally aligned memory.
6890         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6891         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6892         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6893       }
6894     }
6895     return Align;
6896   } else if (isa<BitCastInst>(V) ||
6897              (isa<ConstantExpr>(V) && 
6898               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6899     User *CI = cast<User>(V);
6900     if (isa<PointerType>(CI->getOperand(0)->getType()))
6901       return GetKnownAlignment(CI->getOperand(0), TD);
6902     return 0;
6903   } else if (isa<GetElementPtrInst>(V) ||
6904              (isa<ConstantExpr>(V) && 
6905               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6906     User *GEPI = cast<User>(V);
6907     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6908     if (BaseAlignment == 0) return 0;
6909     
6910     // If all indexes are zero, it is just the alignment of the base pointer.
6911     bool AllZeroOperands = true;
6912     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6913       if (!isa<Constant>(GEPI->getOperand(i)) ||
6914           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6915         AllZeroOperands = false;
6916         break;
6917       }
6918     if (AllZeroOperands)
6919       return BaseAlignment;
6920     
6921     // Otherwise, if the base alignment is >= the alignment we expect for the
6922     // base pointer type, then we know that the resultant pointer is aligned at
6923     // least as much as its type requires.
6924     if (!TD) return 0;
6925
6926     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6927     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6928         <= BaseAlignment) {
6929       const Type *GEPTy = GEPI->getType();
6930       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6931     }
6932     return 0;
6933   }
6934   return 0;
6935 }
6936
6937
6938 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6939 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6940 /// the heavy lifting.
6941 ///
6942 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6943   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6944   if (!II) return visitCallSite(&CI);
6945   
6946   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6947   // visitCallSite.
6948   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6949     bool Changed = false;
6950
6951     // memmove/cpy/set of zero bytes is a noop.
6952     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6953       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6954
6955       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6956         if (CI->getZExtValue() == 1) {
6957           // Replace the instruction with just byte operations.  We would
6958           // transform other cases to loads/stores, but we don't know if
6959           // alignment is sufficient.
6960         }
6961     }
6962
6963     // If we have a memmove and the source operation is a constant global,
6964     // then the source and dest pointers can't alias, so we can change this
6965     // into a call to memcpy.
6966     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6967       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6968         if (GVSrc->isConstant()) {
6969           Module *M = CI.getParent()->getParent()->getParent();
6970           const char *Name;
6971           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6972               Type::Int32Ty)
6973             Name = "llvm.memcpy.i32";
6974           else
6975             Name = "llvm.memcpy.i64";
6976           Constant *MemCpy = M->getOrInsertFunction(Name,
6977                                      CI.getCalledFunction()->getFunctionType());
6978           CI.setOperand(0, MemCpy);
6979           Changed = true;
6980         }
6981     }
6982
6983     // If we can determine a pointer alignment that is bigger than currently
6984     // set, update the alignment.
6985     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6986       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6987       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6988       unsigned Align = std::min(Alignment1, Alignment2);
6989       if (MI->getAlignment()->getZExtValue() < Align) {
6990         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6991         Changed = true;
6992       }
6993     } else if (isa<MemSetInst>(MI)) {
6994       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6995       if (MI->getAlignment()->getZExtValue() < Alignment) {
6996         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6997         Changed = true;
6998       }
6999     }
7000           
7001     if (Changed) return II;
7002   } else {
7003     switch (II->getIntrinsicID()) {
7004     default: break;
7005     case Intrinsic::ppc_altivec_lvx:
7006     case Intrinsic::ppc_altivec_lvxl:
7007     case Intrinsic::x86_sse_loadu_ps:
7008     case Intrinsic::x86_sse2_loadu_pd:
7009     case Intrinsic::x86_sse2_loadu_dq:
7010       // Turn PPC lvx     -> load if the pointer is known aligned.
7011       // Turn X86 loadups -> load if the pointer is known aligned.
7012       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7013         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7014                                       PointerType::get(II->getType()), CI);
7015         return new LoadInst(Ptr);
7016       }
7017       break;
7018     case Intrinsic::ppc_altivec_stvx:
7019     case Intrinsic::ppc_altivec_stvxl:
7020       // Turn stvx -> store if the pointer is known aligned.
7021       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7022         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7023         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7024                                       OpPtrTy, CI);
7025         return new StoreInst(II->getOperand(1), Ptr);
7026       }
7027       break;
7028     case Intrinsic::x86_sse_storeu_ps:
7029     case Intrinsic::x86_sse2_storeu_pd:
7030     case Intrinsic::x86_sse2_storeu_dq:
7031     case Intrinsic::x86_sse2_storel_dq:
7032       // Turn X86 storeu -> store if the pointer is known aligned.
7033       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7034         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7035         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7036                                       OpPtrTy, CI);
7037         return new StoreInst(II->getOperand(2), Ptr);
7038       }
7039       break;
7040       
7041     case Intrinsic::x86_sse_cvttss2si: {
7042       // These intrinsics only demands the 0th element of its input vector.  If
7043       // we can simplify the input based on that, do so now.
7044       uint64_t UndefElts;
7045       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7046                                                 UndefElts)) {
7047         II->setOperand(1, V);
7048         return II;
7049       }
7050       break;
7051     }
7052       
7053     case Intrinsic::ppc_altivec_vperm:
7054       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7055       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7056         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7057         
7058         // Check that all of the elements are integer constants or undefs.
7059         bool AllEltsOk = true;
7060         for (unsigned i = 0; i != 16; ++i) {
7061           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7062               !isa<UndefValue>(Mask->getOperand(i))) {
7063             AllEltsOk = false;
7064             break;
7065           }
7066         }
7067         
7068         if (AllEltsOk) {
7069           // Cast the input vectors to byte vectors.
7070           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7071                                         II->getOperand(1), Mask->getType(), CI);
7072           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7073                                         II->getOperand(2), Mask->getType(), CI);
7074           Value *Result = UndefValue::get(Op0->getType());
7075           
7076           // Only extract each element once.
7077           Value *ExtractedElts[32];
7078           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7079           
7080           for (unsigned i = 0; i != 16; ++i) {
7081             if (isa<UndefValue>(Mask->getOperand(i)))
7082               continue;
7083             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7084             Idx &= 31;  // Match the hardware behavior.
7085             
7086             if (ExtractedElts[Idx] == 0) {
7087               Instruction *Elt = 
7088                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7089               InsertNewInstBefore(Elt, CI);
7090               ExtractedElts[Idx] = Elt;
7091             }
7092           
7093             // Insert this value into the result vector.
7094             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7095             InsertNewInstBefore(cast<Instruction>(Result), CI);
7096           }
7097           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7098         }
7099       }
7100       break;
7101
7102     case Intrinsic::stackrestore: {
7103       // If the save is right next to the restore, remove the restore.  This can
7104       // happen when variable allocas are DCE'd.
7105       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7106         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7107           BasicBlock::iterator BI = SS;
7108           if (&*++BI == II)
7109             return EraseInstFromFunction(CI);
7110         }
7111       }
7112       
7113       // If the stack restore is in a return/unwind block and if there are no
7114       // allocas or calls between the restore and the return, nuke the restore.
7115       TerminatorInst *TI = II->getParent()->getTerminator();
7116       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7117         BasicBlock::iterator BI = II;
7118         bool CannotRemove = false;
7119         for (++BI; &*BI != TI; ++BI) {
7120           if (isa<AllocaInst>(BI) ||
7121               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7122             CannotRemove = true;
7123             break;
7124           }
7125         }
7126         if (!CannotRemove)
7127           return EraseInstFromFunction(CI);
7128       }
7129       break;
7130     }
7131     }
7132   }
7133
7134   return visitCallSite(II);
7135 }
7136
7137 // InvokeInst simplification
7138 //
7139 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7140   return visitCallSite(&II);
7141 }
7142
7143 // visitCallSite - Improvements for call and invoke instructions.
7144 //
7145 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7146   bool Changed = false;
7147
7148   // If the callee is a constexpr cast of a function, attempt to move the cast
7149   // to the arguments of the call/invoke.
7150   if (transformConstExprCastCall(CS)) return 0;
7151
7152   Value *Callee = CS.getCalledValue();
7153
7154   if (Function *CalleeF = dyn_cast<Function>(Callee))
7155     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7156       Instruction *OldCall = CS.getInstruction();
7157       // If the call and callee calling conventions don't match, this call must
7158       // be unreachable, as the call is undefined.
7159       new StoreInst(ConstantInt::getTrue(),
7160                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7161       if (!OldCall->use_empty())
7162         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7163       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7164         return EraseInstFromFunction(*OldCall);
7165       return 0;
7166     }
7167
7168   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7169     // This instruction is not reachable, just remove it.  We insert a store to
7170     // undef so that we know that this code is not reachable, despite the fact
7171     // that we can't modify the CFG here.
7172     new StoreInst(ConstantInt::getTrue(),
7173                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7174                   CS.getInstruction());
7175
7176     if (!CS.getInstruction()->use_empty())
7177       CS.getInstruction()->
7178         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7179
7180     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7181       // Don't break the CFG, insert a dummy cond branch.
7182       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7183                      ConstantInt::getTrue(), II);
7184     }
7185     return EraseInstFromFunction(*CS.getInstruction());
7186   }
7187
7188   const PointerType *PTy = cast<PointerType>(Callee->getType());
7189   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7190   if (FTy->isVarArg()) {
7191     // See if we can optimize any arguments passed through the varargs area of
7192     // the call.
7193     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7194            E = CS.arg_end(); I != E; ++I)
7195       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7196         // If this cast does not effect the value passed through the varargs
7197         // area, we can eliminate the use of the cast.
7198         Value *Op = CI->getOperand(0);
7199         if (CI->isLosslessCast()) {
7200           *I = Op;
7201           Changed = true;
7202         }
7203       }
7204   }
7205
7206   return Changed ? CS.getInstruction() : 0;
7207 }
7208
7209 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7210 // attempt to move the cast to the arguments of the call/invoke.
7211 //
7212 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7213   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7214   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7215   if (CE->getOpcode() != Instruction::BitCast || 
7216       !isa<Function>(CE->getOperand(0)))
7217     return false;
7218   Function *Callee = cast<Function>(CE->getOperand(0));
7219   Instruction *Caller = CS.getInstruction();
7220
7221   // Okay, this is a cast from a function to a different type.  Unless doing so
7222   // would cause a type conversion of one of our arguments, change this call to
7223   // be a direct call with arguments casted to the appropriate types.
7224   //
7225   const FunctionType *FT = Callee->getFunctionType();
7226   const Type *OldRetTy = Caller->getType();
7227
7228   // Check to see if we are changing the return type...
7229   if (OldRetTy != FT->getReturnType()) {
7230     if (Callee->isExternal() && !Caller->use_empty() && 
7231         OldRetTy != FT->getReturnType() &&
7232         // Conversion is ok if changing from pointer to int of same size.
7233         !(isa<PointerType>(FT->getReturnType()) &&
7234           TD->getIntPtrType() == OldRetTy))
7235       return false;   // Cannot transform this return value.
7236
7237     // If the callsite is an invoke instruction, and the return value is used by
7238     // a PHI node in a successor, we cannot change the return type of the call
7239     // because there is no place to put the cast instruction (without breaking
7240     // the critical edge).  Bail out in this case.
7241     if (!Caller->use_empty())
7242       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7243         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7244              UI != E; ++UI)
7245           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7246             if (PN->getParent() == II->getNormalDest() ||
7247                 PN->getParent() == II->getUnwindDest())
7248               return false;
7249   }
7250
7251   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7252   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7253
7254   CallSite::arg_iterator AI = CS.arg_begin();
7255   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7256     const Type *ParamTy = FT->getParamType(i);
7257     const Type *ActTy = (*AI)->getType();
7258     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7259     //Either we can cast directly, or we can upconvert the argument
7260     bool isConvertible = ActTy == ParamTy ||
7261       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7262       (ParamTy->isInteger() && ActTy->isInteger() &&
7263        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7264       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7265        && c->getSExtValue() > 0);
7266     if (Callee->isExternal() && !isConvertible) return false;
7267   }
7268
7269   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7270       Callee->isExternal())
7271     return false;   // Do not delete arguments unless we have a function body...
7272
7273   // Okay, we decided that this is a safe thing to do: go ahead and start
7274   // inserting cast instructions as necessary...
7275   std::vector<Value*> Args;
7276   Args.reserve(NumActualArgs);
7277
7278   AI = CS.arg_begin();
7279   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7280     const Type *ParamTy = FT->getParamType(i);
7281     if ((*AI)->getType() == ParamTy) {
7282       Args.push_back(*AI);
7283     } else {
7284       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7285           false, ParamTy, false);
7286       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7287       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7288     }
7289   }
7290
7291   // If the function takes more arguments than the call was taking, add them
7292   // now...
7293   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7294     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7295
7296   // If we are removing arguments to the function, emit an obnoxious warning...
7297   if (FT->getNumParams() < NumActualArgs)
7298     if (!FT->isVarArg()) {
7299       cerr << "WARNING: While resolving call to function '"
7300            << Callee->getName() << "' arguments were dropped!\n";
7301     } else {
7302       // Add all of the arguments in their promoted form to the arg list...
7303       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7304         const Type *PTy = getPromotedType((*AI)->getType());
7305         if (PTy != (*AI)->getType()) {
7306           // Must promote to pass through va_arg area!
7307           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7308                                                                 PTy, false);
7309           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7310           InsertNewInstBefore(Cast, *Caller);
7311           Args.push_back(Cast);
7312         } else {
7313           Args.push_back(*AI);
7314         }
7315       }
7316     }
7317
7318   if (FT->getReturnType() == Type::VoidTy)
7319     Caller->setName("");   // Void type should not have a name...
7320
7321   Instruction *NC;
7322   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7323     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7324                         Args, Caller->getName(), Caller);
7325     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7326   } else {
7327     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7328     if (cast<CallInst>(Caller)->isTailCall())
7329       cast<CallInst>(NC)->setTailCall();
7330    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7331   }
7332
7333   // Insert a cast of the return type as necessary...
7334   Value *NV = NC;
7335   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7336     if (NV->getType() != Type::VoidTy) {
7337       const Type *CallerTy = Caller->getType();
7338       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7339                                                             CallerTy, false);
7340       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7341
7342       // If this is an invoke instruction, we should insert it after the first
7343       // non-phi, instruction in the normal successor block.
7344       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7345         BasicBlock::iterator I = II->getNormalDest()->begin();
7346         while (isa<PHINode>(I)) ++I;
7347         InsertNewInstBefore(NC, *I);
7348       } else {
7349         // Otherwise, it's a call, just insert cast right after the call instr
7350         InsertNewInstBefore(NC, *Caller);
7351       }
7352       AddUsersToWorkList(*Caller);
7353     } else {
7354       NV = UndefValue::get(Caller->getType());
7355     }
7356   }
7357
7358   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7359     Caller->replaceAllUsesWith(NV);
7360   Caller->getParent()->getInstList().erase(Caller);
7361   removeFromWorkList(Caller);
7362   return true;
7363 }
7364
7365 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7366 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7367 /// and a single binop.
7368 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7369   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7370   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7371          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7372   unsigned Opc = FirstInst->getOpcode();
7373   Value *LHSVal = FirstInst->getOperand(0);
7374   Value *RHSVal = FirstInst->getOperand(1);
7375     
7376   const Type *LHSType = LHSVal->getType();
7377   const Type *RHSType = RHSVal->getType();
7378   
7379   // Scan to see if all operands are the same opcode, all have one use, and all
7380   // kill their operands (i.e. the operands have one use).
7381   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7382     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7383     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7384         // Verify type of the LHS matches so we don't fold cmp's of different
7385         // types or GEP's with different index types.
7386         I->getOperand(0)->getType() != LHSType ||
7387         I->getOperand(1)->getType() != RHSType)
7388       return 0;
7389
7390     // If they are CmpInst instructions, check their predicates
7391     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7392       if (cast<CmpInst>(I)->getPredicate() !=
7393           cast<CmpInst>(FirstInst)->getPredicate())
7394         return 0;
7395     
7396     // Keep track of which operand needs a phi node.
7397     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7398     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7399   }
7400   
7401   // Otherwise, this is safe to transform, determine if it is profitable.
7402
7403   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7404   // Indexes are often folded into load/store instructions, so we don't want to
7405   // hide them behind a phi.
7406   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7407     return 0;
7408   
7409   Value *InLHS = FirstInst->getOperand(0);
7410   Value *InRHS = FirstInst->getOperand(1);
7411   PHINode *NewLHS = 0, *NewRHS = 0;
7412   if (LHSVal == 0) {
7413     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7414     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7415     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7416     InsertNewInstBefore(NewLHS, PN);
7417     LHSVal = NewLHS;
7418   }
7419   
7420   if (RHSVal == 0) {
7421     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7422     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7423     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7424     InsertNewInstBefore(NewRHS, PN);
7425     RHSVal = NewRHS;
7426   }
7427   
7428   // Add all operands to the new PHIs.
7429   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7430     if (NewLHS) {
7431       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7432       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7433     }
7434     if (NewRHS) {
7435       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7436       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7437     }
7438   }
7439     
7440   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7441     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7442   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7443     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7444                            RHSVal);
7445   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7446     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7447   else {
7448     assert(isa<GetElementPtrInst>(FirstInst));
7449     return new GetElementPtrInst(LHSVal, RHSVal);
7450   }
7451 }
7452
7453 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7454 /// of the block that defines it.  This means that it must be obvious the value
7455 /// of the load is not changed from the point of the load to the end of the
7456 /// block it is in.
7457 static bool isSafeToSinkLoad(LoadInst *L) {
7458   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7459   
7460   for (++BBI; BBI != E; ++BBI)
7461     if (BBI->mayWriteToMemory())
7462       return false;
7463   return true;
7464 }
7465
7466
7467 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7468 // operator and they all are only used by the PHI, PHI together their
7469 // inputs, and do the operation once, to the result of the PHI.
7470 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7471   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7472
7473   // Scan the instruction, looking for input operations that can be folded away.
7474   // If all input operands to the phi are the same instruction (e.g. a cast from
7475   // the same type or "+42") we can pull the operation through the PHI, reducing
7476   // code size and simplifying code.
7477   Constant *ConstantOp = 0;
7478   const Type *CastSrcTy = 0;
7479   bool isVolatile = false;
7480   if (isa<CastInst>(FirstInst)) {
7481     CastSrcTy = FirstInst->getOperand(0)->getType();
7482   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7483              isa<CmpInst>(FirstInst)) {
7484     // Can fold binop, compare or shift here if the RHS is a constant, 
7485     // otherwise call FoldPHIArgBinOpIntoPHI.
7486     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7487     if (ConstantOp == 0)
7488       return FoldPHIArgBinOpIntoPHI(PN);
7489   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7490     isVolatile = LI->isVolatile();
7491     // We can't sink the load if the loaded value could be modified between the
7492     // load and the PHI.
7493     if (LI->getParent() != PN.getIncomingBlock(0) ||
7494         !isSafeToSinkLoad(LI))
7495       return 0;
7496   } else if (isa<GetElementPtrInst>(FirstInst)) {
7497     if (FirstInst->getNumOperands() == 2)
7498       return FoldPHIArgBinOpIntoPHI(PN);
7499     // Can't handle general GEPs yet.
7500     return 0;
7501   } else {
7502     return 0;  // Cannot fold this operation.
7503   }
7504
7505   // Check to see if all arguments are the same operation.
7506   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7507     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7508     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7509     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7510       return 0;
7511     if (CastSrcTy) {
7512       if (I->getOperand(0)->getType() != CastSrcTy)
7513         return 0;  // Cast operation must match.
7514     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7515       // We can't sink the load if the loaded value could be modified between 
7516       // the load and the PHI.
7517       if (LI->isVolatile() != isVolatile ||
7518           LI->getParent() != PN.getIncomingBlock(i) ||
7519           !isSafeToSinkLoad(LI))
7520         return 0;
7521     } else if (I->getOperand(1) != ConstantOp) {
7522       return 0;
7523     }
7524   }
7525
7526   // Okay, they are all the same operation.  Create a new PHI node of the
7527   // correct type, and PHI together all of the LHS's of the instructions.
7528   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7529                                PN.getName()+".in");
7530   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7531
7532   Value *InVal = FirstInst->getOperand(0);
7533   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7534
7535   // Add all operands to the new PHI.
7536   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7537     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7538     if (NewInVal != InVal)
7539       InVal = 0;
7540     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7541   }
7542
7543   Value *PhiVal;
7544   if (InVal) {
7545     // The new PHI unions all of the same values together.  This is really
7546     // common, so we handle it intelligently here for compile-time speed.
7547     PhiVal = InVal;
7548     delete NewPN;
7549   } else {
7550     InsertNewInstBefore(NewPN, PN);
7551     PhiVal = NewPN;
7552   }
7553
7554   // Insert and return the new operation.
7555   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7556     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7557   else if (isa<LoadInst>(FirstInst))
7558     return new LoadInst(PhiVal, "", isVolatile);
7559   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7560     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7561   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7562     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7563                            PhiVal, ConstantOp);
7564   else
7565     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7566                          PhiVal, ConstantOp);
7567 }
7568
7569 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7570 /// that is dead.
7571 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7572   if (PN->use_empty()) return true;
7573   if (!PN->hasOneUse()) return false;
7574
7575   // Remember this node, and if we find the cycle, return.
7576   if (!PotentiallyDeadPHIs.insert(PN).second)
7577     return true;
7578
7579   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7580     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7581
7582   return false;
7583 }
7584
7585 // PHINode simplification
7586 //
7587 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7588   // If LCSSA is around, don't mess with Phi nodes
7589   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7590   
7591   if (Value *V = PN.hasConstantValue())
7592     return ReplaceInstUsesWith(PN, V);
7593
7594   // If all PHI operands are the same operation, pull them through the PHI,
7595   // reducing code size.
7596   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7597       PN.getIncomingValue(0)->hasOneUse())
7598     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7599       return Result;
7600
7601   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7602   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7603   // PHI)... break the cycle.
7604   if (PN.hasOneUse()) {
7605     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7606     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7607       std::set<PHINode*> PotentiallyDeadPHIs;
7608       PotentiallyDeadPHIs.insert(&PN);
7609       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7610         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7611     }
7612    
7613     // If this phi has a single use, and if that use just computes a value for
7614     // the next iteration of a loop, delete the phi.  This occurs with unused
7615     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7616     // common case here is good because the only other things that catch this
7617     // are induction variable analysis (sometimes) and ADCE, which is only run
7618     // late.
7619     if (PHIUser->hasOneUse() &&
7620         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7621         PHIUser->use_back() == &PN) {
7622       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7623     }
7624   }
7625
7626   return 0;
7627 }
7628
7629 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7630                                    Instruction *InsertPoint,
7631                                    InstCombiner *IC) {
7632   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7633   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7634   // We must cast correctly to the pointer type. Ensure that we
7635   // sign extend the integer value if it is smaller as this is
7636   // used for address computation.
7637   Instruction::CastOps opcode = 
7638      (VTySize < PtrSize ? Instruction::SExt :
7639       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7640   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7641 }
7642
7643
7644 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7645   Value *PtrOp = GEP.getOperand(0);
7646   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7647   // If so, eliminate the noop.
7648   if (GEP.getNumOperands() == 1)
7649     return ReplaceInstUsesWith(GEP, PtrOp);
7650
7651   if (isa<UndefValue>(GEP.getOperand(0)))
7652     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7653
7654   bool HasZeroPointerIndex = false;
7655   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7656     HasZeroPointerIndex = C->isNullValue();
7657
7658   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7659     return ReplaceInstUsesWith(GEP, PtrOp);
7660
7661   // Eliminate unneeded casts for indices.
7662   bool MadeChange = false;
7663   gep_type_iterator GTI = gep_type_begin(GEP);
7664   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7665     if (isa<SequentialType>(*GTI)) {
7666       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7667         if (CI->getOpcode() == Instruction::ZExt ||
7668             CI->getOpcode() == Instruction::SExt) {
7669           const Type *SrcTy = CI->getOperand(0)->getType();
7670           // We can eliminate a cast from i32 to i64 iff the target 
7671           // is a 32-bit pointer target.
7672           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7673             MadeChange = true;
7674             GEP.setOperand(i, CI->getOperand(0));
7675           }
7676         }
7677       }
7678       // If we are using a wider index than needed for this platform, shrink it
7679       // to what we need.  If the incoming value needs a cast instruction,
7680       // insert it.  This explicit cast can make subsequent optimizations more
7681       // obvious.
7682       Value *Op = GEP.getOperand(i);
7683       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7684         if (Constant *C = dyn_cast<Constant>(Op)) {
7685           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7686           MadeChange = true;
7687         } else {
7688           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7689                                 GEP);
7690           GEP.setOperand(i, Op);
7691           MadeChange = true;
7692         }
7693     }
7694   if (MadeChange) return &GEP;
7695
7696   // Combine Indices - If the source pointer to this getelementptr instruction
7697   // is a getelementptr instruction, combine the indices of the two
7698   // getelementptr instructions into a single instruction.
7699   //
7700   std::vector<Value*> SrcGEPOperands;
7701   if (User *Src = dyn_castGetElementPtr(PtrOp))
7702     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7703
7704   if (!SrcGEPOperands.empty()) {
7705     // Note that if our source is a gep chain itself that we wait for that
7706     // chain to be resolved before we perform this transformation.  This
7707     // avoids us creating a TON of code in some cases.
7708     //
7709     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7710         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7711       return 0;   // Wait until our source is folded to completion.
7712
7713     std::vector<Value *> Indices;
7714
7715     // Find out whether the last index in the source GEP is a sequential idx.
7716     bool EndsWithSequential = false;
7717     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7718            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7719       EndsWithSequential = !isa<StructType>(*I);
7720
7721     // Can we combine the two pointer arithmetics offsets?
7722     if (EndsWithSequential) {
7723       // Replace: gep (gep %P, long B), long A, ...
7724       // With:    T = long A+B; gep %P, T, ...
7725       //
7726       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7727       if (SO1 == Constant::getNullValue(SO1->getType())) {
7728         Sum = GO1;
7729       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7730         Sum = SO1;
7731       } else {
7732         // If they aren't the same type, convert both to an integer of the
7733         // target's pointer size.
7734         if (SO1->getType() != GO1->getType()) {
7735           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7736             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7737           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7738             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7739           } else {
7740             unsigned PS = TD->getPointerSize();
7741             if (TD->getTypeSize(SO1->getType()) == PS) {
7742               // Convert GO1 to SO1's type.
7743               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7744
7745             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7746               // Convert SO1 to GO1's type.
7747               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7748             } else {
7749               const Type *PT = TD->getIntPtrType();
7750               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7751               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7752             }
7753           }
7754         }
7755         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7756           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7757         else {
7758           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7759           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7760         }
7761       }
7762
7763       // Recycle the GEP we already have if possible.
7764       if (SrcGEPOperands.size() == 2) {
7765         GEP.setOperand(0, SrcGEPOperands[0]);
7766         GEP.setOperand(1, Sum);
7767         return &GEP;
7768       } else {
7769         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7770                        SrcGEPOperands.end()-1);
7771         Indices.push_back(Sum);
7772         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7773       }
7774     } else if (isa<Constant>(*GEP.idx_begin()) &&
7775                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7776                SrcGEPOperands.size() != 1) {
7777       // Otherwise we can do the fold if the first index of the GEP is a zero
7778       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7779                      SrcGEPOperands.end());
7780       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7781     }
7782
7783     if (!Indices.empty())
7784       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7785
7786   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7787     // GEP of global variable.  If all of the indices for this GEP are
7788     // constants, we can promote this to a constexpr instead of an instruction.
7789
7790     // Scan for nonconstants...
7791     std::vector<Constant*> Indices;
7792     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7793     for (; I != E && isa<Constant>(*I); ++I)
7794       Indices.push_back(cast<Constant>(*I));
7795
7796     if (I == E) {  // If they are all constants...
7797       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7798
7799       // Replace all uses of the GEP with the new constexpr...
7800       return ReplaceInstUsesWith(GEP, CE);
7801     }
7802   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7803     if (!isa<PointerType>(X->getType())) {
7804       // Not interesting.  Source pointer must be a cast from pointer.
7805     } else if (HasZeroPointerIndex) {
7806       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7807       // into     : GEP [10 x ubyte]* X, long 0, ...
7808       //
7809       // This occurs when the program declares an array extern like "int X[];"
7810       //
7811       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7812       const PointerType *XTy = cast<PointerType>(X->getType());
7813       if (const ArrayType *XATy =
7814           dyn_cast<ArrayType>(XTy->getElementType()))
7815         if (const ArrayType *CATy =
7816             dyn_cast<ArrayType>(CPTy->getElementType()))
7817           if (CATy->getElementType() == XATy->getElementType()) {
7818             // At this point, we know that the cast source type is a pointer
7819             // to an array of the same type as the destination pointer
7820             // array.  Because the array type is never stepped over (there
7821             // is a leading zero) we can fold the cast into this GEP.
7822             GEP.setOperand(0, X);
7823             return &GEP;
7824           }
7825     } else if (GEP.getNumOperands() == 2) {
7826       // Transform things like:
7827       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7828       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7829       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7830       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7831       if (isa<ArrayType>(SrcElTy) &&
7832           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7833           TD->getTypeSize(ResElTy)) {
7834         Value *V = InsertNewInstBefore(
7835                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7836                                      GEP.getOperand(1), GEP.getName()), GEP);
7837         // V and GEP are both pointer types --> BitCast
7838         return new BitCastInst(V, GEP.getType());
7839       }
7840       
7841       // Transform things like:
7842       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7843       //   (where tmp = 8*tmp2) into:
7844       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7845       
7846       if (isa<ArrayType>(SrcElTy) &&
7847           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7848         uint64_t ArrayEltSize =
7849             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7850         
7851         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7852         // allow either a mul, shift, or constant here.
7853         Value *NewIdx = 0;
7854         ConstantInt *Scale = 0;
7855         if (ArrayEltSize == 1) {
7856           NewIdx = GEP.getOperand(1);
7857           Scale = ConstantInt::get(NewIdx->getType(), 1);
7858         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7859           NewIdx = ConstantInt::get(CI->getType(), 1);
7860           Scale = CI;
7861         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7862           if (Inst->getOpcode() == Instruction::Shl &&
7863               isa<ConstantInt>(Inst->getOperand(1))) {
7864             unsigned ShAmt =
7865               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7866             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7867             NewIdx = Inst->getOperand(0);
7868           } else if (Inst->getOpcode() == Instruction::Mul &&
7869                      isa<ConstantInt>(Inst->getOperand(1))) {
7870             Scale = cast<ConstantInt>(Inst->getOperand(1));
7871             NewIdx = Inst->getOperand(0);
7872           }
7873         }
7874
7875         // If the index will be to exactly the right offset with the scale taken
7876         // out, perform the transformation.
7877         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7878           if (isa<ConstantInt>(Scale))
7879             Scale = ConstantInt::get(Scale->getType(),
7880                                       Scale->getZExtValue() / ArrayEltSize);
7881           if (Scale->getZExtValue() != 1) {
7882             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7883                                                        true /*SExt*/);
7884             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7885             NewIdx = InsertNewInstBefore(Sc, GEP);
7886           }
7887
7888           // Insert the new GEP instruction.
7889           Instruction *NewGEP =
7890             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7891                                   NewIdx, GEP.getName());
7892           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7893           // The NewGEP must be pointer typed, so must the old one -> BitCast
7894           return new BitCastInst(NewGEP, GEP.getType());
7895         }
7896       }
7897     }
7898   }
7899
7900   return 0;
7901 }
7902
7903 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7904   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7905   if (AI.isArrayAllocation())    // Check C != 1
7906     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7907       const Type *NewTy = 
7908         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7909       AllocationInst *New = 0;
7910
7911       // Create and insert the replacement instruction...
7912       if (isa<MallocInst>(AI))
7913         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7914       else {
7915         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7916         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7917       }
7918
7919       InsertNewInstBefore(New, AI);
7920
7921       // Scan to the end of the allocation instructions, to skip over a block of
7922       // allocas if possible...
7923       //
7924       BasicBlock::iterator It = New;
7925       while (isa<AllocationInst>(*It)) ++It;
7926
7927       // Now that I is pointing to the first non-allocation-inst in the block,
7928       // insert our getelementptr instruction...
7929       //
7930       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7931       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7932                                        New->getName()+".sub", It);
7933
7934       // Now make everything use the getelementptr instead of the original
7935       // allocation.
7936       return ReplaceInstUsesWith(AI, V);
7937     } else if (isa<UndefValue>(AI.getArraySize())) {
7938       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7939     }
7940
7941   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7942   // Note that we only do this for alloca's, because malloc should allocate and
7943   // return a unique pointer, even for a zero byte allocation.
7944   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7945       TD->getTypeSize(AI.getAllocatedType()) == 0)
7946     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7947
7948   return 0;
7949 }
7950
7951 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7952   Value *Op = FI.getOperand(0);
7953
7954   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7955   if (CastInst *CI = dyn_cast<CastInst>(Op))
7956     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7957       FI.setOperand(0, CI->getOperand(0));
7958       return &FI;
7959     }
7960
7961   // free undef -> unreachable.
7962   if (isa<UndefValue>(Op)) {
7963     // Insert a new store to null because we cannot modify the CFG here.
7964     new StoreInst(ConstantInt::getTrue(),
7965                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7966     return EraseInstFromFunction(FI);
7967   }
7968
7969   // If we have 'free null' delete the instruction.  This can happen in stl code
7970   // when lots of inlining happens.
7971   if (isa<ConstantPointerNull>(Op))
7972     return EraseInstFromFunction(FI);
7973
7974   return 0;
7975 }
7976
7977
7978 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7979 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7980   User *CI = cast<User>(LI.getOperand(0));
7981   Value *CastOp = CI->getOperand(0);
7982
7983   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7984   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7985     const Type *SrcPTy = SrcTy->getElementType();
7986
7987     if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
7988         isa<PointerType>(DestPTy) || isa<PackedType>(DestPTy)) {
7989       // If the source is an array, the code below will not succeed.  Check to
7990       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7991       // constants.
7992       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7993         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7994           if (ASrcTy->getNumElements() != 0) {
7995             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7996             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7997             SrcTy = cast<PointerType>(CastOp->getType());
7998             SrcPTy = SrcTy->getElementType();
7999           }
8000
8001       if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8002            isa<PointerType>(SrcPTy) || isa<PackedType>(SrcPTy)) &&
8003           // Do not allow turning this into a load of an integer, which is then
8004           // casted to a pointer, this pessimizes pointer analysis a lot.
8005           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8006           IC.getTargetData().getTypeSize(SrcPTy) ==
8007                IC.getTargetData().getTypeSize(DestPTy)) {
8008
8009         // Okay, we are casting from one integer or pointer type to another of
8010         // the same size.  Instead of casting the pointer before the load, cast
8011         // the result of the loaded value.
8012         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8013                                                              CI->getName(),
8014                                                          LI.isVolatile()),LI);
8015         // Now cast the result of the load.
8016         return new BitCastInst(NewLoad, LI.getType());
8017       }
8018     }
8019   }
8020   return 0;
8021 }
8022
8023 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8024 /// from this value cannot trap.  If it is not obviously safe to load from the
8025 /// specified pointer, we do a quick local scan of the basic block containing
8026 /// ScanFrom, to determine if the address is already accessed.
8027 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8028   // If it is an alloca or global variable, it is always safe to load from.
8029   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8030
8031   // Otherwise, be a little bit agressive by scanning the local block where we
8032   // want to check to see if the pointer is already being loaded or stored
8033   // from/to.  If so, the previous load or store would have already trapped,
8034   // so there is no harm doing an extra load (also, CSE will later eliminate
8035   // the load entirely).
8036   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8037
8038   while (BBI != E) {
8039     --BBI;
8040
8041     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8042       if (LI->getOperand(0) == V) return true;
8043     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8044       if (SI->getOperand(1) == V) return true;
8045
8046   }
8047   return false;
8048 }
8049
8050 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8051   Value *Op = LI.getOperand(0);
8052
8053   // load (cast X) --> cast (load X) iff safe
8054   if (isa<CastInst>(Op))
8055     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8056       return Res;
8057
8058   // None of the following transforms are legal for volatile loads.
8059   if (LI.isVolatile()) return 0;
8060   
8061   if (&LI.getParent()->front() != &LI) {
8062     BasicBlock::iterator BBI = &LI; --BBI;
8063     // If the instruction immediately before this is a store to the same
8064     // address, do a simple form of store->load forwarding.
8065     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8066       if (SI->getOperand(1) == LI.getOperand(0))
8067         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8068     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8069       if (LIB->getOperand(0) == LI.getOperand(0))
8070         return ReplaceInstUsesWith(LI, LIB);
8071   }
8072
8073   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8074     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8075         isa<UndefValue>(GEPI->getOperand(0))) {
8076       // Insert a new store to null instruction before the load to indicate
8077       // that this code is not reachable.  We do this instead of inserting
8078       // an unreachable instruction directly because we cannot modify the
8079       // CFG.
8080       new StoreInst(UndefValue::get(LI.getType()),
8081                     Constant::getNullValue(Op->getType()), &LI);
8082       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8083     }
8084
8085   if (Constant *C = dyn_cast<Constant>(Op)) {
8086     // load null/undef -> undef
8087     if ((C->isNullValue() || isa<UndefValue>(C))) {
8088       // Insert a new store to null instruction before the load to indicate that
8089       // this code is not reachable.  We do this instead of inserting an
8090       // unreachable instruction directly because we cannot modify the CFG.
8091       new StoreInst(UndefValue::get(LI.getType()),
8092                     Constant::getNullValue(Op->getType()), &LI);
8093       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8094     }
8095
8096     // Instcombine load (constant global) into the value loaded.
8097     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8098       if (GV->isConstant() && !GV->isExternal())
8099         return ReplaceInstUsesWith(LI, GV->getInitializer());
8100
8101     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8102     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8103       if (CE->getOpcode() == Instruction::GetElementPtr) {
8104         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8105           if (GV->isConstant() && !GV->isExternal())
8106             if (Constant *V = 
8107                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8108               return ReplaceInstUsesWith(LI, V);
8109         if (CE->getOperand(0)->isNullValue()) {
8110           // Insert a new store to null instruction before the load to indicate
8111           // that this code is not reachable.  We do this instead of inserting
8112           // an unreachable instruction directly because we cannot modify the
8113           // CFG.
8114           new StoreInst(UndefValue::get(LI.getType()),
8115                         Constant::getNullValue(Op->getType()), &LI);
8116           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8117         }
8118
8119       } else if (CE->isCast()) {
8120         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8121           return Res;
8122       }
8123   }
8124
8125   if (Op->hasOneUse()) {
8126     // Change select and PHI nodes to select values instead of addresses: this
8127     // helps alias analysis out a lot, allows many others simplifications, and
8128     // exposes redundancy in the code.
8129     //
8130     // Note that we cannot do the transformation unless we know that the
8131     // introduced loads cannot trap!  Something like this is valid as long as
8132     // the condition is always false: load (select bool %C, int* null, int* %G),
8133     // but it would not be valid if we transformed it to load from null
8134     // unconditionally.
8135     //
8136     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8137       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8138       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8139           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8140         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8141                                      SI->getOperand(1)->getName()+".val"), LI);
8142         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8143                                      SI->getOperand(2)->getName()+".val"), LI);
8144         return new SelectInst(SI->getCondition(), V1, V2);
8145       }
8146
8147       // load (select (cond, null, P)) -> load P
8148       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8149         if (C->isNullValue()) {
8150           LI.setOperand(0, SI->getOperand(2));
8151           return &LI;
8152         }
8153
8154       // load (select (cond, P, null)) -> load P
8155       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8156         if (C->isNullValue()) {
8157           LI.setOperand(0, SI->getOperand(1));
8158           return &LI;
8159         }
8160     }
8161   }
8162   return 0;
8163 }
8164
8165 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8166 /// when possible.
8167 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8168   User *CI = cast<User>(SI.getOperand(1));
8169   Value *CastOp = CI->getOperand(0);
8170
8171   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8172   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8173     const Type *SrcPTy = SrcTy->getElementType();
8174
8175     if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
8176         isa<PointerType>(DestPTy)) {
8177       // If the source is an array, the code below will not succeed.  Check to
8178       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8179       // constants.
8180       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8181         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8182           if (ASrcTy->getNumElements() != 0) {
8183             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8184             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8185             SrcTy = cast<PointerType>(CastOp->getType());
8186             SrcPTy = SrcTy->getElementType();
8187           }
8188
8189       if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8190            isa<PointerType>(SrcPTy)) &&
8191           IC.getTargetData().getTypeSize(SrcPTy) ==
8192                IC.getTargetData().getTypeSize(DestPTy)) {
8193
8194         // Okay, we are casting from one integer or pointer type to another of
8195         // the same size.  Instead of casting the pointer before 
8196         // the store, cast the value to be stored.
8197         Value *NewCast;
8198         Value *SIOp0 = SI.getOperand(0);
8199         Instruction::CastOps opcode = Instruction::BitCast;
8200         const Type* CastSrcTy = SIOp0->getType();
8201         const Type* CastDstTy = SrcPTy;
8202         if (isa<PointerType>(CastDstTy)) {
8203           if (CastSrcTy->isInteger())
8204             opcode = Instruction::IntToPtr;
8205         } else if (const IntegerType* DITy = dyn_cast<IntegerType>(CastDstTy)) {
8206           if (isa<PointerType>(SIOp0->getType()))
8207             opcode = Instruction::PtrToInt;
8208           else if (const IntegerType* SITy = dyn_cast<IntegerType>(CastSrcTy))
8209             assert(DITy->getBitWidth() == SITy->getBitWidth() &&
8210                    "Illegal store instruction");
8211         }
8212         if (Constant *C = dyn_cast<Constant>(SIOp0))
8213           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8214         else
8215           NewCast = IC.InsertNewInstBefore(
8216             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8217             SI);
8218         return new StoreInst(NewCast, CastOp);
8219       }
8220     }
8221   }
8222   return 0;
8223 }
8224
8225 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8226   Value *Val = SI.getOperand(0);
8227   Value *Ptr = SI.getOperand(1);
8228
8229   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8230     EraseInstFromFunction(SI);
8231     ++NumCombined;
8232     return 0;
8233   }
8234   
8235   // If the RHS is an alloca with a single use, zapify the store, making the
8236   // alloca dead.
8237   if (Ptr->hasOneUse()) {
8238     if (isa<AllocaInst>(Ptr)) {
8239       EraseInstFromFunction(SI);
8240       ++NumCombined;
8241       return 0;
8242     }
8243     
8244     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8245       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8246           GEP->getOperand(0)->hasOneUse()) {
8247         EraseInstFromFunction(SI);
8248         ++NumCombined;
8249         return 0;
8250       }
8251   }
8252
8253   // Do really simple DSE, to catch cases where there are several consequtive
8254   // stores to the same location, separated by a few arithmetic operations. This
8255   // situation often occurs with bitfield accesses.
8256   BasicBlock::iterator BBI = &SI;
8257   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8258        --ScanInsts) {
8259     --BBI;
8260     
8261     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8262       // Prev store isn't volatile, and stores to the same location?
8263       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8264         ++NumDeadStore;
8265         ++BBI;
8266         EraseInstFromFunction(*PrevSI);
8267         continue;
8268       }
8269       break;
8270     }
8271     
8272     // If this is a load, we have to stop.  However, if the loaded value is from
8273     // the pointer we're loading and is producing the pointer we're storing,
8274     // then *this* store is dead (X = load P; store X -> P).
8275     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8276       if (LI == Val && LI->getOperand(0) == Ptr) {
8277         EraseInstFromFunction(SI);
8278         ++NumCombined;
8279         return 0;
8280       }
8281       // Otherwise, this is a load from some other location.  Stores before it
8282       // may not be dead.
8283       break;
8284     }
8285     
8286     // Don't skip over loads or things that can modify memory.
8287     if (BBI->mayWriteToMemory())
8288       break;
8289   }
8290   
8291   
8292   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8293
8294   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8295   if (isa<ConstantPointerNull>(Ptr)) {
8296     if (!isa<UndefValue>(Val)) {
8297       SI.setOperand(0, UndefValue::get(Val->getType()));
8298       if (Instruction *U = dyn_cast<Instruction>(Val))
8299         WorkList.push_back(U);  // Dropped a use.
8300       ++NumCombined;
8301     }
8302     return 0;  // Do not modify these!
8303   }
8304
8305   // store undef, Ptr -> noop
8306   if (isa<UndefValue>(Val)) {
8307     EraseInstFromFunction(SI);
8308     ++NumCombined;
8309     return 0;
8310   }
8311
8312   // If the pointer destination is a cast, see if we can fold the cast into the
8313   // source instead.
8314   if (isa<CastInst>(Ptr))
8315     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8316       return Res;
8317   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8318     if (CE->isCast())
8319       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8320         return Res;
8321
8322   
8323   // If this store is the last instruction in the basic block, and if the block
8324   // ends with an unconditional branch, try to move it to the successor block.
8325   BBI = &SI; ++BBI;
8326   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8327     if (BI->isUnconditional()) {
8328       // Check to see if the successor block has exactly two incoming edges.  If
8329       // so, see if the other predecessor contains a store to the same location.
8330       // if so, insert a PHI node (if needed) and move the stores down.
8331       BasicBlock *Dest = BI->getSuccessor(0);
8332
8333       pred_iterator PI = pred_begin(Dest);
8334       BasicBlock *Other = 0;
8335       if (*PI != BI->getParent())
8336         Other = *PI;
8337       ++PI;
8338       if (PI != pred_end(Dest)) {
8339         if (*PI != BI->getParent())
8340           if (Other)
8341             Other = 0;
8342           else
8343             Other = *PI;
8344         if (++PI != pred_end(Dest))
8345           Other = 0;
8346       }
8347       if (Other) {  // If only one other pred...
8348         BBI = Other->getTerminator();
8349         // Make sure this other block ends in an unconditional branch and that
8350         // there is an instruction before the branch.
8351         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8352             BBI != Other->begin()) {
8353           --BBI;
8354           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8355           
8356           // If this instruction is a store to the same location.
8357           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8358             // Okay, we know we can perform this transformation.  Insert a PHI
8359             // node now if we need it.
8360             Value *MergedVal = OtherStore->getOperand(0);
8361             if (MergedVal != SI.getOperand(0)) {
8362               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8363               PN->reserveOperandSpace(2);
8364               PN->addIncoming(SI.getOperand(0), SI.getParent());
8365               PN->addIncoming(OtherStore->getOperand(0), Other);
8366               MergedVal = InsertNewInstBefore(PN, Dest->front());
8367             }
8368             
8369             // Advance to a place where it is safe to insert the new store and
8370             // insert it.
8371             BBI = Dest->begin();
8372             while (isa<PHINode>(BBI)) ++BBI;
8373             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8374                                               OtherStore->isVolatile()), *BBI);
8375
8376             // Nuke the old stores.
8377             EraseInstFromFunction(SI);
8378             EraseInstFromFunction(*OtherStore);
8379             ++NumCombined;
8380             return 0;
8381           }
8382         }
8383       }
8384     }
8385   
8386   return 0;
8387 }
8388
8389
8390 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8391   // Change br (not X), label True, label False to: br X, label False, True
8392   Value *X = 0;
8393   BasicBlock *TrueDest;
8394   BasicBlock *FalseDest;
8395   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8396       !isa<Constant>(X)) {
8397     // Swap Destinations and condition...
8398     BI.setCondition(X);
8399     BI.setSuccessor(0, FalseDest);
8400     BI.setSuccessor(1, TrueDest);
8401     return &BI;
8402   }
8403
8404   // Cannonicalize fcmp_one -> fcmp_oeq
8405   FCmpInst::Predicate FPred; Value *Y;
8406   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8407                              TrueDest, FalseDest)))
8408     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8409          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8410       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8411       std::string Name = I->getName(); I->setName("");
8412       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8413       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8414       // Swap Destinations and condition...
8415       BI.setCondition(NewSCC);
8416       BI.setSuccessor(0, FalseDest);
8417       BI.setSuccessor(1, TrueDest);
8418       removeFromWorkList(I);
8419       I->getParent()->getInstList().erase(I);
8420       WorkList.push_back(cast<Instruction>(NewSCC));
8421       return &BI;
8422     }
8423
8424   // Cannonicalize icmp_ne -> icmp_eq
8425   ICmpInst::Predicate IPred;
8426   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8427                       TrueDest, FalseDest)))
8428     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8429          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8430          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8431       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8432       std::string Name = I->getName(); I->setName("");
8433       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8434       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8435       // Swap Destinations and condition...
8436       BI.setCondition(NewSCC);
8437       BI.setSuccessor(0, FalseDest);
8438       BI.setSuccessor(1, TrueDest);
8439       removeFromWorkList(I);
8440       I->getParent()->getInstList().erase(I);
8441       WorkList.push_back(cast<Instruction>(NewSCC));
8442       return &BI;
8443     }
8444
8445   return 0;
8446 }
8447
8448 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8449   Value *Cond = SI.getCondition();
8450   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8451     if (I->getOpcode() == Instruction::Add)
8452       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8453         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8454         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8455           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8456                                                 AddRHS));
8457         SI.setOperand(0, I->getOperand(0));
8458         WorkList.push_back(I);
8459         return &SI;
8460       }
8461   }
8462   return 0;
8463 }
8464
8465 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8466 /// is to leave as a vector operation.
8467 static bool CheapToScalarize(Value *V, bool isConstant) {
8468   if (isa<ConstantAggregateZero>(V)) 
8469     return true;
8470   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8471     if (isConstant) return true;
8472     // If all elts are the same, we can extract.
8473     Constant *Op0 = C->getOperand(0);
8474     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8475       if (C->getOperand(i) != Op0)
8476         return false;
8477     return true;
8478   }
8479   Instruction *I = dyn_cast<Instruction>(V);
8480   if (!I) return false;
8481   
8482   // Insert element gets simplified to the inserted element or is deleted if
8483   // this is constant idx extract element and its a constant idx insertelt.
8484   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8485       isa<ConstantInt>(I->getOperand(2)))
8486     return true;
8487   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8488     return true;
8489   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8490     if (BO->hasOneUse() &&
8491         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8492          CheapToScalarize(BO->getOperand(1), isConstant)))
8493       return true;
8494   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8495     if (CI->hasOneUse() &&
8496         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8497          CheapToScalarize(CI->getOperand(1), isConstant)))
8498       return true;
8499   
8500   return false;
8501 }
8502
8503 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8504 /// elements into values that are larger than the #elts in the input.
8505 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8506   unsigned NElts = SVI->getType()->getNumElements();
8507   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8508     return std::vector<unsigned>(NElts, 0);
8509   if (isa<UndefValue>(SVI->getOperand(2)))
8510     return std::vector<unsigned>(NElts, 2*NElts);
8511
8512   std::vector<unsigned> Result;
8513   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8514   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8515     if (isa<UndefValue>(CP->getOperand(i)))
8516       Result.push_back(NElts*2);  // undef -> 8
8517     else
8518       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8519   return Result;
8520 }
8521
8522 /// FindScalarElement - Given a vector and an element number, see if the scalar
8523 /// value is already around as a register, for example if it were inserted then
8524 /// extracted from the vector.
8525 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8526   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8527   const PackedType *PTy = cast<PackedType>(V->getType());
8528   unsigned Width = PTy->getNumElements();
8529   if (EltNo >= Width)  // Out of range access.
8530     return UndefValue::get(PTy->getElementType());
8531   
8532   if (isa<UndefValue>(V))
8533     return UndefValue::get(PTy->getElementType());
8534   else if (isa<ConstantAggregateZero>(V))
8535     return Constant::getNullValue(PTy->getElementType());
8536   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8537     return CP->getOperand(EltNo);
8538   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8539     // If this is an insert to a variable element, we don't know what it is.
8540     if (!isa<ConstantInt>(III->getOperand(2))) 
8541       return 0;
8542     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8543     
8544     // If this is an insert to the element we are looking for, return the
8545     // inserted value.
8546     if (EltNo == IIElt) 
8547       return III->getOperand(1);
8548     
8549     // Otherwise, the insertelement doesn't modify the value, recurse on its
8550     // vector input.
8551     return FindScalarElement(III->getOperand(0), EltNo);
8552   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8553     unsigned InEl = getShuffleMask(SVI)[EltNo];
8554     if (InEl < Width)
8555       return FindScalarElement(SVI->getOperand(0), InEl);
8556     else if (InEl < Width*2)
8557       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8558     else
8559       return UndefValue::get(PTy->getElementType());
8560   }
8561   
8562   // Otherwise, we don't know.
8563   return 0;
8564 }
8565
8566 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8567
8568   // If packed val is undef, replace extract with scalar undef.
8569   if (isa<UndefValue>(EI.getOperand(0)))
8570     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8571
8572   // If packed val is constant 0, replace extract with scalar 0.
8573   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8574     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8575   
8576   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8577     // If packed val is constant with uniform operands, replace EI
8578     // with that operand
8579     Constant *op0 = C->getOperand(0);
8580     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8581       if (C->getOperand(i) != op0) {
8582         op0 = 0; 
8583         break;
8584       }
8585     if (op0)
8586       return ReplaceInstUsesWith(EI, op0);
8587   }
8588   
8589   // If extracting a specified index from the vector, see if we can recursively
8590   // find a previously computed scalar that was inserted into the vector.
8591   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8592     // This instruction only demands the single element from the input vector.
8593     // If the input vector has a single use, simplify it based on this use
8594     // property.
8595     uint64_t IndexVal = IdxC->getZExtValue();
8596     if (EI.getOperand(0)->hasOneUse()) {
8597       uint64_t UndefElts;
8598       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8599                                                 1 << IndexVal,
8600                                                 UndefElts)) {
8601         EI.setOperand(0, V);
8602         return &EI;
8603       }
8604     }
8605     
8606     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8607       return ReplaceInstUsesWith(EI, Elt);
8608   }
8609   
8610   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8611     if (I->hasOneUse()) {
8612       // Push extractelement into predecessor operation if legal and
8613       // profitable to do so
8614       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8615         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8616         if (CheapToScalarize(BO, isConstantElt)) {
8617           ExtractElementInst *newEI0 = 
8618             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8619                                    EI.getName()+".lhs");
8620           ExtractElementInst *newEI1 =
8621             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8622                                    EI.getName()+".rhs");
8623           InsertNewInstBefore(newEI0, EI);
8624           InsertNewInstBefore(newEI1, EI);
8625           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8626         }
8627       } else if (isa<LoadInst>(I)) {
8628         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8629                                       PointerType::get(EI.getType()), EI);
8630         GetElementPtrInst *GEP = 
8631           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8632         InsertNewInstBefore(GEP, EI);
8633         return new LoadInst(GEP);
8634       }
8635     }
8636     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8637       // Extracting the inserted element?
8638       if (IE->getOperand(2) == EI.getOperand(1))
8639         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8640       // If the inserted and extracted elements are constants, they must not
8641       // be the same value, extract from the pre-inserted value instead.
8642       if (isa<Constant>(IE->getOperand(2)) &&
8643           isa<Constant>(EI.getOperand(1))) {
8644         AddUsesToWorkList(EI);
8645         EI.setOperand(0, IE->getOperand(0));
8646         return &EI;
8647       }
8648     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8649       // If this is extracting an element from a shufflevector, figure out where
8650       // it came from and extract from the appropriate input element instead.
8651       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8652         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8653         Value *Src;
8654         if (SrcIdx < SVI->getType()->getNumElements())
8655           Src = SVI->getOperand(0);
8656         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8657           SrcIdx -= SVI->getType()->getNumElements();
8658           Src = SVI->getOperand(1);
8659         } else {
8660           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8661         }
8662         return new ExtractElementInst(Src, SrcIdx);
8663       }
8664     }
8665   }
8666   return 0;
8667 }
8668
8669 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8670 /// elements from either LHS or RHS, return the shuffle mask and true. 
8671 /// Otherwise, return false.
8672 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8673                                          std::vector<Constant*> &Mask) {
8674   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8675          "Invalid CollectSingleShuffleElements");
8676   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8677
8678   if (isa<UndefValue>(V)) {
8679     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8680     return true;
8681   } else if (V == LHS) {
8682     for (unsigned i = 0; i != NumElts; ++i)
8683       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8684     return true;
8685   } else if (V == RHS) {
8686     for (unsigned i = 0; i != NumElts; ++i)
8687       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8688     return true;
8689   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8690     // If this is an insert of an extract from some other vector, include it.
8691     Value *VecOp    = IEI->getOperand(0);
8692     Value *ScalarOp = IEI->getOperand(1);
8693     Value *IdxOp    = IEI->getOperand(2);
8694     
8695     if (!isa<ConstantInt>(IdxOp))
8696       return false;
8697     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8698     
8699     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8700       // Okay, we can handle this if the vector we are insertinting into is
8701       // transitively ok.
8702       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8703         // If so, update the mask to reflect the inserted undef.
8704         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8705         return true;
8706       }      
8707     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8708       if (isa<ConstantInt>(EI->getOperand(1)) &&
8709           EI->getOperand(0)->getType() == V->getType()) {
8710         unsigned ExtractedIdx =
8711           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8712         
8713         // This must be extracting from either LHS or RHS.
8714         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8715           // Okay, we can handle this if the vector we are insertinting into is
8716           // transitively ok.
8717           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8718             // If so, update the mask to reflect the inserted value.
8719             if (EI->getOperand(0) == LHS) {
8720               Mask[InsertedIdx & (NumElts-1)] = 
8721                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8722             } else {
8723               assert(EI->getOperand(0) == RHS);
8724               Mask[InsertedIdx & (NumElts-1)] = 
8725                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8726               
8727             }
8728             return true;
8729           }
8730         }
8731       }
8732     }
8733   }
8734   // TODO: Handle shufflevector here!
8735   
8736   return false;
8737 }
8738
8739 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8740 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8741 /// that computes V and the LHS value of the shuffle.
8742 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8743                                      Value *&RHS) {
8744   assert(isa<PackedType>(V->getType()) && 
8745          (RHS == 0 || V->getType() == RHS->getType()) &&
8746          "Invalid shuffle!");
8747   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8748
8749   if (isa<UndefValue>(V)) {
8750     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8751     return V;
8752   } else if (isa<ConstantAggregateZero>(V)) {
8753     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8754     return V;
8755   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8756     // If this is an insert of an extract from some other vector, include it.
8757     Value *VecOp    = IEI->getOperand(0);
8758     Value *ScalarOp = IEI->getOperand(1);
8759     Value *IdxOp    = IEI->getOperand(2);
8760     
8761     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8762       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8763           EI->getOperand(0)->getType() == V->getType()) {
8764         unsigned ExtractedIdx =
8765           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8766         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8767         
8768         // Either the extracted from or inserted into vector must be RHSVec,
8769         // otherwise we'd end up with a shuffle of three inputs.
8770         if (EI->getOperand(0) == RHS || RHS == 0) {
8771           RHS = EI->getOperand(0);
8772           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8773           Mask[InsertedIdx & (NumElts-1)] = 
8774             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8775           return V;
8776         }
8777         
8778         if (VecOp == RHS) {
8779           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8780           // Everything but the extracted element is replaced with the RHS.
8781           for (unsigned i = 0; i != NumElts; ++i) {
8782             if (i != InsertedIdx)
8783               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8784           }
8785           return V;
8786         }
8787         
8788         // If this insertelement is a chain that comes from exactly these two
8789         // vectors, return the vector and the effective shuffle.
8790         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8791           return EI->getOperand(0);
8792         
8793       }
8794     }
8795   }
8796   // TODO: Handle shufflevector here!
8797   
8798   // Otherwise, can't do anything fancy.  Return an identity vector.
8799   for (unsigned i = 0; i != NumElts; ++i)
8800     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8801   return V;
8802 }
8803
8804 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8805   Value *VecOp    = IE.getOperand(0);
8806   Value *ScalarOp = IE.getOperand(1);
8807   Value *IdxOp    = IE.getOperand(2);
8808   
8809   // If the inserted element was extracted from some other vector, and if the 
8810   // indexes are constant, try to turn this into a shufflevector operation.
8811   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8812     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8813         EI->getOperand(0)->getType() == IE.getType()) {
8814       unsigned NumVectorElts = IE.getType()->getNumElements();
8815       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8816       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8817       
8818       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8819         return ReplaceInstUsesWith(IE, VecOp);
8820       
8821       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8822         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8823       
8824       // If we are extracting a value from a vector, then inserting it right
8825       // back into the same place, just use the input vector.
8826       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8827         return ReplaceInstUsesWith(IE, VecOp);      
8828       
8829       // We could theoretically do this for ANY input.  However, doing so could
8830       // turn chains of insertelement instructions into a chain of shufflevector
8831       // instructions, and right now we do not merge shufflevectors.  As such,
8832       // only do this in a situation where it is clear that there is benefit.
8833       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8834         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8835         // the values of VecOp, except then one read from EIOp0.
8836         // Build a new shuffle mask.
8837         std::vector<Constant*> Mask;
8838         if (isa<UndefValue>(VecOp))
8839           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8840         else {
8841           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8842           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8843                                                        NumVectorElts));
8844         } 
8845         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8846         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8847                                      ConstantPacked::get(Mask));
8848       }
8849       
8850       // If this insertelement isn't used by some other insertelement, turn it
8851       // (and any insertelements it points to), into one big shuffle.
8852       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8853         std::vector<Constant*> Mask;
8854         Value *RHS = 0;
8855         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8856         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8857         // We now have a shuffle of LHS, RHS, Mask.
8858         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8859       }
8860     }
8861   }
8862
8863   return 0;
8864 }
8865
8866
8867 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8868   Value *LHS = SVI.getOperand(0);
8869   Value *RHS = SVI.getOperand(1);
8870   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8871
8872   bool MadeChange = false;
8873   
8874   // Undefined shuffle mask -> undefined value.
8875   if (isa<UndefValue>(SVI.getOperand(2)))
8876     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8877   
8878   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8879   // the undef, change them to undefs.
8880   if (isa<UndefValue>(SVI.getOperand(1))) {
8881     // Scan to see if there are any references to the RHS.  If so, replace them
8882     // with undef element refs and set MadeChange to true.
8883     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8884       if (Mask[i] >= e && Mask[i] != 2*e) {
8885         Mask[i] = 2*e;
8886         MadeChange = true;
8887       }
8888     }
8889     
8890     if (MadeChange) {
8891       // Remap any references to RHS to use LHS.
8892       std::vector<Constant*> Elts;
8893       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8894         if (Mask[i] == 2*e)
8895           Elts.push_back(UndefValue::get(Type::Int32Ty));
8896         else
8897           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8898       }
8899       SVI.setOperand(2, ConstantPacked::get(Elts));
8900     }
8901   }
8902   
8903   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8904   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8905   if (LHS == RHS || isa<UndefValue>(LHS)) {
8906     if (isa<UndefValue>(LHS) && LHS == RHS) {
8907       // shuffle(undef,undef,mask) -> undef.
8908       return ReplaceInstUsesWith(SVI, LHS);
8909     }
8910     
8911     // Remap any references to RHS to use LHS.
8912     std::vector<Constant*> Elts;
8913     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8914       if (Mask[i] >= 2*e)
8915         Elts.push_back(UndefValue::get(Type::Int32Ty));
8916       else {
8917         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8918             (Mask[i] <  e && isa<UndefValue>(LHS)))
8919           Mask[i] = 2*e;     // Turn into undef.
8920         else
8921           Mask[i] &= (e-1);  // Force to LHS.
8922         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8923       }
8924     }
8925     SVI.setOperand(0, SVI.getOperand(1));
8926     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8927     SVI.setOperand(2, ConstantPacked::get(Elts));
8928     LHS = SVI.getOperand(0);
8929     RHS = SVI.getOperand(1);
8930     MadeChange = true;
8931   }
8932   
8933   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8934   bool isLHSID = true, isRHSID = true;
8935     
8936   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8937     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8938     // Is this an identity shuffle of the LHS value?
8939     isLHSID &= (Mask[i] == i);
8940       
8941     // Is this an identity shuffle of the RHS value?
8942     isRHSID &= (Mask[i]-e == i);
8943   }
8944
8945   // Eliminate identity shuffles.
8946   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8947   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8948   
8949   // If the LHS is a shufflevector itself, see if we can combine it with this
8950   // one without producing an unusual shuffle.  Here we are really conservative:
8951   // we are absolutely afraid of producing a shuffle mask not in the input
8952   // program, because the code gen may not be smart enough to turn a merged
8953   // shuffle into two specific shuffles: it may produce worse code.  As such,
8954   // we only merge two shuffles if the result is one of the two input shuffle
8955   // masks.  In this case, merging the shuffles just removes one instruction,
8956   // which we know is safe.  This is good for things like turning:
8957   // (splat(splat)) -> splat.
8958   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8959     if (isa<UndefValue>(RHS)) {
8960       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8961
8962       std::vector<unsigned> NewMask;
8963       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8964         if (Mask[i] >= 2*e)
8965           NewMask.push_back(2*e);
8966         else
8967           NewMask.push_back(LHSMask[Mask[i]]);
8968       
8969       // If the result mask is equal to the src shuffle or this shuffle mask, do
8970       // the replacement.
8971       if (NewMask == LHSMask || NewMask == Mask) {
8972         std::vector<Constant*> Elts;
8973         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8974           if (NewMask[i] >= e*2) {
8975             Elts.push_back(UndefValue::get(Type::Int32Ty));
8976           } else {
8977             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8978           }
8979         }
8980         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8981                                      LHSSVI->getOperand(1),
8982                                      ConstantPacked::get(Elts));
8983       }
8984     }
8985   }
8986   
8987   return MadeChange ? &SVI : 0;
8988 }
8989
8990
8991
8992 void InstCombiner::removeFromWorkList(Instruction *I) {
8993   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8994                  WorkList.end());
8995 }
8996
8997
8998 /// TryToSinkInstruction - Try to move the specified instruction from its
8999 /// current block into the beginning of DestBlock, which can only happen if it's
9000 /// safe to move the instruction past all of the instructions between it and the
9001 /// end of its block.
9002 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9003   assert(I->hasOneUse() && "Invariants didn't hold!");
9004
9005   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9006   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9007
9008   // Do not sink alloca instructions out of the entry block.
9009   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9010     return false;
9011
9012   // We can only sink load instructions if there is nothing between the load and
9013   // the end of block that could change the value.
9014   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9015     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9016          Scan != E; ++Scan)
9017       if (Scan->mayWriteToMemory())
9018         return false;
9019   }
9020
9021   BasicBlock::iterator InsertPos = DestBlock->begin();
9022   while (isa<PHINode>(InsertPos)) ++InsertPos;
9023
9024   I->moveBefore(InsertPos);
9025   ++NumSunkInst;
9026   return true;
9027 }
9028
9029 /// OptimizeConstantExpr - Given a constant expression and target data layout
9030 /// information, symbolically evaluate the constant expr to something simpler
9031 /// if possible.
9032 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9033   if (!TD) return CE;
9034   
9035   Constant *Ptr = CE->getOperand(0);
9036   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9037       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9038     // If this is a constant expr gep that is effectively computing an
9039     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9040     bool isFoldableGEP = true;
9041     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9042       if (!isa<ConstantInt>(CE->getOperand(i)))
9043         isFoldableGEP = false;
9044     if (isFoldableGEP) {
9045       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9046       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9047       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9048       return ConstantExpr::getIntToPtr(C, CE->getType());
9049     }
9050   }
9051   
9052   return CE;
9053 }
9054
9055
9056 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9057 /// all reachable code to the worklist.
9058 ///
9059 /// This has a couple of tricks to make the code faster and more powerful.  In
9060 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9061 /// them to the worklist (this significantly speeds up instcombine on code where
9062 /// many instructions are dead or constant).  Additionally, if we find a branch
9063 /// whose condition is a known constant, we only visit the reachable successors.
9064 ///
9065 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9066                                        std::set<BasicBlock*> &Visited,
9067                                        std::vector<Instruction*> &WorkList,
9068                                        const TargetData *TD) {
9069   // We have now visited this block!  If we've already been here, bail out.
9070   if (!Visited.insert(BB).second) return;
9071     
9072   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9073     Instruction *Inst = BBI++;
9074     
9075     // DCE instruction if trivially dead.
9076     if (isInstructionTriviallyDead(Inst)) {
9077       ++NumDeadInst;
9078       DOUT << "IC: DCE: " << *Inst;
9079       Inst->eraseFromParent();
9080       continue;
9081     }
9082     
9083     // ConstantProp instruction if trivially constant.
9084     if (Constant *C = ConstantFoldInstruction(Inst)) {
9085       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9086         C = OptimizeConstantExpr(CE, TD);
9087       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9088       Inst->replaceAllUsesWith(C);
9089       ++NumConstProp;
9090       Inst->eraseFromParent();
9091       continue;
9092     }
9093     
9094     WorkList.push_back(Inst);
9095   }
9096
9097   // Recursively visit successors.  If this is a branch or switch on a constant,
9098   // only visit the reachable successor.
9099   TerminatorInst *TI = BB->getTerminator();
9100   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9101     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9102       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9103       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9104                                  TD);
9105       return;
9106     }
9107   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9108     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9109       // See if this is an explicit destination.
9110       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9111         if (SI->getCaseValue(i) == Cond) {
9112           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9113           return;
9114         }
9115       
9116       // Otherwise it is the default destination.
9117       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9118       return;
9119     }
9120   }
9121   
9122   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9123     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9124 }
9125
9126 bool InstCombiner::runOnFunction(Function &F) {
9127   bool Changed = false;
9128   TD = &getAnalysis<TargetData>();
9129
9130   {
9131     // Do a depth-first traversal of the function, populate the worklist with
9132     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9133     // track of which blocks we visit.
9134     std::set<BasicBlock*> Visited;
9135     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9136
9137     // Do a quick scan over the function.  If we find any blocks that are
9138     // unreachable, remove any instructions inside of them.  This prevents
9139     // the instcombine code from having to deal with some bad special cases.
9140     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9141       if (!Visited.count(BB)) {
9142         Instruction *Term = BB->getTerminator();
9143         while (Term != BB->begin()) {   // Remove instrs bottom-up
9144           BasicBlock::iterator I = Term; --I;
9145
9146           DOUT << "IC: DCE: " << *I;
9147           ++NumDeadInst;
9148
9149           if (!I->use_empty())
9150             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9151           I->eraseFromParent();
9152         }
9153       }
9154   }
9155
9156   while (!WorkList.empty()) {
9157     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9158     WorkList.pop_back();
9159
9160     // Check to see if we can DCE the instruction.
9161     if (isInstructionTriviallyDead(I)) {
9162       // Add operands to the worklist.
9163       if (I->getNumOperands() < 4)
9164         AddUsesToWorkList(*I);
9165       ++NumDeadInst;
9166
9167       DOUT << "IC: DCE: " << *I;
9168
9169       I->eraseFromParent();
9170       removeFromWorkList(I);
9171       continue;
9172     }
9173
9174     // Instruction isn't dead, see if we can constant propagate it.
9175     if (Constant *C = ConstantFoldInstruction(I)) {
9176       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9177         C = OptimizeConstantExpr(CE, TD);
9178       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9179
9180       // Add operands to the worklist.
9181       AddUsesToWorkList(*I);
9182       ReplaceInstUsesWith(*I, C);
9183
9184       ++NumConstProp;
9185       I->eraseFromParent();
9186       removeFromWorkList(I);
9187       continue;
9188     }
9189
9190     // See if we can trivially sink this instruction to a successor basic block.
9191     if (I->hasOneUse()) {
9192       BasicBlock *BB = I->getParent();
9193       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9194       if (UserParent != BB) {
9195         bool UserIsSuccessor = false;
9196         // See if the user is one of our successors.
9197         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9198           if (*SI == UserParent) {
9199             UserIsSuccessor = true;
9200             break;
9201           }
9202
9203         // If the user is one of our immediate successors, and if that successor
9204         // only has us as a predecessors (we'd have to split the critical edge
9205         // otherwise), we can keep going.
9206         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9207             next(pred_begin(UserParent)) == pred_end(UserParent))
9208           // Okay, the CFG is simple enough, try to sink this instruction.
9209           Changed |= TryToSinkInstruction(I, UserParent);
9210       }
9211     }
9212
9213     // Now that we have an instruction, try combining it to simplify it...
9214     if (Instruction *Result = visit(*I)) {
9215       ++NumCombined;
9216       // Should we replace the old instruction with a new one?
9217       if (Result != I) {
9218         DOUT << "IC: Old = " << *I
9219              << "    New = " << *Result;
9220
9221         // Everything uses the new instruction now.
9222         I->replaceAllUsesWith(Result);
9223
9224         // Push the new instruction and any users onto the worklist.
9225         WorkList.push_back(Result);
9226         AddUsersToWorkList(*Result);
9227
9228         // Move the name to the new instruction first...
9229         std::string OldName = I->getName(); I->setName("");
9230         Result->setName(OldName);
9231
9232         // Insert the new instruction into the basic block...
9233         BasicBlock *InstParent = I->getParent();
9234         BasicBlock::iterator InsertPos = I;
9235
9236         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9237           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9238             ++InsertPos;
9239
9240         InstParent->getInstList().insert(InsertPos, Result);
9241
9242         // Make sure that we reprocess all operands now that we reduced their
9243         // use counts.
9244         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9245           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9246             WorkList.push_back(OpI);
9247
9248         // Instructions can end up on the worklist more than once.  Make sure
9249         // we do not process an instruction that has been deleted.
9250         removeFromWorkList(I);
9251
9252         // Erase the old instruction.
9253         InstParent->getInstList().erase(I);
9254       } else {
9255         DOUT << "IC: MOD = " << *I;
9256
9257         // If the instruction was modified, it's possible that it is now dead.
9258         // if so, remove it.
9259         if (isInstructionTriviallyDead(I)) {
9260           // Make sure we process all operands now that we are reducing their
9261           // use counts.
9262           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9263             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9264               WorkList.push_back(OpI);
9265
9266           // Instructions may end up in the worklist more than once.  Erase all
9267           // occurrences of this instruction.
9268           removeFromWorkList(I);
9269           I->eraseFromParent();
9270         } else {
9271           WorkList.push_back(Result);
9272           AddUsersToWorkList(*Result);
9273         }
9274       }
9275       Changed = true;
9276     }
9277   }
9278
9279   return Changed;
9280 }
9281
9282 FunctionPass *llvm::createInstructionCombiningPass() {
9283   return new InstCombiner();
9284 }
9285