e5207735931729492300c05748ffba93b560fb04
[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 i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <set>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68
69 namespace {
70   class VISIBILITY_HIDDEN InstCombiner
71     : public FunctionPass,
72       public InstVisitor<InstCombiner, Instruction*> {
73     // Worklist of all of the instructions that need to be simplified.
74     std::vector<Instruction*> Worklist;
75     DenseMap<Instruction*, unsigned> WorklistMap;
76     TargetData *TD;
77     bool MustPreserveLCSSA;
78   public:
79     /// AddToWorkList - Add the specified instruction to the worklist if it
80     /// isn't already in it.
81     void AddToWorkList(Instruction *I) {
82       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83         Worklist.push_back(I);
84     }
85     
86     // RemoveFromWorkList - remove I from the worklist if it exists.
87     void RemoveFromWorkList(Instruction *I) {
88       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89       if (It == WorklistMap.end()) return; // Not in worklist.
90       
91       // Don't bother moving everything down, just null out the slot.
92       Worklist[It->second] = 0;
93       
94       WorklistMap.erase(It);
95     }
96     
97     Instruction *RemoveOneFromWorkList() {
98       Instruction *I = Worklist.back();
99       Worklist.pop_back();
100       WorklistMap.erase(I);
101       return I;
102     }
103
104     
105     /// AddUsersToWorkList - When an instruction is simplified, add all users of
106     /// the instruction to the work lists because they might get more simplified
107     /// now.
108     ///
109     void AddUsersToWorkList(Value &I) {
110       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
111            UI != UE; ++UI)
112         AddToWorkList(cast<Instruction>(*UI));
113     }
114
115     /// AddUsesToWorkList - When an instruction is simplified, add operands to
116     /// the work lists because they might get more simplified now.
117     ///
118     void AddUsesToWorkList(Instruction &I) {
119       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
121           AddToWorkList(Op);
122     }
123     
124     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125     /// dead.  Add all of its operands to the worklist, turning them into
126     /// undef's to reduce the number of uses of those instructions.
127     ///
128     /// Return the specified operand before it is turned into an undef.
129     ///
130     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131       Value *R = I.getOperand(op);
132       
133       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
135           AddToWorkList(Op);
136           // Set the operand to undef to drop the use.
137           I.setOperand(i, UndefValue::get(Op->getType()));
138         }
139       
140       return R;
141     }
142
143   public:
144     virtual bool runOnFunction(Function &F);
145     
146     bool DoOneIteration(Function &F, unsigned ItNum);
147
148     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149       AU.addRequired<TargetData>();
150       AU.addPreservedID(LCSSAID);
151       AU.setPreservesCFG();
152     }
153
154     TargetData &getTargetData() const { return *TD; }
155
156     // Visitation implementation - Implement instruction combining for different
157     // instruction types.  The semantics are as follows:
158     // Return Value:
159     //    null        - No change was made
160     //     I          - Change was made, I is still valid, I may be dead though
161     //   otherwise    - Change was made, replace I with returned instruction
162     //
163     Instruction *visitAdd(BinaryOperator &I);
164     Instruction *visitSub(BinaryOperator &I);
165     Instruction *visitMul(BinaryOperator &I);
166     Instruction *visitURem(BinaryOperator &I);
167     Instruction *visitSRem(BinaryOperator &I);
168     Instruction *visitFRem(BinaryOperator &I);
169     Instruction *commonRemTransforms(BinaryOperator &I);
170     Instruction *commonIRemTransforms(BinaryOperator &I);
171     Instruction *commonDivTransforms(BinaryOperator &I);
172     Instruction *commonIDivTransforms(BinaryOperator &I);
173     Instruction *visitUDiv(BinaryOperator &I);
174     Instruction *visitSDiv(BinaryOperator &I);
175     Instruction *visitFDiv(BinaryOperator &I);
176     Instruction *visitAnd(BinaryOperator &I);
177     Instruction *visitOr (BinaryOperator &I);
178     Instruction *visitXor(BinaryOperator &I);
179     Instruction *visitShl(BinaryOperator &I);
180     Instruction *visitAShr(BinaryOperator &I);
181     Instruction *visitLShr(BinaryOperator &I);
182     Instruction *commonShiftTransforms(BinaryOperator &I);
183     Instruction *visitFCmpInst(FCmpInst &I);
184     Instruction *visitICmpInst(ICmpInst &I);
185     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
186
187     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188                              ICmpInst::Predicate Cond, Instruction &I);
189     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
190                                      BinaryOperator &I);
191     Instruction *commonCastTransforms(CastInst &CI);
192     Instruction *commonIntCastTransforms(CastInst &CI);
193     Instruction *visitTrunc(CastInst &CI);
194     Instruction *visitZExt(CastInst &CI);
195     Instruction *visitSExt(CastInst &CI);
196     Instruction *visitFPTrunc(CastInst &CI);
197     Instruction *visitFPExt(CastInst &CI);
198     Instruction *visitFPToUI(CastInst &CI);
199     Instruction *visitFPToSI(CastInst &CI);
200     Instruction *visitUIToFP(CastInst &CI);
201     Instruction *visitSIToFP(CastInst &CI);
202     Instruction *visitPtrToInt(CastInst &CI);
203     Instruction *visitIntToPtr(CastInst &CI);
204     Instruction *visitBitCast(CastInst &CI);
205     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206                                 Instruction *FI);
207     Instruction *visitSelectInst(SelectInst &CI);
208     Instruction *visitCallInst(CallInst &CI);
209     Instruction *visitInvokeInst(InvokeInst &II);
210     Instruction *visitPHINode(PHINode &PN);
211     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
212     Instruction *visitAllocationInst(AllocationInst &AI);
213     Instruction *visitFreeInst(FreeInst &FI);
214     Instruction *visitLoadInst(LoadInst &LI);
215     Instruction *visitStoreInst(StoreInst &SI);
216     Instruction *visitBranchInst(BranchInst &BI);
217     Instruction *visitSwitchInst(SwitchInst &SI);
218     Instruction *visitInsertElementInst(InsertElementInst &IE);
219     Instruction *visitExtractElementInst(ExtractElementInst &EI);
220     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
221
222     // visitInstruction - Specify what to return for unhandled instructions...
223     Instruction *visitInstruction(Instruction &I) { return 0; }
224
225   private:
226     Instruction *visitCallSite(CallSite CS);
227     bool transformConstExprCastCall(CallSite CS);
228
229   public:
230     // InsertNewInstBefore - insert an instruction New before instruction Old
231     // in the program.  Add the new instruction to the worklist.
232     //
233     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
234       assert(New && New->getParent() == 0 &&
235              "New instruction already inserted into a basic block!");
236       BasicBlock *BB = Old.getParent();
237       BB->getInstList().insert(&Old, New);  // Insert inst
238       AddToWorkList(New);
239       return New;
240     }
241
242     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243     /// This also adds the cast to the worklist.  Finally, this returns the
244     /// cast.
245     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246                             Instruction &Pos) {
247       if (V->getType() == Ty) return V;
248
249       if (Constant *CV = dyn_cast<Constant>(V))
250         return ConstantExpr::getCast(opc, CV, Ty);
251       
252       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
253       AddToWorkList(C);
254       return C;
255     }
256
257     // ReplaceInstUsesWith - This method is to be used when an instruction is
258     // found to be dead, replacable with another preexisting expression.  Here
259     // we add all uses of I to the worklist, replace all uses of I with the new
260     // value, then return I, so that the inst combiner will know that I was
261     // modified.
262     //
263     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
264       AddUsersToWorkList(I);         // Add all modified instrs to worklist
265       if (&I != V) {
266         I.replaceAllUsesWith(V);
267         return &I;
268       } else {
269         // If we are replacing the instruction with itself, this must be in a
270         // segment of unreachable code, so just clobber the instruction.
271         I.replaceAllUsesWith(UndefValue::get(I.getType()));
272         return &I;
273       }
274     }
275
276     // UpdateValueUsesWith - This method is to be used when an value is
277     // found to be replacable with another preexisting expression or was
278     // updated.  Here we add all uses of I to the worklist, replace all uses of
279     // I with the new value (unless the instruction was just updated), then
280     // return true, so that the inst combiner will know that I was modified.
281     //
282     bool UpdateValueUsesWith(Value *Old, Value *New) {
283       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
284       if (Old != New)
285         Old->replaceAllUsesWith(New);
286       if (Instruction *I = dyn_cast<Instruction>(Old))
287         AddToWorkList(I);
288       if (Instruction *I = dyn_cast<Instruction>(New))
289         AddToWorkList(I);
290       return true;
291     }
292     
293     // EraseInstFromFunction - When dealing with an instruction that has side
294     // effects or produces a void value, we can't rely on DCE to delete the
295     // instruction.  Instead, visit methods should return the value returned by
296     // this function.
297     Instruction *EraseInstFromFunction(Instruction &I) {
298       assert(I.use_empty() && "Cannot erase instruction that is used!");
299       AddUsesToWorkList(I);
300       RemoveFromWorkList(&I);
301       I.eraseFromParent();
302       return 0;  // Don't do anything with FI
303     }
304
305   private:
306     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
308     /// casts that are known to not do anything...
309     ///
310     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311                                    Value *V, const Type *DestTy,
312                                    Instruction *InsertBefore);
313
314     /// SimplifyCommutative - This performs a few simplifications for 
315     /// commutative operators.
316     bool SimplifyCommutative(BinaryOperator &I);
317
318     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319     /// most-complex to least-complex order.
320     bool SimplifyCompare(CmpInst &I);
321
322     bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask, 
323                               uint64_t &KnownZero, uint64_t &KnownOne,
324                               unsigned Depth = 0);
325
326     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
327                               APInt& KnownZero, APInt& KnownOne,
328                               unsigned Depth = 0);
329
330     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331                                       uint64_t &UndefElts, unsigned Depth = 0);
332       
333     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334     // PHI node as operand #0, see if we can fold the instruction into the PHI
335     // (which is only possible if all operands to the PHI are constants).
336     Instruction *FoldOpIntoPhi(Instruction &I);
337
338     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339     // operator and they all are only used by the PHI, PHI together their
340     // inputs, and do the operation once, to the result of the PHI.
341     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
342     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
343     
344     
345     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
347     
348     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
349                               bool isSub, Instruction &I);
350     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
351                                  bool isSigned, bool Inside, Instruction &IB);
352     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
353     Instruction *MatchBSwap(BinaryOperator &I);
354
355     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
356   };
357
358   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
359 }
360
361 // getComplexity:  Assign a complexity or rank value to LLVM Values...
362 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
363 static unsigned getComplexity(Value *V) {
364   if (isa<Instruction>(V)) {
365     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
366       return 3;
367     return 4;
368   }
369   if (isa<Argument>(V)) return 3;
370   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
371 }
372
373 // isOnlyUse - Return true if this instruction will be deleted if we stop using
374 // it.
375 static bool isOnlyUse(Value *V) {
376   return V->hasOneUse() || isa<Constant>(V);
377 }
378
379 // getPromotedType - Return the specified type promoted as it would be to pass
380 // though a va_arg area...
381 static const Type *getPromotedType(const Type *Ty) {
382   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383     if (ITy->getBitWidth() < 32)
384       return Type::Int32Ty;
385   } else if (Ty == Type::FloatTy)
386     return Type::DoubleTy;
387   return Ty;
388 }
389
390 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
391 /// expression bitcast,  return the operand value, otherwise return null.
392 static Value *getBitCastOperand(Value *V) {
393   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
394     return I->getOperand(0);
395   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
396     if (CE->getOpcode() == Instruction::BitCast)
397       return CE->getOperand(0);
398   return 0;
399 }
400
401 /// This function is a wrapper around CastInst::isEliminableCastPair. It
402 /// simply extracts arguments and returns what that function returns.
403 static Instruction::CastOps 
404 isEliminableCastPair(
405   const CastInst *CI, ///< The first cast instruction
406   unsigned opcode,       ///< The opcode of the second cast instruction
407   const Type *DstTy,     ///< The target type for the second cast instruction
408   TargetData *TD         ///< The target data for pointer size
409 ) {
410   
411   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
412   const Type *MidTy = CI->getType();                  // B from above
413
414   // Get the opcodes of the two Cast instructions
415   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
417
418   return Instruction::CastOps(
419       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420                                      DstTy, TD->getIntPtrType()));
421 }
422
423 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424 /// in any code being generated.  It does not require codegen if V is simple
425 /// enough or if the cast can be folded into other casts.
426 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
427                               const Type *Ty, TargetData *TD) {
428   if (V->getType() == Ty || isa<Constant>(V)) return false;
429   
430   // If this is another cast that can be eliminated, it isn't codegen either.
431   if (const CastInst *CI = dyn_cast<CastInst>(V))
432     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
433       return false;
434   return true;
435 }
436
437 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
439 /// casts that are known to not do anything...
440 ///
441 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442                                              Value *V, const Type *DestTy,
443                                              Instruction *InsertBefore) {
444   if (V->getType() == DestTy) return V;
445   if (Constant *C = dyn_cast<Constant>(V))
446     return ConstantExpr::getCast(opcode, C, DestTy);
447   
448   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
449 }
450
451 // SimplifyCommutative - This performs a few simplifications for commutative
452 // operators:
453 //
454 //  1. Order operands such that they are listed from right (least complex) to
455 //     left (most complex).  This puts constants before unary operators before
456 //     binary operators.
457 //
458 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
460 //
461 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
462   bool Changed = false;
463   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464     Changed = !I.swapOperands();
465
466   if (!I.isAssociative()) return Changed;
467   Instruction::BinaryOps Opcode = I.getOpcode();
468   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470       if (isa<Constant>(I.getOperand(1))) {
471         Constant *Folded = ConstantExpr::get(I.getOpcode(),
472                                              cast<Constant>(I.getOperand(1)),
473                                              cast<Constant>(Op->getOperand(1)));
474         I.setOperand(0, Op->getOperand(0));
475         I.setOperand(1, Folded);
476         return true;
477       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479             isOnlyUse(Op) && isOnlyUse(Op1)) {
480           Constant *C1 = cast<Constant>(Op->getOperand(1));
481           Constant *C2 = cast<Constant>(Op1->getOperand(1));
482
483           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
484           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
485           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
486                                                     Op1->getOperand(0),
487                                                     Op1->getName(), &I);
488           AddToWorkList(New);
489           I.setOperand(0, New);
490           I.setOperand(1, Folded);
491           return true;
492         }
493     }
494   return Changed;
495 }
496
497 /// SimplifyCompare - For a CmpInst this function just orders the operands
498 /// so that theyare listed from right (least complex) to left (most complex).
499 /// This puts constants before unary operators before binary operators.
500 bool InstCombiner::SimplifyCompare(CmpInst &I) {
501   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
502     return false;
503   I.swapOperands();
504   // Compare instructions are not associative so there's nothing else we can do.
505   return true;
506 }
507
508 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509 // if the LHS is a constant zero (which is the 'negate' form).
510 //
511 static inline Value *dyn_castNegVal(Value *V) {
512   if (BinaryOperator::isNeg(V))
513     return BinaryOperator::getNegArgument(V);
514
515   // Constants can be considered to be negated values if they can be folded.
516   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517     return ConstantExpr::getNeg(C);
518   return 0;
519 }
520
521 static inline Value *dyn_castNotVal(Value *V) {
522   if (BinaryOperator::isNot(V))
523     return BinaryOperator::getNotArgument(V);
524
525   // Constants can be considered to be not'ed values...
526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527     return ConstantExpr::getNot(C);
528   return 0;
529 }
530
531 // dyn_castFoldableMul - If this value is a multiply that can be folded into
532 // other computations (because it has a constant operand), return the
533 // non-constant operand of the multiply, and set CST to point to the multiplier.
534 // Otherwise, return null.
535 //
536 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
537   if (V->hasOneUse() && V->getType()->isInteger())
538     if (Instruction *I = dyn_cast<Instruction>(V)) {
539       if (I->getOpcode() == Instruction::Mul)
540         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
541           return I->getOperand(0);
542       if (I->getOpcode() == Instruction::Shl)
543         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
544           // The multiplier is really 1 << CST.
545           Constant *One = ConstantInt::get(V->getType(), 1);
546           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547           return I->getOperand(0);
548         }
549     }
550   return 0;
551 }
552
553 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554 /// expression, return it.
555 static User *dyn_castGetElementPtr(Value *V) {
556   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558     if (CE->getOpcode() == Instruction::GetElementPtr)
559       return cast<User>(V);
560   return false;
561 }
562
563 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
564 static ConstantInt *AddOne(ConstantInt *C) {
565   return cast<ConstantInt>(ConstantExpr::getAdd(C,
566                                          ConstantInt::get(C->getType(), 1)));
567 }
568 static ConstantInt *SubOne(ConstantInt *C) {
569   return cast<ConstantInt>(ConstantExpr::getSub(C,
570                                          ConstantInt::get(C->getType(), 1)));
571 }
572
573 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
574 /// known to be either zero or one and return them in the KnownZero/KnownOne
575 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
576 /// processing.
577 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
578 /// we cannot optimize based on the assumption that it is zero without changing
579 /// it to be an explicit zero.  If we don't change it to zero, other code could
580 /// optimized based on the contradictory assumption that it is non-zero.
581 /// Because instcombine aggressively folds operations with undef args anyway,
582 /// this won't lose us code quality.
583 static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero, 
584                               APInt& KnownOne, unsigned Depth = 0) {
585   assert(V && "No Value?");
586   assert(Depth <= 6 && "Limit Search Depth");
587   uint32_t BitWidth = Mask.getBitWidth();
588   const IntegerType *VTy = cast<IntegerType>(V->getType());
589   assert(VTy->getBitWidth() == BitWidth &&
590          KnownZero.getBitWidth() == BitWidth && 
591          KnownOne.getBitWidth() == BitWidth &&
592          "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
593   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594     // We know all of the bits for a constant!
595     KnownOne = CI->getValue() & Mask;
596     KnownZero = ~KnownOne & Mask;
597     return;
598   }
599
600   if (Depth == 6 || Mask == 0)
601     return;  // Limit search depth.
602
603   Instruction *I = dyn_cast<Instruction>(V);
604   if (!I) return;
605
606   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
607   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
608   Mask &= APInt::getAllOnesValue(BitWidth);
609   
610   switch (I->getOpcode()) {
611   case Instruction::And:
612     // If either the LHS or the RHS are Zero, the result is zero.
613     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614     Mask &= ~KnownZero;
615     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
617     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
618     
619     // Output known-1 bits are only known if set in both the LHS & RHS.
620     KnownOne &= KnownOne2;
621     // Output known-0 are known to be clear if zero in either the LHS | RHS.
622     KnownZero |= KnownZero2;
623     return;
624   case Instruction::Or:
625     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626     Mask &= ~KnownOne;
627     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
629     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
630     
631     // Output known-0 bits are only known if clear in both the LHS & RHS.
632     KnownZero &= KnownZero2;
633     // Output known-1 are known to be set if set in either the LHS | RHS.
634     KnownOne |= KnownOne2;
635     return;
636   case Instruction::Xor: {
637     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
640     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
641     
642     // Output known-0 bits are known if clear or set in both the LHS & RHS.
643     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644     // Output known-1 are known to be set if set in only one of the LHS, RHS.
645     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646     KnownZero = KnownZeroOut;
647     return;
648   }
649   case Instruction::Select:
650     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
653     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
654
655     // Only known if known in both the LHS and RHS.
656     KnownOne &= KnownOne2;
657     KnownZero &= KnownZero2;
658     return;
659   case Instruction::FPTrunc:
660   case Instruction::FPExt:
661   case Instruction::FPToUI:
662   case Instruction::FPToSI:
663   case Instruction::SIToFP:
664   case Instruction::PtrToInt:
665   case Instruction::UIToFP:
666   case Instruction::IntToPtr:
667     return; // Can't work with floating point or pointers
668   case Instruction::Trunc: {
669     // All these have integer operands
670     uint32_t SrcBitWidth = 
671       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672     ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth), 
673       KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674     KnownZero.trunc(BitWidth);
675     KnownOne.trunc(BitWidth);
676     return;
677   }
678   case Instruction::BitCast: {
679     const Type *SrcTy = I->getOperand(0)->getType();
680     if (SrcTy->isInteger()) {
681       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682       return;
683     }
684     break;
685   }
686   case Instruction::ZExt:  {
687     // Compute the bits in the result that are not present in the input.
688     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
689     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
690       
691     uint32_t SrcBitWidth = SrcTy->getBitWidth();
692     ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth), 
693       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
694     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
695     // The top bits are known to be zero.
696     KnownZero.zext(BitWidth);
697     KnownOne.zext(BitWidth);
698     KnownZero |= NewBits;
699     return;
700   }
701   case Instruction::SExt: {
702     // Compute the bits in the result that are not present in the input.
703     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
704     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
705       
706     uint32_t SrcBitWidth = SrcTy->getBitWidth();
707     ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth), 
708       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
709     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
710     KnownZero.zext(BitWidth);
711     KnownOne.zext(BitWidth);
712
713     // If the sign bit of the input is known set or clear, then we know the
714     // top bits of the result.
715     APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
716     InSignBit.zext(BitWidth);
717     if ((KnownZero & InSignBit) != 0) {          // Input sign bit known zero
718       KnownZero |= NewBits;
719       KnownOne &= ~NewBits;
720     } else if ((KnownOne & InSignBit) != 0) {    // Input sign bit known set
721       KnownOne |= NewBits;
722       KnownZero &= ~NewBits;
723     } else {                              // Input sign bit unknown
724       KnownZero &= ~NewBits;
725       KnownOne &= ~NewBits;
726     }
727     return;
728   }
729   case Instruction::Shl:
730     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
731     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732       uint64_t ShiftAmt = SA->getZExtValue();
733       Mask = APIntOps::lshr(Mask, ShiftAmt);
734       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
736       KnownZero <<= ShiftAmt;
737       KnownOne  <<= ShiftAmt;
738       KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1;  // low bits known zero.
739       return;
740     }
741     break;
742   case Instruction::LShr:
743     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
744     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745       // Compute the new bits that are at the top now.
746       uint64_t ShiftAmt = SA->getZExtValue();
747       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748       
749       // Unsigned shift right.
750       Mask <<= ShiftAmt;
751       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
753       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
755       KnownZero |= HighBits;  // high bits known zero.
756       return;
757     }
758     break;
759   case Instruction::AShr:
760     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
761     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762       // Compute the new bits that are at the top now.
763       uint64_t ShiftAmt = SA->getZExtValue();
764       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
765       
766       // Signed shift right.
767       Mask <<= ShiftAmt;
768       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
770       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
772         
773       // Handle the sign bits and adjust to where it is now in the mask.
774       APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
775         
776       if ((KnownZero & SignBit) != 0) {       // New bits are known zero.
777         KnownZero |= HighBits;
778       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779         KnownOne |= HighBits;
780       }
781       return;
782     }
783     break;
784   }
785 }
786
787 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
788 /// known to be either zero or one and return them in the KnownZero/KnownOne
789 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
790 /// processing.
791 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero, 
792                               uint64_t &KnownOne, unsigned Depth = 0) {
793   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
794   // we cannot optimize based on the assumption that it is zero without changing
795   // it to be an explicit zero.  If we don't change it to zero, other code could
796   // optimized based on the contradictory assumption that it is non-zero.
797   // Because instcombine aggressively folds operations with undef args anyway,
798   // this won't lose us code quality.
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getZExtValue() & Mask;
802     KnownZero = ~KnownOne & Mask;
803     return;
804   }
805
806   KnownZero = KnownOne = 0;   // Don't know anything.
807   if (Depth == 6 || Mask == 0)
808     return;  // Limit search depth.
809
810   uint64_t KnownZero2, KnownOne2;
811   Instruction *I = dyn_cast<Instruction>(V);
812   if (!I) return;
813
814   Mask &= cast<IntegerType>(V->getType())->getBitMask();
815   
816   switch (I->getOpcode()) {
817   case Instruction::And:
818     // If either the LHS or the RHS are Zero, the result is zero.
819     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
820     Mask &= ~KnownZero;
821     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
823     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
824     
825     // Output known-1 bits are only known if set in both the LHS & RHS.
826     KnownOne &= KnownOne2;
827     // Output known-0 are known to be clear if zero in either the LHS | RHS.
828     KnownZero |= KnownZero2;
829     return;
830   case Instruction::Or:
831     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
832     Mask &= ~KnownOne;
833     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
835     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
836     
837     // Output known-0 bits are only known if clear in both the LHS & RHS.
838     KnownZero &= KnownZero2;
839     // Output known-1 are known to be set if set in either the LHS | RHS.
840     KnownOne |= KnownOne2;
841     return;
842   case Instruction::Xor: {
843     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
845     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
846     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
847     
848     // Output known-0 bits are known if clear or set in both the LHS & RHS.
849     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850     // Output known-1 are known to be set if set in only one of the LHS, RHS.
851     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852     KnownZero = KnownZeroOut;
853     return;
854   }
855   case Instruction::Select:
856     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
859     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
860
861     // Only known if known in both the LHS and RHS.
862     KnownOne &= KnownOne2;
863     KnownZero &= KnownZero2;
864     return;
865   case Instruction::FPTrunc:
866   case Instruction::FPExt:
867   case Instruction::FPToUI:
868   case Instruction::FPToSI:
869   case Instruction::SIToFP:
870   case Instruction::PtrToInt:
871   case Instruction::UIToFP:
872   case Instruction::IntToPtr:
873     return; // Can't work with floating point or pointers
874   case Instruction::Trunc: 
875     // All these have integer operands
876     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877     return;
878   case Instruction::BitCast: {
879     const Type *SrcTy = I->getOperand(0)->getType();
880     if (SrcTy->isInteger()) {
881       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
882       return;
883     }
884     break;
885   }
886   case Instruction::ZExt:  {
887     // Compute the bits in the result that are not present in the input.
888     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889     uint64_t NotIn = ~SrcTy->getBitMask();
890     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
891       
892     Mask &= SrcTy->getBitMask();
893     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
895     // The top bits are known to be zero.
896     KnownZero |= NewBits;
897     return;
898   }
899   case Instruction::SExt: {
900     // Compute the bits in the result that are not present in the input.
901     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902     uint64_t NotIn = ~SrcTy->getBitMask();
903     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
904       
905     Mask &= SrcTy->getBitMask();
906     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
908
909     // If the sign bit of the input is known set or clear, then we know the
910     // top bits of the result.
911     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912     if (KnownZero & InSignBit) {          // Input sign bit known zero
913       KnownZero |= NewBits;
914       KnownOne &= ~NewBits;
915     } else if (KnownOne & InSignBit) {    // Input sign bit known set
916       KnownOne |= NewBits;
917       KnownZero &= ~NewBits;
918     } else {                              // Input sign bit unknown
919       KnownZero &= ~NewBits;
920       KnownOne &= ~NewBits;
921     }
922     return;
923   }
924   case Instruction::Shl:
925     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
926     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927       uint64_t ShiftAmt = SA->getZExtValue();
928       Mask >>= ShiftAmt;
929       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
931       KnownZero <<= ShiftAmt;
932       KnownOne  <<= ShiftAmt;
933       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
934       return;
935     }
936     break;
937   case Instruction::LShr:
938     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
939     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
940       // Compute the new bits that are at the top now.
941       uint64_t ShiftAmt = SA->getZExtValue();
942       uint64_t HighBits = (1ULL << ShiftAmt)-1;
943       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
944       
945       // Unsigned shift right.
946       Mask <<= ShiftAmt;
947       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
949       KnownZero >>= ShiftAmt;
950       KnownOne  >>= ShiftAmt;
951       KnownZero |= HighBits;  // high bits known zero.
952       return;
953     }
954     break;
955   case Instruction::AShr:
956     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
957     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958       // Compute the new bits that are at the top now.
959       uint64_t ShiftAmt = SA->getZExtValue();
960       uint64_t HighBits = (1ULL << ShiftAmt)-1;
961       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
962       
963       // Signed shift right.
964       Mask <<= ShiftAmt;
965       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
967       KnownZero >>= ShiftAmt;
968       KnownOne  >>= ShiftAmt;
969         
970       // Handle the sign bits.
971       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
973         
974       if (KnownZero & SignBit) {       // New bits are known zero.
975         KnownZero |= HighBits;
976       } else if (KnownOne & SignBit) { // New bits are known one.
977         KnownOne |= HighBits;
978       }
979       return;
980     }
981     break;
982   }
983 }
984
985 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
986 /// this predicate to simplify operations downstream.  Mask is known to be zero
987 /// for bits that V cannot have.
988 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
989   uint64_t KnownZero, KnownOne;
990   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
992   return (KnownZero & Mask) == Mask;
993 }
994
995 #if 0
996 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
997 /// this predicate to simplify operations downstream.  Mask is known to be zero
998 /// for bits that V cannot have.
999 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
1000   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1001   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1002   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1003   return (KnownZero & Mask) == Mask;
1004 }
1005 #endif
1006
1007 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1008 /// specified instruction is a constant integer.  If so, check to see if there
1009 /// are any bits set in the constant that are not demanded.  If so, shrink the
1010 /// constant and return true.
1011 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1012                                    uint64_t Demanded) {
1013   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1014   if (!OpC) return false;
1015
1016   // If there are no bits set that aren't demanded, nothing to do.
1017   if ((~Demanded & OpC->getZExtValue()) == 0)
1018     return false;
1019
1020   // This is producing any bits that are not needed, shrink the RHS.
1021   uint64_t Val = Demanded & OpC->getZExtValue();
1022   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
1023   return true;
1024 }
1025
1026 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1027 /// specified instruction is a constant integer.  If so, check to see if there
1028 /// are any bits set in the constant that are not demanded.  If so, shrink the
1029 /// constant and return true.
1030 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1031                                    APInt Demanded) {
1032   assert(I && "No instruction?");
1033   assert(OpNo < I->getNumOperands() && "Operand index too large");
1034
1035   // If the operand is not a constant integer, nothing to do.
1036   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1037   if (!OpC) return false;
1038
1039   // If there are no bits set that aren't demanded, nothing to do.
1040   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1041   if ((~Demanded & OpC->getValue()) == 0)
1042     return false;
1043
1044   // This instruction is producing bits that are not demanded. Shrink the RHS.
1045   Demanded &= OpC->getValue();
1046   I->setOperand(OpNo, ConstantInt::get(Demanded));
1047   return true;
1048 }
1049
1050 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1051 // set of known zero and one bits, compute the maximum and minimum values that
1052 // could have the specified known zero and known one bits, returning them in
1053 // min/max.
1054 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1055                                                    uint64_t KnownZero,
1056                                                    uint64_t KnownOne,
1057                                                    int64_t &Min, int64_t &Max) {
1058   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1059   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1060
1061   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1062   
1063   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1064   // bit if it is unknown.
1065   Min = KnownOne;
1066   Max = KnownOne|UnknownBits;
1067   
1068   if (SignBit & UnknownBits) { // Sign bit is unknown
1069     Min |= SignBit;
1070     Max &= ~SignBit;
1071   }
1072   
1073   // Sign extend the min/max values.
1074   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1075   Min = (Min << ShAmt) >> ShAmt;
1076   Max = (Max << ShAmt) >> ShAmt;
1077 }
1078
1079 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1080 // a set of known zero and one bits, compute the maximum and minimum values that
1081 // could have the specified known zero and known one bits, returning them in
1082 // min/max.
1083 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1084                                                      uint64_t KnownZero,
1085                                                      uint64_t KnownOne,
1086                                                      uint64_t &Min,
1087                                                      uint64_t &Max) {
1088   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
1089   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1090   
1091   // The minimum value is when the unknown bits are all zeros.
1092   Min = KnownOne;
1093   // The maximum value is when the unknown bits are all ones.
1094   Max = KnownOne|UnknownBits;
1095 }
1096
1097
1098 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
1099 /// DemandedMask bits of the result of V are ever used downstream.  If we can
1100 /// use this information to simplify V, do so and return true.  Otherwise,
1101 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1102 /// the expression (used to simplify the caller).  The KnownZero/One bits may
1103 /// only be accurate for those bits in the DemandedMask.
1104 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1105                                         uint64_t &KnownZero, uint64_t &KnownOne,
1106                                         unsigned Depth) {
1107   const IntegerType *VTy = cast<IntegerType>(V->getType());
1108   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1109     // We know all of the bits for a constant!
1110     KnownOne = CI->getZExtValue() & DemandedMask;
1111     KnownZero = ~KnownOne & DemandedMask;
1112     return false;
1113   }
1114   
1115   KnownZero = KnownOne = 0;
1116   if (!V->hasOneUse()) {    // Other users may use these bits.
1117     if (Depth != 0) {       // Not at the root.
1118       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1119       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1120       return false;
1121     }
1122     // If this is the root being simplified, allow it to have multiple uses,
1123     // just set the DemandedMask to all bits.
1124     DemandedMask = VTy->getBitMask();
1125   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1126     if (V != UndefValue::get(VTy))
1127       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1128     return false;
1129   } else if (Depth == 6) {        // Limit search depth.
1130     return false;
1131   }
1132   
1133   Instruction *I = dyn_cast<Instruction>(V);
1134   if (!I) return false;        // Only analyze instructions.
1135
1136   DemandedMask &= VTy->getBitMask();
1137   
1138   uint64_t KnownZero2 = 0, KnownOne2 = 0;
1139   switch (I->getOpcode()) {
1140   default: break;
1141   case Instruction::And:
1142     // If either the LHS or the RHS are Zero, the result is zero.
1143     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1144                              KnownZero, KnownOne, Depth+1))
1145       return true;
1146     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1147
1148     // If something is known zero on the RHS, the bits aren't demanded on the
1149     // LHS.
1150     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1151                              KnownZero2, KnownOne2, Depth+1))
1152       return true;
1153     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1154
1155     // If all of the demanded bits are known 1 on one side, return the other.
1156     // These bits cannot contribute to the result of the 'and'.
1157     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1158       return UpdateValueUsesWith(I, I->getOperand(0));
1159     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1160       return UpdateValueUsesWith(I, I->getOperand(1));
1161     
1162     // If all of the demanded bits in the inputs are known zeros, return zero.
1163     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
1164       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1165       
1166     // If the RHS is a constant, see if we can simplify it.
1167     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
1168       return UpdateValueUsesWith(I, I);
1169       
1170     // Output known-1 bits are only known if set in both the LHS & RHS.
1171     KnownOne &= KnownOne2;
1172     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1173     KnownZero |= KnownZero2;
1174     break;
1175   case Instruction::Or:
1176     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1177                              KnownZero, KnownOne, Depth+1))
1178       return true;
1179     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1180     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
1181                              KnownZero2, KnownOne2, Depth+1))
1182       return true;
1183     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1184     
1185     // If all of the demanded bits are known zero on one side, return the other.
1186     // These bits cannot contribute to the result of the 'or'.
1187     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
1188       return UpdateValueUsesWith(I, I->getOperand(0));
1189     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
1190       return UpdateValueUsesWith(I, I->getOperand(1));
1191
1192     // If all of the potentially set bits on one side are known to be set on
1193     // the other side, just use the 'other' side.
1194     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
1195         (DemandedMask & (~KnownZero)))
1196       return UpdateValueUsesWith(I, I->getOperand(0));
1197     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
1198         (DemandedMask & (~KnownZero2)))
1199       return UpdateValueUsesWith(I, I->getOperand(1));
1200         
1201     // If the RHS is a constant, see if we can simplify it.
1202     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1203       return UpdateValueUsesWith(I, I);
1204           
1205     // Output known-0 bits are only known if clear in both the LHS & RHS.
1206     KnownZero &= KnownZero2;
1207     // Output known-1 are known to be set if set in either the LHS | RHS.
1208     KnownOne |= KnownOne2;
1209     break;
1210   case Instruction::Xor: {
1211     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1212                              KnownZero, KnownOne, Depth+1))
1213       return true;
1214     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1215     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1216                              KnownZero2, KnownOne2, Depth+1))
1217       return true;
1218     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1219     
1220     // If all of the demanded bits are known zero on one side, return the other.
1221     // These bits cannot contribute to the result of the 'xor'.
1222     if ((DemandedMask & KnownZero) == DemandedMask)
1223       return UpdateValueUsesWith(I, I->getOperand(0));
1224     if ((DemandedMask & KnownZero2) == DemandedMask)
1225       return UpdateValueUsesWith(I, I->getOperand(1));
1226     
1227     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1228     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1229     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1230     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1231     
1232     // If all of the demanded bits are known to be zero on one side or the
1233     // other, turn this into an *inclusive* or.
1234     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1235     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1236       Instruction *Or =
1237         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1238                                  I->getName());
1239       InsertNewInstBefore(Or, *I);
1240       return UpdateValueUsesWith(I, Or);
1241     }
1242     
1243     // If all of the demanded bits on one side are known, and all of the set
1244     // bits on that side are also known to be set on the other side, turn this
1245     // into an AND, as we know the bits will be cleared.
1246     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1247     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1248       if ((KnownOne & KnownOne2) == KnownOne) {
1249         Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
1250         Instruction *And = 
1251           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1252         InsertNewInstBefore(And, *I);
1253         return UpdateValueUsesWith(I, And);
1254       }
1255     }
1256     
1257     // If the RHS is a constant, see if we can simplify it.
1258     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1259     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1260       return UpdateValueUsesWith(I, I);
1261     
1262     KnownZero = KnownZeroOut;
1263     KnownOne  = KnownOneOut;
1264     break;
1265   }
1266   case Instruction::Select:
1267     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1268                              KnownZero, KnownOne, Depth+1))
1269       return true;
1270     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1271                              KnownZero2, KnownOne2, Depth+1))
1272       return true;
1273     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1274     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1275     
1276     // If the operands are constants, see if we can simplify them.
1277     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1278       return UpdateValueUsesWith(I, I);
1279     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1280       return UpdateValueUsesWith(I, I);
1281     
1282     // Only known if known in both the LHS and RHS.
1283     KnownOne &= KnownOne2;
1284     KnownZero &= KnownZero2;
1285     break;
1286   case Instruction::Trunc:
1287     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1288                              KnownZero, KnownOne, Depth+1))
1289       return true;
1290     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1291     break;
1292   case Instruction::BitCast:
1293     if (!I->getOperand(0)->getType()->isInteger())
1294       return false;
1295       
1296     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1297                              KnownZero, KnownOne, Depth+1))
1298       return true;
1299     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1300     break;
1301   case Instruction::ZExt: {
1302     // Compute the bits in the result that are not present in the input.
1303     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1304     uint64_t NotIn = ~SrcTy->getBitMask();
1305     uint64_t NewBits = VTy->getBitMask() & NotIn;
1306     
1307     DemandedMask &= SrcTy->getBitMask();
1308     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1309                              KnownZero, KnownOne, Depth+1))
1310       return true;
1311     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1312     // The top bits are known to be zero.
1313     KnownZero |= NewBits;
1314     break;
1315   }
1316   case Instruction::SExt: {
1317     // Compute the bits in the result that are not present in the input.
1318     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1319     uint64_t NotIn = ~SrcTy->getBitMask();
1320     uint64_t NewBits = VTy->getBitMask() & NotIn;
1321     
1322     // Get the sign bit for the source type
1323     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1324     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1325
1326     // If any of the sign extended bits are demanded, we know that the sign
1327     // bit is demanded.
1328     if (NewBits & DemandedMask)
1329       InputDemandedBits |= InSignBit;
1330       
1331     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1332                              KnownZero, KnownOne, Depth+1))
1333       return true;
1334     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1335       
1336     // If the sign bit of the input is known set or clear, then we know the
1337     // top bits of the result.
1338
1339     // If the input sign bit is known zero, or if the NewBits are not demanded
1340     // convert this into a zero extension.
1341     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1342       // Convert to ZExt cast
1343       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1344       return UpdateValueUsesWith(I, NewCast);
1345     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1346       KnownOne |= NewBits;
1347       KnownZero &= ~NewBits;
1348     } else {                              // Input sign bit unknown
1349       KnownZero &= ~NewBits;
1350       KnownOne &= ~NewBits;
1351     }
1352     break;
1353   }
1354   case Instruction::Add:
1355     // If there is a constant on the RHS, there are a variety of xformations
1356     // we can do.
1357     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358       // If null, this should be simplified elsewhere.  Some of the xforms here
1359       // won't work if the RHS is zero.
1360       if (RHS->isNullValue())
1361         break;
1362       
1363       // Figure out what the input bits are.  If the top bits of the and result
1364       // are not demanded, then the add doesn't demand them from its input
1365       // either.
1366       
1367       // Shift the demanded mask up so that it's at the top of the uint64_t.
1368       unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1369       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1370       
1371       // If the top bit of the output is demanded, demand everything from the
1372       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1373       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1374
1375       // Find information about known zero/one bits in the input.
1376       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1377                                KnownZero2, KnownOne2, Depth+1))
1378         return true;
1379
1380       // If the RHS of the add has bits set that can't affect the input, reduce
1381       // the constant.
1382       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1383         return UpdateValueUsesWith(I, I);
1384       
1385       // Avoid excess work.
1386       if (KnownZero2 == 0 && KnownOne2 == 0)
1387         break;
1388       
1389       // Turn it into OR if input bits are zero.
1390       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1391         Instruction *Or =
1392           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1393                                    I->getName());
1394         InsertNewInstBefore(Or, *I);
1395         return UpdateValueUsesWith(I, Or);
1396       }
1397       
1398       // We can say something about the output known-zero and known-one bits,
1399       // depending on potential carries from the input constant and the
1400       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1401       // bits set and the RHS constant is 0x01001, then we know we have a known
1402       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1403       
1404       // To compute this, we first compute the potential carry bits.  These are
1405       // the bits which may be modified.  I'm not aware of a better way to do
1406       // this scan.
1407       uint64_t RHSVal = RHS->getZExtValue();
1408       
1409       bool CarryIn = false;
1410       uint64_t CarryBits = 0;
1411       uint64_t CurBit = 1;
1412       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1413         // Record the current carry in.
1414         if (CarryIn) CarryBits |= CurBit;
1415         
1416         bool CarryOut;
1417         
1418         // This bit has a carry out unless it is "zero + zero" or
1419         // "zero + anything" with no carry in.
1420         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1421           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1422         } else if (!CarryIn &&
1423                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1424           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1425         } else {
1426           // Otherwise, we have to assume we have a carry out.
1427           CarryOut = true;
1428         }
1429         
1430         // This stage's carry out becomes the next stage's carry-in.
1431         CarryIn = CarryOut;
1432       }
1433       
1434       // Now that we know which bits have carries, compute the known-1/0 sets.
1435       
1436       // Bits are known one if they are known zero in one operand and one in the
1437       // other, and there is no input carry.
1438       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1439       
1440       // Bits are known zero if they are known zero in both operands and there
1441       // is no input carry.
1442       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1443     } else {
1444       // If the high-bits of this ADD are not demanded, then it does not demand
1445       // the high bits of its LHS or RHS.
1446       if ((DemandedMask & VTy->getSignBit()) == 0) {
1447         // Right fill the mask of bits for this ADD to demand the most
1448         // significant bit and all those below it.
1449         unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1450         uint64_t DemandedFromOps = ~0ULL >> NLZ;
1451         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1452                                  KnownZero2, KnownOne2, Depth+1))
1453           return true;
1454         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1455                                  KnownZero2, KnownOne2, Depth+1))
1456           return true;
1457       }
1458     }
1459     break;
1460   case Instruction::Sub:
1461     // If the high-bits of this SUB are not demanded, then it does not demand
1462     // the high bits of its LHS or RHS.
1463     if ((DemandedMask & VTy->getSignBit()) == 0) {
1464       // Right fill the mask of bits for this SUB to demand the most
1465       // significant bit and all those below it.
1466       unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1467       uint64_t DemandedFromOps = ~0ULL >> NLZ;
1468       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1469                                KnownZero2, KnownOne2, Depth+1))
1470         return true;
1471       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1472                                KnownZero2, KnownOne2, Depth+1))
1473         return true;
1474     }
1475     break;
1476   case Instruction::Shl:
1477     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1478       uint64_t ShiftAmt = SA->getZExtValue();
1479       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1480                                KnownZero, KnownOne, Depth+1))
1481         return true;
1482       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1483       KnownZero <<= ShiftAmt;
1484       KnownOne  <<= ShiftAmt;
1485       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1486     }
1487     break;
1488   case Instruction::LShr:
1489     // For a logical shift right
1490     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1491       unsigned ShiftAmt = SA->getZExtValue();
1492       
1493       // Compute the new bits that are at the top now.
1494       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1495       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1496       uint64_t TypeMask = VTy->getBitMask();
1497       // Unsigned shift right.
1498       if (SimplifyDemandedBits(I->getOperand(0),
1499                               (DemandedMask << ShiftAmt) & TypeMask,
1500                                KnownZero, KnownOne, Depth+1))
1501         return true;
1502       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1503       KnownZero &= TypeMask;
1504       KnownOne  &= TypeMask;
1505       KnownZero >>= ShiftAmt;
1506       KnownOne  >>= ShiftAmt;
1507       KnownZero |= HighBits;  // high bits known zero.
1508     }
1509     break;
1510   case Instruction::AShr:
1511     // If this is an arithmetic shift right and only the low-bit is set, we can
1512     // always convert this into a logical shr, even if the shift amount is
1513     // variable.  The low bit of the shift cannot be an input sign bit unless
1514     // the shift amount is >= the size of the datatype, which is undefined.
1515     if (DemandedMask == 1) {
1516       // Perform the logical shift right.
1517       Value *NewVal = BinaryOperator::createLShr(
1518                         I->getOperand(0), I->getOperand(1), I->getName());
1519       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1520       return UpdateValueUsesWith(I, NewVal);
1521     }    
1522     
1523     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1524       unsigned ShiftAmt = SA->getZExtValue();
1525       
1526       // Compute the new bits that are at the top now.
1527       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1528       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1529       uint64_t TypeMask = VTy->getBitMask();
1530       // Signed shift right.
1531       if (SimplifyDemandedBits(I->getOperand(0),
1532                                (DemandedMask << ShiftAmt) & TypeMask,
1533                                KnownZero, KnownOne, Depth+1))
1534         return true;
1535       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1536       KnownZero &= TypeMask;
1537       KnownOne  &= TypeMask;
1538       KnownZero >>= ShiftAmt;
1539       KnownOne  >>= ShiftAmt;
1540         
1541       // Handle the sign bits.
1542       uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
1543       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1544         
1545       // If the input sign bit is known to be zero, or if none of the top bits
1546       // are demanded, turn this into an unsigned shift right.
1547       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1548         // Perform the logical shift right.
1549         Value *NewVal = BinaryOperator::createLShr(
1550                           I->getOperand(0), SA, I->getName());
1551         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1552         return UpdateValueUsesWith(I, NewVal);
1553       } else if (KnownOne & SignBit) { // New bits are known one.
1554         KnownOne |= HighBits;
1555       }
1556     }
1557     break;
1558   }
1559   
1560   // If the client is only demanding bits that we know, return the known
1561   // constant.
1562   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1563     return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
1564   return false;
1565 }  
1566
1567 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1568 /// value based on the demanded bits. When this function is called, it is known
1569 /// that only the bits set in DemandedMask of the result of V are ever used
1570 /// downstream. Consequently, depending on the mask and V, it may be possible
1571 /// to replace V with a constant or one of its operands. In such cases, this
1572 /// function does the replacement and returns true. In all other cases, it
1573 /// returns false after analyzing the expression and setting KnownOne and known
1574 /// to be one in the expression. KnownZero contains all the bits that are known
1575 /// to be zero in the expression. These are provided to potentially allow the
1576 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1577 /// the expression. KnownOne and KnownZero always follow the invariant that 
1578 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1579 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1580 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1581 /// and KnownOne must all be the same.
1582 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1583                                         APInt& KnownZero, APInt& KnownOne,
1584                                         unsigned Depth) {
1585   assert(V != 0 && "Null pointer of Value???");
1586   assert(Depth <= 6 && "Limit Search Depth");
1587   uint32_t BitWidth = DemandedMask.getBitWidth();
1588   const IntegerType *VTy = cast<IntegerType>(V->getType());
1589   assert(VTy->getBitWidth() == BitWidth && 
1590          KnownZero.getBitWidth() == BitWidth && 
1591          KnownOne.getBitWidth() == BitWidth &&
1592          "Value *V, DemandedMask, KnownZero and KnownOne \
1593           must have same BitWidth");
1594   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1595     // We know all of the bits for a constant!
1596     KnownOne = CI->getValue() & DemandedMask;
1597     KnownZero = ~KnownOne & DemandedMask;
1598     return false;
1599   }
1600   
1601   KnownZero.clear(); 
1602   KnownOne.clear();
1603   if (!V->hasOneUse()) {    // Other users may use these bits.
1604     if (Depth != 0) {       // Not at the root.
1605       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1606       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1607       return false;
1608     }
1609     // If this is the root being simplified, allow it to have multiple uses,
1610     // just set the DemandedMask to all bits.
1611     DemandedMask = APInt::getAllOnesValue(BitWidth);
1612   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1613     if (V != UndefValue::get(VTy))
1614       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1615     return false;
1616   } else if (Depth == 6) {        // Limit search depth.
1617     return false;
1618   }
1619   
1620   Instruction *I = dyn_cast<Instruction>(V);
1621   if (!I) return false;        // Only analyze instructions.
1622
1623   DemandedMask &= APInt::getAllOnesValue(BitWidth);
1624   
1625   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1626   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1627   switch (I->getOpcode()) {
1628   default: break;
1629   case Instruction::And:
1630     // If either the LHS or the RHS are Zero, the result is zero.
1631     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1632                              RHSKnownZero, RHSKnownOne, Depth+1))
1633       return true;
1634     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1635            "Bits known to be one AND zero?"); 
1636
1637     // If something is known zero on the RHS, the bits aren't demanded on the
1638     // LHS.
1639     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1640                              LHSKnownZero, LHSKnownOne, Depth+1))
1641       return true;
1642     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1643            "Bits known to be one AND zero?"); 
1644
1645     // If all of the demanded bits are known 1 on one side, return the other.
1646     // These bits cannot contribute to the result of the 'and'.
1647     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1648         (DemandedMask & ~LHSKnownZero))
1649       return UpdateValueUsesWith(I, I->getOperand(0));
1650     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1651         (DemandedMask & ~RHSKnownZero))
1652       return UpdateValueUsesWith(I, I->getOperand(1));
1653     
1654     // If all of the demanded bits in the inputs are known zeros, return zero.
1655     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1656       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1657       
1658     // If the RHS is a constant, see if we can simplify it.
1659     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1660       return UpdateValueUsesWith(I, I);
1661       
1662     // Output known-1 bits are only known if set in both the LHS & RHS.
1663     RHSKnownOne &= LHSKnownOne;
1664     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1665     RHSKnownZero |= LHSKnownZero;
1666     break;
1667   case Instruction::Or:
1668     // If either the LHS or the RHS are One, the result is One.
1669     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1670                              RHSKnownZero, RHSKnownOne, Depth+1))
1671       return true;
1672     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1673            "Bits known to be one AND zero?"); 
1674     // If something is known one on the RHS, the bits aren't demanded on the
1675     // LHS.
1676     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1677                              LHSKnownZero, LHSKnownOne, Depth+1))
1678       return true;
1679     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1680            "Bits known to be one AND zero?"); 
1681     
1682     // If all of the demanded bits are known zero on one side, return the other.
1683     // These bits cannot contribute to the result of the 'or'.
1684     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1685         (DemandedMask & ~LHSKnownOne))
1686       return UpdateValueUsesWith(I, I->getOperand(0));
1687     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1688         (DemandedMask & ~RHSKnownOne))
1689       return UpdateValueUsesWith(I, I->getOperand(1));
1690
1691     // If all of the potentially set bits on one side are known to be set on
1692     // the other side, just use the 'other' side.
1693     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1694         (DemandedMask & (~RHSKnownZero)))
1695       return UpdateValueUsesWith(I, I->getOperand(0));
1696     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1697         (DemandedMask & (~LHSKnownZero)))
1698       return UpdateValueUsesWith(I, I->getOperand(1));
1699         
1700     // If the RHS is a constant, see if we can simplify it.
1701     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1702       return UpdateValueUsesWith(I, I);
1703           
1704     // Output known-0 bits are only known if clear in both the LHS & RHS.
1705     RHSKnownZero &= LHSKnownZero;
1706     // Output known-1 are known to be set if set in either the LHS | RHS.
1707     RHSKnownOne |= LHSKnownOne;
1708     break;
1709   case Instruction::Xor: {
1710     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1711                              RHSKnownZero, RHSKnownOne, Depth+1))
1712       return true;
1713     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1714            "Bits known to be one AND zero?"); 
1715     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1716                              LHSKnownZero, LHSKnownOne, Depth+1))
1717       return true;
1718     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1719            "Bits known to be one AND zero?"); 
1720     
1721     // If all of the demanded bits are known zero on one side, return the other.
1722     // These bits cannot contribute to the result of the 'xor'.
1723     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1724       return UpdateValueUsesWith(I, I->getOperand(0));
1725     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1726       return UpdateValueUsesWith(I, I->getOperand(1));
1727     
1728     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1729     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1730                          (RHSKnownOne & LHSKnownOne);
1731     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1732     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1733                         (RHSKnownOne & LHSKnownZero);
1734     
1735     // If all of the demanded bits are known to be zero on one side or the
1736     // other, turn this into an *inclusive* or.
1737     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1738     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1739       Instruction *Or =
1740         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1741                                  I->getName());
1742       InsertNewInstBefore(Or, *I);
1743       return UpdateValueUsesWith(I, Or);
1744     }
1745     
1746     // If all of the demanded bits on one side are known, and all of the set
1747     // bits on that side are also known to be set on the other side, turn this
1748     // into an AND, as we know the bits will be cleared.
1749     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1750     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1751       // all known
1752       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1753         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1754         Instruction *And = 
1755           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1756         InsertNewInstBefore(And, *I);
1757         return UpdateValueUsesWith(I, And);
1758       }
1759     }
1760     
1761     // If the RHS is a constant, see if we can simplify it.
1762     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1763     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1764       return UpdateValueUsesWith(I, I);
1765     
1766     RHSKnownZero = KnownZeroOut;
1767     RHSKnownOne  = KnownOneOut;
1768     break;
1769   }
1770   case Instruction::Select:
1771     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1772                              RHSKnownZero, RHSKnownOne, Depth+1))
1773       return true;
1774     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1775                              LHSKnownZero, LHSKnownOne, Depth+1))
1776       return true;
1777     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1778            "Bits known to be one AND zero?"); 
1779     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1780            "Bits known to be one AND zero?"); 
1781     
1782     // If the operands are constants, see if we can simplify them.
1783     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1784       return UpdateValueUsesWith(I, I);
1785     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1786       return UpdateValueUsesWith(I, I);
1787     
1788     // Only known if known in both the LHS and RHS.
1789     RHSKnownOne &= LHSKnownOne;
1790     RHSKnownZero &= LHSKnownZero;
1791     break;
1792   case Instruction::Trunc: {
1793     uint32_t truncBf = 
1794       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1795     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1796         RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1797       return true;
1798     DemandedMask.trunc(BitWidth);
1799     RHSKnownZero.trunc(BitWidth);
1800     RHSKnownOne.trunc(BitWidth);
1801     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1802            "Bits known to be one AND zero?"); 
1803     break;
1804   }
1805   case Instruction::BitCast:
1806     if (!I->getOperand(0)->getType()->isInteger())
1807       return false;
1808       
1809     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1810                              RHSKnownZero, RHSKnownOne, Depth+1))
1811       return true;
1812     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1813            "Bits known to be one AND zero?"); 
1814     break;
1815   case Instruction::ZExt: {
1816     // Compute the bits in the result that are not present in the input.
1817     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1818     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1819     
1820     DemandedMask &= SrcTy->getMask().zext(BitWidth);
1821     uint32_t zextBf = SrcTy->getBitWidth();
1822     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1823           RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1824       return true;
1825     DemandedMask.zext(BitWidth);
1826     RHSKnownZero.zext(BitWidth);
1827     RHSKnownOne.zext(BitWidth);
1828     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1829            "Bits known to be one AND zero?"); 
1830     // The top bits are known to be zero.
1831     RHSKnownZero |= NewBits;
1832     break;
1833   }
1834   case Instruction::SExt: {
1835     // Compute the bits in the result that are not present in the input.
1836     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1837     APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1838     
1839     // Get the sign bit for the source type
1840     APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1841     InSignBit.zext(BitWidth);
1842     APInt InputDemandedBits = DemandedMask & 
1843                               SrcTy->getMask().zext(BitWidth);
1844
1845     // If any of the sign extended bits are demanded, we know that the sign
1846     // bit is demanded.
1847     if ((NewBits & DemandedMask) != 0)
1848       InputDemandedBits |= InSignBit;
1849       
1850     uint32_t sextBf = SrcTy->getBitWidth();
1851     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1852           RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1853       return true;
1854     InputDemandedBits.zext(BitWidth);
1855     RHSKnownZero.zext(BitWidth);
1856     RHSKnownOne.zext(BitWidth);
1857     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1858            "Bits known to be one AND zero?"); 
1859       
1860     // If the sign bit of the input is known set or clear, then we know the
1861     // top bits of the result.
1862
1863     // If the input sign bit is known zero, or if the NewBits are not demanded
1864     // convert this into a zero extension.
1865     if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1866     {
1867       // Convert to ZExt cast
1868       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1869       return UpdateValueUsesWith(I, NewCast);
1870     } else if ((RHSKnownOne & InSignBit) != 0) {    // Input sign bit known set
1871       RHSKnownOne |= NewBits;
1872       RHSKnownZero &= ~NewBits;
1873     } else {                              // Input sign bit unknown
1874       RHSKnownZero &= ~NewBits;
1875       RHSKnownOne &= ~NewBits;
1876     }
1877     break;
1878   }
1879   case Instruction::Add: {
1880     // Figure out what the input bits are.  If the top bits of the and result
1881     // are not demanded, then the add doesn't demand them from its input
1882     // either.
1883     unsigned NLZ = DemandedMask.countLeadingZeros();
1884       
1885     // If there is a constant on the RHS, there are a variety of xformations
1886     // we can do.
1887     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1888       // If null, this should be simplified elsewhere.  Some of the xforms here
1889       // won't work if the RHS is zero.
1890       if (RHS->isZero())
1891         break;
1892       
1893       // If the top bit of the output is demanded, demand everything from the
1894       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1895       APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1896
1897       // Find information about known zero/one bits in the input.
1898       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1899                                LHSKnownZero, LHSKnownOne, Depth+1))
1900         return true;
1901
1902       // If the RHS of the add has bits set that can't affect the input, reduce
1903       // the constant.
1904       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1905         return UpdateValueUsesWith(I, I);
1906       
1907       // Avoid excess work.
1908       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1909         break;
1910       
1911       // Turn it into OR if input bits are zero.
1912       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1913         Instruction *Or =
1914           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1915                                    I->getName());
1916         InsertNewInstBefore(Or, *I);
1917         return UpdateValueUsesWith(I, Or);
1918       }
1919       
1920       // We can say something about the output known-zero and known-one bits,
1921       // depending on potential carries from the input constant and the
1922       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1923       // bits set and the RHS constant is 0x01001, then we know we have a known
1924       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1925       
1926       // To compute this, we first compute the potential carry bits.  These are
1927       // the bits which may be modified.  I'm not aware of a better way to do
1928       // this scan.
1929       APInt RHSVal(RHS->getValue());
1930       
1931       bool CarryIn = false;
1932       APInt CarryBits(BitWidth, 0);
1933       const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1934                      *RHSRawVal = RHSVal.getRawData();
1935       for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1936         uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1937                  XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1938         uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1939         if (AddVal < RHSRawVal[i])
1940           CarryIn = true;
1941         else
1942           CarryIn = false;
1943         CarryBits.setWordToValue(i, WordCarryBits);
1944       }
1945       
1946       // Now that we know which bits have carries, compute the known-1/0 sets.
1947       
1948       // Bits are known one if they are known zero in one operand and one in the
1949       // other, and there is no input carry.
1950       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1951                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1952       
1953       // Bits are known zero if they are known zero in both operands and there
1954       // is no input carry.
1955       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1956     } else {
1957       // If the high-bits of this ADD are not demanded, then it does not demand
1958       // the high bits of its LHS or RHS.
1959       if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1960         // Right fill the mask of bits for this ADD to demand the most
1961         // significant bit and all those below it.
1962         APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1963         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1964                                  LHSKnownZero, LHSKnownOne, Depth+1))
1965           return true;
1966         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1967                                  LHSKnownZero, LHSKnownOne, Depth+1))
1968           return true;
1969       }
1970     }
1971     break;
1972   }
1973   case Instruction::Sub:
1974     // If the high-bits of this SUB are not demanded, then it does not demand
1975     // the high bits of its LHS or RHS.
1976     if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1977       // Right fill the mask of bits for this SUB to demand the most
1978       // significant bit and all those below it.
1979       unsigned NLZ = DemandedMask.countLeadingZeros();
1980       APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1981       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1982                                LHSKnownZero, LHSKnownOne, Depth+1))
1983         return true;
1984       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1985                                LHSKnownZero, LHSKnownOne, Depth+1))
1986         return true;
1987     }
1988     break;
1989   case Instruction::Shl:
1990     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1991       uint64_t ShiftAmt = SA->getZExtValue();
1992       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt), 
1993                                RHSKnownZero, RHSKnownOne, Depth+1))
1994         return true;
1995       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1996              "Bits known to be one AND zero?"); 
1997       RHSKnownZero <<= ShiftAmt;
1998       RHSKnownOne  <<= ShiftAmt;
1999       // low bits known zero.
2000       if (ShiftAmt)
2001         RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
2002     }
2003     break;
2004   case Instruction::LShr:
2005     // For a logical shift right
2006     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2007       unsigned ShiftAmt = SA->getZExtValue();
2008       
2009       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2010       // Unsigned shift right.
2011       if (SimplifyDemandedBits(I->getOperand(0),
2012                               (DemandedMask.shl(ShiftAmt)) & TypeMask,
2013                                RHSKnownZero, RHSKnownOne, Depth+1))
2014         return true;
2015       assert((RHSKnownZero & RHSKnownOne) == 0 && 
2016              "Bits known to be one AND zero?"); 
2017       RHSKnownZero &= TypeMask;
2018       RHSKnownOne  &= TypeMask;
2019       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2020       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2021       if (ShiftAmt) {
2022         // Compute the new bits that are at the top now.
2023         APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
2024                          BitWidth - ShiftAmt));
2025         RHSKnownZero |= HighBits;  // high bits known zero.
2026       }
2027     }
2028     break;
2029   case Instruction::AShr:
2030     // If this is an arithmetic shift right and only the low-bit is set, we can
2031     // always convert this into a logical shr, even if the shift amount is
2032     // variable.  The low bit of the shift cannot be an input sign bit unless
2033     // the shift amount is >= the size of the datatype, which is undefined.
2034     if (DemandedMask == 1) {
2035       // Perform the logical shift right.
2036       Value *NewVal = BinaryOperator::createLShr(
2037                         I->getOperand(0), I->getOperand(1), I->getName());
2038       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2039       return UpdateValueUsesWith(I, NewVal);
2040     }    
2041     
2042     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2043       unsigned ShiftAmt = SA->getZExtValue();
2044       
2045       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2046       // Signed shift right.
2047       if (SimplifyDemandedBits(I->getOperand(0),
2048                                (DemandedMask.shl(ShiftAmt)) & TypeMask,
2049                                RHSKnownZero, RHSKnownOne, Depth+1))
2050         return true;
2051       assert((RHSKnownZero & RHSKnownOne) == 0 && 
2052              "Bits known to be one AND zero?"); 
2053       // Compute the new bits that are at the top now.
2054       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
2055       RHSKnownZero &= TypeMask;
2056       RHSKnownOne  &= TypeMask;
2057       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2058       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2059         
2060       // Handle the sign bits.
2061       APInt SignBit(APInt::getSignBit(BitWidth));
2062       // Adjust to where it is now in the mask.
2063       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
2064         
2065       // If the input sign bit is known to be zero, or if none of the top bits
2066       // are demanded, turn this into an unsigned shift right.
2067       if ((RHSKnownZero & SignBit) != 0 || 
2068           (HighBits & ~DemandedMask) == HighBits) {
2069         // Perform the logical shift right.
2070         Value *NewVal = BinaryOperator::createLShr(
2071                           I->getOperand(0), SA, I->getName());
2072         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2073         return UpdateValueUsesWith(I, NewVal);
2074       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2075         RHSKnownOne |= HighBits;
2076       }
2077     }
2078     break;
2079   }
2080   
2081   // If the client is only demanding bits that we know, return the known
2082   // constant.
2083   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2084     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2085   return false;
2086 }
2087
2088
2089 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
2090 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
2091 /// actually used by the caller.  This method analyzes which elements of the
2092 /// operand are undef and returns that information in UndefElts.
2093 ///
2094 /// If the information about demanded elements can be used to simplify the
2095 /// operation, the operation is simplified, then the resultant value is
2096 /// returned.  This returns null if no change was made.
2097 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2098                                                 uint64_t &UndefElts,
2099                                                 unsigned Depth) {
2100   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
2101   assert(VWidth <= 64 && "Vector too wide to analyze!");
2102   uint64_t EltMask = ~0ULL >> (64-VWidth);
2103   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2104          "Invalid DemandedElts!");
2105
2106   if (isa<UndefValue>(V)) {
2107     // If the entire vector is undefined, just return this info.
2108     UndefElts = EltMask;
2109     return 0;
2110   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2111     UndefElts = EltMask;
2112     return UndefValue::get(V->getType());
2113   }
2114   
2115   UndefElts = 0;
2116   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2117     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2118     Constant *Undef = UndefValue::get(EltTy);
2119
2120     std::vector<Constant*> Elts;
2121     for (unsigned i = 0; i != VWidth; ++i)
2122       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
2123         Elts.push_back(Undef);
2124         UndefElts |= (1ULL << i);
2125       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
2126         Elts.push_back(Undef);
2127         UndefElts |= (1ULL << i);
2128       } else {                               // Otherwise, defined.
2129         Elts.push_back(CP->getOperand(i));
2130       }
2131         
2132     // If we changed the constant, return it.
2133     Constant *NewCP = ConstantVector::get(Elts);
2134     return NewCP != CP ? NewCP : 0;
2135   } else if (isa<ConstantAggregateZero>(V)) {
2136     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
2137     // set to undef.
2138     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
2139     Constant *Zero = Constant::getNullValue(EltTy);
2140     Constant *Undef = UndefValue::get(EltTy);
2141     std::vector<Constant*> Elts;
2142     for (unsigned i = 0; i != VWidth; ++i)
2143       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2144     UndefElts = DemandedElts ^ EltMask;
2145     return ConstantVector::get(Elts);
2146   }
2147   
2148   if (!V->hasOneUse()) {    // Other users may use these bits.
2149     if (Depth != 0) {       // Not at the root.
2150       // TODO: Just compute the UndefElts information recursively.
2151       return false;
2152     }
2153     return false;
2154   } else if (Depth == 10) {        // Limit search depth.
2155     return false;
2156   }
2157   
2158   Instruction *I = dyn_cast<Instruction>(V);
2159   if (!I) return false;        // Only analyze instructions.
2160   
2161   bool MadeChange = false;
2162   uint64_t UndefElts2;
2163   Value *TmpV;
2164   switch (I->getOpcode()) {
2165   default: break;
2166     
2167   case Instruction::InsertElement: {
2168     // If this is a variable index, we don't know which element it overwrites.
2169     // demand exactly the same input as we produce.
2170     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
2171     if (Idx == 0) {
2172       // Note that we can't propagate undef elt info, because we don't know
2173       // which elt is getting updated.
2174       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2175                                         UndefElts2, Depth+1);
2176       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2177       break;
2178     }
2179     
2180     // If this is inserting an element that isn't demanded, remove this
2181     // insertelement.
2182     unsigned IdxNo = Idx->getZExtValue();
2183     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2184       return AddSoonDeadInstToWorklist(*I, 0);
2185     
2186     // Otherwise, the element inserted overwrites whatever was there, so the
2187     // input demanded set is simpler than the output set.
2188     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2189                                       DemandedElts & ~(1ULL << IdxNo),
2190                                       UndefElts, Depth+1);
2191     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2192
2193     // The inserted element is defined.
2194     UndefElts |= 1ULL << IdxNo;
2195     break;
2196   }
2197     
2198   case Instruction::And:
2199   case Instruction::Or:
2200   case Instruction::Xor:
2201   case Instruction::Add:
2202   case Instruction::Sub:
2203   case Instruction::Mul:
2204     // div/rem demand all inputs, because they don't want divide by zero.
2205     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2206                                       UndefElts, Depth+1);
2207     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2208     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2209                                       UndefElts2, Depth+1);
2210     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2211       
2212     // Output elements are undefined if both are undefined.  Consider things
2213     // like undef&0.  The result is known zero, not undef.
2214     UndefElts &= UndefElts2;
2215     break;
2216     
2217   case Instruction::Call: {
2218     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2219     if (!II) break;
2220     switch (II->getIntrinsicID()) {
2221     default: break;
2222       
2223     // Binary vector operations that work column-wise.  A dest element is a
2224     // function of the corresponding input elements from the two inputs.
2225     case Intrinsic::x86_sse_sub_ss:
2226     case Intrinsic::x86_sse_mul_ss:
2227     case Intrinsic::x86_sse_min_ss:
2228     case Intrinsic::x86_sse_max_ss:
2229     case Intrinsic::x86_sse2_sub_sd:
2230     case Intrinsic::x86_sse2_mul_sd:
2231     case Intrinsic::x86_sse2_min_sd:
2232     case Intrinsic::x86_sse2_max_sd:
2233       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2234                                         UndefElts, Depth+1);
2235       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2236       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2237                                         UndefElts2, Depth+1);
2238       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2239
2240       // If only the low elt is demanded and this is a scalarizable intrinsic,
2241       // scalarize it now.
2242       if (DemandedElts == 1) {
2243         switch (II->getIntrinsicID()) {
2244         default: break;
2245         case Intrinsic::x86_sse_sub_ss:
2246         case Intrinsic::x86_sse_mul_ss:
2247         case Intrinsic::x86_sse2_sub_sd:
2248         case Intrinsic::x86_sse2_mul_sd:
2249           // TODO: Lower MIN/MAX/ABS/etc
2250           Value *LHS = II->getOperand(1);
2251           Value *RHS = II->getOperand(2);
2252           // Extract the element as scalars.
2253           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2254           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2255           
2256           switch (II->getIntrinsicID()) {
2257           default: assert(0 && "Case stmts out of sync!");
2258           case Intrinsic::x86_sse_sub_ss:
2259           case Intrinsic::x86_sse2_sub_sd:
2260             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2261                                                         II->getName()), *II);
2262             break;
2263           case Intrinsic::x86_sse_mul_ss:
2264           case Intrinsic::x86_sse2_mul_sd:
2265             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2266                                                          II->getName()), *II);
2267             break;
2268           }
2269           
2270           Instruction *New =
2271             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2272                                   II->getName());
2273           InsertNewInstBefore(New, *II);
2274           AddSoonDeadInstToWorklist(*II, 0);
2275           return New;
2276         }            
2277       }
2278         
2279       // Output elements are undefined if both are undefined.  Consider things
2280       // like undef&0.  The result is known zero, not undef.
2281       UndefElts &= UndefElts2;
2282       break;
2283     }
2284     break;
2285   }
2286   }
2287   return MadeChange ? I : 0;
2288 }
2289
2290 /// @returns true if the specified compare instruction is
2291 /// true when both operands are equal...
2292 /// @brief Determine if the ICmpInst returns true if both operands are equal
2293 static bool isTrueWhenEqual(ICmpInst &ICI) {
2294   ICmpInst::Predicate pred = ICI.getPredicate();
2295   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
2296          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2297          pred == ICmpInst::ICMP_SLE;
2298 }
2299
2300 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2301 /// function is designed to check a chain of associative operators for a
2302 /// potential to apply a certain optimization.  Since the optimization may be
2303 /// applicable if the expression was reassociated, this checks the chain, then
2304 /// reassociates the expression as necessary to expose the optimization
2305 /// opportunity.  This makes use of a special Functor, which must define
2306 /// 'shouldApply' and 'apply' methods.
2307 ///
2308 template<typename Functor>
2309 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2310   unsigned Opcode = Root.getOpcode();
2311   Value *LHS = Root.getOperand(0);
2312
2313   // Quick check, see if the immediate LHS matches...
2314   if (F.shouldApply(LHS))
2315     return F.apply(Root);
2316
2317   // Otherwise, if the LHS is not of the same opcode as the root, return.
2318   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2319   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2320     // Should we apply this transform to the RHS?
2321     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2322
2323     // If not to the RHS, check to see if we should apply to the LHS...
2324     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2325       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2326       ShouldApply = true;
2327     }
2328
2329     // If the functor wants to apply the optimization to the RHS of LHSI,
2330     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2331     if (ShouldApply) {
2332       BasicBlock *BB = Root.getParent();
2333
2334       // Now all of the instructions are in the current basic block, go ahead
2335       // and perform the reassociation.
2336       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2337
2338       // First move the selected RHS to the LHS of the root...
2339       Root.setOperand(0, LHSI->getOperand(1));
2340
2341       // Make what used to be the LHS of the root be the user of the root...
2342       Value *ExtraOperand = TmpLHSI->getOperand(1);
2343       if (&Root == TmpLHSI) {
2344         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2345         return 0;
2346       }
2347       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2348       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2349       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2350       BasicBlock::iterator ARI = &Root; ++ARI;
2351       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2352       ARI = Root;
2353
2354       // Now propagate the ExtraOperand down the chain of instructions until we
2355       // get to LHSI.
2356       while (TmpLHSI != LHSI) {
2357         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2358         // Move the instruction to immediately before the chain we are
2359         // constructing to avoid breaking dominance properties.
2360         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2361         BB->getInstList().insert(ARI, NextLHSI);
2362         ARI = NextLHSI;
2363
2364         Value *NextOp = NextLHSI->getOperand(1);
2365         NextLHSI->setOperand(1, ExtraOperand);
2366         TmpLHSI = NextLHSI;
2367         ExtraOperand = NextOp;
2368       }
2369
2370       // Now that the instructions are reassociated, have the functor perform
2371       // the transformation...
2372       return F.apply(Root);
2373     }
2374
2375     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2376   }
2377   return 0;
2378 }
2379
2380
2381 // AddRHS - Implements: X + X --> X << 1
2382 struct AddRHS {
2383   Value *RHS;
2384   AddRHS(Value *rhs) : RHS(rhs) {}
2385   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2386   Instruction *apply(BinaryOperator &Add) const {
2387     return BinaryOperator::createShl(Add.getOperand(0),
2388                                   ConstantInt::get(Add.getType(), 1));
2389   }
2390 };
2391
2392 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2393 //                 iff C1&C2 == 0
2394 struct AddMaskingAnd {
2395   Constant *C2;
2396   AddMaskingAnd(Constant *c) : C2(c) {}
2397   bool shouldApply(Value *LHS) const {
2398     ConstantInt *C1;
2399     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2400            ConstantExpr::getAnd(C1, C2)->isNullValue();
2401   }
2402   Instruction *apply(BinaryOperator &Add) const {
2403     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
2404   }
2405 };
2406
2407 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2408                                              InstCombiner *IC) {
2409   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2410     if (Constant *SOC = dyn_cast<Constant>(SO))
2411       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2412
2413     return IC->InsertNewInstBefore(CastInst::create(
2414           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2415   }
2416
2417   // Figure out if the constant is the left or the right argument.
2418   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2419   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2420
2421   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2422     if (ConstIsRHS)
2423       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2424     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2425   }
2426
2427   Value *Op0 = SO, *Op1 = ConstOperand;
2428   if (!ConstIsRHS)
2429     std::swap(Op0, Op1);
2430   Instruction *New;
2431   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2432     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2433   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2434     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2435                           SO->getName()+".cmp");
2436   else {
2437     assert(0 && "Unknown binary instruction type!");
2438     abort();
2439   }
2440   return IC->InsertNewInstBefore(New, I);
2441 }
2442
2443 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2444 // constant as the other operand, try to fold the binary operator into the
2445 // select arguments.  This also works for Cast instructions, which obviously do
2446 // not have a second operand.
2447 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2448                                      InstCombiner *IC) {
2449   // Don't modify shared select instructions
2450   if (!SI->hasOneUse()) return 0;
2451   Value *TV = SI->getOperand(1);
2452   Value *FV = SI->getOperand(2);
2453
2454   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2455     // Bool selects with constant operands can be folded to logical ops.
2456     if (SI->getType() == Type::Int1Ty) return 0;
2457
2458     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2459     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2460
2461     return new SelectInst(SI->getCondition(), SelectTrueVal,
2462                           SelectFalseVal);
2463   }
2464   return 0;
2465 }
2466
2467
2468 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2469 /// node as operand #0, see if we can fold the instruction into the PHI (which
2470 /// is only possible if all operands to the PHI are constants).
2471 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2472   PHINode *PN = cast<PHINode>(I.getOperand(0));
2473   unsigned NumPHIValues = PN->getNumIncomingValues();
2474   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2475
2476   // Check to see if all of the operands of the PHI are constants.  If there is
2477   // one non-constant value, remember the BB it is.  If there is more than one
2478   // or if *it* is a PHI, bail out.
2479   BasicBlock *NonConstBB = 0;
2480   for (unsigned i = 0; i != NumPHIValues; ++i)
2481     if (!isa<Constant>(PN->getIncomingValue(i))) {
2482       if (NonConstBB) return 0;  // More than one non-const value.
2483       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2484       NonConstBB = PN->getIncomingBlock(i);
2485       
2486       // If the incoming non-constant value is in I's block, we have an infinite
2487       // loop.
2488       if (NonConstBB == I.getParent())
2489         return 0;
2490     }
2491   
2492   // If there is exactly one non-constant value, we can insert a copy of the
2493   // operation in that block.  However, if this is a critical edge, we would be
2494   // inserting the computation one some other paths (e.g. inside a loop).  Only
2495   // do this if the pred block is unconditionally branching into the phi block.
2496   if (NonConstBB) {
2497     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2498     if (!BI || !BI->isUnconditional()) return 0;
2499   }
2500
2501   // Okay, we can do the transformation: create the new PHI node.
2502   PHINode *NewPN = new PHINode(I.getType(), "");
2503   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2504   InsertNewInstBefore(NewPN, *PN);
2505   NewPN->takeName(PN);
2506
2507   // Next, add all of the operands to the PHI.
2508   if (I.getNumOperands() == 2) {
2509     Constant *C = cast<Constant>(I.getOperand(1));
2510     for (unsigned i = 0; i != NumPHIValues; ++i) {
2511       Value *InV;
2512       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2513         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2514           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2515         else
2516           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2517       } else {
2518         assert(PN->getIncomingBlock(i) == NonConstBB);
2519         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2520           InV = BinaryOperator::create(BO->getOpcode(),
2521                                        PN->getIncomingValue(i), C, "phitmp",
2522                                        NonConstBB->getTerminator());
2523         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2524           InV = CmpInst::create(CI->getOpcode(), 
2525                                 CI->getPredicate(),
2526                                 PN->getIncomingValue(i), C, "phitmp",
2527                                 NonConstBB->getTerminator());
2528         else
2529           assert(0 && "Unknown binop!");
2530         
2531         AddToWorkList(cast<Instruction>(InV));
2532       }
2533       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2534     }
2535   } else { 
2536     CastInst *CI = cast<CastInst>(&I);
2537     const Type *RetTy = CI->getType();
2538     for (unsigned i = 0; i != NumPHIValues; ++i) {
2539       Value *InV;
2540       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2541         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2542       } else {
2543         assert(PN->getIncomingBlock(i) == NonConstBB);
2544         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
2545                                I.getType(), "phitmp", 
2546                                NonConstBB->getTerminator());
2547         AddToWorkList(cast<Instruction>(InV));
2548       }
2549       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2550     }
2551   }
2552   return ReplaceInstUsesWith(I, NewPN);
2553 }
2554
2555 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2556   bool Changed = SimplifyCommutative(I);
2557   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2558
2559   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2560     // X + undef -> undef
2561     if (isa<UndefValue>(RHS))
2562       return ReplaceInstUsesWith(I, RHS);
2563
2564     // X + 0 --> X
2565     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2566       if (RHSC->isNullValue())
2567         return ReplaceInstUsesWith(I, LHS);
2568     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2569       if (CFP->isExactlyValue(-0.0))
2570         return ReplaceInstUsesWith(I, LHS);
2571     }
2572
2573     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2574       // X + (signbit) --> X ^ signbit
2575       uint64_t Val = CI->getZExtValue();
2576       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
2577         return BinaryOperator::createXor(LHS, RHS);
2578       
2579       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2580       // (X & 254)+1 -> (X&254)|1
2581       uint64_t KnownZero, KnownOne;
2582       if (!isa<VectorType>(I.getType()) &&
2583           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
2584                                KnownZero, KnownOne))
2585         return &I;
2586     }
2587
2588     if (isa<PHINode>(LHS))
2589       if (Instruction *NV = FoldOpIntoPhi(I))
2590         return NV;
2591     
2592     ConstantInt *XorRHS = 0;
2593     Value *XorLHS = 0;
2594     if (isa<ConstantInt>(RHSC) &&
2595         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2596       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2597       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2598       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2599       
2600       uint64_t C0080Val = 1ULL << 31;
2601       int64_t CFF80Val = -C0080Val;
2602       unsigned Size = 32;
2603       do {
2604         if (TySizeBits > Size) {
2605           bool Found = false;
2606           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2607           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2608           if (RHSSExt == CFF80Val) {
2609             if (XorRHS->getZExtValue() == C0080Val)
2610               Found = true;
2611           } else if (RHSZExt == C0080Val) {
2612             if (XorRHS->getSExtValue() == CFF80Val)
2613               Found = true;
2614           }
2615           if (Found) {
2616             // This is a sign extend if the top bits are known zero.
2617             uint64_t Mask = ~0ULL;
2618             Mask <<= 64-(TySizeBits-Size);
2619             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
2620             if (!MaskedValueIsZero(XorLHS, Mask))
2621               Size = 0;  // Not a sign ext, but can't be any others either.
2622             goto FoundSExt;
2623           }
2624         }
2625         Size >>= 1;
2626         C0080Val >>= Size;
2627         CFF80Val >>= Size;
2628       } while (Size >= 8);
2629       
2630 FoundSExt:
2631       const Type *MiddleType = 0;
2632       switch (Size) {
2633       default: break;
2634       case 32: MiddleType = Type::Int32Ty; break;
2635       case 16: MiddleType = Type::Int16Ty; break;
2636       case 8:  MiddleType = Type::Int8Ty; break;
2637       }
2638       if (MiddleType) {
2639         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2640         InsertNewInstBefore(NewTrunc, I);
2641         return new SExtInst(NewTrunc, I.getType());
2642       }
2643     }
2644   }
2645
2646   // X + X --> X << 1
2647   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2648     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2649
2650     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2651       if (RHSI->getOpcode() == Instruction::Sub)
2652         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2653           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2654     }
2655     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2656       if (LHSI->getOpcode() == Instruction::Sub)
2657         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2658           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2659     }
2660   }
2661
2662   // -A + B  -->  B - A
2663   if (Value *V = dyn_castNegVal(LHS))
2664     return BinaryOperator::createSub(RHS, V);
2665
2666   // A + -B  -->  A - B
2667   if (!isa<Constant>(RHS))
2668     if (Value *V = dyn_castNegVal(RHS))
2669       return BinaryOperator::createSub(LHS, V);
2670
2671
2672   ConstantInt *C2;
2673   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2674     if (X == RHS)   // X*C + X --> X * (C+1)
2675       return BinaryOperator::createMul(RHS, AddOne(C2));
2676
2677     // X*C1 + X*C2 --> X * (C1+C2)
2678     ConstantInt *C1;
2679     if (X == dyn_castFoldableMul(RHS, C1))
2680       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
2681   }
2682
2683   // X + X*C --> X * (C+1)
2684   if (dyn_castFoldableMul(RHS, C2) == LHS)
2685     return BinaryOperator::createMul(LHS, AddOne(C2));
2686
2687   // X + ~X --> -1   since   ~X = -X-1
2688   if (dyn_castNotVal(LHS) == RHS ||
2689       dyn_castNotVal(RHS) == LHS)
2690     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2691   
2692
2693   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2694   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2695     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696       return R;
2697
2698   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2699     Value *X = 0;
2700     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
2701       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2702       return BinaryOperator::createSub(C, X);
2703     }
2704
2705     // (X & FF00) + xx00  -> (X+xx00) & FF00
2706     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2707       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2708       if (Anded == CRHS) {
2709         // See if all bits from the first bit set in the Add RHS up are included
2710         // in the mask.  First, get the rightmost bit.
2711         uint64_t AddRHSV = CRHS->getZExtValue();
2712
2713         // Form a mask of all bits from the lowest bit added through the top.
2714         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2715         AddRHSHighBits &= C2->getType()->getBitMask();
2716
2717         // See if the and mask includes all of these bits.
2718         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
2719
2720         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2721           // Okay, the xform is safe.  Insert the new add pronto.
2722           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2723                                                             LHS->getName()), I);
2724           return BinaryOperator::createAnd(NewAdd, C2);
2725         }
2726       }
2727     }
2728
2729     // Try to fold constant add into select arguments.
2730     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2731       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2732         return R;
2733   }
2734
2735   // add (cast *A to intptrtype) B -> 
2736   //   cast (GEP (cast *A to sbyte*) B) -> 
2737   //     intptrtype
2738   {
2739     CastInst *CI = dyn_cast<CastInst>(LHS);
2740     Value *Other = RHS;
2741     if (!CI) {
2742       CI = dyn_cast<CastInst>(RHS);
2743       Other = LHS;
2744     }
2745     if (CI && CI->getType()->isSized() && 
2746         (CI->getType()->getPrimitiveSizeInBits() == 
2747          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2748         && isa<PointerType>(CI->getOperand(0)->getType())) {
2749       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2750                                    PointerType::get(Type::Int8Ty), I);
2751       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2752       return new PtrToIntInst(I2, CI->getType());
2753     }
2754   }
2755
2756   return Changed ? &I : 0;
2757 }
2758
2759 // isSignBit - Return true if the value represented by the constant only has the
2760 // highest order bit set.
2761 static bool isSignBit(ConstantInt *CI) {
2762   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
2763   return CI->getValue() == APInt::getSignBit(NumBits);
2764 }
2765
2766 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2767   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2768
2769   if (Op0 == Op1)         // sub X, X  -> 0
2770     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2771
2772   // If this is a 'B = x-(-A)', change to B = x+A...
2773   if (Value *V = dyn_castNegVal(Op1))
2774     return BinaryOperator::createAdd(Op0, V);
2775
2776   if (isa<UndefValue>(Op0))
2777     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2778   if (isa<UndefValue>(Op1))
2779     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2780
2781   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2782     // Replace (-1 - A) with (~A)...
2783     if (C->isAllOnesValue())
2784       return BinaryOperator::createNot(Op1);
2785
2786     // C - ~X == X + (1+C)
2787     Value *X = 0;
2788     if (match(Op1, m_Not(m_Value(X))))
2789       return BinaryOperator::createAdd(X,
2790                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2791     // -(X >>u 31) -> (X >>s 31)
2792     // -(X >>s 31) -> (X >>u 31)
2793     if (C->isNullValue()) {
2794       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2795         if (SI->getOpcode() == Instruction::LShr) {
2796           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2797             // Check to see if we are shifting out everything but the sign bit.
2798             if (CU->getZExtValue() == 
2799                 SI->getType()->getPrimitiveSizeInBits()-1) {
2800               // Ok, the transformation is safe.  Insert AShr.
2801               return BinaryOperator::create(Instruction::AShr, 
2802                                           SI->getOperand(0), CU, SI->getName());
2803             }
2804           }
2805         }
2806         else if (SI->getOpcode() == Instruction::AShr) {
2807           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2808             // Check to see if we are shifting out everything but the sign bit.
2809             if (CU->getZExtValue() == 
2810                 SI->getType()->getPrimitiveSizeInBits()-1) {
2811               // Ok, the transformation is safe.  Insert LShr. 
2812               return BinaryOperator::createLShr(
2813                                           SI->getOperand(0), CU, SI->getName());
2814             }
2815           }
2816         } 
2817     }
2818
2819     // Try to fold constant sub into select arguments.
2820     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2821       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2822         return R;
2823
2824     if (isa<PHINode>(Op0))
2825       if (Instruction *NV = FoldOpIntoPhi(I))
2826         return NV;
2827   }
2828
2829   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2830     if (Op1I->getOpcode() == Instruction::Add &&
2831         !Op0->getType()->isFPOrFPVector()) {
2832       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2833         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2834       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2835         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2836       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2837         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2838           // C1-(X+C2) --> (C1-C2)-X
2839           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2840                                            Op1I->getOperand(0));
2841       }
2842     }
2843
2844     if (Op1I->hasOneUse()) {
2845       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2846       // is not used by anyone else...
2847       //
2848       if (Op1I->getOpcode() == Instruction::Sub &&
2849           !Op1I->getType()->isFPOrFPVector()) {
2850         // Swap the two operands of the subexpr...
2851         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2852         Op1I->setOperand(0, IIOp1);
2853         Op1I->setOperand(1, IIOp0);
2854
2855         // Create the new top level add instruction...
2856         return BinaryOperator::createAdd(Op0, Op1);
2857       }
2858
2859       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2860       //
2861       if (Op1I->getOpcode() == Instruction::And &&
2862           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2863         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2864
2865         Value *NewNot =
2866           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2867         return BinaryOperator::createAnd(Op0, NewNot);
2868       }
2869
2870       // 0 - (X sdiv C)  -> (X sdiv -C)
2871       if (Op1I->getOpcode() == Instruction::SDiv)
2872         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2873           if (CSI->isNullValue())
2874             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2875               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2876                                                ConstantExpr::getNeg(DivRHS));
2877
2878       // X - X*C --> X * (1-C)
2879       ConstantInt *C2 = 0;
2880       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2881         Constant *CP1 =
2882           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2883         return BinaryOperator::createMul(Op0, CP1);
2884       }
2885     }
2886   }
2887
2888   if (!Op0->getType()->isFPOrFPVector())
2889     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2890       if (Op0I->getOpcode() == Instruction::Add) {
2891         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2892           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2893         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2894           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2895       } else if (Op0I->getOpcode() == Instruction::Sub) {
2896         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2897           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2898       }
2899
2900   ConstantInt *C1;
2901   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2902     if (X == Op1) { // X*C - X --> X * (C-1)
2903       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2904       return BinaryOperator::createMul(Op1, CP1);
2905     }
2906
2907     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2908     if (X == dyn_castFoldableMul(Op1, C2))
2909       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2910   }
2911   return 0;
2912 }
2913
2914 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2915 /// really just returns true if the most significant (sign) bit is set.
2916 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2917   switch (pred) {
2918     case ICmpInst::ICMP_SLT: 
2919       // True if LHS s< RHS and RHS == 0
2920       return RHS->isNullValue();
2921     case ICmpInst::ICMP_SLE: 
2922       // True if LHS s<= RHS and RHS == -1
2923       return RHS->isAllOnesValue();
2924     case ICmpInst::ICMP_UGE: 
2925       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2926       return RHS->getZExtValue() == (1ULL << 
2927         (RHS->getType()->getPrimitiveSizeInBits()-1));
2928     case ICmpInst::ICMP_UGT:
2929       // True if LHS u> RHS and RHS == high-bit-mask - 1
2930       return RHS->getZExtValue() ==
2931         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2932     default:
2933       return false;
2934   }
2935 }
2936
2937 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2938   bool Changed = SimplifyCommutative(I);
2939   Value *Op0 = I.getOperand(0);
2940
2941   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2942     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2943
2944   // Simplify mul instructions with a constant RHS...
2945   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2946     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2947
2948       // ((X << C1)*C2) == (X * (C2 << C1))
2949       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2950         if (SI->getOpcode() == Instruction::Shl)
2951           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2952             return BinaryOperator::createMul(SI->getOperand(0),
2953                                              ConstantExpr::getShl(CI, ShOp));
2954
2955       if (CI->isNullValue())
2956         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2957       if (CI->equalsInt(1))                  // X * 1  == X
2958         return ReplaceInstUsesWith(I, Op0);
2959       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2960         return BinaryOperator::createNeg(Op0, I.getName());
2961
2962       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2963       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2964         uint64_t C = Log2_64(Val);
2965         return BinaryOperator::createShl(Op0,
2966                                       ConstantInt::get(Op0->getType(), C));
2967       }
2968     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2969       if (Op1F->isNullValue())
2970         return ReplaceInstUsesWith(I, Op1);
2971
2972       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2973       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2974       if (Op1F->getValue() == 1.0)
2975         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2976     }
2977     
2978     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2979       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2980           isa<ConstantInt>(Op0I->getOperand(1))) {
2981         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2982         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2983                                                      Op1, "tmp");
2984         InsertNewInstBefore(Add, I);
2985         Value *C1C2 = ConstantExpr::getMul(Op1, 
2986                                            cast<Constant>(Op0I->getOperand(1)));
2987         return BinaryOperator::createAdd(Add, C1C2);
2988         
2989       }
2990
2991     // Try to fold constant mul into select arguments.
2992     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994         return R;
2995
2996     if (isa<PHINode>(Op0))
2997       if (Instruction *NV = FoldOpIntoPhi(I))
2998         return NV;
2999   }
3000
3001   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3002     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3003       return BinaryOperator::createMul(Op0v, Op1v);
3004
3005   // If one of the operands of the multiply is a cast from a boolean value, then
3006   // we know the bool is either zero or one, so this is a 'masking' multiply.
3007   // See if we can simplify things based on how the boolean was originally
3008   // formed.
3009   CastInst *BoolCast = 0;
3010   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3011     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3012       BoolCast = CI;
3013   if (!BoolCast)
3014     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3015       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3016         BoolCast = CI;
3017   if (BoolCast) {
3018     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3019       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3020       const Type *SCOpTy = SCIOp0->getType();
3021
3022       // If the icmp is true iff the sign bit of X is set, then convert this
3023       // multiply into a shift/and combination.
3024       if (isa<ConstantInt>(SCIOp1) &&
3025           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
3026         // Shift the X value right to turn it into "all signbits".
3027         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3028                                           SCOpTy->getPrimitiveSizeInBits()-1);
3029         Value *V =
3030           InsertNewInstBefore(
3031             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
3032                                             BoolCast->getOperand(0)->getName()+
3033                                             ".mask"), I);
3034
3035         // If the multiply type is not the same as the source type, sign extend
3036         // or truncate to the multiply type.
3037         if (I.getType() != V->getType()) {
3038           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3039           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3040           Instruction::CastOps opcode = 
3041             (SrcBits == DstBits ? Instruction::BitCast : 
3042              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3043           V = InsertCastBefore(opcode, V, I.getType(), I);
3044         }
3045
3046         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3047         return BinaryOperator::createAnd(V, OtherOp);
3048       }
3049     }
3050   }
3051
3052   return Changed ? &I : 0;
3053 }
3054
3055 /// This function implements the transforms on div instructions that work
3056 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3057 /// used by the visitors to those instructions.
3058 /// @brief Transforms common to all three div instructions
3059 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3060   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062   // undef / X -> 0
3063   if (isa<UndefValue>(Op0))
3064     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3065
3066   // X / undef -> undef
3067   if (isa<UndefValue>(Op1))
3068     return ReplaceInstUsesWith(I, Op1);
3069
3070   // Handle cases involving: div X, (select Cond, Y, Z)
3071   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3072     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
3073     // same basic block, then we replace the select with Y, and the condition 
3074     // of the select with false (if the cond value is in the same BB).  If the
3075     // select has uses other than the div, this allows them to be simplified
3076     // also. Note that div X, Y is just as good as div X, 0 (undef)
3077     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3078       if (ST->isNullValue()) {
3079         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3080         if (CondI && CondI->getParent() == I.getParent())
3081           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3082         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3083           I.setOperand(1, SI->getOperand(2));
3084         else
3085           UpdateValueUsesWith(SI, SI->getOperand(2));
3086         return &I;
3087       }
3088
3089     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3090     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3091       if (ST->isNullValue()) {
3092         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3093         if (CondI && CondI->getParent() == I.getParent())
3094           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3095         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3096           I.setOperand(1, SI->getOperand(1));
3097         else
3098           UpdateValueUsesWith(SI, SI->getOperand(1));
3099         return &I;
3100       }
3101   }
3102
3103   return 0;
3104 }
3105
3106 /// This function implements the transforms common to both integer division
3107 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3108 /// division instructions.
3109 /// @brief Common integer divide transforms
3110 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3111   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113   if (Instruction *Common = commonDivTransforms(I))
3114     return Common;
3115
3116   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117     // div X, 1 == X
3118     if (RHS->equalsInt(1))
3119       return ReplaceInstUsesWith(I, Op0);
3120
3121     // (X / C1) / C2  -> X / (C1*C2)
3122     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3123       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3124         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3125           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3126                                         ConstantExpr::getMul(RHS, LHSRHS));
3127         }
3128
3129     if (!RHS->isNullValue()) { // avoid X udiv 0
3130       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3131         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3132           return R;
3133       if (isa<PHINode>(Op0))
3134         if (Instruction *NV = FoldOpIntoPhi(I))
3135           return NV;
3136     }
3137   }
3138
3139   // 0 / X == 0, we don't need to preserve faults!
3140   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3141     if (LHS->equalsInt(0))
3142       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3143
3144   return 0;
3145 }
3146
3147 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3148   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149
3150   // Handle the integer div common cases
3151   if (Instruction *Common = commonIDivTransforms(I))
3152     return Common;
3153
3154   // X udiv C^2 -> X >> C
3155   // Check to see if this is an unsigned division with an exact power of 2,
3156   // if so, convert to a right shift.
3157   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3158     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
3159       if (isPowerOf2_64(Val)) {
3160         uint64_t ShiftAmt = Log2_64(Val);
3161         return BinaryOperator::createLShr(Op0, 
3162                                     ConstantInt::get(Op0->getType(), ShiftAmt));
3163       }
3164   }
3165
3166   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3167   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3168     if (RHSI->getOpcode() == Instruction::Shl &&
3169         isa<ConstantInt>(RHSI->getOperand(0))) {
3170       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3171       if (isPowerOf2_64(C1)) {
3172         Value *N = RHSI->getOperand(1);
3173         const Type *NTy = N->getType();
3174         if (uint64_t C2 = Log2_64(C1)) {
3175           Constant *C2V = ConstantInt::get(NTy, C2);
3176           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
3177         }
3178         return BinaryOperator::createLShr(Op0, N);
3179       }
3180     }
3181   }
3182   
3183   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3184   // where C1&C2 are powers of two.
3185   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3186     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3187       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3188         uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3189         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3190           // Compute the shift amounts
3191           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3192           // Construct the "on true" case of the select
3193           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3194           Instruction *TSI = BinaryOperator::createLShr(
3195                                                  Op0, TC, SI->getName()+".t");
3196           TSI = InsertNewInstBefore(TSI, I);
3197   
3198           // Construct the "on false" case of the select
3199           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3200           Instruction *FSI = BinaryOperator::createLShr(
3201                                                  Op0, FC, SI->getName()+".f");
3202           FSI = InsertNewInstBefore(FSI, I);
3203
3204           // construct the select instruction and return it.
3205           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
3206         }
3207       }
3208   return 0;
3209 }
3210
3211 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3212   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3213
3214   // Handle the integer div common cases
3215   if (Instruction *Common = commonIDivTransforms(I))
3216     return Common;
3217
3218   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3219     // sdiv X, -1 == -X
3220     if (RHS->isAllOnesValue())
3221       return BinaryOperator::createNeg(Op0);
3222
3223     // -X/C -> X/-C
3224     if (Value *LHSNeg = dyn_castNegVal(Op0))
3225       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3226   }
3227
3228   // If the sign bits of both operands are zero (i.e. we can prove they are
3229   // unsigned inputs), turn this into a udiv.
3230   if (I.getType()->isInteger()) {
3231     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3232     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3233       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3234     }
3235   }      
3236   
3237   return 0;
3238 }
3239
3240 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3241   return commonDivTransforms(I);
3242 }
3243
3244 /// GetFactor - If we can prove that the specified value is at least a multiple
3245 /// of some factor, return that factor.
3246 static Constant *GetFactor(Value *V) {
3247   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3248     return CI;
3249   
3250   // Unless we can be tricky, we know this is a multiple of 1.
3251   Constant *Result = ConstantInt::get(V->getType(), 1);
3252   
3253   Instruction *I = dyn_cast<Instruction>(V);
3254   if (!I) return Result;
3255   
3256   if (I->getOpcode() == Instruction::Mul) {
3257     // Handle multiplies by a constant, etc.
3258     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3259                                 GetFactor(I->getOperand(1)));
3260   } else if (I->getOpcode() == Instruction::Shl) {
3261     // (X<<C) -> X * (1 << C)
3262     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3263       ShRHS = ConstantExpr::getShl(Result, ShRHS);
3264       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3265     }
3266   } else if (I->getOpcode() == Instruction::And) {
3267     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3268       // X & 0xFFF0 is known to be a multiple of 16.
3269       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3270       if (Zeros != V->getType()->getPrimitiveSizeInBits())
3271         return ConstantExpr::getShl(Result, 
3272                                     ConstantInt::get(Result->getType(), Zeros));
3273     }
3274   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3275     // Only handle int->int casts.
3276     if (!CI->isIntegerCast())
3277       return Result;
3278     Value *Op = CI->getOperand(0);
3279     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
3280   }    
3281   return Result;
3282 }
3283
3284 /// This function implements the transforms on rem instructions that work
3285 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3286 /// is used by the visitors to those instructions.
3287 /// @brief Transforms common to all three rem instructions
3288 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3289   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3290
3291   // 0 % X == 0, we don't need to preserve faults!
3292   if (Constant *LHS = dyn_cast<Constant>(Op0))
3293     if (LHS->isNullValue())
3294       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3295
3296   if (isa<UndefValue>(Op0))              // undef % X -> 0
3297     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3298   if (isa<UndefValue>(Op1))
3299     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3300
3301   // Handle cases involving: rem X, (select Cond, Y, Z)
3302   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3303     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3304     // the same basic block, then we replace the select with Y, and the
3305     // condition of the select with false (if the cond value is in the same
3306     // BB).  If the select has uses other than the div, this allows them to be
3307     // simplified also.
3308     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3309       if (ST->isNullValue()) {
3310         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3311         if (CondI && CondI->getParent() == I.getParent())
3312           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3313         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3314           I.setOperand(1, SI->getOperand(2));
3315         else
3316           UpdateValueUsesWith(SI, SI->getOperand(2));
3317         return &I;
3318       }
3319     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3320     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3321       if (ST->isNullValue()) {
3322         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3323         if (CondI && CondI->getParent() == I.getParent())
3324           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3325         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3326           I.setOperand(1, SI->getOperand(1));
3327         else
3328           UpdateValueUsesWith(SI, SI->getOperand(1));
3329         return &I;
3330       }
3331   }
3332
3333   return 0;
3334 }
3335
3336 /// This function implements the transforms common to both integer remainder
3337 /// instructions (urem and srem). It is called by the visitors to those integer
3338 /// remainder instructions.
3339 /// @brief Common integer remainder transforms
3340 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3341   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3342
3343   if (Instruction *common = commonRemTransforms(I))
3344     return common;
3345
3346   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3347     // X % 0 == undef, we don't need to preserve faults!
3348     if (RHS->equalsInt(0))
3349       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3350     
3351     if (RHS->equalsInt(1))  // X % 1 == 0
3352       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3353
3354     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3355       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3356         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3357           return R;
3358       } else if (isa<PHINode>(Op0I)) {
3359         if (Instruction *NV = FoldOpIntoPhi(I))
3360           return NV;
3361       }
3362       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
3363       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
3364         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3365     }
3366   }
3367
3368   return 0;
3369 }
3370
3371 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3372   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3373
3374   if (Instruction *common = commonIRemTransforms(I))
3375     return common;
3376   
3377   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3378     // X urem C^2 -> X and C
3379     // Check to see if this is an unsigned remainder with an exact power of 2,
3380     // if so, convert to a bitwise and.
3381     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3382       if (isPowerOf2_64(C->getZExtValue()))
3383         return BinaryOperator::createAnd(Op0, SubOne(C));
3384   }
3385
3386   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3387     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3388     if (RHSI->getOpcode() == Instruction::Shl &&
3389         isa<ConstantInt>(RHSI->getOperand(0))) {
3390       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3391       if (isPowerOf2_64(C1)) {
3392         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3393         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3394                                                                    "tmp"), I);
3395         return BinaryOperator::createAnd(Op0, Add);
3396       }
3397     }
3398   }
3399
3400   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3401   // where C1&C2 are powers of two.
3402   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3403     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3404       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3405         // STO == 0 and SFO == 0 handled above.
3406         if (isPowerOf2_64(STO->getZExtValue()) && 
3407             isPowerOf2_64(SFO->getZExtValue())) {
3408           Value *TrueAnd = InsertNewInstBefore(
3409             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3410           Value *FalseAnd = InsertNewInstBefore(
3411             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3412           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3413         }
3414       }
3415   }
3416   
3417   return 0;
3418 }
3419
3420 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3421   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3422
3423   if (Instruction *common = commonIRemTransforms(I))
3424     return common;
3425   
3426   if (Value *RHSNeg = dyn_castNegVal(Op1))
3427     if (!isa<ConstantInt>(RHSNeg) || 
3428         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3429       // X % -Y -> X % Y
3430       AddUsesToWorkList(I);
3431       I.setOperand(1, RHSNeg);
3432       return &I;
3433     }
3434  
3435   // If the top bits of both operands are zero (i.e. we can prove they are
3436   // unsigned inputs), turn this into a urem.
3437   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3438   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3439     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3440     return BinaryOperator::createURem(Op0, Op1, I.getName());
3441   }
3442
3443   return 0;
3444 }
3445
3446 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3447   return commonRemTransforms(I);
3448 }
3449
3450 // isMaxValueMinusOne - return true if this is Max-1
3451 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3452   if (isSigned) {
3453     // Calculate 0111111111..11111
3454     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
3455     int64_t Val = INT64_MAX;             // All ones
3456     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
3457     return C->getSExtValue() == Val-1;
3458   }
3459   return C->getZExtValue() == C->getType()->getBitMask()-1;
3460 }
3461
3462 // isMinValuePlusOne - return true if this is Min+1
3463 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3464   if (isSigned) {
3465     // Calculate 1111111111000000000000
3466     uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3467     APInt Val(APInt::getSignedMinValue(TypeBits));
3468     return C->getValue() == Val+1;
3469   }
3470   return C->getValue() == 1; // unsigned
3471 }
3472
3473 // isOneBitSet - Return true if there is exactly one bit set in the specified
3474 // constant.
3475 static bool isOneBitSet(const ConstantInt *CI) {
3476   return CI->getValue().countPopulation() == 1;
3477 }
3478
3479 #if 0   // Currently unused
3480 // isLowOnes - Return true if the constant is of the form 0+1+.
3481 static bool isLowOnes(const ConstantInt *CI) {
3482   uint64_t V = CI->getZExtValue();
3483
3484   // There won't be bits set in parts that the type doesn't contain.
3485   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
3486
3487   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
3488   return U && V && (U & V) == 0;
3489 }
3490 #endif
3491
3492 // isHighOnes - Return true if the constant is of the form 1+0+.
3493 // This is the same as lowones(~X).
3494 static bool isHighOnes(const ConstantInt *CI) {
3495   uint64_t V = ~CI->getZExtValue();
3496   if (~V == 0) return false;  // 0's does not match "1+"
3497
3498   // There won't be bits set in parts that the type doesn't contain.
3499   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
3500
3501   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
3502   return U && V && (U & V) == 0;
3503 }
3504
3505 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3506 /// are carefully arranged to allow folding of expressions such as:
3507 ///
3508 ///      (A < B) | (A > B) --> (A != B)
3509 ///
3510 /// Note that this is only valid if the first and second predicates have the
3511 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3512 ///
3513 /// Three bits are used to represent the condition, as follows:
3514 ///   0  A > B
3515 ///   1  A == B
3516 ///   2  A < B
3517 ///
3518 /// <=>  Value  Definition
3519 /// 000     0   Always false
3520 /// 001     1   A >  B
3521 /// 010     2   A == B
3522 /// 011     3   A >= B
3523 /// 100     4   A <  B
3524 /// 101     5   A != B
3525 /// 110     6   A <= B
3526 /// 111     7   Always true
3527 ///  
3528 static unsigned getICmpCode(const ICmpInst *ICI) {
3529   switch (ICI->getPredicate()) {
3530     // False -> 0
3531   case ICmpInst::ICMP_UGT: return 1;  // 001
3532   case ICmpInst::ICMP_SGT: return 1;  // 001
3533   case ICmpInst::ICMP_EQ:  return 2;  // 010
3534   case ICmpInst::ICMP_UGE: return 3;  // 011
3535   case ICmpInst::ICMP_SGE: return 3;  // 011
3536   case ICmpInst::ICMP_ULT: return 4;  // 100
3537   case ICmpInst::ICMP_SLT: return 4;  // 100
3538   case ICmpInst::ICMP_NE:  return 5;  // 101
3539   case ICmpInst::ICMP_ULE: return 6;  // 110
3540   case ICmpInst::ICMP_SLE: return 6;  // 110
3541     // True -> 7
3542   default:
3543     assert(0 && "Invalid ICmp predicate!");
3544     return 0;
3545   }
3546 }
3547
3548 /// getICmpValue - This is the complement of getICmpCode, which turns an
3549 /// opcode and two operands into either a constant true or false, or a brand 
3550 /// new /// ICmp instruction. The sign is passed in to determine which kind
3551 /// of predicate to use in new icmp instructions.
3552 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3553   switch (code) {
3554   default: assert(0 && "Illegal ICmp code!");
3555   case  0: return ConstantInt::getFalse();
3556   case  1: 
3557     if (sign)
3558       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3559     else
3560       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3561   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3562   case  3: 
3563     if (sign)
3564       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3565     else
3566       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3567   case  4: 
3568     if (sign)
3569       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3570     else
3571       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3572   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3573   case  6: 
3574     if (sign)
3575       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3576     else
3577       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3578   case  7: return ConstantInt::getTrue();
3579   }
3580 }
3581
3582 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3583   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3584     (ICmpInst::isSignedPredicate(p1) && 
3585      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3586     (ICmpInst::isSignedPredicate(p2) && 
3587      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3588 }
3589
3590 namespace { 
3591 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3592 struct FoldICmpLogical {
3593   InstCombiner &IC;
3594   Value *LHS, *RHS;
3595   ICmpInst::Predicate pred;
3596   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3597     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3598       pred(ICI->getPredicate()) {}
3599   bool shouldApply(Value *V) const {
3600     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3601       if (PredicatesFoldable(pred, ICI->getPredicate()))
3602         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3603                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3604     return false;
3605   }
3606   Instruction *apply(Instruction &Log) const {
3607     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3608     if (ICI->getOperand(0) != LHS) {
3609       assert(ICI->getOperand(1) == LHS);
3610       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3611     }
3612
3613     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3614     unsigned LHSCode = getICmpCode(ICI);
3615     unsigned RHSCode = getICmpCode(RHSICI);
3616     unsigned Code;
3617     switch (Log.getOpcode()) {
3618     case Instruction::And: Code = LHSCode & RHSCode; break;
3619     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3620     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3621     default: assert(0 && "Illegal logical opcode!"); return 0;
3622     }
3623
3624     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3625                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3626       
3627     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3628     if (Instruction *I = dyn_cast<Instruction>(RV))
3629       return I;
3630     // Otherwise, it's a constant boolean value...
3631     return IC.ReplaceInstUsesWith(Log, RV);
3632   }
3633 };
3634 } // end anonymous namespace
3635
3636 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3637 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3638 // guaranteed to be a binary operator.
3639 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3640                                     ConstantInt *OpRHS,
3641                                     ConstantInt *AndRHS,
3642                                     BinaryOperator &TheAnd) {
3643   Value *X = Op->getOperand(0);
3644   Constant *Together = 0;
3645   if (!Op->isShift())
3646     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3647
3648   switch (Op->getOpcode()) {
3649   case Instruction::Xor:
3650     if (Op->hasOneUse()) {
3651       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3652       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3653       InsertNewInstBefore(And, TheAnd);
3654       And->takeName(Op);
3655       return BinaryOperator::createXor(And, Together);
3656     }
3657     break;
3658   case Instruction::Or:
3659     if (Together == AndRHS) // (X | C) & C --> C
3660       return ReplaceInstUsesWith(TheAnd, AndRHS);
3661
3662     if (Op->hasOneUse() && Together != OpRHS) {
3663       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3664       Instruction *Or = BinaryOperator::createOr(X, Together);
3665       InsertNewInstBefore(Or, TheAnd);
3666       Or->takeName(Op);
3667       return BinaryOperator::createAnd(Or, AndRHS);
3668     }
3669     break;
3670   case Instruction::Add:
3671     if (Op->hasOneUse()) {
3672       // Adding a one to a single bit bit-field should be turned into an XOR
3673       // of the bit.  First thing to check is to see if this AND is with a
3674       // single bit constant.
3675       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
3676
3677       // Clear bits that are not part of the constant.
3678       AndRHSV &= AndRHS->getType()->getBitMask();
3679
3680       // If there is only one bit set...
3681       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3682         // Ok, at this point, we know that we are masking the result of the
3683         // ADD down to exactly one bit.  If the constant we are adding has
3684         // no bits set below this bit, then we can eliminate the ADD.
3685         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
3686
3687         // Check to see if any bits below the one bit set in AndRHSV are set.
3688         if ((AddRHS & (AndRHSV-1)) == 0) {
3689           // If not, the only thing that can effect the output of the AND is
3690           // the bit specified by AndRHSV.  If that bit is set, the effect of
3691           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3692           // no effect.
3693           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3694             TheAnd.setOperand(0, X);
3695             return &TheAnd;
3696           } else {
3697             // Pull the XOR out of the AND.
3698             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3699             InsertNewInstBefore(NewAnd, TheAnd);
3700             NewAnd->takeName(Op);
3701             return BinaryOperator::createXor(NewAnd, AndRHS);
3702           }
3703         }
3704       }
3705     }
3706     break;
3707
3708   case Instruction::Shl: {
3709     // We know that the AND will not produce any of the bits shifted in, so if
3710     // the anded constant includes them, clear them now!
3711     //
3712     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3713     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3714     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
3715
3716     if (CI == ShlMask) {   // Masking out bits that the shift already masks
3717       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3718     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3719       TheAnd.setOperand(1, CI);
3720       return &TheAnd;
3721     }
3722     break;
3723   }
3724   case Instruction::LShr:
3725   {
3726     // We know that the AND will not produce any of the bits shifted in, so if
3727     // the anded constant includes them, clear them now!  This only applies to
3728     // unsigned shifts, because a signed shr may bring in set bits!
3729     //
3730     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3731     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3732     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
3733
3734     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
3735       return ReplaceInstUsesWith(TheAnd, Op);
3736     } else if (CI != AndRHS) {
3737       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3738       return &TheAnd;
3739     }
3740     break;
3741   }
3742   case Instruction::AShr:
3743     // Signed shr.
3744     // See if this is shifting in some sign extension, then masking it out
3745     // with an and.
3746     if (Op->hasOneUse()) {
3747       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3748       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3749       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3750       if (C == AndRHS) {          // Masking out bits shifted in.
3751         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3752         // Make the argument unsigned.
3753         Value *ShVal = Op->getOperand(0);
3754         ShVal = InsertNewInstBefore(
3755             BinaryOperator::createLShr(ShVal, OpRHS, 
3756                                    Op->getName()), TheAnd);
3757         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3758       }
3759     }
3760     break;
3761   }
3762   return 0;
3763 }
3764
3765
3766 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3767 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3768 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3769 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3770 /// insert new instructions.
3771 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3772                                            bool isSigned, bool Inside, 
3773                                            Instruction &IB) {
3774   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3775             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3776          "Lo is not <= Hi in range emission code!");
3777     
3778   if (Inside) {
3779     if (Lo == Hi)  // Trivially false.
3780       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3781
3782     // V >= Min && V < Hi --> V < Hi
3783     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3784     ICmpInst::Predicate pred = (isSigned ? 
3785         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3786       return new ICmpInst(pred, V, Hi);
3787     }
3788
3789     // Emit V-Lo <u Hi-Lo
3790     Constant *NegLo = ConstantExpr::getNeg(Lo);
3791     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3792     InsertNewInstBefore(Add, IB);
3793     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3794     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3795   }
3796
3797   if (Lo == Hi)  // Trivially true.
3798     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3799
3800   // V < Min || V >= Hi ->'V > Hi-1'
3801   Hi = SubOne(cast<ConstantInt>(Hi));
3802   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3803     ICmpInst::Predicate pred = (isSigned ? 
3804         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3805     return new ICmpInst(pred, V, Hi);
3806   }
3807
3808   // Emit V-Lo > Hi-1-Lo
3809   Constant *NegLo = ConstantExpr::getNeg(Lo);
3810   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3811   InsertNewInstBefore(Add, IB);
3812   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3813   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3814 }
3815
3816 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3817 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3818 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3819 // not, since all 1s are not contiguous.
3820 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3821   uint64_t V = Val->getZExtValue();
3822   if (!isShiftedMask_64(V)) return false;
3823
3824   // look for the first zero bit after the run of ones
3825   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3826   // look for the first non-zero bit
3827   ME = 64-CountLeadingZeros_64(V);
3828   return true;
3829 }
3830
3831
3832
3833 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3834 /// where isSub determines whether the operator is a sub.  If we can fold one of
3835 /// the following xforms:
3836 /// 
3837 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3838 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3839 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3840 ///
3841 /// return (A +/- B).
3842 ///
3843 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3844                                         ConstantInt *Mask, bool isSub,
3845                                         Instruction &I) {
3846   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3847   if (!LHSI || LHSI->getNumOperands() != 2 ||
3848       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3849
3850   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3851
3852   switch (LHSI->getOpcode()) {
3853   default: return 0;
3854   case Instruction::And:
3855     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3856       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3857       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3858         break;
3859
3860       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3861       // part, we don't need any explicit masks to take them out of A.  If that
3862       // is all N is, ignore it.
3863       unsigned MB, ME;
3864       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3865         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3866         Mask >>= 64-MB+1;
3867         if (MaskedValueIsZero(RHS, Mask))
3868           break;
3869       }
3870     }
3871     return 0;
3872   case Instruction::Or:
3873   case Instruction::Xor:
3874     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3875     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3876         ConstantExpr::getAnd(N, Mask)->isNullValue())
3877       break;
3878     return 0;
3879   }
3880   
3881   Instruction *New;
3882   if (isSub)
3883     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3884   else
3885     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3886   return InsertNewInstBefore(New, I);
3887 }
3888
3889 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3890   bool Changed = SimplifyCommutative(I);
3891   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3892
3893   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3894     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3895
3896   // and X, X = X
3897   if (Op0 == Op1)
3898     return ReplaceInstUsesWith(I, Op1);
3899
3900   // See if we can simplify any instructions used by the instruction whose sole 
3901   // purpose is to compute bits we don't care about.
3902   uint64_t KnownZero, KnownOne;
3903   if (!isa<VectorType>(I.getType())) {
3904     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3905                              KnownZero, KnownOne))
3906     return &I;
3907   } else {
3908     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3909       if (CP->isAllOnesValue())
3910         return ReplaceInstUsesWith(I, I.getOperand(0));
3911     }
3912   }
3913   
3914   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3915     uint64_t AndRHSMask = AndRHS->getZExtValue();
3916     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3917     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3918
3919     // Optimize a variety of ((val OP C1) & C2) combinations...
3920     if (isa<BinaryOperator>(Op0)) {
3921       Instruction *Op0I = cast<Instruction>(Op0);
3922       Value *Op0LHS = Op0I->getOperand(0);
3923       Value *Op0RHS = Op0I->getOperand(1);
3924       switch (Op0I->getOpcode()) {
3925       case Instruction::Xor:
3926       case Instruction::Or:
3927         // If the mask is only needed on one incoming arm, push it up.
3928         if (Op0I->hasOneUse()) {
3929           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3930             // Not masking anything out for the LHS, move to RHS.
3931             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3932                                                    Op0RHS->getName()+".masked");
3933             InsertNewInstBefore(NewRHS, I);
3934             return BinaryOperator::create(
3935                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3936           }
3937           if (!isa<Constant>(Op0RHS) &&
3938               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3939             // Not masking anything out for the RHS, move to LHS.
3940             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3941                                                    Op0LHS->getName()+".masked");
3942             InsertNewInstBefore(NewLHS, I);
3943             return BinaryOperator::create(
3944                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3945           }
3946         }
3947
3948         break;
3949       case Instruction::Add:
3950         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3951         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3952         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3953         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3954           return BinaryOperator::createAnd(V, AndRHS);
3955         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3956           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3957         break;
3958
3959       case Instruction::Sub:
3960         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3961         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3962         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3963         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3964           return BinaryOperator::createAnd(V, AndRHS);
3965         break;
3966       }
3967
3968       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3969         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3970           return Res;
3971     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3972       // If this is an integer truncation or change from signed-to-unsigned, and
3973       // if the source is an and/or with immediate, transform it.  This
3974       // frequently occurs for bitfield accesses.
3975       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3976         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3977             CastOp->getNumOperands() == 2)
3978           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3979             if (CastOp->getOpcode() == Instruction::And) {
3980               // Change: and (cast (and X, C1) to T), C2
3981               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3982               // This will fold the two constants together, which may allow 
3983               // other simplifications.
3984               Instruction *NewCast = CastInst::createTruncOrBitCast(
3985                 CastOp->getOperand(0), I.getType(), 
3986                 CastOp->getName()+".shrunk");
3987               NewCast = InsertNewInstBefore(NewCast, I);
3988               // trunc_or_bitcast(C1)&C2
3989               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3990               C3 = ConstantExpr::getAnd(C3, AndRHS);
3991               return BinaryOperator::createAnd(NewCast, C3);
3992             } else if (CastOp->getOpcode() == Instruction::Or) {
3993               // Change: and (cast (or X, C1) to T), C2
3994               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3995               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3996               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3997                 return ReplaceInstUsesWith(I, AndRHS);
3998             }
3999       }
4000     }
4001
4002     // Try to fold constant and into select arguments.
4003     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4004       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4005         return R;
4006     if (isa<PHINode>(Op0))
4007       if (Instruction *NV = FoldOpIntoPhi(I))
4008         return NV;
4009   }
4010
4011   Value *Op0NotVal = dyn_castNotVal(Op0);
4012   Value *Op1NotVal = dyn_castNotVal(Op1);
4013
4014   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4015     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4016
4017   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4018   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4019     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4020                                                I.getName()+".demorgan");
4021     InsertNewInstBefore(Or, I);
4022     return BinaryOperator::createNot(Or);
4023   }
4024   
4025   {
4026     Value *A = 0, *B = 0;
4027     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4028       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4029         return ReplaceInstUsesWith(I, Op1);
4030     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4031       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4032         return ReplaceInstUsesWith(I, Op0);
4033     
4034     if (Op0->hasOneUse() &&
4035         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4036       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4037         I.swapOperands();     // Simplify below
4038         std::swap(Op0, Op1);
4039       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4040         cast<BinaryOperator>(Op0)->swapOperands();
4041         I.swapOperands();     // Simplify below
4042         std::swap(Op0, Op1);
4043       }
4044     }
4045     if (Op1->hasOneUse() &&
4046         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4047       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4048         cast<BinaryOperator>(Op1)->swapOperands();
4049         std::swap(A, B);
4050       }
4051       if (A == Op0) {                                // A&(A^B) -> A & ~B
4052         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4053         InsertNewInstBefore(NotB, I);
4054         return BinaryOperator::createAnd(A, NotB);
4055       }
4056     }
4057   }
4058   
4059   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4060     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4061     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4062       return R;
4063
4064     Value *LHSVal, *RHSVal;
4065     ConstantInt *LHSCst, *RHSCst;
4066     ICmpInst::Predicate LHSCC, RHSCC;
4067     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4068       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4069         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4070             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4071             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4072             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4073             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4074             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4075           // Ensure that the larger constant is on the RHS.
4076           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
4077             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4078           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4079           ICmpInst *LHS = cast<ICmpInst>(Op0);
4080           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4081             std::swap(LHS, RHS);
4082             std::swap(LHSCst, RHSCst);
4083             std::swap(LHSCC, RHSCC);
4084           }
4085
4086           // At this point, we know we have have two icmp instructions
4087           // comparing a value against two constants and and'ing the result
4088           // together.  Because of the above check, we know that we only have
4089           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4090           // (from the FoldICmpLogical check above), that the two constants 
4091           // are not equal and that the larger constant is on the RHS
4092           assert(LHSCst != RHSCst && "Compares not folded above?");
4093
4094           switch (LHSCC) {
4095           default: assert(0 && "Unknown integer condition code!");
4096           case ICmpInst::ICMP_EQ:
4097             switch (RHSCC) {
4098             default: assert(0 && "Unknown integer condition code!");
4099             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4100             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4101             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4102               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4103             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4104             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4105             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4106               return ReplaceInstUsesWith(I, LHS);
4107             }
4108           case ICmpInst::ICMP_NE:
4109             switch (RHSCC) {
4110             default: assert(0 && "Unknown integer condition code!");
4111             case ICmpInst::ICMP_ULT:
4112               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4113                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4114               break;                        // (X != 13 & X u< 15) -> no change
4115             case ICmpInst::ICMP_SLT:
4116               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4117                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4118               break;                        // (X != 13 & X s< 15) -> no change
4119             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4120             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4121             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4122               return ReplaceInstUsesWith(I, RHS);
4123             case ICmpInst::ICMP_NE:
4124               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4125                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4126                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4127                                                       LHSVal->getName()+".off");
4128                 InsertNewInstBefore(Add, I);
4129                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4130                                     ConstantInt::get(Add->getType(), 1));
4131               }
4132               break;                        // (X != 13 & X != 15) -> no change
4133             }
4134             break;
4135           case ICmpInst::ICMP_ULT:
4136             switch (RHSCC) {
4137             default: assert(0 && "Unknown integer condition code!");
4138             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4139             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4140               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4141             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4142               break;
4143             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4144             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4145               return ReplaceInstUsesWith(I, LHS);
4146             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4147               break;
4148             }
4149             break;
4150           case ICmpInst::ICMP_SLT:
4151             switch (RHSCC) {
4152             default: assert(0 && "Unknown integer condition code!");
4153             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4154             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4155               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4156             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4157               break;
4158             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4159             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4160               return ReplaceInstUsesWith(I, LHS);
4161             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4162               break;
4163             }
4164             break;
4165           case ICmpInst::ICMP_UGT:
4166             switch (RHSCC) {
4167             default: assert(0 && "Unknown integer condition code!");
4168             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4169               return ReplaceInstUsesWith(I, LHS);
4170             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4171               return ReplaceInstUsesWith(I, RHS);
4172             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4173               break;
4174             case ICmpInst::ICMP_NE:
4175               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4176                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4177               break;                        // (X u> 13 & X != 15) -> no change
4178             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4179               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4180                                      true, I);
4181             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4182               break;
4183             }
4184             break;
4185           case ICmpInst::ICMP_SGT:
4186             switch (RHSCC) {
4187             default: assert(0 && "Unknown integer condition code!");
4188             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
4189               return ReplaceInstUsesWith(I, LHS);
4190             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4191               return ReplaceInstUsesWith(I, RHS);
4192             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4193               break;
4194             case ICmpInst::ICMP_NE:
4195               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4196                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4197               break;                        // (X s> 13 & X != 15) -> no change
4198             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4199               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4200                                      true, I);
4201             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4202               break;
4203             }
4204             break;
4205           }
4206         }
4207   }
4208
4209   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4210   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4211     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4212       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4213         const Type *SrcTy = Op0C->getOperand(0)->getType();
4214         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4215             // Only do this if the casts both really cause code to be generated.
4216             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4217                               I.getType(), TD) &&
4218             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4219                               I.getType(), TD)) {
4220           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4221                                                          Op1C->getOperand(0),
4222                                                          I.getName());
4223           InsertNewInstBefore(NewOp, I);
4224           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4225         }
4226       }
4227     
4228   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4229   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4232           SI0->getOperand(1) == SI1->getOperand(1) &&
4233           (SI0->hasOneUse() || SI1->hasOneUse())) {
4234         Instruction *NewOp =
4235           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4236                                                         SI1->getOperand(0),
4237                                                         SI0->getName()), I);
4238         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4239                                       SI1->getOperand(1));
4240       }
4241   }
4242
4243   return Changed ? &I : 0;
4244 }
4245
4246 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4247 /// in the result.  If it does, and if the specified byte hasn't been filled in
4248 /// yet, fill it in and return false.
4249 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4250   Instruction *I = dyn_cast<Instruction>(V);
4251   if (I == 0) return true;
4252
4253   // If this is an or instruction, it is an inner node of the bswap.
4254   if (I->getOpcode() == Instruction::Or)
4255     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4256            CollectBSwapParts(I->getOperand(1), ByteValues);
4257   
4258   // If this is a shift by a constant int, and it is "24", then its operand
4259   // defines a byte.  We only handle unsigned types here.
4260   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4261     // Not shifting the entire input by N-1 bytes?
4262     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
4263         8*(ByteValues.size()-1))
4264       return true;
4265     
4266     unsigned DestNo;
4267     if (I->getOpcode() == Instruction::Shl) {
4268       // X << 24 defines the top byte with the lowest of the input bytes.
4269       DestNo = ByteValues.size()-1;
4270     } else {
4271       // X >>u 24 defines the low byte with the highest of the input bytes.
4272       DestNo = 0;
4273     }
4274     
4275     // If the destination byte value is already defined, the values are or'd
4276     // together, which isn't a bswap (unless it's an or of the same bits).
4277     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4278       return true;
4279     ByteValues[DestNo] = I->getOperand(0);
4280     return false;
4281   }
4282   
4283   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4284   // don't have this.
4285   Value *Shift = 0, *ShiftLHS = 0;
4286   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4287   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4288       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4289     return true;
4290   Instruction *SI = cast<Instruction>(Shift);
4291
4292   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4293   if (ShiftAmt->getZExtValue() & 7 ||
4294       ShiftAmt->getZExtValue() > 8*ByteValues.size())
4295     return true;
4296   
4297   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4298   unsigned DestByte;
4299   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4300     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
4301       break;
4302   // Unknown mask for bswap.
4303   if (DestByte == ByteValues.size()) return true;
4304   
4305   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4306   unsigned SrcByte;
4307   if (SI->getOpcode() == Instruction::Shl)
4308     SrcByte = DestByte - ShiftBytes;
4309   else
4310     SrcByte = DestByte + ShiftBytes;
4311   
4312   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4313   if (SrcByte != ByteValues.size()-DestByte-1)
4314     return true;
4315   
4316   // If the destination byte value is already defined, the values are or'd
4317   // together, which isn't a bswap (unless it's an or of the same bits).
4318   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4319     return true;
4320   ByteValues[DestByte] = SI->getOperand(0);
4321   return false;
4322 }
4323
4324 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4325 /// If so, insert the new bswap intrinsic and return it.
4326 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4327   // We cannot bswap one byte.
4328   if (I.getType() == Type::Int8Ty)
4329     return 0;
4330   
4331   /// ByteValues - For each byte of the result, we keep track of which value
4332   /// defines each byte.
4333   SmallVector<Value*, 8> ByteValues;
4334   ByteValues.resize(TD->getTypeSize(I.getType()));
4335     
4336   // Try to find all the pieces corresponding to the bswap.
4337   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4338       CollectBSwapParts(I.getOperand(1), ByteValues))
4339     return 0;
4340   
4341   // Check to see if all of the bytes come from the same value.
4342   Value *V = ByteValues[0];
4343   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4344   
4345   // Check to make sure that all of the bytes come from the same value.
4346   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4347     if (ByteValues[i] != V)
4348       return 0;
4349     
4350   // If they do then *success* we can turn this into a bswap.  Figure out what
4351   // bswap to make it into.
4352   Module *M = I.getParent()->getParent()->getParent();
4353   const char *FnName = 0;
4354   if (I.getType() == Type::Int16Ty)
4355     FnName = "llvm.bswap.i16";
4356   else if (I.getType() == Type::Int32Ty)
4357     FnName = "llvm.bswap.i32";
4358   else if (I.getType() == Type::Int64Ty)
4359     FnName = "llvm.bswap.i64";
4360   else
4361     assert(0 && "Unknown integer type!");
4362   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
4363   return new CallInst(F, V);
4364 }
4365
4366
4367 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4368   bool Changed = SimplifyCommutative(I);
4369   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4370
4371   if (isa<UndefValue>(Op1))
4372     return ReplaceInstUsesWith(I,                         // X | undef -> -1
4373                                ConstantInt::getAllOnesValue(I.getType()));
4374
4375   // or X, X = X
4376   if (Op0 == Op1)
4377     return ReplaceInstUsesWith(I, Op0);
4378
4379   // See if we can simplify any instructions used by the instruction whose sole 
4380   // purpose is to compute bits we don't care about.
4381   uint64_t KnownZero, KnownOne;
4382   if (!isa<VectorType>(I.getType()) &&
4383       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4384                            KnownZero, KnownOne))
4385     return &I;
4386   
4387   // or X, -1 == -1
4388   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4389     ConstantInt *C1 = 0; Value *X = 0;
4390     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4391     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4392       Instruction *Or = BinaryOperator::createOr(X, RHS);
4393       InsertNewInstBefore(Or, I);
4394       Or->takeName(Op0);
4395       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4396     }
4397
4398     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4399     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4400       Instruction *Or = BinaryOperator::createOr(X, RHS);
4401       InsertNewInstBefore(Or, I);
4402       Or->takeName(Op0);
4403       return BinaryOperator::createXor(Or,
4404                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
4405     }
4406
4407     // Try to fold constant and into select arguments.
4408     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4409       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4410         return R;
4411     if (isa<PHINode>(Op0))
4412       if (Instruction *NV = FoldOpIntoPhi(I))
4413         return NV;
4414   }
4415
4416   Value *A = 0, *B = 0;
4417   ConstantInt *C1 = 0, *C2 = 0;
4418
4419   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4420     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4421       return ReplaceInstUsesWith(I, Op1);
4422   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4423     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4424       return ReplaceInstUsesWith(I, Op0);
4425
4426   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4427   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4428   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4429       match(Op1, m_Or(m_Value(), m_Value())) ||
4430       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4431        match(Op1, m_Shift(m_Value(), m_Value())))) {
4432     if (Instruction *BSwap = MatchBSwap(I))
4433       return BSwap;
4434   }
4435   
4436   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4437   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4438       MaskedValueIsZero(Op1, C1->getZExtValue())) {
4439     Instruction *NOr = BinaryOperator::createOr(A, Op1);
4440     InsertNewInstBefore(NOr, I);
4441     NOr->takeName(Op0);
4442     return BinaryOperator::createXor(NOr, C1);
4443   }
4444
4445   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4446   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4447       MaskedValueIsZero(Op0, C1->getZExtValue())) {
4448     Instruction *NOr = BinaryOperator::createOr(A, Op0);
4449     InsertNewInstBefore(NOr, I);
4450     NOr->takeName(Op0);
4451     return BinaryOperator::createXor(NOr, C1);
4452   }
4453
4454   // (A & C1)|(B & C2)
4455   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
4456       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4457
4458     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
4459       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4460
4461
4462     // If we have: ((V + N) & C1) | (V & C2)
4463     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4464     // replace with V+N.
4465     if (C1 == ConstantExpr::getNot(C2)) {
4466       Value *V1 = 0, *V2 = 0;
4467       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
4468           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4469         // Add commutes, try both ways.
4470         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
4471           return ReplaceInstUsesWith(I, A);
4472         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
4473           return ReplaceInstUsesWith(I, A);
4474       }
4475       // Or commutes, try both ways.
4476       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
4477           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4478         // Add commutes, try both ways.
4479         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
4480           return ReplaceInstUsesWith(I, B);
4481         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
4482           return ReplaceInstUsesWith(I, B);
4483       }
4484     }
4485   }
4486   
4487   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4488   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4489     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4490       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4491           SI0->getOperand(1) == SI1->getOperand(1) &&
4492           (SI0->hasOneUse() || SI1->hasOneUse())) {
4493         Instruction *NewOp =
4494         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4495                                                      SI1->getOperand(0),
4496                                                      SI0->getName()), I);
4497         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4498                                       SI1->getOperand(1));
4499       }
4500   }
4501
4502   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4503     if (A == Op1)   // ~A | A == -1
4504       return ReplaceInstUsesWith(I,
4505                                 ConstantInt::getAllOnesValue(I.getType()));
4506   } else {
4507     A = 0;
4508   }
4509   // Note, A is still live here!
4510   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4511     if (Op0 == B)
4512       return ReplaceInstUsesWith(I,
4513                                 ConstantInt::getAllOnesValue(I.getType()));
4514
4515     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4516     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4517       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4518                                               I.getName()+".demorgan"), I);
4519       return BinaryOperator::createNot(And);
4520     }
4521   }
4522
4523   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4524   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4525     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4526       return R;
4527
4528     Value *LHSVal, *RHSVal;
4529     ConstantInt *LHSCst, *RHSCst;
4530     ICmpInst::Predicate LHSCC, RHSCC;
4531     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4532       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4533         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4534             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4535             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4536             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4537             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4538             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
4539           // Ensure that the larger constant is on the RHS.
4540           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
4541             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4542           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4543           ICmpInst *LHS = cast<ICmpInst>(Op0);
4544           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4545             std::swap(LHS, RHS);
4546             std::swap(LHSCst, RHSCst);
4547             std::swap(LHSCC, RHSCC);
4548           }
4549
4550           // At this point, we know we have have two icmp instructions
4551           // comparing a value against two constants and or'ing the result
4552           // together.  Because of the above check, we know that we only have
4553           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4554           // FoldICmpLogical check above), that the two constants are not
4555           // equal.
4556           assert(LHSCst != RHSCst && "Compares not folded above?");
4557
4558           switch (LHSCC) {
4559           default: assert(0 && "Unknown integer condition code!");
4560           case ICmpInst::ICMP_EQ:
4561             switch (RHSCC) {
4562             default: assert(0 && "Unknown integer condition code!");
4563             case ICmpInst::ICMP_EQ:
4564               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4565                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4566                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4567                                                       LHSVal->getName()+".off");
4568                 InsertNewInstBefore(Add, I);
4569                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4570                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4571               }
4572               break;                         // (X == 13 | X == 15) -> no change
4573             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4574             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4575               break;
4576             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4577             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4578             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4579               return ReplaceInstUsesWith(I, RHS);
4580             }
4581             break;
4582           case ICmpInst::ICMP_NE:
4583             switch (RHSCC) {
4584             default: assert(0 && "Unknown integer condition code!");
4585             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4586             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4587             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4588               return ReplaceInstUsesWith(I, LHS);
4589             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4590             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4591             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4592               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4593             }
4594             break;
4595           case ICmpInst::ICMP_ULT:
4596             switch (RHSCC) {
4597             default: assert(0 && "Unknown integer condition code!");
4598             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4599               break;
4600             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4601               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4602                                      false, I);
4603             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4604               break;
4605             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4606             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4607               return ReplaceInstUsesWith(I, RHS);
4608             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4609               break;
4610             }
4611             break;
4612           case ICmpInst::ICMP_SLT:
4613             switch (RHSCC) {
4614             default: assert(0 && "Unknown integer condition code!");
4615             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4616               break;
4617             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4618               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4619                                      false, I);
4620             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4621               break;
4622             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4623             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4624               return ReplaceInstUsesWith(I, RHS);
4625             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4626               break;
4627             }
4628             break;
4629           case ICmpInst::ICMP_UGT:
4630             switch (RHSCC) {
4631             default: assert(0 && "Unknown integer condition code!");
4632             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4633             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4634               return ReplaceInstUsesWith(I, LHS);
4635             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4636               break;
4637             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4638             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4639               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4640             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4641               break;
4642             }
4643             break;
4644           case ICmpInst::ICMP_SGT:
4645             switch (RHSCC) {
4646             default: assert(0 && "Unknown integer condition code!");
4647             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4648             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4649               return ReplaceInstUsesWith(I, LHS);
4650             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4651               break;
4652             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4653             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4654               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4655             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4656               break;
4657             }
4658             break;
4659           }
4660         }
4661   }
4662     
4663   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4664   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4665     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4666       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4667         const Type *SrcTy = Op0C->getOperand(0)->getType();
4668         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4669             // Only do this if the casts both really cause code to be generated.
4670             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4671                               I.getType(), TD) &&
4672             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4673                               I.getType(), TD)) {
4674           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4675                                                         Op1C->getOperand(0),
4676                                                         I.getName());
4677           InsertNewInstBefore(NewOp, I);
4678           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4679         }
4680       }
4681       
4682
4683   return Changed ? &I : 0;
4684 }
4685
4686 // XorSelf - Implements: X ^ X --> 0
4687 struct XorSelf {
4688   Value *RHS;
4689   XorSelf(Value *rhs) : RHS(rhs) {}
4690   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4691   Instruction *apply(BinaryOperator &Xor) const {
4692     return &Xor;
4693   }
4694 };
4695
4696
4697 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4698   bool Changed = SimplifyCommutative(I);
4699   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4700
4701   if (isa<UndefValue>(Op1))
4702     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4703
4704   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4705   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4706     assert(Result == &I && "AssociativeOpt didn't work?");
4707     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4708   }
4709   
4710   // See if we can simplify any instructions used by the instruction whose sole 
4711   // purpose is to compute bits we don't care about.
4712   uint64_t KnownZero, KnownOne;
4713   if (!isa<VectorType>(I.getType()) &&
4714       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
4715                            KnownZero, KnownOne))
4716     return &I;
4717
4718   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4719     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4720     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4721       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4722         return new ICmpInst(ICI->getInversePredicate(),
4723                             ICI->getOperand(0), ICI->getOperand(1));
4724
4725     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4726       // ~(c-X) == X-c-1 == X+(-c-1)
4727       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4728         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4729           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4730           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4731                                               ConstantInt::get(I.getType(), 1));
4732           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4733         }
4734
4735       // ~(~X & Y) --> (X | ~Y)
4736       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4737         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4738         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4739           Instruction *NotY =
4740             BinaryOperator::createNot(Op0I->getOperand(1),
4741                                       Op0I->getOperand(1)->getName()+".not");
4742           InsertNewInstBefore(NotY, I);
4743           return BinaryOperator::createOr(Op0NotVal, NotY);
4744         }
4745       }
4746
4747       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4748         if (Op0I->getOpcode() == Instruction::Add) {
4749           // ~(X-c) --> (-c-1)-X
4750           if (RHS->isAllOnesValue()) {
4751             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4752             return BinaryOperator::createSub(
4753                            ConstantExpr::getSub(NegOp0CI,
4754                                              ConstantInt::get(I.getType(), 1)),
4755                                           Op0I->getOperand(0));
4756           }
4757         } else if (Op0I->getOpcode() == Instruction::Or) {
4758           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4759           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4760             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4761             // Anything in both C1 and C2 is known to be zero, remove it from
4762             // NewRHS.
4763             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4764             NewRHS = ConstantExpr::getAnd(NewRHS, 
4765                                           ConstantExpr::getNot(CommonBits));
4766             AddToWorkList(Op0I);
4767             I.setOperand(0, Op0I->getOperand(0));
4768             I.setOperand(1, NewRHS);
4769             return &I;
4770           }
4771         }
4772     }
4773
4774     // Try to fold constant and into select arguments.
4775     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4776       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4777         return R;
4778     if (isa<PHINode>(Op0))
4779       if (Instruction *NV = FoldOpIntoPhi(I))
4780         return NV;
4781   }
4782
4783   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4784     if (X == Op1)
4785       return ReplaceInstUsesWith(I,
4786                                 ConstantInt::getAllOnesValue(I.getType()));
4787
4788   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4789     if (X == Op0)
4790       return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4791
4792   
4793   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4794   if (Op1I) {
4795     Value *A, *B;
4796     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4797       if (A == Op0) {              // B^(B|A) == (A|B)^B
4798         Op1I->swapOperands();
4799         I.swapOperands();
4800         std::swap(Op0, Op1);
4801       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4802         I.swapOperands();     // Simplified below.
4803         std::swap(Op0, Op1);
4804       }
4805     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4806       if (Op0 == A)                                          // A^(A^B) == B
4807         return ReplaceInstUsesWith(I, B);
4808       else if (Op0 == B)                                     // A^(B^A) == B
4809         return ReplaceInstUsesWith(I, A);
4810     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4811       if (A == Op0)                                        // A^(A&B) -> A^(B&A)
4812         Op1I->swapOperands();
4813       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4814         I.swapOperands();     // Simplified below.
4815         std::swap(Op0, Op1);
4816       }
4817     }
4818   }
4819   
4820   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4821   if (Op0I) {
4822     Value *A, *B;
4823     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4824       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4825         std::swap(A, B);
4826       if (B == Op1) {                                // (A|B)^B == A & ~B
4827         Instruction *NotB =
4828           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4829         return BinaryOperator::createAnd(A, NotB);
4830       }
4831     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4832       if (Op1 == A)                                          // (A^B)^A == B
4833         return ReplaceInstUsesWith(I, B);
4834       else if (Op1 == B)                                     // (B^A)^A == B
4835         return ReplaceInstUsesWith(I, A);
4836     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4837       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4838         std::swap(A, B);
4839       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4840           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4841         Instruction *N =
4842           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4843         return BinaryOperator::createAnd(N, Op1);
4844       }
4845     }
4846   }
4847   
4848   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4849   if (Op0I && Op1I && Op0I->isShift() && 
4850       Op0I->getOpcode() == Op1I->getOpcode() && 
4851       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4852       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4853     Instruction *NewOp =
4854       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4855                                                     Op1I->getOperand(0),
4856                                                     Op0I->getName()), I);
4857     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4858                                   Op1I->getOperand(1));
4859   }
4860     
4861   if (Op0I && Op1I) {
4862     Value *A, *B, *C, *D;
4863     // (A & B)^(A | B) -> A ^ B
4864     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4865         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4866       if ((A == C && B == D) || (A == D && B == C)) 
4867         return BinaryOperator::createXor(A, B);
4868     }
4869     // (A | B)^(A & B) -> A ^ B
4870     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4871         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4872       if ((A == C && B == D) || (A == D && B == C)) 
4873         return BinaryOperator::createXor(A, B);
4874     }
4875     
4876     // (A & B)^(C & D)
4877     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4878         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4879         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4880       // (X & Y)^(X & Y) -> (Y^Z) & X
4881       Value *X = 0, *Y = 0, *Z = 0;
4882       if (A == C)
4883         X = A, Y = B, Z = D;
4884       else if (A == D)
4885         X = A, Y = B, Z = C;
4886       else if (B == C)
4887         X = B, Y = A, Z = D;
4888       else if (B == D)
4889         X = B, Y = A, Z = C;
4890       
4891       if (X) {
4892         Instruction *NewOp =
4893         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4894         return BinaryOperator::createAnd(NewOp, X);
4895       }
4896     }
4897   }
4898     
4899   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4900   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4901     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4902       return R;
4903
4904   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4905   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4906     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4907       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4908         const Type *SrcTy = Op0C->getOperand(0)->getType();
4909         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4910             // Only do this if the casts both really cause code to be generated.
4911             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4912                               I.getType(), TD) &&
4913             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4914                               I.getType(), TD)) {
4915           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4916                                                          Op1C->getOperand(0),
4917                                                          I.getName());
4918           InsertNewInstBefore(NewOp, I);
4919           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4920         }
4921       }
4922
4923   return Changed ? &I : 0;
4924 }
4925
4926 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4927 /// overflowed for this type.
4928 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4929                             ConstantInt *In2) {
4930   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4931
4932   return cast<ConstantInt>(Result)->getZExtValue() <
4933          cast<ConstantInt>(In1)->getZExtValue();
4934 }
4935
4936 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4937 /// code necessary to compute the offset from the base pointer (without adding
4938 /// in the base pointer).  Return the result as a signed integer of intptr size.
4939 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4940   TargetData &TD = IC.getTargetData();
4941   gep_type_iterator GTI = gep_type_begin(GEP);
4942   const Type *IntPtrTy = TD.getIntPtrType();
4943   Value *Result = Constant::getNullValue(IntPtrTy);
4944
4945   // Build a mask for high order bits.
4946   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4947
4948   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4949     Value *Op = GEP->getOperand(i);
4950     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4951     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4952     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4953       if (!OpC->isNullValue()) {
4954         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4955         Scale = ConstantExpr::getMul(OpC, Scale);
4956         if (Constant *RC = dyn_cast<Constant>(Result))
4957           Result = ConstantExpr::getAdd(RC, Scale);
4958         else {
4959           // Emit an add instruction.
4960           Result = IC.InsertNewInstBefore(
4961              BinaryOperator::createAdd(Result, Scale,
4962                                        GEP->getName()+".offs"), I);
4963         }
4964       }
4965     } else {
4966       // Convert to correct type.
4967       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4968                                                Op->getName()+".c"), I);
4969       if (Size != 1)
4970         // We'll let instcombine(mul) convert this to a shl if possible.
4971         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4972                                                     GEP->getName()+".idx"), I);
4973
4974       // Emit an add instruction.
4975       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4976                                                     GEP->getName()+".offs"), I);
4977     }
4978   }
4979   return Result;
4980 }
4981
4982 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4983 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4984 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4985                                        ICmpInst::Predicate Cond,
4986                                        Instruction &I) {
4987   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4988
4989   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4990     if (isa<PointerType>(CI->getOperand(0)->getType()))
4991       RHS = CI->getOperand(0);
4992
4993   Value *PtrBase = GEPLHS->getOperand(0);
4994   if (PtrBase == RHS) {
4995     // As an optimization, we don't actually have to compute the actual value of
4996     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4997     // each index is zero or not.
4998     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4999       Instruction *InVal = 0;
5000       gep_type_iterator GTI = gep_type_begin(GEPLHS);
5001       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
5002         bool EmitIt = true;
5003         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
5004           if (isa<UndefValue>(C))  // undef index -> undef.
5005             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5006           if (C->isNullValue())
5007             EmitIt = false;
5008           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
5009             EmitIt = false;  // This is indexing into a zero sized array?
5010           } else if (isa<ConstantInt>(C))
5011             return ReplaceInstUsesWith(I, // No comparison is needed here.
5012                                  ConstantInt::get(Type::Int1Ty, 
5013                                                   Cond == ICmpInst::ICMP_NE));
5014         }
5015
5016         if (EmitIt) {
5017           Instruction *Comp =
5018             new ICmpInst(Cond, GEPLHS->getOperand(i),
5019                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
5020           if (InVal == 0)
5021             InVal = Comp;
5022           else {
5023             InVal = InsertNewInstBefore(InVal, I);
5024             InsertNewInstBefore(Comp, I);
5025             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
5026               InVal = BinaryOperator::createOr(InVal, Comp);
5027             else                              // True if all are equal
5028               InVal = BinaryOperator::createAnd(InVal, Comp);
5029           }
5030         }
5031       }
5032
5033       if (InVal)
5034         return InVal;
5035       else
5036         // No comparison is needed here, all indexes = 0
5037         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5038                                                 Cond == ICmpInst::ICMP_EQ));
5039     }
5040
5041     // Only lower this if the icmp is the only user of the GEP or if we expect
5042     // the result to fold to a constant!
5043     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5044       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5045       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
5046       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5047                           Constant::getNullValue(Offset->getType()));
5048     }
5049   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5050     // If the base pointers are different, but the indices are the same, just
5051     // compare the base pointer.
5052     if (PtrBase != GEPRHS->getOperand(0)) {
5053       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5054       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5055                         GEPRHS->getOperand(0)->getType();
5056       if (IndicesTheSame)
5057         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5058           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5059             IndicesTheSame = false;
5060             break;
5061           }
5062
5063       // If all indices are the same, just compare the base pointers.
5064       if (IndicesTheSame)
5065         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5066                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5067
5068       // Otherwise, the base pointers are different and the indices are
5069       // different, bail out.
5070       return 0;
5071     }
5072
5073     // If one of the GEPs has all zero indices, recurse.
5074     bool AllZeros = true;
5075     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5076       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5077           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5078         AllZeros = false;
5079         break;
5080       }
5081     if (AllZeros)
5082       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5083                           ICmpInst::getSwappedPredicate(Cond), I);
5084
5085     // If the other GEP has all zero indices, recurse.
5086     AllZeros = true;
5087     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5088       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5089           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5090         AllZeros = false;
5091         break;
5092       }
5093     if (AllZeros)
5094       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5095
5096     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5097       // If the GEPs only differ by one index, compare it.
5098       unsigned NumDifferences = 0;  // Keep track of # differences.
5099       unsigned DiffOperand = 0;     // The operand that differs.
5100       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5101         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5102           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5103                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5104             // Irreconcilable differences.
5105             NumDifferences = 2;
5106             break;
5107           } else {
5108             if (NumDifferences++) break;
5109             DiffOperand = i;
5110           }
5111         }
5112
5113       if (NumDifferences == 0)   // SAME GEP?
5114         return ReplaceInstUsesWith(I, // No comparison is needed here.
5115                                    ConstantInt::get(Type::Int1Ty, 
5116                                                     Cond == ICmpInst::ICMP_EQ));
5117       else if (NumDifferences == 1) {
5118         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5119         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5120         // Make sure we do a signed comparison here.
5121         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5122       }
5123     }
5124
5125     // Only lower this if the icmp is the only user of the GEP or if we expect
5126     // the result to fold to a constant!
5127     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5128         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5129       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5130       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5131       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5132       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5133     }
5134   }
5135   return 0;
5136 }
5137
5138 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5139   bool Changed = SimplifyCompare(I);
5140   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5141
5142   // Fold trivial predicates.
5143   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5144     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5145   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5146     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5147   
5148   // Simplify 'fcmp pred X, X'
5149   if (Op0 == Op1) {
5150     switch (I.getPredicate()) {
5151     default: assert(0 && "Unknown predicate!");
5152     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5153     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5154     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5155       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5156     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5157     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5158     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5159       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5160       
5161     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5162     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5163     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5164     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5165       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5166       I.setPredicate(FCmpInst::FCMP_UNO);
5167       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5168       return &I;
5169       
5170     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5171     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5172     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5173     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5174       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5175       I.setPredicate(FCmpInst::FCMP_ORD);
5176       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5177       return &I;
5178     }
5179   }
5180     
5181   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5182     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5183
5184   // Handle fcmp with constant RHS
5185   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5186     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5187       switch (LHSI->getOpcode()) {
5188       case Instruction::PHI:
5189         if (Instruction *NV = FoldOpIntoPhi(I))
5190           return NV;
5191         break;
5192       case Instruction::Select:
5193         // If either operand of the select is a constant, we can fold the
5194         // comparison into the select arms, which will cause one to be
5195         // constant folded and the select turned into a bitwise or.
5196         Value *Op1 = 0, *Op2 = 0;
5197         if (LHSI->hasOneUse()) {
5198           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5199             // Fold the known value into the constant operand.
5200             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5201             // Insert a new FCmp of the other select operand.
5202             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5203                                                       LHSI->getOperand(2), RHSC,
5204                                                       I.getName()), I);
5205           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5206             // Fold the known value into the constant operand.
5207             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5208             // Insert a new FCmp of the other select operand.
5209             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5210                                                       LHSI->getOperand(1), RHSC,
5211                                                       I.getName()), I);
5212           }
5213         }
5214
5215         if (Op1)
5216           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5217         break;
5218       }
5219   }
5220
5221   return Changed ? &I : 0;
5222 }
5223
5224 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5225   bool Changed = SimplifyCompare(I);
5226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5227   const Type *Ty = Op0->getType();
5228
5229   // icmp X, X
5230   if (Op0 == Op1)
5231     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5232                                                    isTrueWhenEqual(I)));
5233
5234   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5235     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5236
5237   // icmp of GlobalValues can never equal each other as long as they aren't
5238   // external weak linkage type.
5239   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5240     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5241       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
5242         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5243                                                        !isTrueWhenEqual(I)));
5244
5245   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5246   // addresses never equal each other!  We already know that Op0 != Op1.
5247   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5248        isa<ConstantPointerNull>(Op0)) &&
5249       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5250        isa<ConstantPointerNull>(Op1)))
5251     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5252                                                    !isTrueWhenEqual(I)));
5253
5254   // icmp's with boolean values can always be turned into bitwise operations
5255   if (Ty == Type::Int1Ty) {
5256     switch (I.getPredicate()) {
5257     default: assert(0 && "Invalid icmp instruction!");
5258     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5259       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
5260       InsertNewInstBefore(Xor, I);
5261       return BinaryOperator::createNot(Xor);
5262     }
5263     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5264       return BinaryOperator::createXor(Op0, Op1);
5265
5266     case ICmpInst::ICMP_UGT:
5267     case ICmpInst::ICMP_SGT:
5268       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5269       // FALL THROUGH
5270     case ICmpInst::ICMP_ULT:
5271     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5272       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5273       InsertNewInstBefore(Not, I);
5274       return BinaryOperator::createAnd(Not, Op1);
5275     }
5276     case ICmpInst::ICMP_UGE:
5277     case ICmpInst::ICMP_SGE:
5278       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5279       // FALL THROUGH
5280     case ICmpInst::ICMP_ULE:
5281     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5282       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5283       InsertNewInstBefore(Not, I);
5284       return BinaryOperator::createOr(Not, Op1);
5285     }
5286     }
5287   }
5288
5289   // See if we are doing a comparison between a constant and an instruction that
5290   // can be folded into the comparison.
5291   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5292     switch (I.getPredicate()) {
5293     default: break;
5294     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5295       if (CI->isMinValue(false))
5296         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5297       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5298         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5299       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5300         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5301       break;
5302
5303     case ICmpInst::ICMP_SLT:
5304       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5305         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5306       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5307         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5308       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5309         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5310       break;
5311
5312     case ICmpInst::ICMP_UGT:
5313       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5314         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5315       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5316         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5317       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5318         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5319       break;
5320
5321     case ICmpInst::ICMP_SGT:
5322       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5323         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5324       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5325         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5326       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5327         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5328       break;
5329
5330     case ICmpInst::ICMP_ULE:
5331       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5332         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5333       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5334         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5335       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5336         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5337       break;
5338
5339     case ICmpInst::ICMP_SLE:
5340       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5341         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5342       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5343         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5344       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5345         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5346       break;
5347
5348     case ICmpInst::ICMP_UGE:
5349       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5350         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5351       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5352         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5353       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5354         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5355       break;
5356
5357     case ICmpInst::ICMP_SGE:
5358       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5359         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5360       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5361         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5362       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5363         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5364       break;
5365     }
5366
5367     // If we still have a icmp le or icmp ge instruction, turn it into the
5368     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5369     // already been handled above, this requires little checking.
5370     //
5371     if (I.getPredicate() == ICmpInst::ICMP_ULE)
5372       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5373     if (I.getPredicate() == ICmpInst::ICMP_SLE)
5374       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5375     if (I.getPredicate() == ICmpInst::ICMP_UGE)
5376       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5377     if (I.getPredicate() == ICmpInst::ICMP_SGE)
5378       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5379     
5380     // See if we can fold the comparison based on bits known to be zero or one
5381     // in the input.
5382     uint64_t KnownZero, KnownOne;
5383     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
5384                              KnownZero, KnownOne, 0))
5385       return &I;
5386         
5387     // Given the known and unknown bits, compute a range that the LHS could be
5388     // in.
5389     if (KnownOne | KnownZero) {
5390       // Compute the Min, Max and RHS values based on the known bits. For the
5391       // EQ and NE we use unsigned values.
5392       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
5393       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
5394       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5395         SRHSVal = CI->getSExtValue();
5396         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
5397                                                SMax);
5398       } else {
5399         URHSVal = CI->getZExtValue();
5400         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
5401                                                  UMax);
5402       }
5403       switch (I.getPredicate()) {  // LE/GE have been folded already.
5404       default: assert(0 && "Unknown icmp opcode!");
5405       case ICmpInst::ICMP_EQ:
5406         if (UMax < URHSVal || UMin > URHSVal)
5407           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5408         break;
5409       case ICmpInst::ICMP_NE:
5410         if (UMax < URHSVal || UMin > URHSVal)
5411           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5412         break;
5413       case ICmpInst::ICMP_ULT:
5414         if (UMax < URHSVal)
5415           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5416         if (UMin > URHSVal)
5417           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5418         break;
5419       case ICmpInst::ICMP_UGT:
5420         if (UMin > URHSVal)
5421           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5422         if (UMax < URHSVal)
5423           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5424         break;
5425       case ICmpInst::ICMP_SLT:
5426         if (SMax < SRHSVal)
5427           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5428         if (SMin > SRHSVal)
5429           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5430         break;
5431       case ICmpInst::ICMP_SGT: 
5432         if (SMin > SRHSVal)
5433           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5434         if (SMax < SRHSVal)
5435           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5436         break;
5437       }
5438     }
5439           
5440     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5441     // instruction, see if that instruction also has constants so that the 
5442     // instruction can be folded into the icmp 
5443     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5444       switch (LHSI->getOpcode()) {
5445       case Instruction::And:
5446         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5447             LHSI->getOperand(0)->hasOneUse()) {
5448           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5449
5450           // If the LHS is an AND of a truncating cast, we can widen the
5451           // and/compare to be the input width without changing the value
5452           // produced, eliminating a cast.
5453           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5454             // We can do this transformation if either the AND constant does not
5455             // have its sign bit set or if it is an equality comparison. 
5456             // Extending a relational comparison when we're checking the sign
5457             // bit would not work.
5458             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
5459                 (I.isEquality() ||
5460                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
5461                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
5462               ConstantInt *NewCST;
5463               ConstantInt *NewCI;
5464               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
5465                                          AndCST->getZExtValue());
5466               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
5467                                         CI->getZExtValue());
5468               Instruction *NewAnd = 
5469                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
5470                                           LHSI->getName());
5471               InsertNewInstBefore(NewAnd, I);
5472               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
5473             }
5474           }
5475           
5476           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5477           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5478           // happens a LOT in code produced by the C front-end, for bitfield
5479           // access.
5480           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5481           if (Shift && !Shift->isShift())
5482             Shift = 0;
5483
5484           ConstantInt *ShAmt;
5485           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5486           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5487           const Type *AndTy = AndCST->getType();          // Type of the and.
5488
5489           // We can fold this as long as we can't shift unknown bits
5490           // into the mask.  This can only happen with signed shift
5491           // rights, as they sign-extend.
5492           if (ShAmt) {
5493             bool CanFold = Shift->isLogicalShift();
5494             if (!CanFold) {
5495               // To test for the bad case of the signed shr, see if any
5496               // of the bits shifted in could be tested after the mask.
5497               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
5498               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5499
5500               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
5501               Constant *ShVal =
5502                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
5503                                      OShAmt);
5504               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5505                 CanFold = true;
5506             }
5507
5508             if (CanFold) {
5509               Constant *NewCst;
5510               if (Shift->getOpcode() == Instruction::Shl)
5511                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
5512               else
5513                 NewCst = ConstantExpr::getShl(CI, ShAmt);
5514
5515               // Check to see if we are shifting out any of the bits being
5516               // compared.
5517               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5518                 // If we shifted bits out, the fold is not going to work out.
5519                 // As a special case, check to see if this means that the
5520                 // result is always true or false now.
5521                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5522                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5523                 if (I.getPredicate() == ICmpInst::ICMP_NE)
5524                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5525               } else {
5526                 I.setOperand(1, NewCst);
5527                 Constant *NewAndCST;
5528                 if (Shift->getOpcode() == Instruction::Shl)
5529                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5530                 else
5531                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5532                 LHSI->setOperand(1, NewAndCST);
5533                 LHSI->setOperand(0, Shift->getOperand(0));
5534                 AddToWorkList(Shift); // Shift is dead.
5535                 AddUsesToWorkList(I);
5536                 return &I;
5537               }
5538             }
5539           }
5540           
5541           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5542           // preferable because it allows the C<<Y expression to be hoisted out
5543           // of a loop if Y is invariant and X is not.
5544           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
5545               I.isEquality() && !Shift->isArithmeticShift() &&
5546               isa<Instruction>(Shift->getOperand(0))) {
5547             // Compute C << Y.
5548             Value *NS;
5549             if (Shift->getOpcode() == Instruction::LShr) {
5550               NS = BinaryOperator::createShl(AndCST, 
5551                                           Shift->getOperand(1), "tmp");
5552             } else {
5553               // Insert a logical shift.
5554               NS = BinaryOperator::createLShr(AndCST,
5555                                           Shift->getOperand(1), "tmp");
5556             }
5557             InsertNewInstBefore(cast<Instruction>(NS), I);
5558
5559             // Compute X & (C << Y).
5560             Instruction *NewAnd = BinaryOperator::createAnd(
5561                 Shift->getOperand(0), NS, LHSI->getName());
5562             InsertNewInstBefore(NewAnd, I);
5563             
5564             I.setOperand(0, NewAnd);
5565             return &I;
5566           }
5567         }
5568         break;
5569
5570       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
5571         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5572           if (I.isEquality()) {
5573             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5574
5575             // Check that the shift amount is in range.  If not, don't perform
5576             // undefined shifts.  When the shift is visited it will be
5577             // simplified.
5578             if (ShAmt->getZExtValue() >= TypeBits)
5579               break;
5580
5581             // If we are comparing against bits always shifted out, the
5582             // comparison cannot succeed.
5583             Constant *Comp =
5584               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
5585             if (Comp != CI) {// Comparing against a bit that we know is zero.
5586               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5587               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5588               return ReplaceInstUsesWith(I, Cst);
5589             }
5590
5591             if (LHSI->hasOneUse()) {
5592               // Otherwise strength reduce the shift into an and.
5593               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5594               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
5595               Constant *Mask = ConstantInt::get(CI->getType(), Val);
5596
5597               Instruction *AndI =
5598                 BinaryOperator::createAnd(LHSI->getOperand(0),
5599                                           Mask, LHSI->getName()+".mask");
5600               Value *And = InsertNewInstBefore(AndI, I);
5601               return new ICmpInst(I.getPredicate(), And,
5602                                      ConstantExpr::getLShr(CI, ShAmt));
5603             }
5604           }
5605         }
5606         break;
5607
5608       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5609       case Instruction::AShr:
5610         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5611           if (I.isEquality()) {
5612             // Check that the shift amount is in range.  If not, don't perform
5613             // undefined shifts.  When the shift is visited it will be
5614             // simplified.
5615             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5616             if (ShAmt->getZExtValue() >= TypeBits)
5617               break;
5618
5619             // If we are comparing against bits always shifted out, the
5620             // comparison cannot succeed.
5621             Constant *Comp;
5622             if (LHSI->getOpcode() == Instruction::LShr) 
5623               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
5624                                            ShAmt);
5625             else
5626               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
5627                                            ShAmt);
5628
5629             if (Comp != CI) {// Comparing against a bit that we know is zero.
5630               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5631               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5632               return ReplaceInstUsesWith(I, Cst);
5633             }
5634
5635             if (LHSI->hasOneUse() || CI->isNullValue()) {
5636               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
5637
5638               // Otherwise strength reduce the shift into an and.
5639               uint64_t Val = ~0ULL;          // All ones.
5640               Val <<= ShAmtVal;              // Shift over to the right spot.
5641               Val &= ~0ULL >> (64-TypeBits);
5642               Constant *Mask = ConstantInt::get(CI->getType(), Val);
5643
5644               Instruction *AndI =
5645                 BinaryOperator::createAnd(LHSI->getOperand(0),
5646                                           Mask, LHSI->getName()+".mask");
5647               Value *And = InsertNewInstBefore(AndI, I);
5648               return new ICmpInst(I.getPredicate(), And,
5649                                      ConstantExpr::getShl(CI, ShAmt));
5650             }
5651           }
5652         }
5653         break;
5654
5655       case Instruction::SDiv:
5656       case Instruction::UDiv:
5657         // Fold: icmp pred ([us]div X, C1), C2 -> range test
5658         // Fold this div into the comparison, producing a range check. 
5659         // Determine, based on the divide type, what the range is being 
5660         // checked.  If there is an overflow on the low or high side, remember 
5661         // it, otherwise compute the range [low, hi) bounding the new value.
5662         // See: InsertRangeTest above for the kinds of replacements possible.
5663         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5664           // FIXME: If the operand types don't match the type of the divide 
5665           // then don't attempt this transform. The code below doesn't have the
5666           // logic to deal with a signed divide and an unsigned compare (and
5667           // vice versa). This is because (x /s C1) <s C2  produces different 
5668           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5669           // (x /u C1) <u C2.  Simply casting the operands and result won't 
5670           // work. :(  The if statement below tests that condition and bails 
5671           // if it finds it. 
5672           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5673           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
5674             break;
5675
5676           // Initialize the variables that will indicate the nature of the
5677           // range check.
5678           bool LoOverflow = false, HiOverflow = false;
5679           ConstantInt *LoBound = 0, *HiBound = 0;
5680
5681           // Compute Prod = CI * DivRHS. We are essentially solving an equation
5682           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5683           // C2 (CI). By solving for X we can turn this into a range check 
5684           // instead of computing a divide. 
5685           ConstantInt *Prod = 
5686             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
5687
5688           // Determine if the product overflows by seeing if the product is
5689           // not equal to the divide. Make sure we do the same kind of divide
5690           // as in the LHS instruction that we're folding. 
5691           bool ProdOV = !DivRHS->isNullValue() && 
5692             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
5693               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5694
5695           // Get the ICmp opcode
5696           ICmpInst::Predicate predicate = I.getPredicate();
5697
5698           if (DivRHS->isNullValue()) {  
5699             // Don't hack on divide by zeros!
5700           } else if (!DivIsSigned) {  // udiv
5701             LoBound = Prod;
5702             LoOverflow = ProdOV;
5703             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
5704           } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5705             if (CI->isNullValue()) {       // (X / pos) op 0
5706               // Can't overflow.
5707               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5708               HiBound = DivRHS;
5709             } else if (CI->getValue().isPositive()) {   // (X / pos) op pos
5710               LoBound = Prod;
5711               LoOverflow = ProdOV;
5712               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5713             } else {                       // (X / pos) op neg
5714               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5715               LoOverflow = AddWithOverflow(LoBound, Prod,
5716                                            cast<ConstantInt>(DivRHSH));
5717               HiBound = Prod;
5718               HiOverflow = ProdOV;
5719             }
5720           } else {                         // Divisor is < 0.
5721             if (CI->isNullValue()) {       // (X / neg) op 0
5722               LoBound = AddOne(DivRHS);
5723               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5724               if (HiBound == DivRHS)
5725                 LoBound = 0;               // - INTMIN = INTMIN
5726             } else if (CI->getValue().isPositive()) {   // (X / neg) op pos
5727               HiOverflow = LoOverflow = ProdOV;
5728               if (!LoOverflow)
5729                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5730               HiBound = AddOne(Prod);
5731             } else {                       // (X / neg) op neg
5732               LoBound = Prod;
5733               LoOverflow = HiOverflow = ProdOV;
5734               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5735             }
5736
5737             // Dividing by a negate swaps the condition.
5738             predicate = ICmpInst::getSwappedPredicate(predicate);
5739           }
5740
5741           if (LoBound) {
5742             Value *X = LHSI->getOperand(0);
5743             switch (predicate) {
5744             default: assert(0 && "Unhandled icmp opcode!");
5745             case ICmpInst::ICMP_EQ:
5746               if (LoOverflow && HiOverflow)
5747                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5748               else if (HiOverflow)
5749                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
5750                                     ICmpInst::ICMP_UGE, X, LoBound);
5751               else if (LoOverflow)
5752                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5753                                     ICmpInst::ICMP_ULT, X, HiBound);
5754               else
5755                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5756                                        true, I);
5757             case ICmpInst::ICMP_NE:
5758               if (LoOverflow && HiOverflow)
5759                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5760               else if (HiOverflow)
5761                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
5762                                     ICmpInst::ICMP_ULT, X, LoBound);
5763               else if (LoOverflow)
5764                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5765                                     ICmpInst::ICMP_UGE, X, HiBound);
5766               else
5767                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5768                                        false, I);
5769             case ICmpInst::ICMP_ULT:
5770             case ICmpInst::ICMP_SLT:
5771               if (LoOverflow)
5772                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5773               return new ICmpInst(predicate, X, LoBound);
5774             case ICmpInst::ICMP_UGT:
5775             case ICmpInst::ICMP_SGT:
5776               if (HiOverflow)
5777                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5778               if (predicate == ICmpInst::ICMP_UGT)
5779                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5780               else
5781                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5782             }
5783           }
5784         }
5785         break;
5786       }
5787
5788     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5789     if (I.isEquality()) {
5790       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5791
5792       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5793       // the second operand is a constant, simplify a bit.
5794       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5795         switch (BO->getOpcode()) {
5796         case Instruction::SRem:
5797           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5798           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5799               BO->hasOneUse()) {
5800             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5801             if (V > 1 && isPowerOf2_64(V)) {
5802               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5803                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
5804               return new ICmpInst(I.getPredicate(), NewRem, 
5805                                   Constant::getNullValue(BO->getType()));
5806             }
5807           }
5808           break;
5809         case Instruction::Add:
5810           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5811           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5812             if (BO->hasOneUse())
5813               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5814                                   ConstantExpr::getSub(CI, BOp1C));
5815           } else if (CI->isNullValue()) {
5816             // Replace ((add A, B) != 0) with (A != -B) if A or B is
5817             // efficiently invertible, or if the add has just this one use.
5818             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5819
5820             if (Value *NegVal = dyn_castNegVal(BOp1))
5821               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5822             else if (Value *NegVal = dyn_castNegVal(BOp0))
5823               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5824             else if (BO->hasOneUse()) {
5825               Instruction *Neg = BinaryOperator::createNeg(BOp1);
5826               InsertNewInstBefore(Neg, I);
5827               Neg->takeName(BO);
5828               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5829             }
5830           }
5831           break;
5832         case Instruction::Xor:
5833           // For the xor case, we can xor two constants together, eliminating
5834           // the explicit xor.
5835           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5836             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5837                                 ConstantExpr::getXor(CI, BOC));
5838
5839           // FALLTHROUGH
5840         case Instruction::Sub:
5841           // Replace (([sub|xor] A, B) != 0) with (A != B)
5842           if (CI->isNullValue())
5843             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5844                                 BO->getOperand(1));
5845           break;
5846
5847         case Instruction::Or:
5848           // If bits are being or'd in that are not present in the constant we
5849           // are comparing against, then the comparison could never succeed!
5850           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5851             Constant *NotCI = ConstantExpr::getNot(CI);
5852             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5853               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5854                                                              isICMP_NE));
5855           }
5856           break;
5857
5858         case Instruction::And:
5859           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5860             // If bits are being compared against that are and'd out, then the
5861             // comparison can never succeed!
5862             if (!ConstantExpr::getAnd(CI,
5863                                       ConstantExpr::getNot(BOC))->isNullValue())
5864               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5865                                                              isICMP_NE));
5866
5867             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5868             if (CI == BOC && isOneBitSet(CI))
5869               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5870                                   ICmpInst::ICMP_NE, Op0,
5871                                   Constant::getNullValue(CI->getType()));
5872
5873             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5874             if (isSignBit(BOC)) {
5875               Value *X = BO->getOperand(0);
5876               Constant *Zero = Constant::getNullValue(X->getType());
5877               ICmpInst::Predicate pred = isICMP_NE ? 
5878                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5879               return new ICmpInst(pred, X, Zero);
5880             }
5881
5882             // ((X & ~7) == 0) --> X < 8
5883             if (CI->isNullValue() && isHighOnes(BOC)) {
5884               Value *X = BO->getOperand(0);
5885               Constant *NegX = ConstantExpr::getNeg(BOC);
5886               ICmpInst::Predicate pred = isICMP_NE ? 
5887                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5888               return new ICmpInst(pred, X, NegX);
5889             }
5890
5891           }
5892         default: break;
5893         }
5894       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5895         // Handle set{eq|ne} <intrinsic>, intcst.
5896         switch (II->getIntrinsicID()) {
5897         default: break;
5898         case Intrinsic::bswap_i16: 
5899           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5900           AddToWorkList(II);  // Dead?
5901           I.setOperand(0, II->getOperand(1));
5902           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5903                                            ByteSwap_16(CI->getZExtValue())));
5904           return &I;
5905         case Intrinsic::bswap_i32:   
5906           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5907           AddToWorkList(II);  // Dead?
5908           I.setOperand(0, II->getOperand(1));
5909           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5910                                            ByteSwap_32(CI->getZExtValue())));
5911           return &I;
5912         case Intrinsic::bswap_i64:   
5913           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5914           AddToWorkList(II);  // Dead?
5915           I.setOperand(0, II->getOperand(1));
5916           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5917                                            ByteSwap_64(CI->getZExtValue())));
5918           return &I;
5919         }
5920       }
5921     } else {  // Not a ICMP_EQ/ICMP_NE
5922       // If the LHS is a cast from an integral value of the same size, then 
5923       // since we know the RHS is a constant, try to simlify.
5924       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5925         Value *CastOp = Cast->getOperand(0);
5926         const Type *SrcTy = CastOp->getType();
5927         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5928         if (SrcTy->isInteger() && 
5929             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5930           // If this is an unsigned comparison, try to make the comparison use
5931           // smaller constant values.
5932           switch (I.getPredicate()) {
5933             default: break;
5934             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5935               ConstantInt *CUI = cast<ConstantInt>(CI);
5936               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5937                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5938                                     ConstantInt::get(SrcTy, -1ULL));
5939               break;
5940             }
5941             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5942               ConstantInt *CUI = cast<ConstantInt>(CI);
5943               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5944                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5945                                     Constant::getNullValue(SrcTy));
5946               break;
5947             }
5948           }
5949
5950         }
5951       }
5952     }
5953   }
5954
5955   // Handle icmp with constant RHS
5956   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5957     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5958       switch (LHSI->getOpcode()) {
5959       case Instruction::GetElementPtr:
5960         if (RHSC->isNullValue()) {
5961           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5962           bool isAllZeros = true;
5963           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5964             if (!isa<Constant>(LHSI->getOperand(i)) ||
5965                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5966               isAllZeros = false;
5967               break;
5968             }
5969           if (isAllZeros)
5970             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5971                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5972         }
5973         break;
5974
5975       case Instruction::PHI:
5976         if (Instruction *NV = FoldOpIntoPhi(I))
5977           return NV;
5978         break;
5979       case Instruction::Select:
5980         // If either operand of the select is a constant, we can fold the
5981         // comparison into the select arms, which will cause one to be
5982         // constant folded and the select turned into a bitwise or.
5983         Value *Op1 = 0, *Op2 = 0;
5984         if (LHSI->hasOneUse()) {
5985           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5986             // Fold the known value into the constant operand.
5987             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988             // Insert a new ICmp of the other select operand.
5989             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990                                                    LHSI->getOperand(2), RHSC,
5991                                                    I.getName()), I);
5992           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5993             // Fold the known value into the constant operand.
5994             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5995             // Insert a new ICmp of the other select operand.
5996             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5997                                                    LHSI->getOperand(1), RHSC,
5998                                                    I.getName()), I);
5999           }
6000         }
6001
6002         if (Op1)
6003           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
6004         break;
6005       }
6006   }
6007
6008   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6009   if (User *GEP = dyn_castGetElementPtr(Op0))
6010     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6011       return NI;
6012   if (User *GEP = dyn_castGetElementPtr(Op1))
6013     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6014                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6015       return NI;
6016
6017   // Test to see if the operands of the icmp are casted versions of other
6018   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6019   // now.
6020   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6021     if (isa<PointerType>(Op0->getType()) && 
6022         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6023       // We keep moving the cast from the left operand over to the right
6024       // operand, where it can often be eliminated completely.
6025       Op0 = CI->getOperand(0);
6026
6027       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6028       // so eliminate it as well.
6029       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6030         Op1 = CI2->getOperand(0);
6031
6032       // If Op1 is a constant, we can fold the cast into the constant.
6033       if (Op0->getType() != Op1->getType())
6034         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6035           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6036         } else {
6037           // Otherwise, cast the RHS right before the icmp
6038           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
6039         }
6040       return new ICmpInst(I.getPredicate(), Op0, Op1);
6041     }
6042   }
6043   
6044   if (isa<CastInst>(Op0)) {
6045     // Handle the special case of: icmp (cast bool to X), <cst>
6046     // This comes up when you have code like
6047     //   int X = A < B;
6048     //   if (X) ...
6049     // For generality, we handle any zero-extension of any operand comparison
6050     // with a constant or another cast from the same type.
6051     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6052       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6053         return R;
6054   }
6055   
6056   if (I.isEquality()) {
6057     Value *A, *B, *C, *D;
6058     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6059       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6060         Value *OtherVal = A == Op1 ? B : A;
6061         return new ICmpInst(I.getPredicate(), OtherVal,
6062                             Constant::getNullValue(A->getType()));
6063       }
6064
6065       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6066         // A^c1 == C^c2 --> A == C^(c1^c2)
6067         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6068           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6069             if (Op1->hasOneUse()) {
6070               Constant *NC = ConstantExpr::getXor(C1, C2);
6071               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6072               return new ICmpInst(I.getPredicate(), A,
6073                                   InsertNewInstBefore(Xor, I));
6074             }
6075         
6076         // A^B == A^D -> B == D
6077         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6078         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6079         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6080         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6081       }
6082     }
6083     
6084     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6085         (A == Op0 || B == Op0)) {
6086       // A == (A^B)  ->  B == 0
6087       Value *OtherVal = A == Op0 ? B : A;
6088       return new ICmpInst(I.getPredicate(), OtherVal,
6089                           Constant::getNullValue(A->getType()));
6090     }
6091     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6092       // (A-B) == A  ->  B == 0
6093       return new ICmpInst(I.getPredicate(), B,
6094                           Constant::getNullValue(B->getType()));
6095     }
6096     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6097       // A == (A-B)  ->  B == 0
6098       return new ICmpInst(I.getPredicate(), B,
6099                           Constant::getNullValue(B->getType()));
6100     }
6101     
6102     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6103     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6104         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6105         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6106       Value *X = 0, *Y = 0, *Z = 0;
6107       
6108       if (A == C) {
6109         X = B; Y = D; Z = A;
6110       } else if (A == D) {
6111         X = B; Y = C; Z = A;
6112       } else if (B == C) {
6113         X = A; Y = D; Z = B;
6114       } else if (B == D) {
6115         X = A; Y = C; Z = B;
6116       }
6117       
6118       if (X) {   // Build (X^Y) & Z
6119         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6120         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6121         I.setOperand(0, Op1);
6122         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6123         return &I;
6124       }
6125     }
6126   }
6127   return Changed ? &I : 0;
6128 }
6129
6130 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6131 // We only handle extending casts so far.
6132 //
6133 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6134   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6135   Value *LHSCIOp        = LHSCI->getOperand(0);
6136   const Type *SrcTy     = LHSCIOp->getType();
6137   const Type *DestTy    = LHSCI->getType();
6138   Value *RHSCIOp;
6139
6140   // We only handle extension cast instructions, so far. Enforce this.
6141   if (LHSCI->getOpcode() != Instruction::ZExt &&
6142       LHSCI->getOpcode() != Instruction::SExt)
6143     return 0;
6144
6145   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6146   bool isSignedCmp = ICI.isSignedPredicate();
6147
6148   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6149     // Not an extension from the same type?
6150     RHSCIOp = CI->getOperand(0);
6151     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6152       return 0;
6153     
6154     // If the signedness of the two compares doesn't agree (i.e. one is a sext
6155     // and the other is a zext), then we can't handle this.
6156     if (CI->getOpcode() != LHSCI->getOpcode())
6157       return 0;
6158
6159     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
6160     // then we can't handle this.
6161     if (isSignedExt != isSignedCmp && !ICI.isEquality())
6162       return 0;
6163     
6164     // Okay, just insert a compare of the reduced operands now!
6165     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6166   }
6167
6168   // If we aren't dealing with a constant on the RHS, exit early
6169   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6170   if (!CI)
6171     return 0;
6172
6173   // Compute the constant that would happen if we truncated to SrcTy then
6174   // reextended to DestTy.
6175   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6176   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6177
6178   // If the re-extended constant didn't change...
6179   if (Res2 == CI) {
6180     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6181     // For example, we might have:
6182     //    %A = sext short %X to uint
6183     //    %B = icmp ugt uint %A, 1330
6184     // It is incorrect to transform this into 
6185     //    %B = icmp ugt short %X, 1330 
6186     // because %A may have negative value. 
6187     //
6188     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6189     // OR operation is EQ/NE.
6190     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6191       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6192     else
6193       return 0;
6194   }
6195
6196   // The re-extended constant changed so the constant cannot be represented 
6197   // in the shorter type. Consequently, we cannot emit a simple comparison.
6198
6199   // First, handle some easy cases. We know the result cannot be equal at this
6200   // point so handle the ICI.isEquality() cases
6201   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6202     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6203   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6204     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6205
6206   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6207   // should have been folded away previously and not enter in here.
6208   Value *Result;
6209   if (isSignedCmp) {
6210     // We're performing a signed comparison.
6211     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
6212       Result = ConstantInt::getFalse();          // X < (small) --> false
6213     else
6214       Result = ConstantInt::getTrue();           // X < (large) --> true
6215   } else {
6216     // We're performing an unsigned comparison.
6217     if (isSignedExt) {
6218       // We're performing an unsigned comp with a sign extended value.
6219       // This is true if the input is >= 0. [aka >s -1]
6220       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6221       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6222                                    NegOne, ICI.getName()), ICI);
6223     } else {
6224       // Unsigned extend & unsigned compare -> always true.
6225       Result = ConstantInt::getTrue();
6226     }
6227   }
6228
6229   // Finally, return the value computed.
6230   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6231       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6232     return ReplaceInstUsesWith(ICI, Result);
6233   } else {
6234     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6235             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6236            "ICmp should be folded!");
6237     if (Constant *CI = dyn_cast<Constant>(Result))
6238       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6239     else
6240       return BinaryOperator::createNot(Result);
6241   }
6242 }
6243
6244 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6245   return commonShiftTransforms(I);
6246 }
6247
6248 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6249   return commonShiftTransforms(I);
6250 }
6251
6252 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6253   return commonShiftTransforms(I);
6254 }
6255
6256 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6257   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6258   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6259
6260   // shl X, 0 == X and shr X, 0 == X
6261   // shl 0, X == 0 and shr 0, X == 0
6262   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6263       Op0 == Constant::getNullValue(Op0->getType()))
6264     return ReplaceInstUsesWith(I, Op0);
6265   
6266   if (isa<UndefValue>(Op0)) {            
6267     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6268       return ReplaceInstUsesWith(I, Op0);
6269     else                                    // undef << X -> 0, undef >>u X -> 0
6270       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6271   }
6272   if (isa<UndefValue>(Op1)) {
6273     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6274       return ReplaceInstUsesWith(I, Op0);          
6275     else                                     // X << undef, X >>u undef -> 0
6276       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6277   }
6278
6279   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6280   if (I.getOpcode() == Instruction::AShr)
6281     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6282       if (CSI->isAllOnesValue())
6283         return ReplaceInstUsesWith(I, CSI);
6284
6285   // Try to fold constant and into select arguments.
6286   if (isa<Constant>(Op0))
6287     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6288       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6289         return R;
6290
6291   // See if we can turn a signed shr into an unsigned shr.
6292   if (I.isArithmeticShift()) {
6293     if (MaskedValueIsZero(Op0,
6294                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
6295       return BinaryOperator::createLShr(Op0, Op1, I.getName());
6296     }
6297   }
6298
6299   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6300     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6301       return Res;
6302   return 0;
6303 }
6304
6305 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6306                                                BinaryOperator &I) {
6307   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6308
6309   // See if we can simplify any instructions used by the instruction whose sole 
6310   // purpose is to compute bits we don't care about.
6311   uint64_t KnownZero, KnownOne;
6312   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
6313                            KnownZero, KnownOne))
6314     return &I;
6315   
6316   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6317   // of a signed value.
6318   //
6319   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6320   if (Op1->getZExtValue() >= TypeBits) {
6321     if (I.getOpcode() != Instruction::AShr)
6322       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6323     else {
6324       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6325       return &I;
6326     }
6327   }
6328   
6329   // ((X*C1) << C2) == (X * (C1 << C2))
6330   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6331     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6332       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6333         return BinaryOperator::createMul(BO->getOperand(0),
6334                                          ConstantExpr::getShl(BOOp, Op1));
6335   
6336   // Try to fold constant and into select arguments.
6337   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6338     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6339       return R;
6340   if (isa<PHINode>(Op0))
6341     if (Instruction *NV = FoldOpIntoPhi(I))
6342       return NV;
6343   
6344   if (Op0->hasOneUse()) {
6345     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6346       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6347       Value *V1, *V2;
6348       ConstantInt *CC;
6349       switch (Op0BO->getOpcode()) {
6350         default: break;
6351         case Instruction::Add:
6352         case Instruction::And:
6353         case Instruction::Or:
6354         case Instruction::Xor: {
6355           // These operators commute.
6356           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6357           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6358               match(Op0BO->getOperand(1),
6359                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6360             Instruction *YS = BinaryOperator::createShl(
6361                                             Op0BO->getOperand(0), Op1,
6362                                             Op0BO->getName());
6363             InsertNewInstBefore(YS, I); // (Y << C)
6364             Instruction *X = 
6365               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6366                                      Op0BO->getOperand(1)->getName());
6367             InsertNewInstBefore(X, I);  // (X + (Y << C))
6368             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6369             C2 = ConstantExpr::getShl(C2, Op1);
6370             return BinaryOperator::createAnd(X, C2);
6371           }
6372           
6373           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6374           Value *Op0BOOp1 = Op0BO->getOperand(1);
6375           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6376               match(Op0BOOp1, 
6377                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6378               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6379               V2 == Op1) {
6380             Instruction *YS = BinaryOperator::createShl(
6381                                                      Op0BO->getOperand(0), Op1,
6382                                                      Op0BO->getName());
6383             InsertNewInstBefore(YS, I); // (Y << C)
6384             Instruction *XM =
6385               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6386                                         V1->getName()+".mask");
6387             InsertNewInstBefore(XM, I); // X & (CC << C)
6388             
6389             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6390           }
6391         }
6392           
6393         // FALL THROUGH.
6394         case Instruction::Sub: {
6395           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6396           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6397               match(Op0BO->getOperand(0),
6398                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6399             Instruction *YS = BinaryOperator::createShl(
6400                                                      Op0BO->getOperand(1), Op1,
6401                                                      Op0BO->getName());
6402             InsertNewInstBefore(YS, I); // (Y << C)
6403             Instruction *X =
6404               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6405                                      Op0BO->getOperand(0)->getName());
6406             InsertNewInstBefore(X, I);  // (X + (Y << C))
6407             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
6408             C2 = ConstantExpr::getShl(C2, Op1);
6409             return BinaryOperator::createAnd(X, C2);
6410           }
6411           
6412           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6413           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6414               match(Op0BO->getOperand(0),
6415                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6416                           m_ConstantInt(CC))) && V2 == Op1 &&
6417               cast<BinaryOperator>(Op0BO->getOperand(0))
6418                   ->getOperand(0)->hasOneUse()) {
6419             Instruction *YS = BinaryOperator::createShl(
6420                                                      Op0BO->getOperand(1), Op1,
6421                                                      Op0BO->getName());
6422             InsertNewInstBefore(YS, I); // (Y << C)
6423             Instruction *XM =
6424               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6425                                         V1->getName()+".mask");
6426             InsertNewInstBefore(XM, I); // X & (CC << C)
6427             
6428             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6429           }
6430           
6431           break;
6432         }
6433       }
6434       
6435       
6436       // If the operand is an bitwise operator with a constant RHS, and the
6437       // shift is the only use, we can pull it out of the shift.
6438       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6439         bool isValid = true;     // Valid only for And, Or, Xor
6440         bool highBitSet = false; // Transform if high bit of constant set?
6441         
6442         switch (Op0BO->getOpcode()) {
6443           default: isValid = false; break;   // Do not perform transform!
6444           case Instruction::Add:
6445             isValid = isLeftShift;
6446             break;
6447           case Instruction::Or:
6448           case Instruction::Xor:
6449             highBitSet = false;
6450             break;
6451           case Instruction::And:
6452             highBitSet = true;
6453             break;
6454         }
6455         
6456         // If this is a signed shift right, and the high bit is modified
6457         // by the logical operation, do not perform the transformation.
6458         // The highBitSet boolean indicates the value of the high bit of
6459         // the constant which would cause it to be modified for this
6460         // operation.
6461         //
6462         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6463           uint64_t Val = Op0C->getZExtValue();
6464           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
6465         }
6466         
6467         if (isValid) {
6468           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6469           
6470           Instruction *NewShift =
6471             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6472           InsertNewInstBefore(NewShift, I);
6473           NewShift->takeName(Op0BO);
6474           
6475           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6476                                         NewRHS);
6477         }
6478       }
6479     }
6480   }
6481   
6482   // Find out if this is a shift of a shift by a constant.
6483   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6484   if (ShiftOp && !ShiftOp->isShift())
6485     ShiftOp = 0;
6486   
6487   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6488     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6489     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6490     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
6491     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6492     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6493     Value *X = ShiftOp->getOperand(0);
6494     
6495     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6496     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
6497       AmtSum = I.getType()->getPrimitiveSizeInBits();
6498     
6499     const IntegerType *Ty = cast<IntegerType>(I.getType());
6500     
6501     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6502     if (I.getOpcode() == ShiftOp->getOpcode()) {
6503       return BinaryOperator::create(I.getOpcode(), X,
6504                                     ConstantInt::get(Ty, AmtSum));
6505     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6506                I.getOpcode() == Instruction::AShr) {
6507       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6508       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6509     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6510                I.getOpcode() == Instruction::LShr) {
6511       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6512       Instruction *Shift =
6513         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6514       InsertNewInstBefore(Shift, I);
6515
6516       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6517       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6518     }
6519     
6520     // Okay, if we get here, one shift must be left, and the other shift must be
6521     // right.  See if the amounts are equal.
6522     if (ShiftAmt1 == ShiftAmt2) {
6523       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6524       if (I.getOpcode() == Instruction::Shl) {
6525         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
6526         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6527       }
6528       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6529       if (I.getOpcode() == Instruction::LShr) {
6530         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
6531         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
6532       }
6533       // We can simplify ((X << C) >>s C) into a trunc + sext.
6534       // NOTE: we could do this for any C, but that would make 'unusual' integer
6535       // types.  For now, just stick to ones well-supported by the code
6536       // generators.
6537       const Type *SExtType = 0;
6538       switch (Ty->getBitWidth() - ShiftAmt1) {
6539       case 8 : SExtType = Type::Int8Ty; break;
6540       case 16: SExtType = Type::Int16Ty; break;
6541       case 32: SExtType = Type::Int32Ty; break;
6542       default: break;
6543       }
6544       if (SExtType) {
6545         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6546         InsertNewInstBefore(NewTrunc, I);
6547         return new SExtInst(NewTrunc, Ty);
6548       }
6549       // Otherwise, we can't handle it yet.
6550     } else if (ShiftAmt1 < ShiftAmt2) {
6551       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
6552       
6553       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6554       if (I.getOpcode() == Instruction::Shl) {
6555         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6556                ShiftOp->getOpcode() == Instruction::AShr);
6557         Instruction *Shift =
6558           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6559         InsertNewInstBefore(Shift, I);
6560         
6561         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6562         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6563       }
6564       
6565       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6566       if (I.getOpcode() == Instruction::LShr) {
6567         assert(ShiftOp->getOpcode() == Instruction::Shl);
6568         Instruction *Shift =
6569           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6570         InsertNewInstBefore(Shift, I);
6571         
6572         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6573         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6574       }
6575       
6576       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6577     } else {
6578       assert(ShiftAmt2 < ShiftAmt1);
6579       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6580
6581       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6582       if (I.getOpcode() == Instruction::Shl) {
6583         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6584                ShiftOp->getOpcode() == Instruction::AShr);
6585         Instruction *Shift =
6586           BinaryOperator::create(ShiftOp->getOpcode(), X,
6587                                  ConstantInt::get(Ty, ShiftDiff));
6588         InsertNewInstBefore(Shift, I);
6589         
6590         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
6591         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6592       }
6593       
6594       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6595       if (I.getOpcode() == Instruction::LShr) {
6596         assert(ShiftOp->getOpcode() == Instruction::Shl);
6597         Instruction *Shift =
6598           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6599         InsertNewInstBefore(Shift, I);
6600         
6601         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6602         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6603       }
6604       
6605       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6606     }
6607   }
6608   return 0;
6609 }
6610
6611
6612 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6613 /// expression.  If so, decompose it, returning some value X, such that Val is
6614 /// X*Scale+Offset.
6615 ///
6616 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6617                                         unsigned &Offset) {
6618   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6619   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6620     Offset = CI->getZExtValue();
6621     Scale  = 1;
6622     return ConstantInt::get(Type::Int32Ty, 0);
6623   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6624     if (I->getNumOperands() == 2) {
6625       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6626         if (I->getOpcode() == Instruction::Shl) {
6627           // This is a value scaled by '1 << the shift amt'.
6628           Scale = 1U << CUI->getZExtValue();
6629           Offset = 0;
6630           return I->getOperand(0);
6631         } else if (I->getOpcode() == Instruction::Mul) {
6632           // This value is scaled by 'CUI'.
6633           Scale = CUI->getZExtValue();
6634           Offset = 0;
6635           return I->getOperand(0);
6636         } else if (I->getOpcode() == Instruction::Add) {
6637           // We have X+C.  Check to see if we really have (X*C2)+C1, 
6638           // where C1 is divisible by C2.
6639           unsigned SubScale;
6640           Value *SubVal = 
6641             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6642           Offset += CUI->getZExtValue();
6643           if (SubScale > 1 && (Offset % SubScale == 0)) {
6644             Scale = SubScale;
6645             return SubVal;
6646           }
6647         }
6648       }
6649     }
6650   }
6651
6652   // Otherwise, we can't look past this.
6653   Scale = 1;
6654   Offset = 0;
6655   return Val;
6656 }
6657
6658
6659 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6660 /// try to eliminate the cast by moving the type information into the alloc.
6661 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6662                                                    AllocationInst &AI) {
6663   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
6664   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
6665   
6666   // Remove any uses of AI that are dead.
6667   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6668   
6669   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6670     Instruction *User = cast<Instruction>(*UI++);
6671     if (isInstructionTriviallyDead(User)) {
6672       while (UI != E && *UI == User)
6673         ++UI; // If this instruction uses AI more than once, don't break UI.
6674       
6675       ++NumDeadInst;
6676       DOUT << "IC: DCE: " << *User;
6677       EraseInstFromFunction(*User);
6678     }
6679   }
6680   
6681   // Get the type really allocated and the type casted to.
6682   const Type *AllocElTy = AI.getAllocatedType();
6683   const Type *CastElTy = PTy->getElementType();
6684   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6685
6686   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6687   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6688   if (CastElTyAlign < AllocElTyAlign) return 0;
6689
6690   // If the allocation has multiple uses, only promote it if we are strictly
6691   // increasing the alignment of the resultant allocation.  If we keep it the
6692   // same, we open the door to infinite loops of various kinds.
6693   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6694
6695   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6696   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6697   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6698
6699   // See if we can satisfy the modulus by pulling a scale out of the array
6700   // size argument.
6701   unsigned ArraySizeScale, ArrayOffset;
6702   Value *NumElements = // See if the array size is a decomposable linear expr.
6703     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6704  
6705   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6706   // do the xform.
6707   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6708       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6709
6710   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6711   Value *Amt = 0;
6712   if (Scale == 1) {
6713     Amt = NumElements;
6714   } else {
6715     // If the allocation size is constant, form a constant mul expression
6716     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6717     if (isa<ConstantInt>(NumElements))
6718       Amt = ConstantExpr::getMul(
6719               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6720     // otherwise multiply the amount and the number of elements
6721     else if (Scale != 1) {
6722       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6723       Amt = InsertNewInstBefore(Tmp, AI);
6724     }
6725   }
6726   
6727   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6728     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
6729     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6730     Amt = InsertNewInstBefore(Tmp, AI);
6731   }
6732   
6733   AllocationInst *New;
6734   if (isa<MallocInst>(AI))
6735     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6736   else
6737     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6738   InsertNewInstBefore(New, AI);
6739   New->takeName(&AI);
6740   
6741   // If the allocation has multiple uses, insert a cast and change all things
6742   // that used it to use the new cast.  This will also hack on CI, but it will
6743   // die soon.
6744   if (!AI.hasOneUse()) {
6745     AddUsesToWorkList(AI);
6746     // New is the allocation instruction, pointer typed. AI is the original
6747     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6748     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6749     InsertNewInstBefore(NewCast, AI);
6750     AI.replaceAllUsesWith(NewCast);
6751   }
6752   return ReplaceInstUsesWith(CI, New);
6753 }
6754
6755 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6756 /// and return it as type Ty without inserting any new casts and without
6757 /// changing the computed value.  This is used by code that tries to decide
6758 /// whether promoting or shrinking integer operations to wider or smaller types
6759 /// will allow us to eliminate a truncate or extend.
6760 ///
6761 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6762 /// extension operation if Ty is larger.
6763 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6764                                        int &NumCastsRemoved) {
6765   // We can always evaluate constants in another type.
6766   if (isa<ConstantInt>(V))
6767     return true;
6768   
6769   Instruction *I = dyn_cast<Instruction>(V);
6770   if (!I) return false;
6771   
6772   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6773   
6774   switch (I->getOpcode()) {
6775   case Instruction::Add:
6776   case Instruction::Sub:
6777   case Instruction::And:
6778   case Instruction::Or:
6779   case Instruction::Xor:
6780     if (!I->hasOneUse()) return false;
6781     // These operators can all arbitrarily be extended or truncated.
6782     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6783            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6784
6785   case Instruction::Shl:
6786     if (!I->hasOneUse()) return false;
6787     // If we are truncating the result of this SHL, and if it's a shift of a
6788     // constant amount, we can always perform a SHL in a smaller type.
6789     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6790       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6791           CI->getZExtValue() < Ty->getBitWidth())
6792         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6793     }
6794     break;
6795   case Instruction::LShr:
6796     if (!I->hasOneUse()) return false;
6797     // If this is a truncate of a logical shr, we can truncate it to a smaller
6798     // lshr iff we know that the bits we would otherwise be shifting in are
6799     // already zeros.
6800     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6801       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6802           MaskedValueIsZero(I->getOperand(0),
6803                             OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6804           CI->getZExtValue() < Ty->getBitWidth()) {
6805         return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6806       }
6807     }
6808     break;
6809   case Instruction::Trunc:
6810   case Instruction::ZExt:
6811   case Instruction::SExt:
6812     // If this is a cast from the destination type, we can trivially eliminate
6813     // it, and this will remove a cast overall.
6814     if (I->getOperand(0)->getType() == Ty) {
6815       // If the first operand is itself a cast, and is eliminable, do not count
6816       // this as an eliminable cast.  We would prefer to eliminate those two
6817       // casts first.
6818       if (isa<CastInst>(I->getOperand(0)))
6819         return true;
6820       
6821       ++NumCastsRemoved;
6822       return true;
6823     }
6824     break;
6825   default:
6826     // TODO: Can handle more cases here.
6827     break;
6828   }
6829   
6830   return false;
6831 }
6832
6833 /// EvaluateInDifferentType - Given an expression that 
6834 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6835 /// evaluate the expression.
6836 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6837                                              bool isSigned) {
6838   if (Constant *C = dyn_cast<Constant>(V))
6839     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6840
6841   // Otherwise, it must be an instruction.
6842   Instruction *I = cast<Instruction>(V);
6843   Instruction *Res = 0;
6844   switch (I->getOpcode()) {
6845   case Instruction::Add:
6846   case Instruction::Sub:
6847   case Instruction::And:
6848   case Instruction::Or:
6849   case Instruction::Xor:
6850   case Instruction::AShr:
6851   case Instruction::LShr:
6852   case Instruction::Shl: {
6853     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6854     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6855     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6856                                  LHS, RHS, I->getName());
6857     break;
6858   }    
6859   case Instruction::Trunc:
6860   case Instruction::ZExt:
6861   case Instruction::SExt:
6862   case Instruction::BitCast:
6863     // If the source type of the cast is the type we're trying for then we can
6864     // just return the source. There's no need to insert it because its not new.
6865     if (I->getOperand(0)->getType() == Ty)
6866       return I->getOperand(0);
6867     
6868     // Some other kind of cast, which shouldn't happen, so just ..
6869     // FALL THROUGH
6870   default: 
6871     // TODO: Can handle more cases here.
6872     assert(0 && "Unreachable!");
6873     break;
6874   }
6875   
6876   return InsertNewInstBefore(Res, *I);
6877 }
6878
6879 /// @brief Implement the transforms common to all CastInst visitors.
6880 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6881   Value *Src = CI.getOperand(0);
6882
6883   // Casting undef to anything results in undef so might as just replace it and
6884   // get rid of the cast.
6885   if (isa<UndefValue>(Src))   // cast undef -> undef
6886     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6887
6888   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6889   // eliminate it now.
6890   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6891     if (Instruction::CastOps opc = 
6892         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6893       // The first cast (CSrc) is eliminable so we need to fix up or replace
6894       // the second cast (CI). CSrc will then have a good chance of being dead.
6895       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6896     }
6897   }
6898
6899   // If casting the result of a getelementptr instruction with no offset, turn
6900   // this into a cast of the original pointer!
6901   //
6902   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6903     bool AllZeroOperands = true;
6904     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6905       if (!isa<Constant>(GEP->getOperand(i)) ||
6906           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6907         AllZeroOperands = false;
6908         break;
6909       }
6910     if (AllZeroOperands) {
6911       // Changing the cast operand is usually not a good idea but it is safe
6912       // here because the pointer operand is being replaced with another 
6913       // pointer operand so the opcode doesn't need to change.
6914       CI.setOperand(0, GEP->getOperand(0));
6915       return &CI;
6916     }
6917   }
6918     
6919   // If we are casting a malloc or alloca to a pointer to a type of the same
6920   // size, rewrite the allocation instruction to allocate the "right" type.
6921   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6922     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6923       return V;
6924
6925   // If we are casting a select then fold the cast into the select
6926   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6927     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6928       return NV;
6929
6930   // If we are casting a PHI then fold the cast into the PHI
6931   if (isa<PHINode>(Src))
6932     if (Instruction *NV = FoldOpIntoPhi(CI))
6933       return NV;
6934   
6935   return 0;
6936 }
6937
6938 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6939 /// integer types. This function implements the common transforms for all those
6940 /// cases.
6941 /// @brief Implement the transforms common to CastInst with integer operands
6942 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6943   if (Instruction *Result = commonCastTransforms(CI))
6944     return Result;
6945
6946   Value *Src = CI.getOperand(0);
6947   const Type *SrcTy = Src->getType();
6948   const Type *DestTy = CI.getType();
6949   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6950   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6951
6952   // See if we can simplify any instructions used by the LHS whose sole 
6953   // purpose is to compute bits we don't care about.
6954   uint64_t KnownZero = 0, KnownOne = 0;
6955   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6956                            KnownZero, KnownOne))
6957     return &CI;
6958
6959   // If the source isn't an instruction or has more than one use then we
6960   // can't do anything more. 
6961   Instruction *SrcI = dyn_cast<Instruction>(Src);
6962   if (!SrcI || !Src->hasOneUse())
6963     return 0;
6964
6965   // Attempt to propagate the cast into the instruction for int->int casts.
6966   int NumCastsRemoved = 0;
6967   if (!isa<BitCastInst>(CI) &&
6968       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6969                                  NumCastsRemoved)) {
6970     // If this cast is a truncate, evaluting in a different type always
6971     // eliminates the cast, so it is always a win.  If this is a noop-cast
6972     // this just removes a noop cast which isn't pointful, but simplifies
6973     // the code.  If this is a zero-extension, we need to do an AND to
6974     // maintain the clear top-part of the computation, so we require that
6975     // the input have eliminated at least one cast.  If this is a sign
6976     // extension, we insert two new casts (to do the extension) so we
6977     // require that two casts have been eliminated.
6978     bool DoXForm;
6979     switch (CI.getOpcode()) {
6980     default:
6981       // All the others use floating point so we shouldn't actually 
6982       // get here because of the check above.
6983       assert(0 && "Unknown cast type");
6984     case Instruction::Trunc:
6985       DoXForm = true;
6986       break;
6987     case Instruction::ZExt:
6988       DoXForm = NumCastsRemoved >= 1;
6989       break;
6990     case Instruction::SExt:
6991       DoXForm = NumCastsRemoved >= 2;
6992       break;
6993     case Instruction::BitCast:
6994       DoXForm = false;
6995       break;
6996     }
6997     
6998     if (DoXForm) {
6999       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7000                                            CI.getOpcode() == Instruction::SExt);
7001       assert(Res->getType() == DestTy);
7002       switch (CI.getOpcode()) {
7003       default: assert(0 && "Unknown cast type!");
7004       case Instruction::Trunc:
7005       case Instruction::BitCast:
7006         // Just replace this cast with the result.
7007         return ReplaceInstUsesWith(CI, Res);
7008       case Instruction::ZExt: {
7009         // We need to emit an AND to clear the high bits.
7010         assert(SrcBitSize < DestBitSize && "Not a zext?");
7011         Constant *C = 
7012           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
7013         if (DestBitSize < 64)
7014           C = ConstantExpr::getTrunc(C, DestTy);
7015         return BinaryOperator::createAnd(Res, C);
7016       }
7017       case Instruction::SExt:
7018         // We need to emit a cast to truncate, then a cast to sext.
7019         return CastInst::create(Instruction::SExt,
7020             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7021                              CI), DestTy);
7022       }
7023     }
7024   }
7025   
7026   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7027   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7028
7029   switch (SrcI->getOpcode()) {
7030   case Instruction::Add:
7031   case Instruction::Mul:
7032   case Instruction::And:
7033   case Instruction::Or:
7034   case Instruction::Xor:
7035     // If we are discarding information, or just changing the sign, 
7036     // rewrite.
7037     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7038       // Don't insert two casts if they cannot be eliminated.  We allow 
7039       // two casts to be inserted if the sizes are the same.  This could 
7040       // only be converting signedness, which is a noop.
7041       if (DestBitSize == SrcBitSize || 
7042           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7043           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7044         Instruction::CastOps opcode = CI.getOpcode();
7045         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7046         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7047         return BinaryOperator::create(
7048             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7049       }
7050     }
7051
7052     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7053     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7054         SrcI->getOpcode() == Instruction::Xor &&
7055         Op1 == ConstantInt::getTrue() &&
7056         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7057       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7058       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7059     }
7060     break;
7061   case Instruction::SDiv:
7062   case Instruction::UDiv:
7063   case Instruction::SRem:
7064   case Instruction::URem:
7065     // If we are just changing the sign, rewrite.
7066     if (DestBitSize == SrcBitSize) {
7067       // Don't insert two casts if they cannot be eliminated.  We allow 
7068       // two casts to be inserted if the sizes are the same.  This could 
7069       // only be converting signedness, which is a noop.
7070       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7071           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7072         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7073                                               Op0, DestTy, SrcI);
7074         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7075                                               Op1, DestTy, SrcI);
7076         return BinaryOperator::create(
7077           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7078       }
7079     }
7080     break;
7081
7082   case Instruction::Shl:
7083     // Allow changing the sign of the source operand.  Do not allow 
7084     // changing the size of the shift, UNLESS the shift amount is a 
7085     // constant.  We must not change variable sized shifts to a smaller 
7086     // size, because it is undefined to shift more bits out than exist 
7087     // in the value.
7088     if (DestBitSize == SrcBitSize ||
7089         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7090       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7091           Instruction::BitCast : Instruction::Trunc);
7092       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7093       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7094       return BinaryOperator::createShl(Op0c, Op1c);
7095     }
7096     break;
7097   case Instruction::AShr:
7098     // If this is a signed shr, and if all bits shifted in are about to be
7099     // truncated off, turn it into an unsigned shr to allow greater
7100     // simplifications.
7101     if (DestBitSize < SrcBitSize &&
7102         isa<ConstantInt>(Op1)) {
7103       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7104       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7105         // Insert the new logical shift right.
7106         return BinaryOperator::createLShr(Op0, Op1);
7107       }
7108     }
7109     break;
7110
7111   case Instruction::ICmp:
7112     // If we are just checking for a icmp eq of a single bit and casting it
7113     // to an integer, then shift the bit to the appropriate place and then
7114     // cast to integer to avoid the comparison.
7115     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
7116       uint64_t Op1CV = Op1C->getZExtValue();
7117       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
7118       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7119       // cast (X == 1) to int --> X        iff X has only the low bit set.
7120       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
7121       // cast (X != 0) to int --> X        iff X has only the low bit set.
7122       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
7123       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
7124       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7125       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
7126         // If Op1C some other power of two, convert:
7127         uint64_t KnownZero, KnownOne;
7128         uint64_t TypeMask = Op1C->getType()->getBitMask();
7129         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
7130
7131         // This only works for EQ and NE
7132         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7133         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7134           break;
7135         
7136         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
7137           bool isNE = pred == ICmpInst::ICMP_NE;
7138           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
7139             // (X&4) == 2 --> false
7140             // (X&4) != 2 --> true
7141             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7142             Res = ConstantExpr::getZExt(Res, CI.getType());
7143             return ReplaceInstUsesWith(CI, Res);
7144           }
7145           
7146           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
7147           Value *In = Op0;
7148           if (ShiftAmt) {
7149             // Perform a logical shr by shiftamt.
7150             // Insert the shift to put the result in the low bit.
7151             In = InsertNewInstBefore(
7152               BinaryOperator::createLShr(In,
7153                                      ConstantInt::get(In->getType(), ShiftAmt),
7154                                      In->getName()+".lobit"), CI);
7155           }
7156           
7157           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7158             Constant *One = ConstantInt::get(In->getType(), 1);
7159             In = BinaryOperator::createXor(In, One, "tmp");
7160             InsertNewInstBefore(cast<Instruction>(In), CI);
7161           }
7162           
7163           if (CI.getType() == In->getType())
7164             return ReplaceInstUsesWith(CI, In);
7165           else
7166             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7167         }
7168       }
7169     }
7170     break;
7171   }
7172   return 0;
7173 }
7174
7175 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
7176   if (Instruction *Result = commonIntCastTransforms(CI))
7177     return Result;
7178   
7179   Value *Src = CI.getOperand(0);
7180   const Type *Ty = CI.getType();
7181   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
7182   
7183   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7184     switch (SrcI->getOpcode()) {
7185     default: break;
7186     case Instruction::LShr:
7187       // We can shrink lshr to something smaller if we know the bits shifted in
7188       // are already zeros.
7189       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7190         unsigned ShAmt = ShAmtV->getZExtValue();
7191         
7192         // Get a mask for the bits shifting in.
7193         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
7194         Value* SrcIOp0 = SrcI->getOperand(0);
7195         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7196           if (ShAmt >= DestBitWidth)        // All zeros.
7197             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7198
7199           // Okay, we can shrink this.  Truncate the input, then return a new
7200           // shift.
7201           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7202           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7203                                        Ty, CI);
7204           return BinaryOperator::createLShr(V1, V2);
7205         }
7206       } else {     // This is a variable shr.
7207         
7208         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7209         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7210         // loop-invariant and CSE'd.
7211         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7212           Value *One = ConstantInt::get(SrcI->getType(), 1);
7213
7214           Value *V = InsertNewInstBefore(
7215               BinaryOperator::createShl(One, SrcI->getOperand(1),
7216                                      "tmp"), CI);
7217           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7218                                                             SrcI->getOperand(0),
7219                                                             "tmp"), CI);
7220           Value *Zero = Constant::getNullValue(V->getType());
7221           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7222         }
7223       }
7224       break;
7225     }
7226   }
7227   
7228   return 0;
7229 }
7230
7231 Instruction *InstCombiner::visitZExt(CastInst &CI) {
7232   // If one of the common conversion will work ..
7233   if (Instruction *Result = commonIntCastTransforms(CI))
7234     return Result;
7235
7236   Value *Src = CI.getOperand(0);
7237
7238   // If this is a cast of a cast
7239   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7240     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7241     // types and if the sizes are just right we can convert this into a logical
7242     // 'and' which will be much cheaper than the pair of casts.
7243     if (isa<TruncInst>(CSrc)) {
7244       // Get the sizes of the types involved
7245       Value *A = CSrc->getOperand(0);
7246       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7247       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7248       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7249       // If we're actually extending zero bits and the trunc is a no-op
7250       if (MidSize < DstSize && SrcSize == DstSize) {
7251         // Replace both of the casts with an And of the type mask.
7252         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
7253         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
7254         Instruction *And = 
7255           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7256         // Unfortunately, if the type changed, we need to cast it back.
7257         if (And->getType() != CI.getType()) {
7258           And->setName(CSrc->getName()+".mask");
7259           InsertNewInstBefore(And, CI);
7260           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7261         }
7262         return And;
7263       }
7264     }
7265   }
7266
7267   return 0;
7268 }
7269
7270 Instruction *InstCombiner::visitSExt(CastInst &CI) {
7271   return commonIntCastTransforms(CI);
7272 }
7273
7274 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7275   return commonCastTransforms(CI);
7276 }
7277
7278 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7279   return commonCastTransforms(CI);
7280 }
7281
7282 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7283   return commonCastTransforms(CI);
7284 }
7285
7286 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7287   return commonCastTransforms(CI);
7288 }
7289
7290 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7291   return commonCastTransforms(CI);
7292 }
7293
7294 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7295   return commonCastTransforms(CI);
7296 }
7297
7298 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7299   return commonCastTransforms(CI);
7300 }
7301
7302 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7303   return commonCastTransforms(CI);
7304 }
7305
7306 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7307
7308   // If the operands are integer typed then apply the integer transforms,
7309   // otherwise just apply the common ones.
7310   Value *Src = CI.getOperand(0);
7311   const Type *SrcTy = Src->getType();
7312   const Type *DestTy = CI.getType();
7313
7314   if (SrcTy->isInteger() && DestTy->isInteger()) {
7315     if (Instruction *Result = commonIntCastTransforms(CI))
7316       return Result;
7317   } else {
7318     if (Instruction *Result = commonCastTransforms(CI))
7319       return Result;
7320   }
7321
7322
7323   // Get rid of casts from one type to the same type. These are useless and can
7324   // be replaced by the operand.
7325   if (DestTy == Src->getType())
7326     return ReplaceInstUsesWith(CI, Src);
7327
7328   // If the source and destination are pointers, and this cast is equivalent to
7329   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
7330   // This can enhance SROA and other transforms that want type-safe pointers.
7331   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7332     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7333       const Type *DstElTy = DstPTy->getElementType();
7334       const Type *SrcElTy = SrcPTy->getElementType();
7335       
7336       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7337       unsigned NumZeros = 0;
7338       while (SrcElTy != DstElTy && 
7339              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7340              SrcElTy->getNumContainedTypes() /* not "{}" */) {
7341         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7342         ++NumZeros;
7343       }
7344
7345       // If we found a path from the src to dest, create the getelementptr now.
7346       if (SrcElTy == DstElTy) {
7347         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7348         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
7349       }
7350     }
7351   }
7352
7353   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7354     if (SVI->hasOneUse()) {
7355       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7356       // a bitconvert to a vector with the same # elts.
7357       if (isa<VectorType>(DestTy) && 
7358           cast<VectorType>(DestTy)->getNumElements() == 
7359                 SVI->getType()->getNumElements()) {
7360         CastInst *Tmp;
7361         // If either of the operands is a cast from CI.getType(), then
7362         // evaluating the shuffle in the casted destination's type will allow
7363         // us to eliminate at least one cast.
7364         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7365              Tmp->getOperand(0)->getType() == DestTy) ||
7366             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7367              Tmp->getOperand(0)->getType() == DestTy)) {
7368           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7369                                                SVI->getOperand(0), DestTy, &CI);
7370           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7371                                                SVI->getOperand(1), DestTy, &CI);
7372           // Return a new shuffle vector.  Use the same element ID's, as we
7373           // know the vector types match #elts.
7374           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7375         }
7376       }
7377     }
7378   }
7379   return 0;
7380 }
7381
7382 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7383 ///   %C = or %A, %B
7384 ///   %D = select %cond, %C, %A
7385 /// into:
7386 ///   %C = select %cond, %B, 0
7387 ///   %D = or %A, %C
7388 ///
7389 /// Assuming that the specified instruction is an operand to the select, return
7390 /// a bitmask indicating which operands of this instruction are foldable if they
7391 /// equal the other incoming value of the select.
7392 ///
7393 static unsigned GetSelectFoldableOperands(Instruction *I) {
7394   switch (I->getOpcode()) {
7395   case Instruction::Add:
7396   case Instruction::Mul:
7397   case Instruction::And:
7398   case Instruction::Or:
7399   case Instruction::Xor:
7400     return 3;              // Can fold through either operand.
7401   case Instruction::Sub:   // Can only fold on the amount subtracted.
7402   case Instruction::Shl:   // Can only fold on the shift amount.
7403   case Instruction::LShr:
7404   case Instruction::AShr:
7405     return 1;
7406   default:
7407     return 0;              // Cannot fold
7408   }
7409 }
7410
7411 /// GetSelectFoldableConstant - For the same transformation as the previous
7412 /// function, return the identity constant that goes into the select.
7413 static Constant *GetSelectFoldableConstant(Instruction *I) {
7414   switch (I->getOpcode()) {
7415   default: assert(0 && "This cannot happen!"); abort();
7416   case Instruction::Add:
7417   case Instruction::Sub:
7418   case Instruction::Or:
7419   case Instruction::Xor:
7420   case Instruction::Shl:
7421   case Instruction::LShr:
7422   case Instruction::AShr:
7423     return Constant::getNullValue(I->getType());
7424   case Instruction::And:
7425     return ConstantInt::getAllOnesValue(I->getType());
7426   case Instruction::Mul:
7427     return ConstantInt::get(I->getType(), 1);
7428   }
7429 }
7430
7431 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7432 /// have the same opcode and only one use each.  Try to simplify this.
7433 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7434                                           Instruction *FI) {
7435   if (TI->getNumOperands() == 1) {
7436     // If this is a non-volatile load or a cast from the same type,
7437     // merge.
7438     if (TI->isCast()) {
7439       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7440         return 0;
7441     } else {
7442       return 0;  // unknown unary op.
7443     }
7444
7445     // Fold this by inserting a select from the input values.
7446     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7447                                        FI->getOperand(0), SI.getName()+".v");
7448     InsertNewInstBefore(NewSI, SI);
7449     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7450                             TI->getType());
7451   }
7452
7453   // Only handle binary operators here.
7454   if (!isa<BinaryOperator>(TI))
7455     return 0;
7456
7457   // Figure out if the operations have any operands in common.
7458   Value *MatchOp, *OtherOpT, *OtherOpF;
7459   bool MatchIsOpZero;
7460   if (TI->getOperand(0) == FI->getOperand(0)) {
7461     MatchOp  = TI->getOperand(0);
7462     OtherOpT = TI->getOperand(1);
7463     OtherOpF = FI->getOperand(1);
7464     MatchIsOpZero = true;
7465   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7466     MatchOp  = TI->getOperand(1);
7467     OtherOpT = TI->getOperand(0);
7468     OtherOpF = FI->getOperand(0);
7469     MatchIsOpZero = false;
7470   } else if (!TI->isCommutative()) {
7471     return 0;
7472   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7473     MatchOp  = TI->getOperand(0);
7474     OtherOpT = TI->getOperand(1);
7475     OtherOpF = FI->getOperand(0);
7476     MatchIsOpZero = true;
7477   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7478     MatchOp  = TI->getOperand(1);
7479     OtherOpT = TI->getOperand(0);
7480     OtherOpF = FI->getOperand(1);
7481     MatchIsOpZero = true;
7482   } else {
7483     return 0;
7484   }
7485
7486   // If we reach here, they do have operations in common.
7487   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7488                                      OtherOpF, SI.getName()+".v");
7489   InsertNewInstBefore(NewSI, SI);
7490
7491   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7492     if (MatchIsOpZero)
7493       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7494     else
7495       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7496   }
7497   assert(0 && "Shouldn't get here");
7498   return 0;
7499 }
7500
7501 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7502   Value *CondVal = SI.getCondition();
7503   Value *TrueVal = SI.getTrueValue();
7504   Value *FalseVal = SI.getFalseValue();
7505
7506   // select true, X, Y  -> X
7507   // select false, X, Y -> Y
7508   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7509     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7510
7511   // select C, X, X -> X
7512   if (TrueVal == FalseVal)
7513     return ReplaceInstUsesWith(SI, TrueVal);
7514
7515   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7516     return ReplaceInstUsesWith(SI, FalseVal);
7517   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7518     return ReplaceInstUsesWith(SI, TrueVal);
7519   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7520     if (isa<Constant>(TrueVal))
7521       return ReplaceInstUsesWith(SI, TrueVal);
7522     else
7523       return ReplaceInstUsesWith(SI, FalseVal);
7524   }
7525
7526   if (SI.getType() == Type::Int1Ty) {
7527     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7528       if (C->getZExtValue()) {
7529         // Change: A = select B, true, C --> A = or B, C
7530         return BinaryOperator::createOr(CondVal, FalseVal);
7531       } else {
7532         // Change: A = select B, false, C --> A = and !B, C
7533         Value *NotCond =
7534           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7535                                              "not."+CondVal->getName()), SI);
7536         return BinaryOperator::createAnd(NotCond, FalseVal);
7537       }
7538     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7539       if (C->getZExtValue() == false) {
7540         // Change: A = select B, C, false --> A = and B, C
7541         return BinaryOperator::createAnd(CondVal, TrueVal);
7542       } else {
7543         // Change: A = select B, C, true --> A = or !B, C
7544         Value *NotCond =
7545           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7546                                              "not."+CondVal->getName()), SI);
7547         return BinaryOperator::createOr(NotCond, TrueVal);
7548       }
7549     }
7550   }
7551
7552   // Selecting between two integer constants?
7553   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7554     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7555       // select C, 1, 0 -> cast C to int
7556       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
7557         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7558       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
7559         // select C, 0, 1 -> cast !C to int
7560         Value *NotCond =
7561           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7562                                                "not."+CondVal->getName()), SI);
7563         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7564       }
7565
7566       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7567
7568         // (x <s 0) ? -1 : 0 -> ashr x, 31
7569         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
7570         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7571           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7572             bool CanXForm = false;
7573             if (IC->isSignedPredicate())
7574               CanXForm = CmpCst->isNullValue() && 
7575                          IC->getPredicate() == ICmpInst::ICMP_SLT;
7576             else {
7577               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
7578               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
7579                          IC->getPredicate() == ICmpInst::ICMP_UGT;
7580             }
7581             
7582             if (CanXForm) {
7583               // The comparison constant and the result are not neccessarily the
7584               // same width. Make an all-ones value by inserting a AShr.
7585               Value *X = IC->getOperand(0);
7586               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
7587               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7588               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7589                                                         ShAmt, "ones");
7590               InsertNewInstBefore(SRA, SI);
7591               
7592               // Finally, convert to the type of the select RHS.  We figure out
7593               // if this requires a SExt, Trunc or BitCast based on the sizes.
7594               Instruction::CastOps opc = Instruction::BitCast;
7595               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7596               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
7597               if (SRASize < SISize)
7598                 opc = Instruction::SExt;
7599               else if (SRASize > SISize)
7600                 opc = Instruction::Trunc;
7601               return CastInst::create(opc, SRA, SI.getType());
7602             }
7603           }
7604
7605
7606         // If one of the constants is zero (we know they can't both be) and we
7607         // have a fcmp instruction with zero, and we have an 'and' with the
7608         // non-constant value, eliminate this whole mess.  This corresponds to
7609         // cases like this: ((X & 27) ? 27 : 0)
7610         if (TrueValC->isNullValue() || FalseValC->isNullValue())
7611           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7612               cast<Constant>(IC->getOperand(1))->isNullValue())
7613             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7614               if (ICA->getOpcode() == Instruction::And &&
7615                   isa<ConstantInt>(ICA->getOperand(1)) &&
7616                   (ICA->getOperand(1) == TrueValC ||
7617                    ICA->getOperand(1) == FalseValC) &&
7618                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7619                 // Okay, now we know that everything is set up, we just don't
7620                 // know whether we have a icmp_ne or icmp_eq and whether the 
7621                 // true or false val is the zero.
7622                 bool ShouldNotVal = !TrueValC->isNullValue();
7623                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7624                 Value *V = ICA;
7625                 if (ShouldNotVal)
7626                   V = InsertNewInstBefore(BinaryOperator::create(
7627                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7628                 return ReplaceInstUsesWith(SI, V);
7629               }
7630       }
7631     }
7632
7633   // See if we are selecting two values based on a comparison of the two values.
7634   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7635     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7636       // Transform (X == Y) ? X : Y  -> Y
7637       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7638         return ReplaceInstUsesWith(SI, FalseVal);
7639       // Transform (X != Y) ? X : Y  -> X
7640       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7641         return ReplaceInstUsesWith(SI, TrueVal);
7642       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7643
7644     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7645       // Transform (X == Y) ? Y : X  -> X
7646       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7647         return ReplaceInstUsesWith(SI, FalseVal);
7648       // Transform (X != Y) ? Y : X  -> Y
7649       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7650         return ReplaceInstUsesWith(SI, TrueVal);
7651       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7652     }
7653   }
7654
7655   // See if we are selecting two values based on a comparison of the two values.
7656   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7657     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7658       // Transform (X == Y) ? X : Y  -> Y
7659       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7660         return ReplaceInstUsesWith(SI, FalseVal);
7661       // Transform (X != Y) ? X : Y  -> X
7662       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7663         return ReplaceInstUsesWith(SI, TrueVal);
7664       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7665
7666     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7667       // Transform (X == Y) ? Y : X  -> X
7668       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7669         return ReplaceInstUsesWith(SI, FalseVal);
7670       // Transform (X != Y) ? Y : X  -> Y
7671       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7672         return ReplaceInstUsesWith(SI, TrueVal);
7673       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7674     }
7675   }
7676
7677   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7678     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7679       if (TI->hasOneUse() && FI->hasOneUse()) {
7680         Instruction *AddOp = 0, *SubOp = 0;
7681
7682         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7683         if (TI->getOpcode() == FI->getOpcode())
7684           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7685             return IV;
7686
7687         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7688         // even legal for FP.
7689         if (TI->getOpcode() == Instruction::Sub &&
7690             FI->getOpcode() == Instruction::Add) {
7691           AddOp = FI; SubOp = TI;
7692         } else if (FI->getOpcode() == Instruction::Sub &&
7693                    TI->getOpcode() == Instruction::Add) {
7694           AddOp = TI; SubOp = FI;
7695         }
7696
7697         if (AddOp) {
7698           Value *OtherAddOp = 0;
7699           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7700             OtherAddOp = AddOp->getOperand(1);
7701           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7702             OtherAddOp = AddOp->getOperand(0);
7703           }
7704
7705           if (OtherAddOp) {
7706             // So at this point we know we have (Y -> OtherAddOp):
7707             //        select C, (add X, Y), (sub X, Z)
7708             Value *NegVal;  // Compute -Z
7709             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7710               NegVal = ConstantExpr::getNeg(C);
7711             } else {
7712               NegVal = InsertNewInstBefore(
7713                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7714             }
7715
7716             Value *NewTrueOp = OtherAddOp;
7717             Value *NewFalseOp = NegVal;
7718             if (AddOp != TI)
7719               std::swap(NewTrueOp, NewFalseOp);
7720             Instruction *NewSel =
7721               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7722
7723             NewSel = InsertNewInstBefore(NewSel, SI);
7724             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7725           }
7726         }
7727       }
7728
7729   // See if we can fold the select into one of our operands.
7730   if (SI.getType()->isInteger()) {
7731     // See the comment above GetSelectFoldableOperands for a description of the
7732     // transformation we are doing here.
7733     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7734       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7735           !isa<Constant>(FalseVal))
7736         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7737           unsigned OpToFold = 0;
7738           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7739             OpToFold = 1;
7740           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7741             OpToFold = 2;
7742           }
7743
7744           if (OpToFold) {
7745             Constant *C = GetSelectFoldableConstant(TVI);
7746             Instruction *NewSel =
7747               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7748             InsertNewInstBefore(NewSel, SI);
7749             NewSel->takeName(TVI);
7750             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7751               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7752             else {
7753               assert(0 && "Unknown instruction!!");
7754             }
7755           }
7756         }
7757
7758     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7759       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7760           !isa<Constant>(TrueVal))
7761         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7762           unsigned OpToFold = 0;
7763           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7764             OpToFold = 1;
7765           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7766             OpToFold = 2;
7767           }
7768
7769           if (OpToFold) {
7770             Constant *C = GetSelectFoldableConstant(FVI);
7771             Instruction *NewSel =
7772               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7773             InsertNewInstBefore(NewSel, SI);
7774             NewSel->takeName(FVI);
7775             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7776               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7777             else
7778               assert(0 && "Unknown instruction!!");
7779           }
7780         }
7781   }
7782
7783   if (BinaryOperator::isNot(CondVal)) {
7784     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7785     SI.setOperand(1, FalseVal);
7786     SI.setOperand(2, TrueVal);
7787     return &SI;
7788   }
7789
7790   return 0;
7791 }
7792
7793 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7794 /// determine, return it, otherwise return 0.
7795 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7796   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7797     unsigned Align = GV->getAlignment();
7798     if (Align == 0 && TD) 
7799       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7800     return Align;
7801   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7802     unsigned Align = AI->getAlignment();
7803     if (Align == 0 && TD) {
7804       if (isa<AllocaInst>(AI))
7805         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7806       else if (isa<MallocInst>(AI)) {
7807         // Malloc returns maximally aligned memory.
7808         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7809         Align =
7810           std::max(Align,
7811                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7812         Align =
7813           std::max(Align,
7814                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7815       }
7816     }
7817     return Align;
7818   } else if (isa<BitCastInst>(V) ||
7819              (isa<ConstantExpr>(V) && 
7820               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7821     User *CI = cast<User>(V);
7822     if (isa<PointerType>(CI->getOperand(0)->getType()))
7823       return GetKnownAlignment(CI->getOperand(0), TD);
7824     return 0;
7825   } else if (isa<GetElementPtrInst>(V) ||
7826              (isa<ConstantExpr>(V) && 
7827               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7828     User *GEPI = cast<User>(V);
7829     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7830     if (BaseAlignment == 0) return 0;
7831     
7832     // If all indexes are zero, it is just the alignment of the base pointer.
7833     bool AllZeroOperands = true;
7834     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7835       if (!isa<Constant>(GEPI->getOperand(i)) ||
7836           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7837         AllZeroOperands = false;
7838         break;
7839       }
7840     if (AllZeroOperands)
7841       return BaseAlignment;
7842     
7843     // Otherwise, if the base alignment is >= the alignment we expect for the
7844     // base pointer type, then we know that the resultant pointer is aligned at
7845     // least as much as its type requires.
7846     if (!TD) return 0;
7847
7848     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7849     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7850     if (TD->getABITypeAlignment(PtrTy->getElementType())
7851         <= BaseAlignment) {
7852       const Type *GEPTy = GEPI->getType();
7853       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7854       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7855     }
7856     return 0;
7857   }
7858   return 0;
7859 }
7860
7861
7862 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7863 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7864 /// the heavy lifting.
7865 ///
7866 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7867   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7868   if (!II) return visitCallSite(&CI);
7869   
7870   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7871   // visitCallSite.
7872   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7873     bool Changed = false;
7874
7875     // memmove/cpy/set of zero bytes is a noop.
7876     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7877       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7878
7879       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7880         if (CI->getZExtValue() == 1) {
7881           // Replace the instruction with just byte operations.  We would
7882           // transform other cases to loads/stores, but we don't know if
7883           // alignment is sufficient.
7884         }
7885     }
7886
7887     // If we have a memmove and the source operation is a constant global,
7888     // then the source and dest pointers can't alias, so we can change this
7889     // into a call to memcpy.
7890     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7891       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7892         if (GVSrc->isConstant()) {
7893           Module *M = CI.getParent()->getParent()->getParent();
7894           const char *Name;
7895           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7896               Type::Int32Ty)
7897             Name = "llvm.memcpy.i32";
7898           else
7899             Name = "llvm.memcpy.i64";
7900           Constant *MemCpy = M->getOrInsertFunction(Name,
7901                                      CI.getCalledFunction()->getFunctionType());
7902           CI.setOperand(0, MemCpy);
7903           Changed = true;
7904         }
7905     }
7906
7907     // If we can determine a pointer alignment that is bigger than currently
7908     // set, update the alignment.
7909     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7910       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7911       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7912       unsigned Align = std::min(Alignment1, Alignment2);
7913       if (MI->getAlignment()->getZExtValue() < Align) {
7914         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7915         Changed = true;
7916       }
7917     } else if (isa<MemSetInst>(MI)) {
7918       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7919       if (MI->getAlignment()->getZExtValue() < Alignment) {
7920         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7921         Changed = true;
7922       }
7923     }
7924           
7925     if (Changed) return II;
7926   } else {
7927     switch (II->getIntrinsicID()) {
7928     default: break;
7929     case Intrinsic::ppc_altivec_lvx:
7930     case Intrinsic::ppc_altivec_lvxl:
7931     case Intrinsic::x86_sse_loadu_ps:
7932     case Intrinsic::x86_sse2_loadu_pd:
7933     case Intrinsic::x86_sse2_loadu_dq:
7934       // Turn PPC lvx     -> load if the pointer is known aligned.
7935       // Turn X86 loadups -> load if the pointer is known aligned.
7936       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7937         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7938                                       PointerType::get(II->getType()), CI);
7939         return new LoadInst(Ptr);
7940       }
7941       break;
7942     case Intrinsic::ppc_altivec_stvx:
7943     case Intrinsic::ppc_altivec_stvxl:
7944       // Turn stvx -> store if the pointer is known aligned.
7945       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7946         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7947         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7948                                       OpPtrTy, CI);
7949         return new StoreInst(II->getOperand(1), Ptr);
7950       }
7951       break;
7952     case Intrinsic::x86_sse_storeu_ps:
7953     case Intrinsic::x86_sse2_storeu_pd:
7954     case Intrinsic::x86_sse2_storeu_dq:
7955     case Intrinsic::x86_sse2_storel_dq:
7956       // Turn X86 storeu -> store if the pointer is known aligned.
7957       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7958         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7959         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7960                                       OpPtrTy, CI);
7961         return new StoreInst(II->getOperand(2), Ptr);
7962       }
7963       break;
7964       
7965     case Intrinsic::x86_sse_cvttss2si: {
7966       // These intrinsics only demands the 0th element of its input vector.  If
7967       // we can simplify the input based on that, do so now.
7968       uint64_t UndefElts;
7969       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7970                                                 UndefElts)) {
7971         II->setOperand(1, V);
7972         return II;
7973       }
7974       break;
7975     }
7976       
7977     case Intrinsic::ppc_altivec_vperm:
7978       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7979       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7980         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7981         
7982         // Check that all of the elements are integer constants or undefs.
7983         bool AllEltsOk = true;
7984         for (unsigned i = 0; i != 16; ++i) {
7985           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7986               !isa<UndefValue>(Mask->getOperand(i))) {
7987             AllEltsOk = false;
7988             break;
7989           }
7990         }
7991         
7992         if (AllEltsOk) {
7993           // Cast the input vectors to byte vectors.
7994           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7995                                         II->getOperand(1), Mask->getType(), CI);
7996           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7997                                         II->getOperand(2), Mask->getType(), CI);
7998           Value *Result = UndefValue::get(Op0->getType());
7999           
8000           // Only extract each element once.
8001           Value *ExtractedElts[32];
8002           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8003           
8004           for (unsigned i = 0; i != 16; ++i) {
8005             if (isa<UndefValue>(Mask->getOperand(i)))
8006               continue;
8007             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8008             Idx &= 31;  // Match the hardware behavior.
8009             
8010             if (ExtractedElts[Idx] == 0) {
8011               Instruction *Elt = 
8012                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8013               InsertNewInstBefore(Elt, CI);
8014               ExtractedElts[Idx] = Elt;
8015             }
8016           
8017             // Insert this value into the result vector.
8018             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8019             InsertNewInstBefore(cast<Instruction>(Result), CI);
8020           }
8021           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8022         }
8023       }
8024       break;
8025
8026     case Intrinsic::stackrestore: {
8027       // If the save is right next to the restore, remove the restore.  This can
8028       // happen when variable allocas are DCE'd.
8029       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8030         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8031           BasicBlock::iterator BI = SS;
8032           if (&*++BI == II)
8033             return EraseInstFromFunction(CI);
8034         }
8035       }
8036       
8037       // If the stack restore is in a return/unwind block and if there are no
8038       // allocas or calls between the restore and the return, nuke the restore.
8039       TerminatorInst *TI = II->getParent()->getTerminator();
8040       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8041         BasicBlock::iterator BI = II;
8042         bool CannotRemove = false;
8043         for (++BI; &*BI != TI; ++BI) {
8044           if (isa<AllocaInst>(BI) ||
8045               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8046             CannotRemove = true;
8047             break;
8048           }
8049         }
8050         if (!CannotRemove)
8051           return EraseInstFromFunction(CI);
8052       }
8053       break;
8054     }
8055     }
8056   }
8057
8058   return visitCallSite(II);
8059 }
8060
8061 // InvokeInst simplification
8062 //
8063 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8064   return visitCallSite(&II);
8065 }
8066
8067 // visitCallSite - Improvements for call and invoke instructions.
8068 //
8069 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8070   bool Changed = false;
8071
8072   // If the callee is a constexpr cast of a function, attempt to move the cast
8073   // to the arguments of the call/invoke.
8074   if (transformConstExprCastCall(CS)) return 0;
8075
8076   Value *Callee = CS.getCalledValue();
8077
8078   if (Function *CalleeF = dyn_cast<Function>(Callee))
8079     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8080       Instruction *OldCall = CS.getInstruction();
8081       // If the call and callee calling conventions don't match, this call must
8082       // be unreachable, as the call is undefined.
8083       new StoreInst(ConstantInt::getTrue(),
8084                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
8085       if (!OldCall->use_empty())
8086         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8087       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8088         return EraseInstFromFunction(*OldCall);
8089       return 0;
8090     }
8091
8092   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8093     // This instruction is not reachable, just remove it.  We insert a store to
8094     // undef so that we know that this code is not reachable, despite the fact
8095     // that we can't modify the CFG here.
8096     new StoreInst(ConstantInt::getTrue(),
8097                   UndefValue::get(PointerType::get(Type::Int1Ty)),
8098                   CS.getInstruction());
8099
8100     if (!CS.getInstruction()->use_empty())
8101       CS.getInstruction()->
8102         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8103
8104     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8105       // Don't break the CFG, insert a dummy cond branch.
8106       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8107                      ConstantInt::getTrue(), II);
8108     }
8109     return EraseInstFromFunction(*CS.getInstruction());
8110   }
8111
8112   const PointerType *PTy = cast<PointerType>(Callee->getType());
8113   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8114   if (FTy->isVarArg()) {
8115     // See if we can optimize any arguments passed through the varargs area of
8116     // the call.
8117     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8118            E = CS.arg_end(); I != E; ++I)
8119       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8120         // If this cast does not effect the value passed through the varargs
8121         // area, we can eliminate the use of the cast.
8122         Value *Op = CI->getOperand(0);
8123         if (CI->isLosslessCast()) {
8124           *I = Op;
8125           Changed = true;
8126         }
8127       }
8128   }
8129
8130   return Changed ? CS.getInstruction() : 0;
8131 }
8132
8133 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8134 // attempt to move the cast to the arguments of the call/invoke.
8135 //
8136 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8137   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8138   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8139   if (CE->getOpcode() != Instruction::BitCast || 
8140       !isa<Function>(CE->getOperand(0)))
8141     return false;
8142   Function *Callee = cast<Function>(CE->getOperand(0));
8143   Instruction *Caller = CS.getInstruction();
8144
8145   // Okay, this is a cast from a function to a different type.  Unless doing so
8146   // would cause a type conversion of one of our arguments, change this call to
8147   // be a direct call with arguments casted to the appropriate types.
8148   //
8149   const FunctionType *FT = Callee->getFunctionType();
8150   const Type *OldRetTy = Caller->getType();
8151
8152   // Check to see if we are changing the return type...
8153   if (OldRetTy != FT->getReturnType()) {
8154     if (Callee->isDeclaration() && !Caller->use_empty() && 
8155         // Conversion is ok if changing from pointer to int of same size.
8156         !(isa<PointerType>(FT->getReturnType()) &&
8157           TD->getIntPtrType() == OldRetTy))
8158       return false;   // Cannot transform this return value.
8159
8160     // If the callsite is an invoke instruction, and the return value is used by
8161     // a PHI node in a successor, we cannot change the return type of the call
8162     // because there is no place to put the cast instruction (without breaking
8163     // the critical edge).  Bail out in this case.
8164     if (!Caller->use_empty())
8165       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8166         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8167              UI != E; ++UI)
8168           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8169             if (PN->getParent() == II->getNormalDest() ||
8170                 PN->getParent() == II->getUnwindDest())
8171               return false;
8172   }
8173
8174   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8175   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8176
8177   CallSite::arg_iterator AI = CS.arg_begin();
8178   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8179     const Type *ParamTy = FT->getParamType(i);
8180     const Type *ActTy = (*AI)->getType();
8181     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8182     //Either we can cast directly, or we can upconvert the argument
8183     bool isConvertible = ActTy == ParamTy ||
8184       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8185       (ParamTy->isInteger() && ActTy->isInteger() &&
8186        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8187       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8188        && c->getSExtValue() > 0);
8189     if (Callee->isDeclaration() && !isConvertible) return false;
8190   }
8191
8192   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8193       Callee->isDeclaration())
8194     return false;   // Do not delete arguments unless we have a function body...
8195
8196   // Okay, we decided that this is a safe thing to do: go ahead and start
8197   // inserting cast instructions as necessary...
8198   std::vector<Value*> Args;
8199   Args.reserve(NumActualArgs);
8200
8201   AI = CS.arg_begin();
8202   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8203     const Type *ParamTy = FT->getParamType(i);
8204     if ((*AI)->getType() == ParamTy) {
8205       Args.push_back(*AI);
8206     } else {
8207       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8208           false, ParamTy, false);
8209       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8210       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8211     }
8212   }
8213
8214   // If the function takes more arguments than the call was taking, add them
8215   // now...
8216   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8217     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8218
8219   // If we are removing arguments to the function, emit an obnoxious warning...
8220   if (FT->getNumParams() < NumActualArgs)
8221     if (!FT->isVarArg()) {
8222       cerr << "WARNING: While resolving call to function '"
8223            << Callee->getName() << "' arguments were dropped!\n";
8224     } else {
8225       // Add all of the arguments in their promoted form to the arg list...
8226       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8227         const Type *PTy = getPromotedType((*AI)->getType());
8228         if (PTy != (*AI)->getType()) {
8229           // Must promote to pass through va_arg area!
8230           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8231                                                                 PTy, false);
8232           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8233           InsertNewInstBefore(Cast, *Caller);
8234           Args.push_back(Cast);
8235         } else {
8236           Args.push_back(*AI);
8237         }
8238       }
8239     }
8240
8241   if (FT->getReturnType() == Type::VoidTy)
8242     Caller->setName("");   // Void type should not have a name.
8243
8244   Instruction *NC;
8245   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8246     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8247                         &Args[0], Args.size(), Caller->getName(), Caller);
8248     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
8249   } else {
8250     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
8251     if (cast<CallInst>(Caller)->isTailCall())
8252       cast<CallInst>(NC)->setTailCall();
8253    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8254   }
8255
8256   // Insert a cast of the return type as necessary.
8257   Value *NV = NC;
8258   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8259     if (NV->getType() != Type::VoidTy) {
8260       const Type *CallerTy = Caller->getType();
8261       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8262                                                             CallerTy, false);
8263       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8264
8265       // If this is an invoke instruction, we should insert it after the first
8266       // non-phi, instruction in the normal successor block.
8267       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8268         BasicBlock::iterator I = II->getNormalDest()->begin();
8269         while (isa<PHINode>(I)) ++I;
8270         InsertNewInstBefore(NC, *I);
8271       } else {
8272         // Otherwise, it's a call, just insert cast right after the call instr
8273         InsertNewInstBefore(NC, *Caller);
8274       }
8275       AddUsersToWorkList(*Caller);
8276     } else {
8277       NV = UndefValue::get(Caller->getType());
8278     }
8279   }
8280
8281   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8282     Caller->replaceAllUsesWith(NV);
8283   Caller->eraseFromParent();
8284   RemoveFromWorkList(Caller);
8285   return true;
8286 }
8287
8288 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8289 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8290 /// and a single binop.
8291 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8292   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8293   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8294          isa<CmpInst>(FirstInst));
8295   unsigned Opc = FirstInst->getOpcode();
8296   Value *LHSVal = FirstInst->getOperand(0);
8297   Value *RHSVal = FirstInst->getOperand(1);
8298     
8299   const Type *LHSType = LHSVal->getType();
8300   const Type *RHSType = RHSVal->getType();
8301   
8302   // Scan to see if all operands are the same opcode, all have one use, and all
8303   // kill their operands (i.e. the operands have one use).
8304   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8305     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8306     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8307         // Verify type of the LHS matches so we don't fold cmp's of different
8308         // types or GEP's with different index types.
8309         I->getOperand(0)->getType() != LHSType ||
8310         I->getOperand(1)->getType() != RHSType)
8311       return 0;
8312
8313     // If they are CmpInst instructions, check their predicates
8314     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8315       if (cast<CmpInst>(I)->getPredicate() !=
8316           cast<CmpInst>(FirstInst)->getPredicate())
8317         return 0;
8318     
8319     // Keep track of which operand needs a phi node.
8320     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8321     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8322   }
8323   
8324   // Otherwise, this is safe to transform, determine if it is profitable.
8325
8326   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8327   // Indexes are often folded into load/store instructions, so we don't want to
8328   // hide them behind a phi.
8329   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8330     return 0;
8331   
8332   Value *InLHS = FirstInst->getOperand(0);
8333   Value *InRHS = FirstInst->getOperand(1);
8334   PHINode *NewLHS = 0, *NewRHS = 0;
8335   if (LHSVal == 0) {
8336     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8337     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8338     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8339     InsertNewInstBefore(NewLHS, PN);
8340     LHSVal = NewLHS;
8341   }
8342   
8343   if (RHSVal == 0) {
8344     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8345     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8346     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8347     InsertNewInstBefore(NewRHS, PN);
8348     RHSVal = NewRHS;
8349   }
8350   
8351   // Add all operands to the new PHIs.
8352   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8353     if (NewLHS) {
8354       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8355       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8356     }
8357     if (NewRHS) {
8358       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8359       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8360     }
8361   }
8362     
8363   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8364     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8365   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8366     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8367                            RHSVal);
8368   else {
8369     assert(isa<GetElementPtrInst>(FirstInst));
8370     return new GetElementPtrInst(LHSVal, RHSVal);
8371   }
8372 }
8373
8374 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8375 /// of the block that defines it.  This means that it must be obvious the value
8376 /// of the load is not changed from the point of the load to the end of the
8377 /// block it is in.
8378 ///
8379 /// Finally, it is safe, but not profitable, to sink a load targetting a
8380 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8381 /// to a register.
8382 static bool isSafeToSinkLoad(LoadInst *L) {
8383   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8384   
8385   for (++BBI; BBI != E; ++BBI)
8386     if (BBI->mayWriteToMemory())
8387       return false;
8388   
8389   // Check for non-address taken alloca.  If not address-taken already, it isn't
8390   // profitable to do this xform.
8391   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8392     bool isAddressTaken = false;
8393     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8394          UI != E; ++UI) {
8395       if (isa<LoadInst>(UI)) continue;
8396       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8397         // If storing TO the alloca, then the address isn't taken.
8398         if (SI->getOperand(1) == AI) continue;
8399       }
8400       isAddressTaken = true;
8401       break;
8402     }
8403     
8404     if (!isAddressTaken)
8405       return false;
8406   }
8407   
8408   return true;
8409 }
8410
8411
8412 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8413 // operator and they all are only used by the PHI, PHI together their
8414 // inputs, and do the operation once, to the result of the PHI.
8415 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8416   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8417
8418   // Scan the instruction, looking for input operations that can be folded away.
8419   // If all input operands to the phi are the same instruction (e.g. a cast from
8420   // the same type or "+42") we can pull the operation through the PHI, reducing
8421   // code size and simplifying code.
8422   Constant *ConstantOp = 0;
8423   const Type *CastSrcTy = 0;
8424   bool isVolatile = false;
8425   if (isa<CastInst>(FirstInst)) {
8426     CastSrcTy = FirstInst->getOperand(0)->getType();
8427   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8428     // Can fold binop, compare or shift here if the RHS is a constant, 
8429     // otherwise call FoldPHIArgBinOpIntoPHI.
8430     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8431     if (ConstantOp == 0)
8432       return FoldPHIArgBinOpIntoPHI(PN);
8433   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8434     isVolatile = LI->isVolatile();
8435     // We can't sink the load if the loaded value could be modified between the
8436     // load and the PHI.
8437     if (LI->getParent() != PN.getIncomingBlock(0) ||
8438         !isSafeToSinkLoad(LI))
8439       return 0;
8440   } else if (isa<GetElementPtrInst>(FirstInst)) {
8441     if (FirstInst->getNumOperands() == 2)
8442       return FoldPHIArgBinOpIntoPHI(PN);
8443     // Can't handle general GEPs yet.
8444     return 0;
8445   } else {
8446     return 0;  // Cannot fold this operation.
8447   }
8448
8449   // Check to see if all arguments are the same operation.
8450   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8451     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8452     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8453     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8454       return 0;
8455     if (CastSrcTy) {
8456       if (I->getOperand(0)->getType() != CastSrcTy)
8457         return 0;  // Cast operation must match.
8458     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8459       // We can't sink the load if the loaded value could be modified between 
8460       // the load and the PHI.
8461       if (LI->isVolatile() != isVolatile ||
8462           LI->getParent() != PN.getIncomingBlock(i) ||
8463           !isSafeToSinkLoad(LI))
8464         return 0;
8465     } else if (I->getOperand(1) != ConstantOp) {
8466       return 0;
8467     }
8468   }
8469
8470   // Okay, they are all the same operation.  Create a new PHI node of the
8471   // correct type, and PHI together all of the LHS's of the instructions.
8472   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8473                                PN.getName()+".in");
8474   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8475
8476   Value *InVal = FirstInst->getOperand(0);
8477   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8478
8479   // Add all operands to the new PHI.
8480   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8481     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8482     if (NewInVal != InVal)
8483       InVal = 0;
8484     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8485   }
8486
8487   Value *PhiVal;
8488   if (InVal) {
8489     // The new PHI unions all of the same values together.  This is really
8490     // common, so we handle it intelligently here for compile-time speed.
8491     PhiVal = InVal;
8492     delete NewPN;
8493   } else {
8494     InsertNewInstBefore(NewPN, PN);
8495     PhiVal = NewPN;
8496   }
8497
8498   // Insert and return the new operation.
8499   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8500     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8501   else if (isa<LoadInst>(FirstInst))
8502     return new LoadInst(PhiVal, "", isVolatile);
8503   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8504     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8505   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8506     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8507                            PhiVal, ConstantOp);
8508   else
8509     assert(0 && "Unknown operation");
8510   return 0;
8511 }
8512
8513 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8514 /// that is dead.
8515 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8516   if (PN->use_empty()) return true;
8517   if (!PN->hasOneUse()) return false;
8518
8519   // Remember this node, and if we find the cycle, return.
8520   if (!PotentiallyDeadPHIs.insert(PN).second)
8521     return true;
8522
8523   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8524     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8525
8526   return false;
8527 }
8528
8529 // PHINode simplification
8530 //
8531 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8532   // If LCSSA is around, don't mess with Phi nodes
8533   if (MustPreserveLCSSA) return 0;
8534   
8535   if (Value *V = PN.hasConstantValue())
8536     return ReplaceInstUsesWith(PN, V);
8537
8538   // If all PHI operands are the same operation, pull them through the PHI,
8539   // reducing code size.
8540   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8541       PN.getIncomingValue(0)->hasOneUse())
8542     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8543       return Result;
8544
8545   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8546   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8547   // PHI)... break the cycle.
8548   if (PN.hasOneUse()) {
8549     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8550     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8551       std::set<PHINode*> PotentiallyDeadPHIs;
8552       PotentiallyDeadPHIs.insert(&PN);
8553       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8554         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8555     }
8556    
8557     // If this phi has a single use, and if that use just computes a value for
8558     // the next iteration of a loop, delete the phi.  This occurs with unused
8559     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8560     // common case here is good because the only other things that catch this
8561     // are induction variable analysis (sometimes) and ADCE, which is only run
8562     // late.
8563     if (PHIUser->hasOneUse() &&
8564         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8565         PHIUser->use_back() == &PN) {
8566       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8567     }
8568   }
8569
8570   return 0;
8571 }
8572
8573 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8574                                    Instruction *InsertPoint,
8575                                    InstCombiner *IC) {
8576   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8577   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8578   // We must cast correctly to the pointer type. Ensure that we
8579   // sign extend the integer value if it is smaller as this is
8580   // used for address computation.
8581   Instruction::CastOps opcode = 
8582      (VTySize < PtrSize ? Instruction::SExt :
8583       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8584   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8585 }
8586
8587
8588 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8589   Value *PtrOp = GEP.getOperand(0);
8590   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
8591   // If so, eliminate the noop.
8592   if (GEP.getNumOperands() == 1)
8593     return ReplaceInstUsesWith(GEP, PtrOp);
8594
8595   if (isa<UndefValue>(GEP.getOperand(0)))
8596     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8597
8598   bool HasZeroPointerIndex = false;
8599   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8600     HasZeroPointerIndex = C->isNullValue();
8601
8602   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8603     return ReplaceInstUsesWith(GEP, PtrOp);
8604
8605   // Eliminate unneeded casts for indices.
8606   bool MadeChange = false;
8607   gep_type_iterator GTI = gep_type_begin(GEP);
8608   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8609     if (isa<SequentialType>(*GTI)) {
8610       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8611         if (CI->getOpcode() == Instruction::ZExt ||
8612             CI->getOpcode() == Instruction::SExt) {
8613           const Type *SrcTy = CI->getOperand(0)->getType();
8614           // We can eliminate a cast from i32 to i64 iff the target 
8615           // is a 32-bit pointer target.
8616           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8617             MadeChange = true;
8618             GEP.setOperand(i, CI->getOperand(0));
8619           }
8620         }
8621       }
8622       // If we are using a wider index than needed for this platform, shrink it
8623       // to what we need.  If the incoming value needs a cast instruction,
8624       // insert it.  This explicit cast can make subsequent optimizations more
8625       // obvious.
8626       Value *Op = GEP.getOperand(i);
8627       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8628         if (Constant *C = dyn_cast<Constant>(Op)) {
8629           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8630           MadeChange = true;
8631         } else {
8632           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8633                                 GEP);
8634           GEP.setOperand(i, Op);
8635           MadeChange = true;
8636         }
8637     }
8638   if (MadeChange) return &GEP;
8639
8640   // Combine Indices - If the source pointer to this getelementptr instruction
8641   // is a getelementptr instruction, combine the indices of the two
8642   // getelementptr instructions into a single instruction.
8643   //
8644   SmallVector<Value*, 8> SrcGEPOperands;
8645   if (User *Src = dyn_castGetElementPtr(PtrOp))
8646     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8647
8648   if (!SrcGEPOperands.empty()) {
8649     // Note that if our source is a gep chain itself that we wait for that
8650     // chain to be resolved before we perform this transformation.  This
8651     // avoids us creating a TON of code in some cases.
8652     //
8653     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8654         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8655       return 0;   // Wait until our source is folded to completion.
8656
8657     SmallVector<Value*, 8> Indices;
8658
8659     // Find out whether the last index in the source GEP is a sequential idx.
8660     bool EndsWithSequential = false;
8661     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8662            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8663       EndsWithSequential = !isa<StructType>(*I);
8664
8665     // Can we combine the two pointer arithmetics offsets?
8666     if (EndsWithSequential) {
8667       // Replace: gep (gep %P, long B), long A, ...
8668       // With:    T = long A+B; gep %P, T, ...
8669       //
8670       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8671       if (SO1 == Constant::getNullValue(SO1->getType())) {
8672         Sum = GO1;
8673       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8674         Sum = SO1;
8675       } else {
8676         // If they aren't the same type, convert both to an integer of the
8677         // target's pointer size.
8678         if (SO1->getType() != GO1->getType()) {
8679           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8680             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8681           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8682             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8683           } else {
8684             unsigned PS = TD->getPointerSize();
8685             if (TD->getTypeSize(SO1->getType()) == PS) {
8686               // Convert GO1 to SO1's type.
8687               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8688
8689             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8690               // Convert SO1 to GO1's type.
8691               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8692             } else {
8693               const Type *PT = TD->getIntPtrType();
8694               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8695               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8696             }
8697           }
8698         }
8699         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8700           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8701         else {
8702           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8703           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8704         }
8705       }
8706
8707       // Recycle the GEP we already have if possible.
8708       if (SrcGEPOperands.size() == 2) {
8709         GEP.setOperand(0, SrcGEPOperands[0]);
8710         GEP.setOperand(1, Sum);
8711         return &GEP;
8712       } else {
8713         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8714                        SrcGEPOperands.end()-1);
8715         Indices.push_back(Sum);
8716         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8717       }
8718     } else if (isa<Constant>(*GEP.idx_begin()) &&
8719                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8720                SrcGEPOperands.size() != 1) {
8721       // Otherwise we can do the fold if the first index of the GEP is a zero
8722       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8723                      SrcGEPOperands.end());
8724       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8725     }
8726
8727     if (!Indices.empty())
8728       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8729                                    Indices.size(), GEP.getName());
8730
8731   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8732     // GEP of global variable.  If all of the indices for this GEP are
8733     // constants, we can promote this to a constexpr instead of an instruction.
8734
8735     // Scan for nonconstants...
8736     SmallVector<Constant*, 8> Indices;
8737     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8738     for (; I != E && isa<Constant>(*I); ++I)
8739       Indices.push_back(cast<Constant>(*I));
8740
8741     if (I == E) {  // If they are all constants...
8742       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8743                                                     &Indices[0],Indices.size());
8744
8745       // Replace all uses of the GEP with the new constexpr...
8746       return ReplaceInstUsesWith(GEP, CE);
8747     }
8748   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8749     if (!isa<PointerType>(X->getType())) {
8750       // Not interesting.  Source pointer must be a cast from pointer.
8751     } else if (HasZeroPointerIndex) {
8752       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8753       // into     : GEP [10 x ubyte]* X, long 0, ...
8754       //
8755       // This occurs when the program declares an array extern like "int X[];"
8756       //
8757       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8758       const PointerType *XTy = cast<PointerType>(X->getType());
8759       if (const ArrayType *XATy =
8760           dyn_cast<ArrayType>(XTy->getElementType()))
8761         if (const ArrayType *CATy =
8762             dyn_cast<ArrayType>(CPTy->getElementType()))
8763           if (CATy->getElementType() == XATy->getElementType()) {
8764             // At this point, we know that the cast source type is a pointer
8765             // to an array of the same type as the destination pointer
8766             // array.  Because the array type is never stepped over (there
8767             // is a leading zero) we can fold the cast into this GEP.
8768             GEP.setOperand(0, X);
8769             return &GEP;
8770           }
8771     } else if (GEP.getNumOperands() == 2) {
8772       // Transform things like:
8773       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8774       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8775       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8776       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8777       if (isa<ArrayType>(SrcElTy) &&
8778           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8779           TD->getTypeSize(ResElTy)) {
8780         Value *V = InsertNewInstBefore(
8781                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8782                                      GEP.getOperand(1), GEP.getName()), GEP);
8783         // V and GEP are both pointer types --> BitCast
8784         return new BitCastInst(V, GEP.getType());
8785       }
8786       
8787       // Transform things like:
8788       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8789       //   (where tmp = 8*tmp2) into:
8790       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8791       
8792       if (isa<ArrayType>(SrcElTy) &&
8793           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8794         uint64_t ArrayEltSize =
8795             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8796         
8797         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8798         // allow either a mul, shift, or constant here.
8799         Value *NewIdx = 0;
8800         ConstantInt *Scale = 0;
8801         if (ArrayEltSize == 1) {
8802           NewIdx = GEP.getOperand(1);
8803           Scale = ConstantInt::get(NewIdx->getType(), 1);
8804         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8805           NewIdx = ConstantInt::get(CI->getType(), 1);
8806           Scale = CI;
8807         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8808           if (Inst->getOpcode() == Instruction::Shl &&
8809               isa<ConstantInt>(Inst->getOperand(1))) {
8810             unsigned ShAmt =
8811               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8812             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8813             NewIdx = Inst->getOperand(0);
8814           } else if (Inst->getOpcode() == Instruction::Mul &&
8815                      isa<ConstantInt>(Inst->getOperand(1))) {
8816             Scale = cast<ConstantInt>(Inst->getOperand(1));
8817             NewIdx = Inst->getOperand(0);
8818           }
8819         }
8820
8821         // If the index will be to exactly the right offset with the scale taken
8822         // out, perform the transformation.
8823         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8824           if (isa<ConstantInt>(Scale))
8825             Scale = ConstantInt::get(Scale->getType(),
8826                                       Scale->getZExtValue() / ArrayEltSize);
8827           if (Scale->getZExtValue() != 1) {
8828             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8829                                                        true /*SExt*/);
8830             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8831             NewIdx = InsertNewInstBefore(Sc, GEP);
8832           }
8833
8834           // Insert the new GEP instruction.
8835           Instruction *NewGEP =
8836             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8837                                   NewIdx, GEP.getName());
8838           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8839           // The NewGEP must be pointer typed, so must the old one -> BitCast
8840           return new BitCastInst(NewGEP, GEP.getType());
8841         }
8842       }
8843     }
8844   }
8845
8846   return 0;
8847 }
8848
8849 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8850   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8851   if (AI.isArrayAllocation())    // Check C != 1
8852     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8853       const Type *NewTy = 
8854         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8855       AllocationInst *New = 0;
8856
8857       // Create and insert the replacement instruction...
8858       if (isa<MallocInst>(AI))
8859         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8860       else {
8861         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8862         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8863       }
8864
8865       InsertNewInstBefore(New, AI);
8866
8867       // Scan to the end of the allocation instructions, to skip over a block of
8868       // allocas if possible...
8869       //
8870       BasicBlock::iterator It = New;
8871       while (isa<AllocationInst>(*It)) ++It;
8872
8873       // Now that I is pointing to the first non-allocation-inst in the block,
8874       // insert our getelementptr instruction...
8875       //
8876       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8877       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8878                                        New->getName()+".sub", It);
8879
8880       // Now make everything use the getelementptr instead of the original
8881       // allocation.
8882       return ReplaceInstUsesWith(AI, V);
8883     } else if (isa<UndefValue>(AI.getArraySize())) {
8884       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8885     }
8886
8887   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8888   // Note that we only do this for alloca's, because malloc should allocate and
8889   // return a unique pointer, even for a zero byte allocation.
8890   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8891       TD->getTypeSize(AI.getAllocatedType()) == 0)
8892     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8893
8894   return 0;
8895 }
8896
8897 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8898   Value *Op = FI.getOperand(0);
8899
8900   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8901   if (CastInst *CI = dyn_cast<CastInst>(Op))
8902     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8903       FI.setOperand(0, CI->getOperand(0));
8904       return &FI;
8905     }
8906
8907   // free undef -> unreachable.
8908   if (isa<UndefValue>(Op)) {
8909     // Insert a new store to null because we cannot modify the CFG here.
8910     new StoreInst(ConstantInt::getTrue(),
8911                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8912     return EraseInstFromFunction(FI);
8913   }
8914
8915   // If we have 'free null' delete the instruction.  This can happen in stl code
8916   // when lots of inlining happens.
8917   if (isa<ConstantPointerNull>(Op))
8918     return EraseInstFromFunction(FI);
8919
8920   return 0;
8921 }
8922
8923
8924 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8925 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8926   User *CI = cast<User>(LI.getOperand(0));
8927   Value *CastOp = CI->getOperand(0);
8928
8929   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8930   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8931     const Type *SrcPTy = SrcTy->getElementType();
8932
8933     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8934          isa<VectorType>(DestPTy)) {
8935       // If the source is an array, the code below will not succeed.  Check to
8936       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8937       // constants.
8938       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8939         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8940           if (ASrcTy->getNumElements() != 0) {
8941             Value *Idxs[2];
8942             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8943             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8944             SrcTy = cast<PointerType>(CastOp->getType());
8945             SrcPTy = SrcTy->getElementType();
8946           }
8947
8948       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8949             isa<VectorType>(SrcPTy)) &&
8950           // Do not allow turning this into a load of an integer, which is then
8951           // casted to a pointer, this pessimizes pointer analysis a lot.
8952           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8953           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8954                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8955
8956         // Okay, we are casting from one integer or pointer type to another of
8957         // the same size.  Instead of casting the pointer before the load, cast
8958         // the result of the loaded value.
8959         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8960                                                              CI->getName(),
8961                                                          LI.isVolatile()),LI);
8962         // Now cast the result of the load.
8963         return new BitCastInst(NewLoad, LI.getType());
8964       }
8965     }
8966   }
8967   return 0;
8968 }
8969
8970 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8971 /// from this value cannot trap.  If it is not obviously safe to load from the
8972 /// specified pointer, we do a quick local scan of the basic block containing
8973 /// ScanFrom, to determine if the address is already accessed.
8974 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8975   // If it is an alloca or global variable, it is always safe to load from.
8976   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8977
8978   // Otherwise, be a little bit agressive by scanning the local block where we
8979   // want to check to see if the pointer is already being loaded or stored
8980   // from/to.  If so, the previous load or store would have already trapped,
8981   // so there is no harm doing an extra load (also, CSE will later eliminate
8982   // the load entirely).
8983   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8984
8985   while (BBI != E) {
8986     --BBI;
8987
8988     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8989       if (LI->getOperand(0) == V) return true;
8990     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8991       if (SI->getOperand(1) == V) return true;
8992
8993   }
8994   return false;
8995 }
8996
8997 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8998   Value *Op = LI.getOperand(0);
8999
9000   // load (cast X) --> cast (load X) iff safe
9001   if (isa<CastInst>(Op))
9002     if (Instruction *Res = InstCombineLoadCast(*this, LI))
9003       return Res;
9004
9005   // None of the following transforms are legal for volatile loads.
9006   if (LI.isVolatile()) return 0;
9007   
9008   if (&LI.getParent()->front() != &LI) {
9009     BasicBlock::iterator BBI = &LI; --BBI;
9010     // If the instruction immediately before this is a store to the same
9011     // address, do a simple form of store->load forwarding.
9012     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9013       if (SI->getOperand(1) == LI.getOperand(0))
9014         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9015     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9016       if (LIB->getOperand(0) == LI.getOperand(0))
9017         return ReplaceInstUsesWith(LI, LIB);
9018   }
9019
9020   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9021     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
9022         isa<UndefValue>(GEPI->getOperand(0))) {
9023       // Insert a new store to null instruction before the load to indicate
9024       // that this code is not reachable.  We do this instead of inserting
9025       // an unreachable instruction directly because we cannot modify the
9026       // CFG.
9027       new StoreInst(UndefValue::get(LI.getType()),
9028                     Constant::getNullValue(Op->getType()), &LI);
9029       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9030     }
9031
9032   if (Constant *C = dyn_cast<Constant>(Op)) {
9033     // load null/undef -> undef
9034     if ((C->isNullValue() || isa<UndefValue>(C))) {
9035       // Insert a new store to null instruction before the load to indicate that
9036       // this code is not reachable.  We do this instead of inserting an
9037       // unreachable instruction directly because we cannot modify the CFG.
9038       new StoreInst(UndefValue::get(LI.getType()),
9039                     Constant::getNullValue(Op->getType()), &LI);
9040       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9041     }
9042
9043     // Instcombine load (constant global) into the value loaded.
9044     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9045       if (GV->isConstant() && !GV->isDeclaration())
9046         return ReplaceInstUsesWith(LI, GV->getInitializer());
9047
9048     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9049     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9050       if (CE->getOpcode() == Instruction::GetElementPtr) {
9051         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9052           if (GV->isConstant() && !GV->isDeclaration())
9053             if (Constant *V = 
9054                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9055               return ReplaceInstUsesWith(LI, V);
9056         if (CE->getOperand(0)->isNullValue()) {
9057           // Insert a new store to null instruction before the load to indicate
9058           // that this code is not reachable.  We do this instead of inserting
9059           // an unreachable instruction directly because we cannot modify the
9060           // CFG.
9061           new StoreInst(UndefValue::get(LI.getType()),
9062                         Constant::getNullValue(Op->getType()), &LI);
9063           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9064         }
9065
9066       } else if (CE->isCast()) {
9067         if (Instruction *Res = InstCombineLoadCast(*this, LI))
9068           return Res;
9069       }
9070   }
9071
9072   if (Op->hasOneUse()) {
9073     // Change select and PHI nodes to select values instead of addresses: this
9074     // helps alias analysis out a lot, allows many others simplifications, and
9075     // exposes redundancy in the code.
9076     //
9077     // Note that we cannot do the transformation unless we know that the
9078     // introduced loads cannot trap!  Something like this is valid as long as
9079     // the condition is always false: load (select bool %C, int* null, int* %G),
9080     // but it would not be valid if we transformed it to load from null
9081     // unconditionally.
9082     //
9083     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9084       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9085       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9086           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9087         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9088                                      SI->getOperand(1)->getName()+".val"), LI);
9089         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9090                                      SI->getOperand(2)->getName()+".val"), LI);
9091         return new SelectInst(SI->getCondition(), V1, V2);
9092       }
9093
9094       // load (select (cond, null, P)) -> load P
9095       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9096         if (C->isNullValue()) {
9097           LI.setOperand(0, SI->getOperand(2));
9098           return &LI;
9099         }
9100
9101       // load (select (cond, P, null)) -> load P
9102       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9103         if (C->isNullValue()) {
9104           LI.setOperand(0, SI->getOperand(1));
9105           return &LI;
9106         }
9107     }
9108   }
9109   return 0;
9110 }
9111
9112 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9113 /// when possible.
9114 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9115   User *CI = cast<User>(SI.getOperand(1));
9116   Value *CastOp = CI->getOperand(0);
9117
9118   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9119   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9120     const Type *SrcPTy = SrcTy->getElementType();
9121
9122     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9123       // If the source is an array, the code below will not succeed.  Check to
9124       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9125       // constants.
9126       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9127         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9128           if (ASrcTy->getNumElements() != 0) {
9129             Value* Idxs[2];
9130             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9131             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9132             SrcTy = cast<PointerType>(CastOp->getType());
9133             SrcPTy = SrcTy->getElementType();
9134           }
9135
9136       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9137           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9138                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9139
9140         // Okay, we are casting from one integer or pointer type to another of
9141         // the same size.  Instead of casting the pointer before 
9142         // the store, cast the value to be stored.
9143         Value *NewCast;
9144         Value *SIOp0 = SI.getOperand(0);
9145         Instruction::CastOps opcode = Instruction::BitCast;
9146         const Type* CastSrcTy = SIOp0->getType();
9147         const Type* CastDstTy = SrcPTy;
9148         if (isa<PointerType>(CastDstTy)) {
9149           if (CastSrcTy->isInteger())
9150             opcode = Instruction::IntToPtr;
9151         } else if (isa<IntegerType>(CastDstTy)) {
9152           if (isa<PointerType>(SIOp0->getType()))
9153             opcode = Instruction::PtrToInt;
9154         }
9155         if (Constant *C = dyn_cast<Constant>(SIOp0))
9156           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9157         else
9158           NewCast = IC.InsertNewInstBefore(
9159             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9160             SI);
9161         return new StoreInst(NewCast, CastOp);
9162       }
9163     }
9164   }
9165   return 0;
9166 }
9167
9168 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9169   Value *Val = SI.getOperand(0);
9170   Value *Ptr = SI.getOperand(1);
9171
9172   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9173     EraseInstFromFunction(SI);
9174     ++NumCombined;
9175     return 0;
9176   }
9177   
9178   // If the RHS is an alloca with a single use, zapify the store, making the
9179   // alloca dead.
9180   if (Ptr->hasOneUse()) {
9181     if (isa<AllocaInst>(Ptr)) {
9182       EraseInstFromFunction(SI);
9183       ++NumCombined;
9184       return 0;
9185     }
9186     
9187     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9188       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9189           GEP->getOperand(0)->hasOneUse()) {
9190         EraseInstFromFunction(SI);
9191         ++NumCombined;
9192         return 0;
9193       }
9194   }
9195
9196   // Do really simple DSE, to catch cases where there are several consequtive
9197   // stores to the same location, separated by a few arithmetic operations. This
9198   // situation often occurs with bitfield accesses.
9199   BasicBlock::iterator BBI = &SI;
9200   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9201        --ScanInsts) {
9202     --BBI;
9203     
9204     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9205       // Prev store isn't volatile, and stores to the same location?
9206       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9207         ++NumDeadStore;
9208         ++BBI;
9209         EraseInstFromFunction(*PrevSI);
9210         continue;
9211       }
9212       break;
9213     }
9214     
9215     // If this is a load, we have to stop.  However, if the loaded value is from
9216     // the pointer we're loading and is producing the pointer we're storing,
9217     // then *this* store is dead (X = load P; store X -> P).
9218     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9219       if (LI == Val && LI->getOperand(0) == Ptr) {
9220         EraseInstFromFunction(SI);
9221         ++NumCombined;
9222         return 0;
9223       }
9224       // Otherwise, this is a load from some other location.  Stores before it
9225       // may not be dead.
9226       break;
9227     }
9228     
9229     // Don't skip over loads or things that can modify memory.
9230     if (BBI->mayWriteToMemory())
9231       break;
9232   }
9233   
9234   
9235   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9236
9237   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9238   if (isa<ConstantPointerNull>(Ptr)) {
9239     if (!isa<UndefValue>(Val)) {
9240       SI.setOperand(0, UndefValue::get(Val->getType()));
9241       if (Instruction *U = dyn_cast<Instruction>(Val))
9242         AddToWorkList(U);  // Dropped a use.
9243       ++NumCombined;
9244     }
9245     return 0;  // Do not modify these!
9246   }
9247
9248   // store undef, Ptr -> noop
9249   if (isa<UndefValue>(Val)) {
9250     EraseInstFromFunction(SI);
9251     ++NumCombined;
9252     return 0;
9253   }
9254
9255   // If the pointer destination is a cast, see if we can fold the cast into the
9256   // source instead.
9257   if (isa<CastInst>(Ptr))
9258     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9259       return Res;
9260   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9261     if (CE->isCast())
9262       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9263         return Res;
9264
9265   
9266   // If this store is the last instruction in the basic block, and if the block
9267   // ends with an unconditional branch, try to move it to the successor block.
9268   BBI = &SI; ++BBI;
9269   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9270     if (BI->isUnconditional()) {
9271       // Check to see if the successor block has exactly two incoming edges.  If
9272       // so, see if the other predecessor contains a store to the same location.
9273       // if so, insert a PHI node (if needed) and move the stores down.
9274       BasicBlock *Dest = BI->getSuccessor(0);
9275
9276       pred_iterator PI = pred_begin(Dest);
9277       BasicBlock *Other = 0;
9278       if (*PI != BI->getParent())
9279         Other = *PI;
9280       ++PI;
9281       if (PI != pred_end(Dest)) {
9282         if (*PI != BI->getParent())
9283           if (Other)
9284             Other = 0;
9285           else
9286             Other = *PI;
9287         if (++PI != pred_end(Dest))
9288           Other = 0;
9289       }
9290       if (Other) {  // If only one other pred...
9291         BBI = Other->getTerminator();
9292         // Make sure this other block ends in an unconditional branch and that
9293         // there is an instruction before the branch.
9294         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9295             BBI != Other->begin()) {
9296           --BBI;
9297           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9298           
9299           // If this instruction is a store to the same location.
9300           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9301             // Okay, we know we can perform this transformation.  Insert a PHI
9302             // node now if we need it.
9303             Value *MergedVal = OtherStore->getOperand(0);
9304             if (MergedVal != SI.getOperand(0)) {
9305               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9306               PN->reserveOperandSpace(2);
9307               PN->addIncoming(SI.getOperand(0), SI.getParent());
9308               PN->addIncoming(OtherStore->getOperand(0), Other);
9309               MergedVal = InsertNewInstBefore(PN, Dest->front());
9310             }
9311             
9312             // Advance to a place where it is safe to insert the new store and
9313             // insert it.
9314             BBI = Dest->begin();
9315             while (isa<PHINode>(BBI)) ++BBI;
9316             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9317                                               OtherStore->isVolatile()), *BBI);
9318
9319             // Nuke the old stores.
9320             EraseInstFromFunction(SI);
9321             EraseInstFromFunction(*OtherStore);
9322             ++NumCombined;
9323             return 0;
9324           }
9325         }
9326       }
9327     }
9328   
9329   return 0;
9330 }
9331
9332
9333 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9334   // Change br (not X), label True, label False to: br X, label False, True
9335   Value *X = 0;
9336   BasicBlock *TrueDest;
9337   BasicBlock *FalseDest;
9338   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9339       !isa<Constant>(X)) {
9340     // Swap Destinations and condition...
9341     BI.setCondition(X);
9342     BI.setSuccessor(0, FalseDest);
9343     BI.setSuccessor(1, TrueDest);
9344     return &BI;
9345   }
9346
9347   // Cannonicalize fcmp_one -> fcmp_oeq
9348   FCmpInst::Predicate FPred; Value *Y;
9349   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9350                              TrueDest, FalseDest)))
9351     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9352          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9353       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9354       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9355       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9356       NewSCC->takeName(I);
9357       // Swap Destinations and condition...
9358       BI.setCondition(NewSCC);
9359       BI.setSuccessor(0, FalseDest);
9360       BI.setSuccessor(1, TrueDest);
9361       RemoveFromWorkList(I);
9362       I->eraseFromParent();
9363       AddToWorkList(NewSCC);
9364       return &BI;
9365     }
9366
9367   // Cannonicalize icmp_ne -> icmp_eq
9368   ICmpInst::Predicate IPred;
9369   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9370                       TrueDest, FalseDest)))
9371     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9372          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9373          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9374       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9375       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9376       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9377       NewSCC->takeName(I);
9378       // Swap Destinations and condition...
9379       BI.setCondition(NewSCC);
9380       BI.setSuccessor(0, FalseDest);
9381       BI.setSuccessor(1, TrueDest);
9382       RemoveFromWorkList(I);
9383       I->eraseFromParent();;
9384       AddToWorkList(NewSCC);
9385       return &BI;
9386     }
9387
9388   return 0;
9389 }
9390
9391 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9392   Value *Cond = SI.getCondition();
9393   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9394     if (I->getOpcode() == Instruction::Add)
9395       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9396         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9397         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9398           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9399                                                 AddRHS));
9400         SI.setOperand(0, I->getOperand(0));
9401         AddToWorkList(I);
9402         return &SI;
9403       }
9404   }
9405   return 0;
9406 }
9407
9408 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9409 /// is to leave as a vector operation.
9410 static bool CheapToScalarize(Value *V, bool isConstant) {
9411   if (isa<ConstantAggregateZero>(V)) 
9412     return true;
9413   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9414     if (isConstant) return true;
9415     // If all elts are the same, we can extract.
9416     Constant *Op0 = C->getOperand(0);
9417     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9418       if (C->getOperand(i) != Op0)
9419         return false;
9420     return true;
9421   }
9422   Instruction *I = dyn_cast<Instruction>(V);
9423   if (!I) return false;
9424   
9425   // Insert element gets simplified to the inserted element or is deleted if
9426   // this is constant idx extract element and its a constant idx insertelt.
9427   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9428       isa<ConstantInt>(I->getOperand(2)))
9429     return true;
9430   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9431     return true;
9432   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9433     if (BO->hasOneUse() &&
9434         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9435          CheapToScalarize(BO->getOperand(1), isConstant)))
9436       return true;
9437   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9438     if (CI->hasOneUse() &&
9439         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9440          CheapToScalarize(CI->getOperand(1), isConstant)))
9441       return true;
9442   
9443   return false;
9444 }
9445
9446 /// Read and decode a shufflevector mask.
9447 ///
9448 /// It turns undef elements into values that are larger than the number of
9449 /// elements in the input.
9450 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9451   unsigned NElts = SVI->getType()->getNumElements();
9452   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9453     return std::vector<unsigned>(NElts, 0);
9454   if (isa<UndefValue>(SVI->getOperand(2)))
9455     return std::vector<unsigned>(NElts, 2*NElts);
9456
9457   std::vector<unsigned> Result;
9458   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9459   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9460     if (isa<UndefValue>(CP->getOperand(i)))
9461       Result.push_back(NElts*2);  // undef -> 8
9462     else
9463       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9464   return Result;
9465 }
9466
9467 /// FindScalarElement - Given a vector and an element number, see if the scalar
9468 /// value is already around as a register, for example if it were inserted then
9469 /// extracted from the vector.
9470 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9471   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9472   const VectorType *PTy = cast<VectorType>(V->getType());
9473   unsigned Width = PTy->getNumElements();
9474   if (EltNo >= Width)  // Out of range access.
9475     return UndefValue::get(PTy->getElementType());
9476   
9477   if (isa<UndefValue>(V))
9478     return UndefValue::get(PTy->getElementType());
9479   else if (isa<ConstantAggregateZero>(V))
9480     return Constant::getNullValue(PTy->getElementType());
9481   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9482     return CP->getOperand(EltNo);
9483   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9484     // If this is an insert to a variable element, we don't know what it is.
9485     if (!isa<ConstantInt>(III->getOperand(2))) 
9486       return 0;
9487     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9488     
9489     // If this is an insert to the element we are looking for, return the
9490     // inserted value.
9491     if (EltNo == IIElt) 
9492       return III->getOperand(1);
9493     
9494     // Otherwise, the insertelement doesn't modify the value, recurse on its
9495     // vector input.
9496     return FindScalarElement(III->getOperand(0), EltNo);
9497   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9498     unsigned InEl = getShuffleMask(SVI)[EltNo];
9499     if (InEl < Width)
9500       return FindScalarElement(SVI->getOperand(0), InEl);
9501     else if (InEl < Width*2)
9502       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9503     else
9504       return UndefValue::get(PTy->getElementType());
9505   }
9506   
9507   // Otherwise, we don't know.
9508   return 0;
9509 }
9510
9511 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9512
9513   // If packed val is undef, replace extract with scalar undef.
9514   if (isa<UndefValue>(EI.getOperand(0)))
9515     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9516
9517   // If packed val is constant 0, replace extract with scalar 0.
9518   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9519     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9520   
9521   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9522     // If packed val is constant with uniform operands, replace EI
9523     // with that operand
9524     Constant *op0 = C->getOperand(0);
9525     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9526       if (C->getOperand(i) != op0) {
9527         op0 = 0; 
9528         break;
9529       }
9530     if (op0)
9531       return ReplaceInstUsesWith(EI, op0);
9532   }
9533   
9534   // If extracting a specified index from the vector, see if we can recursively
9535   // find a previously computed scalar that was inserted into the vector.
9536   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9537     // This instruction only demands the single element from the input vector.
9538     // If the input vector has a single use, simplify it based on this use
9539     // property.
9540     uint64_t IndexVal = IdxC->getZExtValue();
9541     if (EI.getOperand(0)->hasOneUse()) {
9542       uint64_t UndefElts;
9543       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9544                                                 1 << IndexVal,
9545                                                 UndefElts)) {
9546         EI.setOperand(0, V);
9547         return &EI;
9548       }
9549     }
9550     
9551     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9552       return ReplaceInstUsesWith(EI, Elt);
9553   }
9554   
9555   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9556     if (I->hasOneUse()) {
9557       // Push extractelement into predecessor operation if legal and
9558       // profitable to do so
9559       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9560         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9561         if (CheapToScalarize(BO, isConstantElt)) {
9562           ExtractElementInst *newEI0 = 
9563             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9564                                    EI.getName()+".lhs");
9565           ExtractElementInst *newEI1 =
9566             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9567                                    EI.getName()+".rhs");
9568           InsertNewInstBefore(newEI0, EI);
9569           InsertNewInstBefore(newEI1, EI);
9570           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9571         }
9572       } else if (isa<LoadInst>(I)) {
9573         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9574                                       PointerType::get(EI.getType()), EI);
9575         GetElementPtrInst *GEP = 
9576           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9577         InsertNewInstBefore(GEP, EI);
9578         return new LoadInst(GEP);
9579       }
9580     }
9581     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9582       // Extracting the inserted element?
9583       if (IE->getOperand(2) == EI.getOperand(1))
9584         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9585       // If the inserted and extracted elements are constants, they must not
9586       // be the same value, extract from the pre-inserted value instead.
9587       if (isa<Constant>(IE->getOperand(2)) &&
9588           isa<Constant>(EI.getOperand(1))) {
9589         AddUsesToWorkList(EI);
9590         EI.setOperand(0, IE->getOperand(0));
9591         return &EI;
9592       }
9593     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9594       // If this is extracting an element from a shufflevector, figure out where
9595       // it came from and extract from the appropriate input element instead.
9596       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9597         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9598         Value *Src;
9599         if (SrcIdx < SVI->getType()->getNumElements())
9600           Src = SVI->getOperand(0);
9601         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9602           SrcIdx -= SVI->getType()->getNumElements();
9603           Src = SVI->getOperand(1);
9604         } else {
9605           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9606         }
9607         return new ExtractElementInst(Src, SrcIdx);
9608       }
9609     }
9610   }
9611   return 0;
9612 }
9613
9614 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9615 /// elements from either LHS or RHS, return the shuffle mask and true. 
9616 /// Otherwise, return false.
9617 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9618                                          std::vector<Constant*> &Mask) {
9619   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9620          "Invalid CollectSingleShuffleElements");
9621   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9622
9623   if (isa<UndefValue>(V)) {
9624     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9625     return true;
9626   } else if (V == LHS) {
9627     for (unsigned i = 0; i != NumElts; ++i)
9628       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9629     return true;
9630   } else if (V == RHS) {
9631     for (unsigned i = 0; i != NumElts; ++i)
9632       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9633     return true;
9634   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9635     // If this is an insert of an extract from some other vector, include it.
9636     Value *VecOp    = IEI->getOperand(0);
9637     Value *ScalarOp = IEI->getOperand(1);
9638     Value *IdxOp    = IEI->getOperand(2);
9639     
9640     if (!isa<ConstantInt>(IdxOp))
9641       return false;
9642     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9643     
9644     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9645       // Okay, we can handle this if the vector we are insertinting into is
9646       // transitively ok.
9647       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9648         // If so, update the mask to reflect the inserted undef.
9649         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9650         return true;
9651       }      
9652     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9653       if (isa<ConstantInt>(EI->getOperand(1)) &&
9654           EI->getOperand(0)->getType() == V->getType()) {
9655         unsigned ExtractedIdx =
9656           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9657         
9658         // This must be extracting from either LHS or RHS.
9659         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9660           // Okay, we can handle this if the vector we are insertinting into is
9661           // transitively ok.
9662           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9663             // If so, update the mask to reflect the inserted value.
9664             if (EI->getOperand(0) == LHS) {
9665               Mask[InsertedIdx & (NumElts-1)] = 
9666                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9667             } else {
9668               assert(EI->getOperand(0) == RHS);
9669               Mask[InsertedIdx & (NumElts-1)] = 
9670                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9671               
9672             }
9673             return true;
9674           }
9675         }
9676       }
9677     }
9678   }
9679   // TODO: Handle shufflevector here!
9680   
9681   return false;
9682 }
9683
9684 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9685 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9686 /// that computes V and the LHS value of the shuffle.
9687 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9688                                      Value *&RHS) {
9689   assert(isa<VectorType>(V->getType()) && 
9690          (RHS == 0 || V->getType() == RHS->getType()) &&
9691          "Invalid shuffle!");
9692   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9693
9694   if (isa<UndefValue>(V)) {
9695     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9696     return V;
9697   } else if (isa<ConstantAggregateZero>(V)) {
9698     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9699     return V;
9700   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9701     // If this is an insert of an extract from some other vector, include it.
9702     Value *VecOp    = IEI->getOperand(0);
9703     Value *ScalarOp = IEI->getOperand(1);
9704     Value *IdxOp    = IEI->getOperand(2);
9705     
9706     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9707       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9708           EI->getOperand(0)->getType() == V->getType()) {
9709         unsigned ExtractedIdx =
9710           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9711         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9712         
9713         // Either the extracted from or inserted into vector must be RHSVec,
9714         // otherwise we'd end up with a shuffle of three inputs.
9715         if (EI->getOperand(0) == RHS || RHS == 0) {
9716           RHS = EI->getOperand(0);
9717           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9718           Mask[InsertedIdx & (NumElts-1)] = 
9719             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9720           return V;
9721         }
9722         
9723         if (VecOp == RHS) {
9724           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9725           // Everything but the extracted element is replaced with the RHS.
9726           for (unsigned i = 0; i != NumElts; ++i) {
9727             if (i != InsertedIdx)
9728               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9729           }
9730           return V;
9731         }
9732         
9733         // If this insertelement is a chain that comes from exactly these two
9734         // vectors, return the vector and the effective shuffle.
9735         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9736           return EI->getOperand(0);
9737         
9738       }
9739     }
9740   }
9741   // TODO: Handle shufflevector here!
9742   
9743   // Otherwise, can't do anything fancy.  Return an identity vector.
9744   for (unsigned i = 0; i != NumElts; ++i)
9745     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9746   return V;
9747 }
9748
9749 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9750   Value *VecOp    = IE.getOperand(0);
9751   Value *ScalarOp = IE.getOperand(1);
9752   Value *IdxOp    = IE.getOperand(2);
9753   
9754   // If the inserted element was extracted from some other vector, and if the 
9755   // indexes are constant, try to turn this into a shufflevector operation.
9756   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9757     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9758         EI->getOperand(0)->getType() == IE.getType()) {
9759       unsigned NumVectorElts = IE.getType()->getNumElements();
9760       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9761       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9762       
9763       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9764         return ReplaceInstUsesWith(IE, VecOp);
9765       
9766       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9767         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9768       
9769       // If we are extracting a value from a vector, then inserting it right
9770       // back into the same place, just use the input vector.
9771       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9772         return ReplaceInstUsesWith(IE, VecOp);      
9773       
9774       // We could theoretically do this for ANY input.  However, doing so could
9775       // turn chains of insertelement instructions into a chain of shufflevector
9776       // instructions, and right now we do not merge shufflevectors.  As such,
9777       // only do this in a situation where it is clear that there is benefit.
9778       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9779         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9780         // the values of VecOp, except then one read from EIOp0.
9781         // Build a new shuffle mask.
9782         std::vector<Constant*> Mask;
9783         if (isa<UndefValue>(VecOp))
9784           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9785         else {
9786           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9787           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9788                                                        NumVectorElts));
9789         } 
9790         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9791         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9792                                      ConstantVector::get(Mask));
9793       }
9794       
9795       // If this insertelement isn't used by some other insertelement, turn it
9796       // (and any insertelements it points to), into one big shuffle.
9797       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9798         std::vector<Constant*> Mask;
9799         Value *RHS = 0;
9800         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9801         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9802         // We now have a shuffle of LHS, RHS, Mask.
9803         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9804       }
9805     }
9806   }
9807
9808   return 0;
9809 }
9810
9811
9812 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9813   Value *LHS = SVI.getOperand(0);
9814   Value *RHS = SVI.getOperand(1);
9815   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9816
9817   bool MadeChange = false;
9818   
9819   // Undefined shuffle mask -> undefined value.
9820   if (isa<UndefValue>(SVI.getOperand(2)))
9821     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9822   
9823   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9824   // the undef, change them to undefs.
9825   if (isa<UndefValue>(SVI.getOperand(1))) {
9826     // Scan to see if there are any references to the RHS.  If so, replace them
9827     // with undef element refs and set MadeChange to true.
9828     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9829       if (Mask[i] >= e && Mask[i] != 2*e) {
9830         Mask[i] = 2*e;
9831         MadeChange = true;
9832       }
9833     }
9834     
9835     if (MadeChange) {
9836       // Remap any references to RHS to use LHS.
9837       std::vector<Constant*> Elts;
9838       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9839         if (Mask[i] == 2*e)
9840           Elts.push_back(UndefValue::get(Type::Int32Ty));
9841         else
9842           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9843       }
9844       SVI.setOperand(2, ConstantVector::get(Elts));
9845     }
9846   }
9847   
9848   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9849   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9850   if (LHS == RHS || isa<UndefValue>(LHS)) {
9851     if (isa<UndefValue>(LHS) && LHS == RHS) {
9852       // shuffle(undef,undef,mask) -> undef.
9853       return ReplaceInstUsesWith(SVI, LHS);
9854     }
9855     
9856     // Remap any references to RHS to use LHS.
9857     std::vector<Constant*> Elts;
9858     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9859       if (Mask[i] >= 2*e)
9860         Elts.push_back(UndefValue::get(Type::Int32Ty));
9861       else {
9862         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9863             (Mask[i] <  e && isa<UndefValue>(LHS)))
9864           Mask[i] = 2*e;     // Turn into undef.
9865         else
9866           Mask[i] &= (e-1);  // Force to LHS.
9867         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9868       }
9869     }
9870     SVI.setOperand(0, SVI.getOperand(1));
9871     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9872     SVI.setOperand(2, ConstantVector::get(Elts));
9873     LHS = SVI.getOperand(0);
9874     RHS = SVI.getOperand(1);
9875     MadeChange = true;
9876   }
9877   
9878   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9879   bool isLHSID = true, isRHSID = true;
9880     
9881   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9882     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9883     // Is this an identity shuffle of the LHS value?
9884     isLHSID &= (Mask[i] == i);
9885       
9886     // Is this an identity shuffle of the RHS value?
9887     isRHSID &= (Mask[i]-e == i);
9888   }
9889
9890   // Eliminate identity shuffles.
9891   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9892   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9893   
9894   // If the LHS is a shufflevector itself, see if we can combine it with this
9895   // one without producing an unusual shuffle.  Here we are really conservative:
9896   // we are absolutely afraid of producing a shuffle mask not in the input
9897   // program, because the code gen may not be smart enough to turn a merged
9898   // shuffle into two specific shuffles: it may produce worse code.  As such,
9899   // we only merge two shuffles if the result is one of the two input shuffle
9900   // masks.  In this case, merging the shuffles just removes one instruction,
9901   // which we know is safe.  This is good for things like turning:
9902   // (splat(splat)) -> splat.
9903   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9904     if (isa<UndefValue>(RHS)) {
9905       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9906
9907       std::vector<unsigned> NewMask;
9908       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9909         if (Mask[i] >= 2*e)
9910           NewMask.push_back(2*e);
9911         else
9912           NewMask.push_back(LHSMask[Mask[i]]);
9913       
9914       // If the result mask is equal to the src shuffle or this shuffle mask, do
9915       // the replacement.
9916       if (NewMask == LHSMask || NewMask == Mask) {
9917         std::vector<Constant*> Elts;
9918         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9919           if (NewMask[i] >= e*2) {
9920             Elts.push_back(UndefValue::get(Type::Int32Ty));
9921           } else {
9922             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9923           }
9924         }
9925         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9926                                      LHSSVI->getOperand(1),
9927                                      ConstantVector::get(Elts));
9928       }
9929     }
9930   }
9931
9932   return MadeChange ? &SVI : 0;
9933 }
9934
9935
9936
9937
9938 /// TryToSinkInstruction - Try to move the specified instruction from its
9939 /// current block into the beginning of DestBlock, which can only happen if it's
9940 /// safe to move the instruction past all of the instructions between it and the
9941 /// end of its block.
9942 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9943   assert(I->hasOneUse() && "Invariants didn't hold!");
9944
9945   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9946   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9947
9948   // Do not sink alloca instructions out of the entry block.
9949   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9950     return false;
9951
9952   // We can only sink load instructions if there is nothing between the load and
9953   // the end of block that could change the value.
9954   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9955     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9956          Scan != E; ++Scan)
9957       if (Scan->mayWriteToMemory())
9958         return false;
9959   }
9960
9961   BasicBlock::iterator InsertPos = DestBlock->begin();
9962   while (isa<PHINode>(InsertPos)) ++InsertPos;
9963
9964   I->moveBefore(InsertPos);
9965   ++NumSunkInst;
9966   return true;
9967 }
9968
9969
9970 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9971 /// all reachable code to the worklist.
9972 ///
9973 /// This has a couple of tricks to make the code faster and more powerful.  In
9974 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9975 /// them to the worklist (this significantly speeds up instcombine on code where
9976 /// many instructions are dead or constant).  Additionally, if we find a branch
9977 /// whose condition is a known constant, we only visit the reachable successors.
9978 ///
9979 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9980                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9981                                        InstCombiner &IC,
9982                                        const TargetData *TD) {
9983   // We have now visited this block!  If we've already been here, bail out.
9984   if (!Visited.insert(BB)) return;
9985     
9986   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9987     Instruction *Inst = BBI++;
9988     
9989     // DCE instruction if trivially dead.
9990     if (isInstructionTriviallyDead(Inst)) {
9991       ++NumDeadInst;
9992       DOUT << "IC: DCE: " << *Inst;
9993       Inst->eraseFromParent();
9994       continue;
9995     }
9996     
9997     // ConstantProp instruction if trivially constant.
9998     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9999       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10000       Inst->replaceAllUsesWith(C);
10001       ++NumConstProp;
10002       Inst->eraseFromParent();
10003       continue;
10004     }
10005     
10006     IC.AddToWorkList(Inst);
10007   }
10008
10009   // Recursively visit successors.  If this is a branch or switch on a constant,
10010   // only visit the reachable successor.
10011   TerminatorInst *TI = BB->getTerminator();
10012   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10013     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10014       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10015       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
10016       return;
10017     }
10018   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10019     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10020       // See if this is an explicit destination.
10021       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10022         if (SI->getCaseValue(i) == Cond) {
10023           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
10024           return;
10025         }
10026       
10027       // Otherwise it is the default destination.
10028       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
10029       return;
10030     }
10031   }
10032   
10033   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10034     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
10035 }
10036
10037 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10038   bool Changed = false;
10039   TD = &getAnalysis<TargetData>();
10040   
10041   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10042              << F.getNameStr() << "\n");
10043
10044   {
10045     // Do a depth-first traversal of the function, populate the worklist with
10046     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10047     // track of which blocks we visit.
10048     SmallPtrSet<BasicBlock*, 64> Visited;
10049     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10050
10051     // Do a quick scan over the function.  If we find any blocks that are
10052     // unreachable, remove any instructions inside of them.  This prevents
10053     // the instcombine code from having to deal with some bad special cases.
10054     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10055       if (!Visited.count(BB)) {
10056         Instruction *Term = BB->getTerminator();
10057         while (Term != BB->begin()) {   // Remove instrs bottom-up
10058           BasicBlock::iterator I = Term; --I;
10059
10060           DOUT << "IC: DCE: " << *I;
10061           ++NumDeadInst;
10062
10063           if (!I->use_empty())
10064             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10065           I->eraseFromParent();
10066         }
10067       }
10068   }
10069
10070   while (!Worklist.empty()) {
10071     Instruction *I = RemoveOneFromWorkList();
10072     if (I == 0) continue;  // skip null values.
10073
10074     // Check to see if we can DCE the instruction.
10075     if (isInstructionTriviallyDead(I)) {
10076       // Add operands to the worklist.
10077       if (I->getNumOperands() < 4)
10078         AddUsesToWorkList(*I);
10079       ++NumDeadInst;
10080
10081       DOUT << "IC: DCE: " << *I;
10082
10083       I->eraseFromParent();
10084       RemoveFromWorkList(I);
10085       continue;
10086     }
10087
10088     // Instruction isn't dead, see if we can constant propagate it.
10089     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10090       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10091
10092       // Add operands to the worklist.
10093       AddUsesToWorkList(*I);
10094       ReplaceInstUsesWith(*I, C);
10095
10096       ++NumConstProp;
10097       I->eraseFromParent();
10098       RemoveFromWorkList(I);
10099       continue;
10100     }
10101
10102     // See if we can trivially sink this instruction to a successor basic block.
10103     if (I->hasOneUse()) {
10104       BasicBlock *BB = I->getParent();
10105       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10106       if (UserParent != BB) {
10107         bool UserIsSuccessor = false;
10108         // See if the user is one of our successors.
10109         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10110           if (*SI == UserParent) {
10111             UserIsSuccessor = true;
10112             break;
10113           }
10114
10115         // If the user is one of our immediate successors, and if that successor
10116         // only has us as a predecessors (we'd have to split the critical edge
10117         // otherwise), we can keep going.
10118         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10119             next(pred_begin(UserParent)) == pred_end(UserParent))
10120           // Okay, the CFG is simple enough, try to sink this instruction.
10121           Changed |= TryToSinkInstruction(I, UserParent);
10122       }
10123     }
10124
10125     // Now that we have an instruction, try combining it to simplify it...
10126     if (Instruction *Result = visit(*I)) {
10127       ++NumCombined;
10128       // Should we replace the old instruction with a new one?
10129       if (Result != I) {
10130         DOUT << "IC: Old = " << *I
10131              << "    New = " << *Result;
10132
10133         // Everything uses the new instruction now.
10134         I->replaceAllUsesWith(Result);
10135
10136         // Push the new instruction and any users onto the worklist.
10137         AddToWorkList(Result);
10138         AddUsersToWorkList(*Result);
10139
10140         // Move the name to the new instruction first.
10141         Result->takeName(I);
10142
10143         // Insert the new instruction into the basic block...
10144         BasicBlock *InstParent = I->getParent();
10145         BasicBlock::iterator InsertPos = I;
10146
10147         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10148           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10149             ++InsertPos;
10150
10151         InstParent->getInstList().insert(InsertPos, Result);
10152
10153         // Make sure that we reprocess all operands now that we reduced their
10154         // use counts.
10155         AddUsesToWorkList(*I);
10156
10157         // Instructions can end up on the worklist more than once.  Make sure
10158         // we do not process an instruction that has been deleted.
10159         RemoveFromWorkList(I);
10160
10161         // Erase the old instruction.
10162         InstParent->getInstList().erase(I);
10163       } else {
10164         DOUT << "IC: MOD = " << *I;
10165
10166         // If the instruction was modified, it's possible that it is now dead.
10167         // if so, remove it.
10168         if (isInstructionTriviallyDead(I)) {
10169           // Make sure we process all operands now that we are reducing their
10170           // use counts.
10171           AddUsesToWorkList(*I);
10172
10173           // Instructions may end up in the worklist more than once.  Erase all
10174           // occurrences of this instruction.
10175           RemoveFromWorkList(I);
10176           I->eraseFromParent();
10177         } else {
10178           AddToWorkList(I);
10179           AddUsersToWorkList(*I);
10180         }
10181       }
10182       Changed = true;
10183     }
10184   }
10185
10186   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10187   return Changed;
10188 }
10189
10190
10191 bool InstCombiner::runOnFunction(Function &F) {
10192   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10193   
10194   bool EverMadeChange = false;
10195
10196   // Iterate while there is work to do.
10197   unsigned Iteration = 0;
10198   while (DoOneIteration(F, Iteration++)) 
10199     EverMadeChange = true;
10200   return EverMadeChange;
10201 }
10202
10203 FunctionPass *llvm::createInstructionCombiningPass() {
10204   return new InstCombiner();
10205 }
10206