fix a subtle bug that caused an MSVC warning. Thanks to Jeffc for pointing this...
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/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 Mask, 
323                               uint64_t &KnownZero, uint64_t &KnownOne,
324                               unsigned Depth = 0);
325
326     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327                                       uint64_t &UndefElts, unsigned Depth = 0);
328       
329     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330     // PHI node as operand #0, see if we can fold the instruction into the PHI
331     // (which is only possible if all operands to the PHI are constants).
332     Instruction *FoldOpIntoPhi(Instruction &I);
333
334     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335     // operator and they all are only used by the PHI, PHI together their
336     // inputs, and do the operation once, to the result of the PHI.
337     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
338     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339     
340     
341     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
343     
344     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
345                               bool isSub, Instruction &I);
346     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
347                                  bool isSigned, bool Inside, Instruction &IB);
348     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
349     Instruction *MatchBSwap(BinaryOperator &I);
350
351     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
352   };
353
354   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
355 }
356
357 // getComplexity:  Assign a complexity or rank value to LLVM Values...
358 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
359 static unsigned getComplexity(Value *V) {
360   if (isa<Instruction>(V)) {
361     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
362       return 3;
363     return 4;
364   }
365   if (isa<Argument>(V)) return 3;
366   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
367 }
368
369 // isOnlyUse - Return true if this instruction will be deleted if we stop using
370 // it.
371 static bool isOnlyUse(Value *V) {
372   return V->hasOneUse() || isa<Constant>(V);
373 }
374
375 // getPromotedType - Return the specified type promoted as it would be to pass
376 // though a va_arg area...
377 static const Type *getPromotedType(const Type *Ty) {
378   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379     if (ITy->getBitWidth() < 32)
380       return Type::Int32Ty;
381   } else if (Ty == Type::FloatTy)
382     return Type::DoubleTy;
383   return Ty;
384 }
385
386 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
387 /// expression bitcast,  return the operand value, otherwise return null.
388 static Value *getBitCastOperand(Value *V) {
389   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
390     return I->getOperand(0);
391   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
392     if (CE->getOpcode() == Instruction::BitCast)
393       return CE->getOperand(0);
394   return 0;
395 }
396
397 /// This function is a wrapper around CastInst::isEliminableCastPair. It
398 /// simply extracts arguments and returns what that function returns.
399 static Instruction::CastOps 
400 isEliminableCastPair(
401   const CastInst *CI, ///< The first cast instruction
402   unsigned opcode,       ///< The opcode of the second cast instruction
403   const Type *DstTy,     ///< The target type for the second cast instruction
404   TargetData *TD         ///< The target data for pointer size
405 ) {
406   
407   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
408   const Type *MidTy = CI->getType();                  // B from above
409
410   // Get the opcodes of the two Cast instructions
411   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
413
414   return Instruction::CastOps(
415       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416                                      DstTy, TD->getIntPtrType()));
417 }
418
419 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420 /// in any code being generated.  It does not require codegen if V is simple
421 /// enough or if the cast can be folded into other casts.
422 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
423                               const Type *Ty, TargetData *TD) {
424   if (V->getType() == Ty || isa<Constant>(V)) return false;
425   
426   // If this is another cast that can be eliminated, it isn't codegen either.
427   if (const CastInst *CI = dyn_cast<CastInst>(V))
428     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
429       return false;
430   return true;
431 }
432
433 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
435 /// casts that are known to not do anything...
436 ///
437 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438                                              Value *V, const Type *DestTy,
439                                              Instruction *InsertBefore) {
440   if (V->getType() == DestTy) return V;
441   if (Constant *C = dyn_cast<Constant>(V))
442     return ConstantExpr::getCast(opcode, C, DestTy);
443   
444   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
445 }
446
447 // SimplifyCommutative - This performs a few simplifications for commutative
448 // operators:
449 //
450 //  1. Order operands such that they are listed from right (least complex) to
451 //     left (most complex).  This puts constants before unary operators before
452 //     binary operators.
453 //
454 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
456 //
457 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
458   bool Changed = false;
459   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460     Changed = !I.swapOperands();
461
462   if (!I.isAssociative()) return Changed;
463   Instruction::BinaryOps Opcode = I.getOpcode();
464   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466       if (isa<Constant>(I.getOperand(1))) {
467         Constant *Folded = ConstantExpr::get(I.getOpcode(),
468                                              cast<Constant>(I.getOperand(1)),
469                                              cast<Constant>(Op->getOperand(1)));
470         I.setOperand(0, Op->getOperand(0));
471         I.setOperand(1, Folded);
472         return true;
473       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475             isOnlyUse(Op) && isOnlyUse(Op1)) {
476           Constant *C1 = cast<Constant>(Op->getOperand(1));
477           Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
480           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
481           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482                                                     Op1->getOperand(0),
483                                                     Op1->getName(), &I);
484           AddToWorkList(New);
485           I.setOperand(0, New);
486           I.setOperand(1, Folded);
487           return true;
488         }
489     }
490   return Changed;
491 }
492
493 /// SimplifyCompare - For a CmpInst this function just orders the operands
494 /// so that theyare listed from right (least complex) to left (most complex).
495 /// This puts constants before unary operators before binary operators.
496 bool InstCombiner::SimplifyCompare(CmpInst &I) {
497   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498     return false;
499   I.swapOperands();
500   // Compare instructions are not associative so there's nothing else we can do.
501   return true;
502 }
503
504 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505 // if the LHS is a constant zero (which is the 'negate' form).
506 //
507 static inline Value *dyn_castNegVal(Value *V) {
508   if (BinaryOperator::isNeg(V))
509     return BinaryOperator::getNegArgument(V);
510
511   // Constants can be considered to be negated values if they can be folded.
512   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513     return ConstantExpr::getNeg(C);
514   return 0;
515 }
516
517 static inline Value *dyn_castNotVal(Value *V) {
518   if (BinaryOperator::isNot(V))
519     return BinaryOperator::getNotArgument(V);
520
521   // Constants can be considered to be not'ed values...
522   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
523     return ConstantExpr::getNot(C);
524   return 0;
525 }
526
527 // dyn_castFoldableMul - If this value is a multiply that can be folded into
528 // other computations (because it has a constant operand), return the
529 // non-constant operand of the multiply, and set CST to point to the multiplier.
530 // Otherwise, return null.
531 //
532 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
533   if (V->hasOneUse() && V->getType()->isInteger())
534     if (Instruction *I = dyn_cast<Instruction>(V)) {
535       if (I->getOpcode() == Instruction::Mul)
536         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
537           return I->getOperand(0);
538       if (I->getOpcode() == Instruction::Shl)
539         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
540           // The multiplier is really 1 << CST.
541           Constant *One = ConstantInt::get(V->getType(), 1);
542           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543           return I->getOperand(0);
544         }
545     }
546   return 0;
547 }
548
549 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550 /// expression, return it.
551 static User *dyn_castGetElementPtr(Value *V) {
552   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554     if (CE->getOpcode() == Instruction::GetElementPtr)
555       return cast<User>(V);
556   return false;
557 }
558
559 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
560 static ConstantInt *AddOne(ConstantInt *C) {
561   return cast<ConstantInt>(ConstantExpr::getAdd(C,
562                                          ConstantInt::get(C->getType(), 1)));
563 }
564 static ConstantInt *SubOne(ConstantInt *C) {
565   return cast<ConstantInt>(ConstantExpr::getSub(C,
566                                          ConstantInt::get(C->getType(), 1)));
567 }
568
569 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
570 /// known to be either zero or one and return them in the KnownZero/KnownOne
571 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
572 /// processing.
573 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
574                               uint64_t &KnownOne, unsigned Depth = 0) {
575   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
576   // we cannot optimize based on the assumption that it is zero without changing
577   // it to be an explicit zero.  If we don't change it to zero, other code could
578   // optimized based on the contradictory assumption that it is non-zero.
579   // Because instcombine aggressively folds operations with undef args anyway,
580   // this won't lose us code quality.
581   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
582     // We know all of the bits for a constant!
583     KnownOne = CI->getZExtValue() & Mask;
584     KnownZero = ~KnownOne & Mask;
585     return;
586   }
587
588   KnownZero = KnownOne = 0;   // Don't know anything.
589   if (Depth == 6 || Mask == 0)
590     return;  // Limit search depth.
591
592   uint64_t KnownZero2, KnownOne2;
593   Instruction *I = dyn_cast<Instruction>(V);
594   if (!I) return;
595
596   Mask &= cast<IntegerType>(V->getType())->getBitMask();
597   
598   switch (I->getOpcode()) {
599   case Instruction::And:
600     // If either the LHS or the RHS are Zero, the result is zero.
601     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
602     Mask &= ~KnownZero;
603     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
604     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
605     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
606     
607     // Output known-1 bits are only known if set in both the LHS & RHS.
608     KnownOne &= KnownOne2;
609     // Output known-0 are known to be clear if zero in either the LHS | RHS.
610     KnownZero |= KnownZero2;
611     return;
612   case Instruction::Or:
613     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614     Mask &= ~KnownOne;
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-0 bits are only known if clear in both the LHS & RHS.
620     KnownZero &= KnownZero2;
621     // Output known-1 are known to be set if set in either the LHS | RHS.
622     KnownOne |= KnownOne2;
623     return;
624   case Instruction::Xor: {
625     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
627     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
628     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
629     
630     // Output known-0 bits are known if clear or set in both the LHS & RHS.
631     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
632     // Output known-1 are known to be set if set in only one of the LHS, RHS.
633     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
634     KnownZero = KnownZeroOut;
635     return;
636   }
637   case Instruction::Select:
638     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
639     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
640     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
641     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
642
643     // Only known if known in both the LHS and RHS.
644     KnownOne &= KnownOne2;
645     KnownZero &= KnownZero2;
646     return;
647   case Instruction::FPTrunc:
648   case Instruction::FPExt:
649   case Instruction::FPToUI:
650   case Instruction::FPToSI:
651   case Instruction::SIToFP:
652   case Instruction::PtrToInt:
653   case Instruction::UIToFP:
654   case Instruction::IntToPtr:
655     return; // Can't work with floating point or pointers
656   case Instruction::Trunc: 
657     // All these have integer operands
658     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
659     return;
660   case Instruction::BitCast: {
661     const Type *SrcTy = I->getOperand(0)->getType();
662     if (SrcTy->isInteger()) {
663       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
664       return;
665     }
666     break;
667   }
668   case Instruction::ZExt:  {
669     // Compute the bits in the result that are not present in the input.
670     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
671     uint64_t NotIn = ~SrcTy->getBitMask();
672     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
673       
674     Mask &= SrcTy->getBitMask();
675     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
676     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
677     // The top bits are known to be zero.
678     KnownZero |= NewBits;
679     return;
680   }
681   case Instruction::SExt: {
682     // Compute the bits in the result that are not present in the input.
683     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
684     uint64_t NotIn = ~SrcTy->getBitMask();
685     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
686       
687     Mask &= SrcTy->getBitMask();
688     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
689     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
690
691     // If the sign bit of the input is known set or clear, then we know the
692     // top bits of the result.
693     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
694     if (KnownZero & InSignBit) {          // Input sign bit known zero
695       KnownZero |= NewBits;
696       KnownOne &= ~NewBits;
697     } else if (KnownOne & InSignBit) {    // Input sign bit known set
698       KnownOne |= NewBits;
699       KnownZero &= ~NewBits;
700     } else {                              // Input sign bit unknown
701       KnownZero &= ~NewBits;
702       KnownOne &= ~NewBits;
703     }
704     return;
705   }
706   case Instruction::Shl:
707     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
708     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709       uint64_t ShiftAmt = SA->getZExtValue();
710       Mask >>= ShiftAmt;
711       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
712       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
713       KnownZero <<= ShiftAmt;
714       KnownOne  <<= ShiftAmt;
715       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
716       return;
717     }
718     break;
719   case Instruction::LShr:
720     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
721     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
722       // Compute the new bits that are at the top now.
723       uint64_t ShiftAmt = SA->getZExtValue();
724       uint64_t HighBits = (1ULL << ShiftAmt)-1;
725       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
726       
727       // Unsigned shift right.
728       Mask <<= ShiftAmt;
729       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
730       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
731       KnownZero >>= ShiftAmt;
732       KnownOne  >>= ShiftAmt;
733       KnownZero |= HighBits;  // high bits known zero.
734       return;
735     }
736     break;
737   case Instruction::AShr:
738     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
739     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
740       // Compute the new bits that are at the top now.
741       uint64_t ShiftAmt = SA->getZExtValue();
742       uint64_t HighBits = (1ULL << ShiftAmt)-1;
743       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
744       
745       // Signed shift right.
746       Mask <<= ShiftAmt;
747       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
749       KnownZero >>= ShiftAmt;
750       KnownOne  >>= ShiftAmt;
751         
752       // Handle the sign bits.
753       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
754       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
755         
756       if (KnownZero & SignBit) {       // New bits are known zero.
757         KnownZero |= HighBits;
758       } else if (KnownOne & SignBit) { // New bits are known one.
759         KnownOne |= HighBits;
760       }
761       return;
762     }
763     break;
764   }
765 }
766
767 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
768 /// this predicate to simplify operations downstream.  Mask is known to be zero
769 /// for bits that V cannot have.
770 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
771   uint64_t KnownZero, KnownOne;
772   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
773   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
774   return (KnownZero & Mask) == Mask;
775 }
776
777 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
778 /// specified instruction is a constant integer.  If so, check to see if there
779 /// are any bits set in the constant that are not demanded.  If so, shrink the
780 /// constant and return true.
781 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
782                                    uint64_t Demanded) {
783   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
784   if (!OpC) return false;
785
786   // If there are no bits set that aren't demanded, nothing to do.
787   if ((~Demanded & OpC->getZExtValue()) == 0)
788     return false;
789
790   // This is producing any bits that are not needed, shrink the RHS.
791   uint64_t Val = Demanded & OpC->getZExtValue();
792   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
793   return true;
794 }
795
796 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
797 // set of known zero and one bits, compute the maximum and minimum values that
798 // could have the specified known zero and known one bits, returning them in
799 // min/max.
800 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
801                                                    uint64_t KnownZero,
802                                                    uint64_t KnownOne,
803                                                    int64_t &Min, int64_t &Max) {
804   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
805   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
808   
809   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
810   // bit if it is unknown.
811   Min = KnownOne;
812   Max = KnownOne|UnknownBits;
813   
814   if (SignBit & UnknownBits) { // Sign bit is unknown
815     Min |= SignBit;
816     Max &= ~SignBit;
817   }
818   
819   // Sign extend the min/max values.
820   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
821   Min = (Min << ShAmt) >> ShAmt;
822   Max = (Max << ShAmt) >> ShAmt;
823 }
824
825 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
826 // a set of known zero and one bits, compute the maximum and minimum values that
827 // could have the specified known zero and known one bits, returning them in
828 // min/max.
829 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
830                                                      uint64_t KnownZero,
831                                                      uint64_t KnownOne,
832                                                      uint64_t &Min,
833                                                      uint64_t &Max) {
834   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
835   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
836   
837   // The minimum value is when the unknown bits are all zeros.
838   Min = KnownOne;
839   // The maximum value is when the unknown bits are all ones.
840   Max = KnownOne|UnknownBits;
841 }
842
843
844 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
845 /// DemandedMask bits of the result of V are ever used downstream.  If we can
846 /// use this information to simplify V, do so and return true.  Otherwise,
847 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
848 /// the expression (used to simplify the caller).  The KnownZero/One bits may
849 /// only be accurate for those bits in the DemandedMask.
850 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
851                                         uint64_t &KnownZero, uint64_t &KnownOne,
852                                         unsigned Depth) {
853   const IntegerType *VTy = cast<IntegerType>(V->getType());
854   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
855     // We know all of the bits for a constant!
856     KnownOne = CI->getZExtValue() & DemandedMask;
857     KnownZero = ~KnownOne & DemandedMask;
858     return false;
859   }
860   
861   KnownZero = KnownOne = 0;
862   if (!V->hasOneUse()) {    // Other users may use these bits.
863     if (Depth != 0) {       // Not at the root.
864       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
865       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
866       return false;
867     }
868     // If this is the root being simplified, allow it to have multiple uses,
869     // just set the DemandedMask to all bits.
870     DemandedMask = VTy->getBitMask();
871   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
872     if (V != UndefValue::get(VTy))
873       return UpdateValueUsesWith(V, UndefValue::get(VTy));
874     return false;
875   } else if (Depth == 6) {        // Limit search depth.
876     return false;
877   }
878   
879   Instruction *I = dyn_cast<Instruction>(V);
880   if (!I) return false;        // Only analyze instructions.
881
882   DemandedMask &= VTy->getBitMask();
883   
884   uint64_t KnownZero2 = 0, KnownOne2 = 0;
885   switch (I->getOpcode()) {
886   default: break;
887   case Instruction::And:
888     // If either the LHS or the RHS are Zero, the result is zero.
889     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890                              KnownZero, KnownOne, Depth+1))
891       return true;
892     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
893
894     // If something is known zero on the RHS, the bits aren't demanded on the
895     // LHS.
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
897                              KnownZero2, KnownOne2, Depth+1))
898       return true;
899     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
900
901     // If all of the demanded bits are known 1 on one side, return the other.
902     // These bits cannot contribute to the result of the 'and'.
903     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
904       return UpdateValueUsesWith(I, I->getOperand(0));
905     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
906       return UpdateValueUsesWith(I, I->getOperand(1));
907     
908     // If all of the demanded bits in the inputs are known zeros, return zero.
909     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
910       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
911       
912     // If the RHS is a constant, see if we can simplify it.
913     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
914       return UpdateValueUsesWith(I, I);
915       
916     // Output known-1 bits are only known if set in both the LHS & RHS.
917     KnownOne &= KnownOne2;
918     // Output known-0 are known to be clear if zero in either the LHS | RHS.
919     KnownZero |= KnownZero2;
920     break;
921   case Instruction::Or:
922     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
923                              KnownZero, KnownOne, Depth+1))
924       return true;
925     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
926     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
927                              KnownZero2, KnownOne2, Depth+1))
928       return true;
929     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
930     
931     // If all of the demanded bits are known zero on one side, return the other.
932     // These bits cannot contribute to the result of the 'or'.
933     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
934       return UpdateValueUsesWith(I, I->getOperand(0));
935     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
936       return UpdateValueUsesWith(I, I->getOperand(1));
937
938     // If all of the potentially set bits on one side are known to be set on
939     // the other side, just use the 'other' side.
940     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
941         (DemandedMask & (~KnownZero)))
942       return UpdateValueUsesWith(I, I->getOperand(0));
943     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
944         (DemandedMask & (~KnownZero2)))
945       return UpdateValueUsesWith(I, I->getOperand(1));
946         
947     // If the RHS is a constant, see if we can simplify it.
948     if (ShrinkDemandedConstant(I, 1, DemandedMask))
949       return UpdateValueUsesWith(I, I);
950           
951     // Output known-0 bits are only known if clear in both the LHS & RHS.
952     KnownZero &= KnownZero2;
953     // Output known-1 are known to be set if set in either the LHS | RHS.
954     KnownOne |= KnownOne2;
955     break;
956   case Instruction::Xor: {
957     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958                              KnownZero, KnownOne, Depth+1))
959       return true;
960     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
961     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
962                              KnownZero2, KnownOne2, Depth+1))
963       return true;
964     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
965     
966     // If all of the demanded bits are known zero on one side, return the other.
967     // These bits cannot contribute to the result of the 'xor'.
968     if ((DemandedMask & KnownZero) == DemandedMask)
969       return UpdateValueUsesWith(I, I->getOperand(0));
970     if ((DemandedMask & KnownZero2) == DemandedMask)
971       return UpdateValueUsesWith(I, I->getOperand(1));
972     
973     // Output known-0 bits are known if clear or set in both the LHS & RHS.
974     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
975     // Output known-1 are known to be set if set in only one of the LHS, RHS.
976     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
977     
978     // If all of the demanded bits are known to be zero on one side or the
979     // other, turn this into an *inclusive* or.
980     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
981     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
982       Instruction *Or =
983         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
984                                  I->getName());
985       InsertNewInstBefore(Or, *I);
986       return UpdateValueUsesWith(I, Or);
987     }
988     
989     // If all of the demanded bits on one side are known, and all of the set
990     // bits on that side are also known to be set on the other side, turn this
991     // into an AND, as we know the bits will be cleared.
992     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
993     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
994       if ((KnownOne & KnownOne2) == KnownOne) {
995         Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
996         Instruction *And = 
997           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
998         InsertNewInstBefore(And, *I);
999         return UpdateValueUsesWith(I, And);
1000       }
1001     }
1002     
1003     // If the RHS is a constant, see if we can simplify it.
1004     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1005     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006       return UpdateValueUsesWith(I, I);
1007     
1008     KnownZero = KnownZeroOut;
1009     KnownOne  = KnownOneOut;
1010     break;
1011   }
1012   case Instruction::Select:
1013     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1014                              KnownZero, KnownOne, Depth+1))
1015       return true;
1016     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1017                              KnownZero2, KnownOne2, Depth+1))
1018       return true;
1019     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1020     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1021     
1022     // If the operands are constants, see if we can simplify them.
1023     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024       return UpdateValueUsesWith(I, I);
1025     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1026       return UpdateValueUsesWith(I, I);
1027     
1028     // Only known if known in both the LHS and RHS.
1029     KnownOne &= KnownOne2;
1030     KnownZero &= KnownZero2;
1031     break;
1032   case Instruction::Trunc:
1033     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1034                              KnownZero, KnownOne, Depth+1))
1035       return true;
1036     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1037     break;
1038   case Instruction::BitCast:
1039     if (!I->getOperand(0)->getType()->isInteger())
1040       return false;
1041       
1042     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1043                              KnownZero, KnownOne, Depth+1))
1044       return true;
1045     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1046     break;
1047   case Instruction::ZExt: {
1048     // Compute the bits in the result that are not present in the input.
1049     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1050     uint64_t NotIn = ~SrcTy->getBitMask();
1051     uint64_t NewBits = VTy->getBitMask() & NotIn;
1052     
1053     DemandedMask &= SrcTy->getBitMask();
1054     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1055                              KnownZero, KnownOne, Depth+1))
1056       return true;
1057     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1058     // The top bits are known to be zero.
1059     KnownZero |= NewBits;
1060     break;
1061   }
1062   case Instruction::SExt: {
1063     // Compute the bits in the result that are not present in the input.
1064     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1065     uint64_t NotIn = ~SrcTy->getBitMask();
1066     uint64_t NewBits = VTy->getBitMask() & NotIn;
1067     
1068     // Get the sign bit for the source type
1069     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1070     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1071
1072     // If any of the sign extended bits are demanded, we know that the sign
1073     // bit is demanded.
1074     if (NewBits & DemandedMask)
1075       InputDemandedBits |= InSignBit;
1076       
1077     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1078                              KnownZero, KnownOne, Depth+1))
1079       return true;
1080     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1081       
1082     // If the sign bit of the input is known set or clear, then we know the
1083     // top bits of the result.
1084
1085     // If the input sign bit is known zero, or if the NewBits are not demanded
1086     // convert this into a zero extension.
1087     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1088       // Convert to ZExt cast
1089       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1090       return UpdateValueUsesWith(I, NewCast);
1091     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1092       KnownOne |= NewBits;
1093       KnownZero &= ~NewBits;
1094     } else {                              // Input sign bit unknown
1095       KnownZero &= ~NewBits;
1096       KnownOne &= ~NewBits;
1097     }
1098     break;
1099   }
1100   case Instruction::Add:
1101     // If there is a constant on the RHS, there are a variety of xformations
1102     // we can do.
1103     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1104       // If null, this should be simplified elsewhere.  Some of the xforms here
1105       // won't work if the RHS is zero.
1106       if (RHS->isNullValue())
1107         break;
1108       
1109       // Figure out what the input bits are.  If the top bits of the and result
1110       // are not demanded, then the add doesn't demand them from its input
1111       // either.
1112       
1113       // Shift the demanded mask up so that it's at the top of the uint64_t.
1114       unsigned BitWidth = VTy->getPrimitiveSizeInBits();
1115       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1116       
1117       // If the top bit of the output is demanded, demand everything from the
1118       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1119       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1120
1121       // Find information about known zero/one bits in the input.
1122       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1123                                KnownZero2, KnownOne2, Depth+1))
1124         return true;
1125
1126       // If the RHS of the add has bits set that can't affect the input, reduce
1127       // the constant.
1128       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1129         return UpdateValueUsesWith(I, I);
1130       
1131       // Avoid excess work.
1132       if (KnownZero2 == 0 && KnownOne2 == 0)
1133         break;
1134       
1135       // Turn it into OR if input bits are zero.
1136       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1137         Instruction *Or =
1138           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1139                                    I->getName());
1140         InsertNewInstBefore(Or, *I);
1141         return UpdateValueUsesWith(I, Or);
1142       }
1143       
1144       // We can say something about the output known-zero and known-one bits,
1145       // depending on potential carries from the input constant and the
1146       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1147       // bits set and the RHS constant is 0x01001, then we know we have a known
1148       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1149       
1150       // To compute this, we first compute the potential carry bits.  These are
1151       // the bits which may be modified.  I'm not aware of a better way to do
1152       // this scan.
1153       uint64_t RHSVal = RHS->getZExtValue();
1154       
1155       bool CarryIn = false;
1156       uint64_t CarryBits = 0;
1157       uint64_t CurBit = 1;
1158       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1159         // Record the current carry in.
1160         if (CarryIn) CarryBits |= CurBit;
1161         
1162         bool CarryOut;
1163         
1164         // This bit has a carry out unless it is "zero + zero" or
1165         // "zero + anything" with no carry in.
1166         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1167           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1168         } else if (!CarryIn &&
1169                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1170           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1171         } else {
1172           // Otherwise, we have to assume we have a carry out.
1173           CarryOut = true;
1174         }
1175         
1176         // This stage's carry out becomes the next stage's carry-in.
1177         CarryIn = CarryOut;
1178       }
1179       
1180       // Now that we know which bits have carries, compute the known-1/0 sets.
1181       
1182       // Bits are known one if they are known zero in one operand and one in the
1183       // other, and there is no input carry.
1184       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1185       
1186       // Bits are known zero if they are known zero in both operands and there
1187       // is no input carry.
1188       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1189     } else {
1190       // If the high-bits of this ADD are not demanded, then it does not demand
1191       // the high bits of its LHS or RHS.
1192       if ((DemandedMask & VTy->getSignBit()) == 0) {
1193         // Right fill the mask of bits for this ADD to demand the most
1194         // significant bit and all those below it.
1195         unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1196         uint64_t DemandedFromOps = ~0ULL >> NLZ;
1197         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1198                                  KnownZero2, KnownOne2, Depth+1))
1199           return true;
1200         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1201                                  KnownZero2, KnownOne2, Depth+1))
1202           return true;
1203       }
1204     }
1205     break;
1206   case Instruction::Sub:
1207     // If the high-bits of this SUB are not demanded, then it does not demand
1208     // the high bits of its LHS or RHS.
1209     if ((DemandedMask & VTy->getSignBit()) == 0) {
1210       // Right fill the mask of bits for this SUB to demand the most
1211       // significant bit and all those below it.
1212       unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1213       uint64_t DemandedFromOps = ~0ULL >> NLZ;
1214       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1215                                KnownZero2, KnownOne2, Depth+1))
1216         return true;
1217       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1218                                KnownZero2, KnownOne2, Depth+1))
1219         return true;
1220     }
1221     break;
1222   case Instruction::Shl:
1223     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1224       uint64_t ShiftAmt = SA->getZExtValue();
1225       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1226                                KnownZero, KnownOne, Depth+1))
1227         return true;
1228       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1229       KnownZero <<= ShiftAmt;
1230       KnownOne  <<= ShiftAmt;
1231       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1232     }
1233     break;
1234   case Instruction::LShr:
1235     // For a logical shift right
1236     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1237       unsigned ShiftAmt = SA->getZExtValue();
1238       
1239       // Compute the new bits that are at the top now.
1240       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1241       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1242       uint64_t TypeMask = VTy->getBitMask();
1243       // Unsigned shift right.
1244       if (SimplifyDemandedBits(I->getOperand(0),
1245                               (DemandedMask << ShiftAmt) & TypeMask,
1246                                KnownZero, KnownOne, Depth+1))
1247         return true;
1248       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1249       KnownZero &= TypeMask;
1250       KnownOne  &= TypeMask;
1251       KnownZero >>= ShiftAmt;
1252       KnownOne  >>= ShiftAmt;
1253       KnownZero |= HighBits;  // high bits known zero.
1254     }
1255     break;
1256   case Instruction::AShr:
1257     // If this is an arithmetic shift right and only the low-bit is set, we can
1258     // always convert this into a logical shr, even if the shift amount is
1259     // variable.  The low bit of the shift cannot be an input sign bit unless
1260     // the shift amount is >= the size of the datatype, which is undefined.
1261     if (DemandedMask == 1) {
1262       // Perform the logical shift right.
1263       Value *NewVal = BinaryOperator::createLShr(
1264                         I->getOperand(0), I->getOperand(1), I->getName());
1265       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1266       return UpdateValueUsesWith(I, NewVal);
1267     }    
1268     
1269     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270       unsigned ShiftAmt = SA->getZExtValue();
1271       
1272       // Compute the new bits that are at the top now.
1273       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1274       HighBits <<= VTy->getBitWidth() - ShiftAmt;
1275       uint64_t TypeMask = VTy->getBitMask();
1276       // Signed shift right.
1277       if (SimplifyDemandedBits(I->getOperand(0),
1278                                (DemandedMask << ShiftAmt) & TypeMask,
1279                                KnownZero, KnownOne, Depth+1))
1280         return true;
1281       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1282       KnownZero &= TypeMask;
1283       KnownOne  &= TypeMask;
1284       KnownZero >>= ShiftAmt;
1285       KnownOne  >>= ShiftAmt;
1286         
1287       // Handle the sign bits.
1288       uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
1289       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1290         
1291       // If the input sign bit is known to be zero, or if none of the top bits
1292       // are demanded, turn this into an unsigned shift right.
1293       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1294         // Perform the logical shift right.
1295         Value *NewVal = BinaryOperator::createLShr(
1296                           I->getOperand(0), SA, I->getName());
1297         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1298         return UpdateValueUsesWith(I, NewVal);
1299       } else if (KnownOne & SignBit) { // New bits are known one.
1300         KnownOne |= HighBits;
1301       }
1302     }
1303     break;
1304   }
1305   
1306   // If the client is only demanding bits that we know, return the known
1307   // constant.
1308   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1309     return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
1310   return false;
1311 }  
1312
1313
1314 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1315 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1316 /// actually used by the caller.  This method analyzes which elements of the
1317 /// operand are undef and returns that information in UndefElts.
1318 ///
1319 /// If the information about demanded elements can be used to simplify the
1320 /// operation, the operation is simplified, then the resultant value is
1321 /// returned.  This returns null if no change was made.
1322 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1323                                                 uint64_t &UndefElts,
1324                                                 unsigned Depth) {
1325   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1326   assert(VWidth <= 64 && "Vector too wide to analyze!");
1327   uint64_t EltMask = ~0ULL >> (64-VWidth);
1328   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1329          "Invalid DemandedElts!");
1330
1331   if (isa<UndefValue>(V)) {
1332     // If the entire vector is undefined, just return this info.
1333     UndefElts = EltMask;
1334     return 0;
1335   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1336     UndefElts = EltMask;
1337     return UndefValue::get(V->getType());
1338   }
1339   
1340   UndefElts = 0;
1341   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1342     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1343     Constant *Undef = UndefValue::get(EltTy);
1344
1345     std::vector<Constant*> Elts;
1346     for (unsigned i = 0; i != VWidth; ++i)
1347       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1348         Elts.push_back(Undef);
1349         UndefElts |= (1ULL << i);
1350       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1351         Elts.push_back(Undef);
1352         UndefElts |= (1ULL << i);
1353       } else {                               // Otherwise, defined.
1354         Elts.push_back(CP->getOperand(i));
1355       }
1356         
1357     // If we changed the constant, return it.
1358     Constant *NewCP = ConstantVector::get(Elts);
1359     return NewCP != CP ? NewCP : 0;
1360   } else if (isa<ConstantAggregateZero>(V)) {
1361     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1362     // set to undef.
1363     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1364     Constant *Zero = Constant::getNullValue(EltTy);
1365     Constant *Undef = UndefValue::get(EltTy);
1366     std::vector<Constant*> Elts;
1367     for (unsigned i = 0; i != VWidth; ++i)
1368       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1369     UndefElts = DemandedElts ^ EltMask;
1370     return ConstantVector::get(Elts);
1371   }
1372   
1373   if (!V->hasOneUse()) {    // Other users may use these bits.
1374     if (Depth != 0) {       // Not at the root.
1375       // TODO: Just compute the UndefElts information recursively.
1376       return false;
1377     }
1378     return false;
1379   } else if (Depth == 10) {        // Limit search depth.
1380     return false;
1381   }
1382   
1383   Instruction *I = dyn_cast<Instruction>(V);
1384   if (!I) return false;        // Only analyze instructions.
1385   
1386   bool MadeChange = false;
1387   uint64_t UndefElts2;
1388   Value *TmpV;
1389   switch (I->getOpcode()) {
1390   default: break;
1391     
1392   case Instruction::InsertElement: {
1393     // If this is a variable index, we don't know which element it overwrites.
1394     // demand exactly the same input as we produce.
1395     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1396     if (Idx == 0) {
1397       // Note that we can't propagate undef elt info, because we don't know
1398       // which elt is getting updated.
1399       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1400                                         UndefElts2, Depth+1);
1401       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1402       break;
1403     }
1404     
1405     // If this is inserting an element that isn't demanded, remove this
1406     // insertelement.
1407     unsigned IdxNo = Idx->getZExtValue();
1408     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1409       return AddSoonDeadInstToWorklist(*I, 0);
1410     
1411     // Otherwise, the element inserted overwrites whatever was there, so the
1412     // input demanded set is simpler than the output set.
1413     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1414                                       DemandedElts & ~(1ULL << IdxNo),
1415                                       UndefElts, Depth+1);
1416     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1417
1418     // The inserted element is defined.
1419     UndefElts |= 1ULL << IdxNo;
1420     break;
1421   }
1422     
1423   case Instruction::And:
1424   case Instruction::Or:
1425   case Instruction::Xor:
1426   case Instruction::Add:
1427   case Instruction::Sub:
1428   case Instruction::Mul:
1429     // div/rem demand all inputs, because they don't want divide by zero.
1430     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1431                                       UndefElts, Depth+1);
1432     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1433     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1434                                       UndefElts2, Depth+1);
1435     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1436       
1437     // Output elements are undefined if both are undefined.  Consider things
1438     // like undef&0.  The result is known zero, not undef.
1439     UndefElts &= UndefElts2;
1440     break;
1441     
1442   case Instruction::Call: {
1443     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1444     if (!II) break;
1445     switch (II->getIntrinsicID()) {
1446     default: break;
1447       
1448     // Binary vector operations that work column-wise.  A dest element is a
1449     // function of the corresponding input elements from the two inputs.
1450     case Intrinsic::x86_sse_sub_ss:
1451     case Intrinsic::x86_sse_mul_ss:
1452     case Intrinsic::x86_sse_min_ss:
1453     case Intrinsic::x86_sse_max_ss:
1454     case Intrinsic::x86_sse2_sub_sd:
1455     case Intrinsic::x86_sse2_mul_sd:
1456     case Intrinsic::x86_sse2_min_sd:
1457     case Intrinsic::x86_sse2_max_sd:
1458       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1459                                         UndefElts, Depth+1);
1460       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1461       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1462                                         UndefElts2, Depth+1);
1463       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1464
1465       // If only the low elt is demanded and this is a scalarizable intrinsic,
1466       // scalarize it now.
1467       if (DemandedElts == 1) {
1468         switch (II->getIntrinsicID()) {
1469         default: break;
1470         case Intrinsic::x86_sse_sub_ss:
1471         case Intrinsic::x86_sse_mul_ss:
1472         case Intrinsic::x86_sse2_sub_sd:
1473         case Intrinsic::x86_sse2_mul_sd:
1474           // TODO: Lower MIN/MAX/ABS/etc
1475           Value *LHS = II->getOperand(1);
1476           Value *RHS = II->getOperand(2);
1477           // Extract the element as scalars.
1478           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1479           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1480           
1481           switch (II->getIntrinsicID()) {
1482           default: assert(0 && "Case stmts out of sync!");
1483           case Intrinsic::x86_sse_sub_ss:
1484           case Intrinsic::x86_sse2_sub_sd:
1485             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1486                                                         II->getName()), *II);
1487             break;
1488           case Intrinsic::x86_sse_mul_ss:
1489           case Intrinsic::x86_sse2_mul_sd:
1490             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1491                                                          II->getName()), *II);
1492             break;
1493           }
1494           
1495           Instruction *New =
1496             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1497                                   II->getName());
1498           InsertNewInstBefore(New, *II);
1499           AddSoonDeadInstToWorklist(*II, 0);
1500           return New;
1501         }            
1502       }
1503         
1504       // Output elements are undefined if both are undefined.  Consider things
1505       // like undef&0.  The result is known zero, not undef.
1506       UndefElts &= UndefElts2;
1507       break;
1508     }
1509     break;
1510   }
1511   }
1512   return MadeChange ? I : 0;
1513 }
1514
1515 /// @returns true if the specified compare instruction is
1516 /// true when both operands are equal...
1517 /// @brief Determine if the ICmpInst returns true if both operands are equal
1518 static bool isTrueWhenEqual(ICmpInst &ICI) {
1519   ICmpInst::Predicate pred = ICI.getPredicate();
1520   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1521          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1522          pred == ICmpInst::ICMP_SLE;
1523 }
1524
1525 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1526 /// function is designed to check a chain of associative operators for a
1527 /// potential to apply a certain optimization.  Since the optimization may be
1528 /// applicable if the expression was reassociated, this checks the chain, then
1529 /// reassociates the expression as necessary to expose the optimization
1530 /// opportunity.  This makes use of a special Functor, which must define
1531 /// 'shouldApply' and 'apply' methods.
1532 ///
1533 template<typename Functor>
1534 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1535   unsigned Opcode = Root.getOpcode();
1536   Value *LHS = Root.getOperand(0);
1537
1538   // Quick check, see if the immediate LHS matches...
1539   if (F.shouldApply(LHS))
1540     return F.apply(Root);
1541
1542   // Otherwise, if the LHS is not of the same opcode as the root, return.
1543   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1544   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1545     // Should we apply this transform to the RHS?
1546     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1547
1548     // If not to the RHS, check to see if we should apply to the LHS...
1549     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1550       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1551       ShouldApply = true;
1552     }
1553
1554     // If the functor wants to apply the optimization to the RHS of LHSI,
1555     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1556     if (ShouldApply) {
1557       BasicBlock *BB = Root.getParent();
1558
1559       // Now all of the instructions are in the current basic block, go ahead
1560       // and perform the reassociation.
1561       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1562
1563       // First move the selected RHS to the LHS of the root...
1564       Root.setOperand(0, LHSI->getOperand(1));
1565
1566       // Make what used to be the LHS of the root be the user of the root...
1567       Value *ExtraOperand = TmpLHSI->getOperand(1);
1568       if (&Root == TmpLHSI) {
1569         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1570         return 0;
1571       }
1572       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1573       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1574       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1575       BasicBlock::iterator ARI = &Root; ++ARI;
1576       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1577       ARI = Root;
1578
1579       // Now propagate the ExtraOperand down the chain of instructions until we
1580       // get to LHSI.
1581       while (TmpLHSI != LHSI) {
1582         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1583         // Move the instruction to immediately before the chain we are
1584         // constructing to avoid breaking dominance properties.
1585         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1586         BB->getInstList().insert(ARI, NextLHSI);
1587         ARI = NextLHSI;
1588
1589         Value *NextOp = NextLHSI->getOperand(1);
1590         NextLHSI->setOperand(1, ExtraOperand);
1591         TmpLHSI = NextLHSI;
1592         ExtraOperand = NextOp;
1593       }
1594
1595       // Now that the instructions are reassociated, have the functor perform
1596       // the transformation...
1597       return F.apply(Root);
1598     }
1599
1600     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1601   }
1602   return 0;
1603 }
1604
1605
1606 // AddRHS - Implements: X + X --> X << 1
1607 struct AddRHS {
1608   Value *RHS;
1609   AddRHS(Value *rhs) : RHS(rhs) {}
1610   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1611   Instruction *apply(BinaryOperator &Add) const {
1612     return BinaryOperator::createShl(Add.getOperand(0),
1613                                   ConstantInt::get(Add.getType(), 1));
1614   }
1615 };
1616
1617 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1618 //                 iff C1&C2 == 0
1619 struct AddMaskingAnd {
1620   Constant *C2;
1621   AddMaskingAnd(Constant *c) : C2(c) {}
1622   bool shouldApply(Value *LHS) const {
1623     ConstantInt *C1;
1624     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1625            ConstantExpr::getAnd(C1, C2)->isNullValue();
1626   }
1627   Instruction *apply(BinaryOperator &Add) const {
1628     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1629   }
1630 };
1631
1632 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1633                                              InstCombiner *IC) {
1634   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1635     if (Constant *SOC = dyn_cast<Constant>(SO))
1636       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1637
1638     return IC->InsertNewInstBefore(CastInst::create(
1639           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1640   }
1641
1642   // Figure out if the constant is the left or the right argument.
1643   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1644   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1645
1646   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1647     if (ConstIsRHS)
1648       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1649     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1650   }
1651
1652   Value *Op0 = SO, *Op1 = ConstOperand;
1653   if (!ConstIsRHS)
1654     std::swap(Op0, Op1);
1655   Instruction *New;
1656   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1657     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1658   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1659     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1660                           SO->getName()+".cmp");
1661   else {
1662     assert(0 && "Unknown binary instruction type!");
1663     abort();
1664   }
1665   return IC->InsertNewInstBefore(New, I);
1666 }
1667
1668 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1669 // constant as the other operand, try to fold the binary operator into the
1670 // select arguments.  This also works for Cast instructions, which obviously do
1671 // not have a second operand.
1672 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1673                                      InstCombiner *IC) {
1674   // Don't modify shared select instructions
1675   if (!SI->hasOneUse()) return 0;
1676   Value *TV = SI->getOperand(1);
1677   Value *FV = SI->getOperand(2);
1678
1679   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1680     // Bool selects with constant operands can be folded to logical ops.
1681     if (SI->getType() == Type::Int1Ty) return 0;
1682
1683     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1684     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1685
1686     return new SelectInst(SI->getCondition(), SelectTrueVal,
1687                           SelectFalseVal);
1688   }
1689   return 0;
1690 }
1691
1692
1693 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1694 /// node as operand #0, see if we can fold the instruction into the PHI (which
1695 /// is only possible if all operands to the PHI are constants).
1696 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1697   PHINode *PN = cast<PHINode>(I.getOperand(0));
1698   unsigned NumPHIValues = PN->getNumIncomingValues();
1699   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1700
1701   // Check to see if all of the operands of the PHI are constants.  If there is
1702   // one non-constant value, remember the BB it is.  If there is more than one
1703   // or if *it* is a PHI, bail out.
1704   BasicBlock *NonConstBB = 0;
1705   for (unsigned i = 0; i != NumPHIValues; ++i)
1706     if (!isa<Constant>(PN->getIncomingValue(i))) {
1707       if (NonConstBB) return 0;  // More than one non-const value.
1708       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1709       NonConstBB = PN->getIncomingBlock(i);
1710       
1711       // If the incoming non-constant value is in I's block, we have an infinite
1712       // loop.
1713       if (NonConstBB == I.getParent())
1714         return 0;
1715     }
1716   
1717   // If there is exactly one non-constant value, we can insert a copy of the
1718   // operation in that block.  However, if this is a critical edge, we would be
1719   // inserting the computation one some other paths (e.g. inside a loop).  Only
1720   // do this if the pred block is unconditionally branching into the phi block.
1721   if (NonConstBB) {
1722     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1723     if (!BI || !BI->isUnconditional()) return 0;
1724   }
1725
1726   // Okay, we can do the transformation: create the new PHI node.
1727   PHINode *NewPN = new PHINode(I.getType(), "");
1728   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1729   InsertNewInstBefore(NewPN, *PN);
1730   NewPN->takeName(PN);
1731
1732   // Next, add all of the operands to the PHI.
1733   if (I.getNumOperands() == 2) {
1734     Constant *C = cast<Constant>(I.getOperand(1));
1735     for (unsigned i = 0; i != NumPHIValues; ++i) {
1736       Value *InV;
1737       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1738         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1739           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1740         else
1741           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1742       } else {
1743         assert(PN->getIncomingBlock(i) == NonConstBB);
1744         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1745           InV = BinaryOperator::create(BO->getOpcode(),
1746                                        PN->getIncomingValue(i), C, "phitmp",
1747                                        NonConstBB->getTerminator());
1748         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1749           InV = CmpInst::create(CI->getOpcode(), 
1750                                 CI->getPredicate(),
1751                                 PN->getIncomingValue(i), C, "phitmp",
1752                                 NonConstBB->getTerminator());
1753         else
1754           assert(0 && "Unknown binop!");
1755         
1756         AddToWorkList(cast<Instruction>(InV));
1757       }
1758       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1759     }
1760   } else { 
1761     CastInst *CI = cast<CastInst>(&I);
1762     const Type *RetTy = CI->getType();
1763     for (unsigned i = 0; i != NumPHIValues; ++i) {
1764       Value *InV;
1765       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1766         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1767       } else {
1768         assert(PN->getIncomingBlock(i) == NonConstBB);
1769         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1770                                I.getType(), "phitmp", 
1771                                NonConstBB->getTerminator());
1772         AddToWorkList(cast<Instruction>(InV));
1773       }
1774       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1775     }
1776   }
1777   return ReplaceInstUsesWith(I, NewPN);
1778 }
1779
1780 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1781   bool Changed = SimplifyCommutative(I);
1782   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1783
1784   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1785     // X + undef -> undef
1786     if (isa<UndefValue>(RHS))
1787       return ReplaceInstUsesWith(I, RHS);
1788
1789     // X + 0 --> X
1790     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1791       if (RHSC->isNullValue())
1792         return ReplaceInstUsesWith(I, LHS);
1793     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1794       if (CFP->isExactlyValue(-0.0))
1795         return ReplaceInstUsesWith(I, LHS);
1796     }
1797
1798     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1799       // X + (signbit) --> X ^ signbit
1800       uint64_t Val = CI->getZExtValue();
1801       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1802         return BinaryOperator::createXor(LHS, RHS);
1803       
1804       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1805       // (X & 254)+1 -> (X&254)|1
1806       uint64_t KnownZero, KnownOne;
1807       if (!isa<VectorType>(I.getType()) &&
1808           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
1809                                KnownZero, KnownOne))
1810         return &I;
1811     }
1812
1813     if (isa<PHINode>(LHS))
1814       if (Instruction *NV = FoldOpIntoPhi(I))
1815         return NV;
1816     
1817     ConstantInt *XorRHS = 0;
1818     Value *XorLHS = 0;
1819     if (isa<ConstantInt>(RHSC) &&
1820         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1821       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1822       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1823       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1824       
1825       uint64_t C0080Val = 1ULL << 31;
1826       int64_t CFF80Val = -C0080Val;
1827       unsigned Size = 32;
1828       do {
1829         if (TySizeBits > Size) {
1830           bool Found = false;
1831           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1832           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1833           if (RHSSExt == CFF80Val) {
1834             if (XorRHS->getZExtValue() == C0080Val)
1835               Found = true;
1836           } else if (RHSZExt == C0080Val) {
1837             if (XorRHS->getSExtValue() == CFF80Val)
1838               Found = true;
1839           }
1840           if (Found) {
1841             // This is a sign extend if the top bits are known zero.
1842             uint64_t Mask = ~0ULL;
1843             Mask <<= 64-(TySizeBits-Size);
1844             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
1845             if (!MaskedValueIsZero(XorLHS, Mask))
1846               Size = 0;  // Not a sign ext, but can't be any others either.
1847             goto FoundSExt;
1848           }
1849         }
1850         Size >>= 1;
1851         C0080Val >>= Size;
1852         CFF80Val >>= Size;
1853       } while (Size >= 8);
1854       
1855 FoundSExt:
1856       const Type *MiddleType = 0;
1857       switch (Size) {
1858       default: break;
1859       case 32: MiddleType = Type::Int32Ty; break;
1860       case 16: MiddleType = Type::Int16Ty; break;
1861       case 8:  MiddleType = Type::Int8Ty; break;
1862       }
1863       if (MiddleType) {
1864         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1865         InsertNewInstBefore(NewTrunc, I);
1866         return new SExtInst(NewTrunc, I.getType());
1867       }
1868     }
1869   }
1870
1871   // X + X --> X << 1
1872   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1873     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1874
1875     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1876       if (RHSI->getOpcode() == Instruction::Sub)
1877         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1878           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1879     }
1880     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1881       if (LHSI->getOpcode() == Instruction::Sub)
1882         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1883           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1884     }
1885   }
1886
1887   // -A + B  -->  B - A
1888   if (Value *V = dyn_castNegVal(LHS))
1889     return BinaryOperator::createSub(RHS, V);
1890
1891   // A + -B  -->  A - B
1892   if (!isa<Constant>(RHS))
1893     if (Value *V = dyn_castNegVal(RHS))
1894       return BinaryOperator::createSub(LHS, V);
1895
1896
1897   ConstantInt *C2;
1898   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1899     if (X == RHS)   // X*C + X --> X * (C+1)
1900       return BinaryOperator::createMul(RHS, AddOne(C2));
1901
1902     // X*C1 + X*C2 --> X * (C1+C2)
1903     ConstantInt *C1;
1904     if (X == dyn_castFoldableMul(RHS, C1))
1905       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1906   }
1907
1908   // X + X*C --> X * (C+1)
1909   if (dyn_castFoldableMul(RHS, C2) == LHS)
1910     return BinaryOperator::createMul(LHS, AddOne(C2));
1911
1912   // X + ~X --> -1   since   ~X = -X-1
1913   if (dyn_castNotVal(LHS) == RHS ||
1914       dyn_castNotVal(RHS) == LHS)
1915     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1916   
1917
1918   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1919   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1920     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1921       return R;
1922
1923   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1924     Value *X = 0;
1925     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1926       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1927       return BinaryOperator::createSub(C, X);
1928     }
1929
1930     // (X & FF00) + xx00  -> (X+xx00) & FF00
1931     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1932       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1933       if (Anded == CRHS) {
1934         // See if all bits from the first bit set in the Add RHS up are included
1935         // in the mask.  First, get the rightmost bit.
1936         uint64_t AddRHSV = CRHS->getZExtValue();
1937
1938         // Form a mask of all bits from the lowest bit added through the top.
1939         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1940         AddRHSHighBits &= C2->getType()->getBitMask();
1941
1942         // See if the and mask includes all of these bits.
1943         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1944
1945         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1946           // Okay, the xform is safe.  Insert the new add pronto.
1947           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1948                                                             LHS->getName()), I);
1949           return BinaryOperator::createAnd(NewAdd, C2);
1950         }
1951       }
1952     }
1953
1954     // Try to fold constant add into select arguments.
1955     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1956       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1957         return R;
1958   }
1959
1960   // add (cast *A to intptrtype) B -> 
1961   //   cast (GEP (cast *A to sbyte*) B) -> 
1962   //     intptrtype
1963   {
1964     CastInst *CI = dyn_cast<CastInst>(LHS);
1965     Value *Other = RHS;
1966     if (!CI) {
1967       CI = dyn_cast<CastInst>(RHS);
1968       Other = LHS;
1969     }
1970     if (CI && CI->getType()->isSized() && 
1971         (CI->getType()->getPrimitiveSizeInBits() == 
1972          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1973         && isa<PointerType>(CI->getOperand(0)->getType())) {
1974       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1975                                    PointerType::get(Type::Int8Ty), I);
1976       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1977       return new PtrToIntInst(I2, CI->getType());
1978     }
1979   }
1980
1981   return Changed ? &I : 0;
1982 }
1983
1984 // isSignBit - Return true if the value represented by the constant only has the
1985 // highest order bit set.
1986 static bool isSignBit(ConstantInt *CI) {
1987   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1988   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1989 }
1990
1991 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1992   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1993
1994   if (Op0 == Op1)         // sub X, X  -> 0
1995     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1996
1997   // If this is a 'B = x-(-A)', change to B = x+A...
1998   if (Value *V = dyn_castNegVal(Op1))
1999     return BinaryOperator::createAdd(Op0, V);
2000
2001   if (isa<UndefValue>(Op0))
2002     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2003   if (isa<UndefValue>(Op1))
2004     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2005
2006   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2007     // Replace (-1 - A) with (~A)...
2008     if (C->isAllOnesValue())
2009       return BinaryOperator::createNot(Op1);
2010
2011     // C - ~X == X + (1+C)
2012     Value *X = 0;
2013     if (match(Op1, m_Not(m_Value(X))))
2014       return BinaryOperator::createAdd(X,
2015                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
2016     // -(X >>u 31) -> (X >>s 31)
2017     // -(X >>s 31) -> (X >>u 31)
2018     if (C->isNullValue()) {
2019       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2020         if (SI->getOpcode() == Instruction::LShr) {
2021           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2022             // Check to see if we are shifting out everything but the sign bit.
2023             if (CU->getZExtValue() == 
2024                 SI->getType()->getPrimitiveSizeInBits()-1) {
2025               // Ok, the transformation is safe.  Insert AShr.
2026               return BinaryOperator::create(Instruction::AShr, 
2027                                           SI->getOperand(0), CU, SI->getName());
2028             }
2029           }
2030         }
2031         else if (SI->getOpcode() == Instruction::AShr) {
2032           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2033             // Check to see if we are shifting out everything but the sign bit.
2034             if (CU->getZExtValue() == 
2035                 SI->getType()->getPrimitiveSizeInBits()-1) {
2036               // Ok, the transformation is safe.  Insert LShr. 
2037               return BinaryOperator::createLShr(
2038                                           SI->getOperand(0), CU, SI->getName());
2039             }
2040           }
2041         } 
2042     }
2043
2044     // Try to fold constant sub into select arguments.
2045     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2046       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2047         return R;
2048
2049     if (isa<PHINode>(Op0))
2050       if (Instruction *NV = FoldOpIntoPhi(I))
2051         return NV;
2052   }
2053
2054   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2055     if (Op1I->getOpcode() == Instruction::Add &&
2056         !Op0->getType()->isFPOrFPVector()) {
2057       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2058         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2059       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2060         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2061       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2062         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2063           // C1-(X+C2) --> (C1-C2)-X
2064           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2065                                            Op1I->getOperand(0));
2066       }
2067     }
2068
2069     if (Op1I->hasOneUse()) {
2070       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2071       // is not used by anyone else...
2072       //
2073       if (Op1I->getOpcode() == Instruction::Sub &&
2074           !Op1I->getType()->isFPOrFPVector()) {
2075         // Swap the two operands of the subexpr...
2076         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2077         Op1I->setOperand(0, IIOp1);
2078         Op1I->setOperand(1, IIOp0);
2079
2080         // Create the new top level add instruction...
2081         return BinaryOperator::createAdd(Op0, Op1);
2082       }
2083
2084       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2085       //
2086       if (Op1I->getOpcode() == Instruction::And &&
2087           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2088         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2089
2090         Value *NewNot =
2091           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2092         return BinaryOperator::createAnd(Op0, NewNot);
2093       }
2094
2095       // 0 - (X sdiv C)  -> (X sdiv -C)
2096       if (Op1I->getOpcode() == Instruction::SDiv)
2097         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2098           if (CSI->isNullValue())
2099             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2100               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2101                                                ConstantExpr::getNeg(DivRHS));
2102
2103       // X - X*C --> X * (1-C)
2104       ConstantInt *C2 = 0;
2105       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2106         Constant *CP1 =
2107           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2108         return BinaryOperator::createMul(Op0, CP1);
2109       }
2110     }
2111   }
2112
2113   if (!Op0->getType()->isFPOrFPVector())
2114     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2115       if (Op0I->getOpcode() == Instruction::Add) {
2116         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2117           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2118         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2119           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2120       } else if (Op0I->getOpcode() == Instruction::Sub) {
2121         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2122           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2123       }
2124
2125   ConstantInt *C1;
2126   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2127     if (X == Op1) { // X*C - X --> X * (C-1)
2128       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2129       return BinaryOperator::createMul(Op1, CP1);
2130     }
2131
2132     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2133     if (X == dyn_castFoldableMul(Op1, C2))
2134       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2135   }
2136   return 0;
2137 }
2138
2139 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2140 /// really just returns true if the most significant (sign) bit is set.
2141 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2142   switch (pred) {
2143     case ICmpInst::ICMP_SLT: 
2144       // True if LHS s< RHS and RHS == 0
2145       return RHS->isNullValue();
2146     case ICmpInst::ICMP_SLE: 
2147       // True if LHS s<= RHS and RHS == -1
2148       return RHS->isAllOnesValue();
2149     case ICmpInst::ICMP_UGE: 
2150       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2151       return RHS->getZExtValue() == (1ULL << 
2152         (RHS->getType()->getPrimitiveSizeInBits()-1));
2153     case ICmpInst::ICMP_UGT:
2154       // True if LHS u> RHS and RHS == high-bit-mask - 1
2155       return RHS->getZExtValue() ==
2156         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2157     default:
2158       return false;
2159   }
2160 }
2161
2162 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2163   bool Changed = SimplifyCommutative(I);
2164   Value *Op0 = I.getOperand(0);
2165
2166   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2167     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2168
2169   // Simplify mul instructions with a constant RHS...
2170   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2171     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2172
2173       // ((X << C1)*C2) == (X * (C2 << C1))
2174       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2175         if (SI->getOpcode() == Instruction::Shl)
2176           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2177             return BinaryOperator::createMul(SI->getOperand(0),
2178                                              ConstantExpr::getShl(CI, ShOp));
2179
2180       if (CI->isNullValue())
2181         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2182       if (CI->equalsInt(1))                  // X * 1  == X
2183         return ReplaceInstUsesWith(I, Op0);
2184       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2185         return BinaryOperator::createNeg(Op0, I.getName());
2186
2187       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2188       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2189         uint64_t C = Log2_64(Val);
2190         return BinaryOperator::createShl(Op0,
2191                                       ConstantInt::get(Op0->getType(), C));
2192       }
2193     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2194       if (Op1F->isNullValue())
2195         return ReplaceInstUsesWith(I, Op1);
2196
2197       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2198       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2199       if (Op1F->getValue() == 1.0)
2200         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2201     }
2202     
2203     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2204       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2205           isa<ConstantInt>(Op0I->getOperand(1))) {
2206         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2207         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2208                                                      Op1, "tmp");
2209         InsertNewInstBefore(Add, I);
2210         Value *C1C2 = ConstantExpr::getMul(Op1, 
2211                                            cast<Constant>(Op0I->getOperand(1)));
2212         return BinaryOperator::createAdd(Add, C1C2);
2213         
2214       }
2215
2216     // Try to fold constant mul into select arguments.
2217     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2218       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2219         return R;
2220
2221     if (isa<PHINode>(Op0))
2222       if (Instruction *NV = FoldOpIntoPhi(I))
2223         return NV;
2224   }
2225
2226   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2227     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2228       return BinaryOperator::createMul(Op0v, Op1v);
2229
2230   // If one of the operands of the multiply is a cast from a boolean value, then
2231   // we know the bool is either zero or one, so this is a 'masking' multiply.
2232   // See if we can simplify things based on how the boolean was originally
2233   // formed.
2234   CastInst *BoolCast = 0;
2235   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2236     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2237       BoolCast = CI;
2238   if (!BoolCast)
2239     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2240       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2241         BoolCast = CI;
2242   if (BoolCast) {
2243     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2244       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2245       const Type *SCOpTy = SCIOp0->getType();
2246
2247       // If the icmp is true iff the sign bit of X is set, then convert this
2248       // multiply into a shift/and combination.
2249       if (isa<ConstantInt>(SCIOp1) &&
2250           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2251         // Shift the X value right to turn it into "all signbits".
2252         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2253                                           SCOpTy->getPrimitiveSizeInBits()-1);
2254         Value *V =
2255           InsertNewInstBefore(
2256             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2257                                             BoolCast->getOperand(0)->getName()+
2258                                             ".mask"), I);
2259
2260         // If the multiply type is not the same as the source type, sign extend
2261         // or truncate to the multiply type.
2262         if (I.getType() != V->getType()) {
2263           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2264           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2265           Instruction::CastOps opcode = 
2266             (SrcBits == DstBits ? Instruction::BitCast : 
2267              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2268           V = InsertCastBefore(opcode, V, I.getType(), I);
2269         }
2270
2271         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2272         return BinaryOperator::createAnd(V, OtherOp);
2273       }
2274     }
2275   }
2276
2277   return Changed ? &I : 0;
2278 }
2279
2280 /// This function implements the transforms on div instructions that work
2281 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2282 /// used by the visitors to those instructions.
2283 /// @brief Transforms common to all three div instructions
2284 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2285   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2286
2287   // undef / X -> 0
2288   if (isa<UndefValue>(Op0))
2289     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2290
2291   // X / undef -> undef
2292   if (isa<UndefValue>(Op1))
2293     return ReplaceInstUsesWith(I, Op1);
2294
2295   // Handle cases involving: div X, (select Cond, Y, Z)
2296   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2297     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2298     // same basic block, then we replace the select with Y, and the condition 
2299     // of the select with false (if the cond value is in the same BB).  If the
2300     // select has uses other than the div, this allows them to be simplified
2301     // also. Note that div X, Y is just as good as div X, 0 (undef)
2302     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2303       if (ST->isNullValue()) {
2304         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2305         if (CondI && CondI->getParent() == I.getParent())
2306           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2307         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2308           I.setOperand(1, SI->getOperand(2));
2309         else
2310           UpdateValueUsesWith(SI, SI->getOperand(2));
2311         return &I;
2312       }
2313
2314     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2315     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2316       if (ST->isNullValue()) {
2317         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2318         if (CondI && CondI->getParent() == I.getParent())
2319           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2320         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2321           I.setOperand(1, SI->getOperand(1));
2322         else
2323           UpdateValueUsesWith(SI, SI->getOperand(1));
2324         return &I;
2325       }
2326   }
2327
2328   return 0;
2329 }
2330
2331 /// This function implements the transforms common to both integer division
2332 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2333 /// division instructions.
2334 /// @brief Common integer divide transforms
2335 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2336   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2337
2338   if (Instruction *Common = commonDivTransforms(I))
2339     return Common;
2340
2341   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2342     // div X, 1 == X
2343     if (RHS->equalsInt(1))
2344       return ReplaceInstUsesWith(I, Op0);
2345
2346     // (X / C1) / C2  -> X / (C1*C2)
2347     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2348       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2349         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2350           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2351                                         ConstantExpr::getMul(RHS, LHSRHS));
2352         }
2353
2354     if (!RHS->isNullValue()) { // avoid X udiv 0
2355       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2356         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2357           return R;
2358       if (isa<PHINode>(Op0))
2359         if (Instruction *NV = FoldOpIntoPhi(I))
2360           return NV;
2361     }
2362   }
2363
2364   // 0 / X == 0, we don't need to preserve faults!
2365   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2366     if (LHS->equalsInt(0))
2367       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2368
2369   return 0;
2370 }
2371
2372 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2373   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2374
2375   // Handle the integer div common cases
2376   if (Instruction *Common = commonIDivTransforms(I))
2377     return Common;
2378
2379   // X udiv C^2 -> X >> C
2380   // Check to see if this is an unsigned division with an exact power of 2,
2381   // if so, convert to a right shift.
2382   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2383     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2384       if (isPowerOf2_64(Val)) {
2385         uint64_t ShiftAmt = Log2_64(Val);
2386         return BinaryOperator::createLShr(Op0, 
2387                                     ConstantInt::get(Op0->getType(), ShiftAmt));
2388       }
2389   }
2390
2391   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2392   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2393     if (RHSI->getOpcode() == Instruction::Shl &&
2394         isa<ConstantInt>(RHSI->getOperand(0))) {
2395       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2396       if (isPowerOf2_64(C1)) {
2397         Value *N = RHSI->getOperand(1);
2398         const Type *NTy = N->getType();
2399         if (uint64_t C2 = Log2_64(C1)) {
2400           Constant *C2V = ConstantInt::get(NTy, C2);
2401           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2402         }
2403         return BinaryOperator::createLShr(Op0, N);
2404       }
2405     }
2406   }
2407   
2408   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2409   // where C1&C2 are powers of two.
2410   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2411     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2412       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2413         if (!STO->isNullValue() && !STO->isNullValue()) {
2414           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2415           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2416             // Compute the shift amounts
2417             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2418             // Construct the "on true" case of the select
2419             Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2420             Instruction *TSI = BinaryOperator::createLShr(
2421                                                    Op0, TC, SI->getName()+".t");
2422             TSI = InsertNewInstBefore(TSI, I);
2423     
2424             // Construct the "on false" case of the select
2425             Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2426             Instruction *FSI = BinaryOperator::createLShr(
2427                                                    Op0, FC, SI->getName()+".f");
2428             FSI = InsertNewInstBefore(FSI, I);
2429
2430             // construct the select instruction and return it.
2431             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2432           }
2433         }
2434   }
2435   return 0;
2436 }
2437
2438 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2439   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2440
2441   // Handle the integer div common cases
2442   if (Instruction *Common = commonIDivTransforms(I))
2443     return Common;
2444
2445   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2446     // sdiv X, -1 == -X
2447     if (RHS->isAllOnesValue())
2448       return BinaryOperator::createNeg(Op0);
2449
2450     // -X/C -> X/-C
2451     if (Value *LHSNeg = dyn_castNegVal(Op0))
2452       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2453   }
2454
2455   // If the sign bits of both operands are zero (i.e. we can prove they are
2456   // unsigned inputs), turn this into a udiv.
2457   if (I.getType()->isInteger()) {
2458     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2459     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2460       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2461     }
2462   }      
2463   
2464   return 0;
2465 }
2466
2467 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2468   return commonDivTransforms(I);
2469 }
2470
2471 /// GetFactor - If we can prove that the specified value is at least a multiple
2472 /// of some factor, return that factor.
2473 static Constant *GetFactor(Value *V) {
2474   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2475     return CI;
2476   
2477   // Unless we can be tricky, we know this is a multiple of 1.
2478   Constant *Result = ConstantInt::get(V->getType(), 1);
2479   
2480   Instruction *I = dyn_cast<Instruction>(V);
2481   if (!I) return Result;
2482   
2483   if (I->getOpcode() == Instruction::Mul) {
2484     // Handle multiplies by a constant, etc.
2485     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2486                                 GetFactor(I->getOperand(1)));
2487   } else if (I->getOpcode() == Instruction::Shl) {
2488     // (X<<C) -> X * (1 << C)
2489     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2490       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2491       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2492     }
2493   } else if (I->getOpcode() == Instruction::And) {
2494     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2495       // X & 0xFFF0 is known to be a multiple of 16.
2496       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2497       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2498         return ConstantExpr::getShl(Result, 
2499                                     ConstantInt::get(Result->getType(), Zeros));
2500     }
2501   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2502     // Only handle int->int casts.
2503     if (!CI->isIntegerCast())
2504       return Result;
2505     Value *Op = CI->getOperand(0);
2506     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2507   }    
2508   return Result;
2509 }
2510
2511 /// This function implements the transforms on rem instructions that work
2512 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2513 /// is used by the visitors to those instructions.
2514 /// @brief Transforms common to all three rem instructions
2515 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2516   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2517
2518   // 0 % X == 0, we don't need to preserve faults!
2519   if (Constant *LHS = dyn_cast<Constant>(Op0))
2520     if (LHS->isNullValue())
2521       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2522
2523   if (isa<UndefValue>(Op0))              // undef % X -> 0
2524     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2525   if (isa<UndefValue>(Op1))
2526     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2527
2528   // Handle cases involving: rem X, (select Cond, Y, Z)
2529   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2530     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2531     // the same basic block, then we replace the select with Y, and the
2532     // condition of the select with false (if the cond value is in the same
2533     // BB).  If the select has uses other than the div, this allows them to be
2534     // simplified also.
2535     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2536       if (ST->isNullValue()) {
2537         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2538         if (CondI && CondI->getParent() == I.getParent())
2539           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2540         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2541           I.setOperand(1, SI->getOperand(2));
2542         else
2543           UpdateValueUsesWith(SI, SI->getOperand(2));
2544         return &I;
2545       }
2546     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2547     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2548       if (ST->isNullValue()) {
2549         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2550         if (CondI && CondI->getParent() == I.getParent())
2551           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2552         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2553           I.setOperand(1, SI->getOperand(1));
2554         else
2555           UpdateValueUsesWith(SI, SI->getOperand(1));
2556         return &I;
2557       }
2558   }
2559
2560   return 0;
2561 }
2562
2563 /// This function implements the transforms common to both integer remainder
2564 /// instructions (urem and srem). It is called by the visitors to those integer
2565 /// remainder instructions.
2566 /// @brief Common integer remainder transforms
2567 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2568   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2569
2570   if (Instruction *common = commonRemTransforms(I))
2571     return common;
2572
2573   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574     // X % 0 == undef, we don't need to preserve faults!
2575     if (RHS->equalsInt(0))
2576       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2577     
2578     if (RHS->equalsInt(1))  // X % 1 == 0
2579       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2580
2581     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2582       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2583         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2584           return R;
2585       } else if (isa<PHINode>(Op0I)) {
2586         if (Instruction *NV = FoldOpIntoPhi(I))
2587           return NV;
2588       }
2589       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2590       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2591         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2592     }
2593   }
2594
2595   return 0;
2596 }
2597
2598 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2599   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2600
2601   if (Instruction *common = commonIRemTransforms(I))
2602     return common;
2603   
2604   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2605     // X urem C^2 -> X and C
2606     // Check to see if this is an unsigned remainder with an exact power of 2,
2607     // if so, convert to a bitwise and.
2608     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2609       if (isPowerOf2_64(C->getZExtValue()))
2610         return BinaryOperator::createAnd(Op0, SubOne(C));
2611   }
2612
2613   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2614     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2615     if (RHSI->getOpcode() == Instruction::Shl &&
2616         isa<ConstantInt>(RHSI->getOperand(0))) {
2617       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2618       if (isPowerOf2_64(C1)) {
2619         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2620         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2621                                                                    "tmp"), I);
2622         return BinaryOperator::createAnd(Op0, Add);
2623       }
2624     }
2625   }
2626
2627   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2628   // where C1&C2 are powers of two.
2629   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2630     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2631       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2632         // STO == 0 and SFO == 0 handled above.
2633         if (isPowerOf2_64(STO->getZExtValue()) && 
2634             isPowerOf2_64(SFO->getZExtValue())) {
2635           Value *TrueAnd = InsertNewInstBefore(
2636             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2637           Value *FalseAnd = InsertNewInstBefore(
2638             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2639           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2640         }
2641       }
2642   }
2643   
2644   return 0;
2645 }
2646
2647 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2648   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650   if (Instruction *common = commonIRemTransforms(I))
2651     return common;
2652   
2653   if (Value *RHSNeg = dyn_castNegVal(Op1))
2654     if (!isa<ConstantInt>(RHSNeg) || 
2655         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2656       // X % -Y -> X % Y
2657       AddUsesToWorkList(I);
2658       I.setOperand(1, RHSNeg);
2659       return &I;
2660     }
2661  
2662   // If the top bits of both operands are zero (i.e. we can prove they are
2663   // unsigned inputs), turn this into a urem.
2664   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2665   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2666     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2667     return BinaryOperator::createURem(Op0, Op1, I.getName());
2668   }
2669
2670   return 0;
2671 }
2672
2673 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2674   return commonRemTransforms(I);
2675 }
2676
2677 // isMaxValueMinusOne - return true if this is Max-1
2678 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2679   if (isSigned) {
2680     // Calculate 0111111111..11111
2681     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2682     int64_t Val = INT64_MAX;             // All ones
2683     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2684     return C->getSExtValue() == Val-1;
2685   }
2686   return C->getZExtValue() == C->getType()->getBitMask()-1;
2687 }
2688
2689 // isMinValuePlusOne - return true if this is Min+1
2690 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2691   if (isSigned) {
2692     // Calculate 1111111111000000000000
2693     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2694     int64_t Val = -1;                    // All ones
2695     Val <<= TypeBits-1;                  // Shift over to the right spot
2696     return C->getSExtValue() == Val+1;
2697   }
2698   return C->getZExtValue() == 1; // unsigned
2699 }
2700
2701 // isOneBitSet - Return true if there is exactly one bit set in the specified
2702 // constant.
2703 static bool isOneBitSet(const ConstantInt *CI) {
2704   uint64_t V = CI->getZExtValue();
2705   return V && (V & (V-1)) == 0;
2706 }
2707
2708 #if 0   // Currently unused
2709 // isLowOnes - Return true if the constant is of the form 0+1+.
2710 static bool isLowOnes(const ConstantInt *CI) {
2711   uint64_t V = CI->getZExtValue();
2712
2713   // There won't be bits set in parts that the type doesn't contain.
2714   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2715
2716   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2717   return U && V && (U & V) == 0;
2718 }
2719 #endif
2720
2721 // isHighOnes - Return true if the constant is of the form 1+0+.
2722 // This is the same as lowones(~X).
2723 static bool isHighOnes(const ConstantInt *CI) {
2724   uint64_t V = ~CI->getZExtValue();
2725   if (~V == 0) return false;  // 0's does not match "1+"
2726
2727   // There won't be bits set in parts that the type doesn't contain.
2728   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2729
2730   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2731   return U && V && (U & V) == 0;
2732 }
2733
2734 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2735 /// are carefully arranged to allow folding of expressions such as:
2736 ///
2737 ///      (A < B) | (A > B) --> (A != B)
2738 ///
2739 /// Note that this is only valid if the first and second predicates have the
2740 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2741 ///
2742 /// Three bits are used to represent the condition, as follows:
2743 ///   0  A > B
2744 ///   1  A == B
2745 ///   2  A < B
2746 ///
2747 /// <=>  Value  Definition
2748 /// 000     0   Always false
2749 /// 001     1   A >  B
2750 /// 010     2   A == B
2751 /// 011     3   A >= B
2752 /// 100     4   A <  B
2753 /// 101     5   A != B
2754 /// 110     6   A <= B
2755 /// 111     7   Always true
2756 ///  
2757 static unsigned getICmpCode(const ICmpInst *ICI) {
2758   switch (ICI->getPredicate()) {
2759     // False -> 0
2760   case ICmpInst::ICMP_UGT: return 1;  // 001
2761   case ICmpInst::ICMP_SGT: return 1;  // 001
2762   case ICmpInst::ICMP_EQ:  return 2;  // 010
2763   case ICmpInst::ICMP_UGE: return 3;  // 011
2764   case ICmpInst::ICMP_SGE: return 3;  // 011
2765   case ICmpInst::ICMP_ULT: return 4;  // 100
2766   case ICmpInst::ICMP_SLT: return 4;  // 100
2767   case ICmpInst::ICMP_NE:  return 5;  // 101
2768   case ICmpInst::ICMP_ULE: return 6;  // 110
2769   case ICmpInst::ICMP_SLE: return 6;  // 110
2770     // True -> 7
2771   default:
2772     assert(0 && "Invalid ICmp predicate!");
2773     return 0;
2774   }
2775 }
2776
2777 /// getICmpValue - This is the complement of getICmpCode, which turns an
2778 /// opcode and two operands into either a constant true or false, or a brand 
2779 /// new /// ICmp instruction. The sign is passed in to determine which kind
2780 /// of predicate to use in new icmp instructions.
2781 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2782   switch (code) {
2783   default: assert(0 && "Illegal ICmp code!");
2784   case  0: return ConstantInt::getFalse();
2785   case  1: 
2786     if (sign)
2787       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2788     else
2789       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2790   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2791   case  3: 
2792     if (sign)
2793       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2794     else
2795       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2796   case  4: 
2797     if (sign)
2798       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2799     else
2800       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2801   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2802   case  6: 
2803     if (sign)
2804       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2805     else
2806       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2807   case  7: return ConstantInt::getTrue();
2808   }
2809 }
2810
2811 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2812   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2813     (ICmpInst::isSignedPredicate(p1) && 
2814      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2815     (ICmpInst::isSignedPredicate(p2) && 
2816      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2817 }
2818
2819 namespace { 
2820 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2821 struct FoldICmpLogical {
2822   InstCombiner &IC;
2823   Value *LHS, *RHS;
2824   ICmpInst::Predicate pred;
2825   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2826     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2827       pred(ICI->getPredicate()) {}
2828   bool shouldApply(Value *V) const {
2829     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2830       if (PredicatesFoldable(pred, ICI->getPredicate()))
2831         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2832                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2833     return false;
2834   }
2835   Instruction *apply(Instruction &Log) const {
2836     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2837     if (ICI->getOperand(0) != LHS) {
2838       assert(ICI->getOperand(1) == LHS);
2839       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2840     }
2841
2842     unsigned LHSCode = getICmpCode(ICI);
2843     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2844     unsigned Code;
2845     switch (Log.getOpcode()) {
2846     case Instruction::And: Code = LHSCode & RHSCode; break;
2847     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2848     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2849     default: assert(0 && "Illegal logical opcode!"); return 0;
2850     }
2851
2852     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2853     if (Instruction *I = dyn_cast<Instruction>(RV))
2854       return I;
2855     // Otherwise, it's a constant boolean value...
2856     return IC.ReplaceInstUsesWith(Log, RV);
2857   }
2858 };
2859 } // end anonymous namespace
2860
2861 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2862 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2863 // guaranteed to be a binary operator.
2864 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2865                                     ConstantInt *OpRHS,
2866                                     ConstantInt *AndRHS,
2867                                     BinaryOperator &TheAnd) {
2868   Value *X = Op->getOperand(0);
2869   Constant *Together = 0;
2870   if (!Op->isShift())
2871     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2872
2873   switch (Op->getOpcode()) {
2874   case Instruction::Xor:
2875     if (Op->hasOneUse()) {
2876       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2877       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2878       InsertNewInstBefore(And, TheAnd);
2879       And->takeName(Op);
2880       return BinaryOperator::createXor(And, Together);
2881     }
2882     break;
2883   case Instruction::Or:
2884     if (Together == AndRHS) // (X | C) & C --> C
2885       return ReplaceInstUsesWith(TheAnd, AndRHS);
2886
2887     if (Op->hasOneUse() && Together != OpRHS) {
2888       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2889       Instruction *Or = BinaryOperator::createOr(X, Together);
2890       InsertNewInstBefore(Or, TheAnd);
2891       Or->takeName(Op);
2892       return BinaryOperator::createAnd(Or, AndRHS);
2893     }
2894     break;
2895   case Instruction::Add:
2896     if (Op->hasOneUse()) {
2897       // Adding a one to a single bit bit-field should be turned into an XOR
2898       // of the bit.  First thing to check is to see if this AND is with a
2899       // single bit constant.
2900       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2901
2902       // Clear bits that are not part of the constant.
2903       AndRHSV &= AndRHS->getType()->getBitMask();
2904
2905       // If there is only one bit set...
2906       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2907         // Ok, at this point, we know that we are masking the result of the
2908         // ADD down to exactly one bit.  If the constant we are adding has
2909         // no bits set below this bit, then we can eliminate the ADD.
2910         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2911
2912         // Check to see if any bits below the one bit set in AndRHSV are set.
2913         if ((AddRHS & (AndRHSV-1)) == 0) {
2914           // If not, the only thing that can effect the output of the AND is
2915           // the bit specified by AndRHSV.  If that bit is set, the effect of
2916           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2917           // no effect.
2918           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2919             TheAnd.setOperand(0, X);
2920             return &TheAnd;
2921           } else {
2922             // Pull the XOR out of the AND.
2923             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
2924             InsertNewInstBefore(NewAnd, TheAnd);
2925             NewAnd->takeName(Op);
2926             return BinaryOperator::createXor(NewAnd, AndRHS);
2927           }
2928         }
2929       }
2930     }
2931     break;
2932
2933   case Instruction::Shl: {
2934     // We know that the AND will not produce any of the bits shifted in, so if
2935     // the anded constant includes them, clear them now!
2936     //
2937     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2938     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2939     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2940
2941     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2942       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2943     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2944       TheAnd.setOperand(1, CI);
2945       return &TheAnd;
2946     }
2947     break;
2948   }
2949   case Instruction::LShr:
2950   {
2951     // We know that the AND will not produce any of the bits shifted in, so if
2952     // the anded constant includes them, clear them now!  This only applies to
2953     // unsigned shifts, because a signed shr may bring in set bits!
2954     //
2955     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2956     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2957     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2958
2959     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2960       return ReplaceInstUsesWith(TheAnd, Op);
2961     } else if (CI != AndRHS) {
2962       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2963       return &TheAnd;
2964     }
2965     break;
2966   }
2967   case Instruction::AShr:
2968     // Signed shr.
2969     // See if this is shifting in some sign extension, then masking it out
2970     // with an and.
2971     if (Op->hasOneUse()) {
2972       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2973       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2974       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2975       if (C == AndRHS) {          // Masking out bits shifted in.
2976         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2977         // Make the argument unsigned.
2978         Value *ShVal = Op->getOperand(0);
2979         ShVal = InsertNewInstBefore(
2980             BinaryOperator::createLShr(ShVal, OpRHS, 
2981                                    Op->getName()), TheAnd);
2982         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2983       }
2984     }
2985     break;
2986   }
2987   return 0;
2988 }
2989
2990
2991 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2992 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2993 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2994 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2995 /// insert new instructions.
2996 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2997                                            bool isSigned, bool Inside, 
2998                                            Instruction &IB) {
2999   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3000             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3001          "Lo is not <= Hi in range emission code!");
3002     
3003   if (Inside) {
3004     if (Lo == Hi)  // Trivially false.
3005       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3006
3007     // V >= Min && V < Hi --> V < Hi
3008     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3009     ICmpInst::Predicate pred = (isSigned ? 
3010         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3011       return new ICmpInst(pred, V, Hi);
3012     }
3013
3014     // Emit V-Lo <u Hi-Lo
3015     Constant *NegLo = ConstantExpr::getNeg(Lo);
3016     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3017     InsertNewInstBefore(Add, IB);
3018     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3019     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3020   }
3021
3022   if (Lo == Hi)  // Trivially true.
3023     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3024
3025   // V < Min || V >= Hi ->'V > Hi-1'
3026   Hi = SubOne(cast<ConstantInt>(Hi));
3027   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3028     ICmpInst::Predicate pred = (isSigned ? 
3029         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3030     return new ICmpInst(pred, V, Hi);
3031   }
3032
3033   // Emit V-Lo > Hi-1-Lo
3034   Constant *NegLo = ConstantExpr::getNeg(Lo);
3035   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3036   InsertNewInstBefore(Add, IB);
3037   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3038   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3039 }
3040
3041 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3042 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3043 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3044 // not, since all 1s are not contiguous.
3045 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3046   uint64_t V = Val->getZExtValue();
3047   if (!isShiftedMask_64(V)) return false;
3048
3049   // look for the first zero bit after the run of ones
3050   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3051   // look for the first non-zero bit
3052   ME = 64-CountLeadingZeros_64(V);
3053   return true;
3054 }
3055
3056
3057
3058 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3059 /// where isSub determines whether the operator is a sub.  If we can fold one of
3060 /// the following xforms:
3061 /// 
3062 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3063 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3064 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3065 ///
3066 /// return (A +/- B).
3067 ///
3068 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3069                                         ConstantInt *Mask, bool isSub,
3070                                         Instruction &I) {
3071   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3072   if (!LHSI || LHSI->getNumOperands() != 2 ||
3073       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3074
3075   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3076
3077   switch (LHSI->getOpcode()) {
3078   default: return 0;
3079   case Instruction::And:
3080     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3081       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3082       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3083         break;
3084
3085       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3086       // part, we don't need any explicit masks to take them out of A.  If that
3087       // is all N is, ignore it.
3088       unsigned MB, ME;
3089       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3090         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3091         Mask >>= 64-MB+1;
3092         if (MaskedValueIsZero(RHS, Mask))
3093           break;
3094       }
3095     }
3096     return 0;
3097   case Instruction::Or:
3098   case Instruction::Xor:
3099     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3100     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3101         ConstantExpr::getAnd(N, Mask)->isNullValue())
3102       break;
3103     return 0;
3104   }
3105   
3106   Instruction *New;
3107   if (isSub)
3108     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3109   else
3110     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3111   return InsertNewInstBefore(New, I);
3112 }
3113
3114 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3115   bool Changed = SimplifyCommutative(I);
3116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3119     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3120
3121   // and X, X = X
3122   if (Op0 == Op1)
3123     return ReplaceInstUsesWith(I, Op1);
3124
3125   // See if we can simplify any instructions used by the instruction whose sole 
3126   // purpose is to compute bits we don't care about.
3127   uint64_t KnownZero, KnownOne;
3128   if (!isa<VectorType>(I.getType())) {
3129     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3130                              KnownZero, KnownOne))
3131     return &I;
3132   } else {
3133     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3134       if (CP->isAllOnesValue())
3135         return ReplaceInstUsesWith(I, I.getOperand(0));
3136     }
3137   }
3138   
3139   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3140     uint64_t AndRHSMask = AndRHS->getZExtValue();
3141     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3142     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3143
3144     // Optimize a variety of ((val OP C1) & C2) combinations...
3145     if (isa<BinaryOperator>(Op0)) {
3146       Instruction *Op0I = cast<Instruction>(Op0);
3147       Value *Op0LHS = Op0I->getOperand(0);
3148       Value *Op0RHS = Op0I->getOperand(1);
3149       switch (Op0I->getOpcode()) {
3150       case Instruction::Xor:
3151       case Instruction::Or:
3152         // If the mask is only needed on one incoming arm, push it up.
3153         if (Op0I->hasOneUse()) {
3154           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3155             // Not masking anything out for the LHS, move to RHS.
3156             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3157                                                    Op0RHS->getName()+".masked");
3158             InsertNewInstBefore(NewRHS, I);
3159             return BinaryOperator::create(
3160                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3161           }
3162           if (!isa<Constant>(Op0RHS) &&
3163               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3164             // Not masking anything out for the RHS, move to LHS.
3165             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3166                                                    Op0LHS->getName()+".masked");
3167             InsertNewInstBefore(NewLHS, I);
3168             return BinaryOperator::create(
3169                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3170           }
3171         }
3172
3173         break;
3174       case Instruction::Add:
3175         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3176         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3177         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3178         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3179           return BinaryOperator::createAnd(V, AndRHS);
3180         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3181           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3182         break;
3183
3184       case Instruction::Sub:
3185         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3186         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3187         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3188         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3189           return BinaryOperator::createAnd(V, AndRHS);
3190         break;
3191       }
3192
3193       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3194         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3195           return Res;
3196     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3197       // If this is an integer truncation or change from signed-to-unsigned, and
3198       // if the source is an and/or with immediate, transform it.  This
3199       // frequently occurs for bitfield accesses.
3200       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3201         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3202             CastOp->getNumOperands() == 2)
3203           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3204             if (CastOp->getOpcode() == Instruction::And) {
3205               // Change: and (cast (and X, C1) to T), C2
3206               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3207               // This will fold the two constants together, which may allow 
3208               // other simplifications.
3209               Instruction *NewCast = CastInst::createTruncOrBitCast(
3210                 CastOp->getOperand(0), I.getType(), 
3211                 CastOp->getName()+".shrunk");
3212               NewCast = InsertNewInstBefore(NewCast, I);
3213               // trunc_or_bitcast(C1)&C2
3214               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3215               C3 = ConstantExpr::getAnd(C3, AndRHS);
3216               return BinaryOperator::createAnd(NewCast, C3);
3217             } else if (CastOp->getOpcode() == Instruction::Or) {
3218               // Change: and (cast (or X, C1) to T), C2
3219               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3220               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3221               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3222                 return ReplaceInstUsesWith(I, AndRHS);
3223             }
3224       }
3225     }
3226
3227     // Try to fold constant and into select arguments.
3228     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3229       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3230         return R;
3231     if (isa<PHINode>(Op0))
3232       if (Instruction *NV = FoldOpIntoPhi(I))
3233         return NV;
3234   }
3235
3236   Value *Op0NotVal = dyn_castNotVal(Op0);
3237   Value *Op1NotVal = dyn_castNotVal(Op1);
3238
3239   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3240     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3241
3242   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3243   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3244     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3245                                                I.getName()+".demorgan");
3246     InsertNewInstBefore(Or, I);
3247     return BinaryOperator::createNot(Or);
3248   }
3249   
3250   {
3251     Value *A = 0, *B = 0;
3252     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3253       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3254         return ReplaceInstUsesWith(I, Op1);
3255     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3256       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3257         return ReplaceInstUsesWith(I, Op0);
3258     
3259     if (Op0->hasOneUse() &&
3260         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3261       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3262         I.swapOperands();     // Simplify below
3263         std::swap(Op0, Op1);
3264       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3265         cast<BinaryOperator>(Op0)->swapOperands();
3266         I.swapOperands();     // Simplify below
3267         std::swap(Op0, Op1);
3268       }
3269     }
3270     if (Op1->hasOneUse() &&
3271         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3272       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3273         cast<BinaryOperator>(Op1)->swapOperands();
3274         std::swap(A, B);
3275       }
3276       if (A == Op0) {                                // A&(A^B) -> A & ~B
3277         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3278         InsertNewInstBefore(NotB, I);
3279         return BinaryOperator::createAnd(A, NotB);
3280       }
3281     }
3282   }
3283   
3284   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3285     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3286     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3287       return R;
3288
3289     Value *LHSVal, *RHSVal;
3290     ConstantInt *LHSCst, *RHSCst;
3291     ICmpInst::Predicate LHSCC, RHSCC;
3292     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3293       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3294         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3295             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3296             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3297             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3298             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3299             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3300           // Ensure that the larger constant is on the RHS.
3301           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3302             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3303           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3304           ICmpInst *LHS = cast<ICmpInst>(Op0);
3305           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3306             std::swap(LHS, RHS);
3307             std::swap(LHSCst, RHSCst);
3308             std::swap(LHSCC, RHSCC);
3309           }
3310
3311           // At this point, we know we have have two icmp instructions
3312           // comparing a value against two constants and and'ing the result
3313           // together.  Because of the above check, we know that we only have
3314           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3315           // (from the FoldICmpLogical check above), that the two constants 
3316           // are not equal and that the larger constant is on the RHS
3317           assert(LHSCst != RHSCst && "Compares not folded above?");
3318
3319           switch (LHSCC) {
3320           default: assert(0 && "Unknown integer condition code!");
3321           case ICmpInst::ICMP_EQ:
3322             switch (RHSCC) {
3323             default: assert(0 && "Unknown integer condition code!");
3324             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3325             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3326             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3327               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3328             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3329             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3330             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3331               return ReplaceInstUsesWith(I, LHS);
3332             }
3333           case ICmpInst::ICMP_NE:
3334             switch (RHSCC) {
3335             default: assert(0 && "Unknown integer condition code!");
3336             case ICmpInst::ICMP_ULT:
3337               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3338                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3339               break;                        // (X != 13 & X u< 15) -> no change
3340             case ICmpInst::ICMP_SLT:
3341               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3342                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3343               break;                        // (X != 13 & X s< 15) -> no change
3344             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3345             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3346             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3347               return ReplaceInstUsesWith(I, RHS);
3348             case ICmpInst::ICMP_NE:
3349               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3350                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3351                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3352                                                       LHSVal->getName()+".off");
3353                 InsertNewInstBefore(Add, I);
3354                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3355                                     ConstantInt::get(Add->getType(), 1));
3356               }
3357               break;                        // (X != 13 & X != 15) -> no change
3358             }
3359             break;
3360           case ICmpInst::ICMP_ULT:
3361             switch (RHSCC) {
3362             default: assert(0 && "Unknown integer condition code!");
3363             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3364             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3365               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3366             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3367               break;
3368             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3369             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3370               return ReplaceInstUsesWith(I, LHS);
3371             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3372               break;
3373             }
3374             break;
3375           case ICmpInst::ICMP_SLT:
3376             switch (RHSCC) {
3377             default: assert(0 && "Unknown integer condition code!");
3378             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3379             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3380               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3381             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3382               break;
3383             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3384             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3385               return ReplaceInstUsesWith(I, LHS);
3386             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3387               break;
3388             }
3389             break;
3390           case ICmpInst::ICMP_UGT:
3391             switch (RHSCC) {
3392             default: assert(0 && "Unknown integer condition code!");
3393             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3394               return ReplaceInstUsesWith(I, LHS);
3395             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3396               return ReplaceInstUsesWith(I, RHS);
3397             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3398               break;
3399             case ICmpInst::ICMP_NE:
3400               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3401                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3402               break;                        // (X u> 13 & X != 15) -> no change
3403             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3404               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3405                                      true, I);
3406             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3407               break;
3408             }
3409             break;
3410           case ICmpInst::ICMP_SGT:
3411             switch (RHSCC) {
3412             default: assert(0 && "Unknown integer condition code!");
3413             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3414               return ReplaceInstUsesWith(I, LHS);
3415             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3416               return ReplaceInstUsesWith(I, RHS);
3417             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3418               break;
3419             case ICmpInst::ICMP_NE:
3420               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3421                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3422               break;                        // (X s> 13 & X != 15) -> no change
3423             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3424               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3425                                      true, I);
3426             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3427               break;
3428             }
3429             break;
3430           }
3431         }
3432   }
3433
3434   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3435   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3436     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3437       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3438         const Type *SrcTy = Op0C->getOperand(0)->getType();
3439         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3440             // Only do this if the casts both really cause code to be generated.
3441             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3442                               I.getType(), TD) &&
3443             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3444                               I.getType(), TD)) {
3445           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3446                                                          Op1C->getOperand(0),
3447                                                          I.getName());
3448           InsertNewInstBefore(NewOp, I);
3449           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3450         }
3451       }
3452     
3453   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3454   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3455     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3456       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3457           SI0->getOperand(1) == SI1->getOperand(1) &&
3458           (SI0->hasOneUse() || SI1->hasOneUse())) {
3459         Instruction *NewOp =
3460           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3461                                                         SI1->getOperand(0),
3462                                                         SI0->getName()), I);
3463         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3464                                       SI1->getOperand(1));
3465       }
3466   }
3467
3468   return Changed ? &I : 0;
3469 }
3470
3471 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3472 /// in the result.  If it does, and if the specified byte hasn't been filled in
3473 /// yet, fill it in and return false.
3474 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3475   Instruction *I = dyn_cast<Instruction>(V);
3476   if (I == 0) return true;
3477
3478   // If this is an or instruction, it is an inner node of the bswap.
3479   if (I->getOpcode() == Instruction::Or)
3480     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3481            CollectBSwapParts(I->getOperand(1), ByteValues);
3482   
3483   // If this is a shift by a constant int, and it is "24", then its operand
3484   // defines a byte.  We only handle unsigned types here.
3485   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3486     // Not shifting the entire input by N-1 bytes?
3487     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3488         8*(ByteValues.size()-1))
3489       return true;
3490     
3491     unsigned DestNo;
3492     if (I->getOpcode() == Instruction::Shl) {
3493       // X << 24 defines the top byte with the lowest of the input bytes.
3494       DestNo = ByteValues.size()-1;
3495     } else {
3496       // X >>u 24 defines the low byte with the highest of the input bytes.
3497       DestNo = 0;
3498     }
3499     
3500     // If the destination byte value is already defined, the values are or'd
3501     // together, which isn't a bswap (unless it's an or of the same bits).
3502     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3503       return true;
3504     ByteValues[DestNo] = I->getOperand(0);
3505     return false;
3506   }
3507   
3508   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3509   // don't have this.
3510   Value *Shift = 0, *ShiftLHS = 0;
3511   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3512   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3513       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3514     return true;
3515   Instruction *SI = cast<Instruction>(Shift);
3516
3517   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3518   if (ShiftAmt->getZExtValue() & 7 ||
3519       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3520     return true;
3521   
3522   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3523   unsigned DestByte;
3524   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3525     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3526       break;
3527   // Unknown mask for bswap.
3528   if (DestByte == ByteValues.size()) return true;
3529   
3530   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3531   unsigned SrcByte;
3532   if (SI->getOpcode() == Instruction::Shl)
3533     SrcByte = DestByte - ShiftBytes;
3534   else
3535     SrcByte = DestByte + ShiftBytes;
3536   
3537   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3538   if (SrcByte != ByteValues.size()-DestByte-1)
3539     return true;
3540   
3541   // If the destination byte value is already defined, the values are or'd
3542   // together, which isn't a bswap (unless it's an or of the same bits).
3543   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3544     return true;
3545   ByteValues[DestByte] = SI->getOperand(0);
3546   return false;
3547 }
3548
3549 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3550 /// If so, insert the new bswap intrinsic and return it.
3551 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3552   // We cannot bswap one byte.
3553   if (I.getType() == Type::Int8Ty)
3554     return 0;
3555   
3556   /// ByteValues - For each byte of the result, we keep track of which value
3557   /// defines each byte.
3558   SmallVector<Value*, 8> ByteValues;
3559   ByteValues.resize(TD->getTypeSize(I.getType()));
3560     
3561   // Try to find all the pieces corresponding to the bswap.
3562   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3563       CollectBSwapParts(I.getOperand(1), ByteValues))
3564     return 0;
3565   
3566   // Check to see if all of the bytes come from the same value.
3567   Value *V = ByteValues[0];
3568   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3569   
3570   // Check to make sure that all of the bytes come from the same value.
3571   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3572     if (ByteValues[i] != V)
3573       return 0;
3574     
3575   // If they do then *success* we can turn this into a bswap.  Figure out what
3576   // bswap to make it into.
3577   Module *M = I.getParent()->getParent()->getParent();
3578   const char *FnName = 0;
3579   if (I.getType() == Type::Int16Ty)
3580     FnName = "llvm.bswap.i16";
3581   else if (I.getType() == Type::Int32Ty)
3582     FnName = "llvm.bswap.i32";
3583   else if (I.getType() == Type::Int64Ty)
3584     FnName = "llvm.bswap.i64";
3585   else
3586     assert(0 && "Unknown integer type!");
3587   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3588   return new CallInst(F, V);
3589 }
3590
3591
3592 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3593   bool Changed = SimplifyCommutative(I);
3594   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3595
3596   if (isa<UndefValue>(Op1))
3597     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3598                                ConstantInt::getAllOnesValue(I.getType()));
3599
3600   // or X, X = X
3601   if (Op0 == Op1)
3602     return ReplaceInstUsesWith(I, Op0);
3603
3604   // See if we can simplify any instructions used by the instruction whose sole 
3605   // purpose is to compute bits we don't care about.
3606   uint64_t KnownZero, KnownOne;
3607   if (!isa<VectorType>(I.getType()) &&
3608       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3609                            KnownZero, KnownOne))
3610     return &I;
3611   
3612   // or X, -1 == -1
3613   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3614     ConstantInt *C1 = 0; Value *X = 0;
3615     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3616     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3617       Instruction *Or = BinaryOperator::createOr(X, RHS);
3618       InsertNewInstBefore(Or, I);
3619       Or->takeName(Op0);
3620       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3621     }
3622
3623     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3624     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3625       Instruction *Or = BinaryOperator::createOr(X, RHS);
3626       InsertNewInstBefore(Or, I);
3627       Or->takeName(Op0);
3628       return BinaryOperator::createXor(Or,
3629                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3630     }
3631
3632     // Try to fold constant and into select arguments.
3633     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3634       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3635         return R;
3636     if (isa<PHINode>(Op0))
3637       if (Instruction *NV = FoldOpIntoPhi(I))
3638         return NV;
3639   }
3640
3641   Value *A = 0, *B = 0;
3642   ConstantInt *C1 = 0, *C2 = 0;
3643
3644   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3645     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3646       return ReplaceInstUsesWith(I, Op1);
3647   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3648     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3649       return ReplaceInstUsesWith(I, Op0);
3650
3651   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3652   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3653   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3654       match(Op1, m_Or(m_Value(), m_Value())) ||
3655       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3656        match(Op1, m_Shift(m_Value(), m_Value())))) {
3657     if (Instruction *BSwap = MatchBSwap(I))
3658       return BSwap;
3659   }
3660   
3661   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3662   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3663       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3664     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3665     InsertNewInstBefore(NOr, I);
3666     NOr->takeName(Op0);
3667     return BinaryOperator::createXor(NOr, C1);
3668   }
3669
3670   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3671   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3672       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3673     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3674     InsertNewInstBefore(NOr, I);
3675     NOr->takeName(Op0);
3676     return BinaryOperator::createXor(NOr, C1);
3677   }
3678
3679   // (A & C1)|(B & C2)
3680   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3681       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3682
3683     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3684       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3685
3686
3687     // If we have: ((V + N) & C1) | (V & C2)
3688     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3689     // replace with V+N.
3690     if (C1 == ConstantExpr::getNot(C2)) {
3691       Value *V1 = 0, *V2 = 0;
3692       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3693           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3694         // Add commutes, try both ways.
3695         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3696           return ReplaceInstUsesWith(I, A);
3697         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3698           return ReplaceInstUsesWith(I, A);
3699       }
3700       // Or commutes, try both ways.
3701       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3702           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3703         // Add commutes, try both ways.
3704         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3705           return ReplaceInstUsesWith(I, B);
3706         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3707           return ReplaceInstUsesWith(I, B);
3708       }
3709     }
3710   }
3711   
3712   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3713   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3714     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3715       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3716           SI0->getOperand(1) == SI1->getOperand(1) &&
3717           (SI0->hasOneUse() || SI1->hasOneUse())) {
3718         Instruction *NewOp =
3719         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3720                                                      SI1->getOperand(0),
3721                                                      SI0->getName()), I);
3722         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3723                                       SI1->getOperand(1));
3724       }
3725   }
3726
3727   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3728     if (A == Op1)   // ~A | A == -1
3729       return ReplaceInstUsesWith(I,
3730                                 ConstantInt::getAllOnesValue(I.getType()));
3731   } else {
3732     A = 0;
3733   }
3734   // Note, A is still live here!
3735   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3736     if (Op0 == B)
3737       return ReplaceInstUsesWith(I,
3738                                 ConstantInt::getAllOnesValue(I.getType()));
3739
3740     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3741     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3742       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3743                                               I.getName()+".demorgan"), I);
3744       return BinaryOperator::createNot(And);
3745     }
3746   }
3747
3748   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3749   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3750     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3751       return R;
3752
3753     Value *LHSVal, *RHSVal;
3754     ConstantInt *LHSCst, *RHSCst;
3755     ICmpInst::Predicate LHSCC, RHSCC;
3756     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3757       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3758         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3759             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3760             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3761             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3762             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3763             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3764           // Ensure that the larger constant is on the RHS.
3765           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3766             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3767           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3768           ICmpInst *LHS = cast<ICmpInst>(Op0);
3769           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3770             std::swap(LHS, RHS);
3771             std::swap(LHSCst, RHSCst);
3772             std::swap(LHSCC, RHSCC);
3773           }
3774
3775           // At this point, we know we have have two icmp instructions
3776           // comparing a value against two constants and or'ing the result
3777           // together.  Because of the above check, we know that we only have
3778           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3779           // FoldICmpLogical check above), that the two constants are not
3780           // equal.
3781           assert(LHSCst != RHSCst && "Compares not folded above?");
3782
3783           switch (LHSCC) {
3784           default: assert(0 && "Unknown integer condition code!");
3785           case ICmpInst::ICMP_EQ:
3786             switch (RHSCC) {
3787             default: assert(0 && "Unknown integer condition code!");
3788             case ICmpInst::ICMP_EQ:
3789               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3790                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3791                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3792                                                       LHSVal->getName()+".off");
3793                 InsertNewInstBefore(Add, I);
3794                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3795                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3796               }
3797               break;                         // (X == 13 | X == 15) -> no change
3798             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3799             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3800               break;
3801             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3802             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3803             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3804               return ReplaceInstUsesWith(I, RHS);
3805             }
3806             break;
3807           case ICmpInst::ICMP_NE:
3808             switch (RHSCC) {
3809             default: assert(0 && "Unknown integer condition code!");
3810             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3811             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3812             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3813               return ReplaceInstUsesWith(I, LHS);
3814             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3815             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3816             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3817               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3818             }
3819             break;
3820           case ICmpInst::ICMP_ULT:
3821             switch (RHSCC) {
3822             default: assert(0 && "Unknown integer condition code!");
3823             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3824               break;
3825             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3826               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3827                                      false, I);
3828             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3829               break;
3830             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3831             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3832               return ReplaceInstUsesWith(I, RHS);
3833             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3834               break;
3835             }
3836             break;
3837           case ICmpInst::ICMP_SLT:
3838             switch (RHSCC) {
3839             default: assert(0 && "Unknown integer condition code!");
3840             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3841               break;
3842             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3843               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3844                                      false, I);
3845             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3846               break;
3847             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3848             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3849               return ReplaceInstUsesWith(I, RHS);
3850             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3851               break;
3852             }
3853             break;
3854           case ICmpInst::ICMP_UGT:
3855             switch (RHSCC) {
3856             default: assert(0 && "Unknown integer condition code!");
3857             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3858             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3859               return ReplaceInstUsesWith(I, LHS);
3860             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3861               break;
3862             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3863             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3864               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3865             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3866               break;
3867             }
3868             break;
3869           case ICmpInst::ICMP_SGT:
3870             switch (RHSCC) {
3871             default: assert(0 && "Unknown integer condition code!");
3872             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3873             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3874               return ReplaceInstUsesWith(I, LHS);
3875             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3876               break;
3877             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3878             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3879               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3880             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3881               break;
3882             }
3883             break;
3884           }
3885         }
3886   }
3887     
3888   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3889   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3890     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3891       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3892         const Type *SrcTy = Op0C->getOperand(0)->getType();
3893         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3894             // Only do this if the casts both really cause code to be generated.
3895             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3896                               I.getType(), TD) &&
3897             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3898                               I.getType(), TD)) {
3899           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3900                                                         Op1C->getOperand(0),
3901                                                         I.getName());
3902           InsertNewInstBefore(NewOp, I);
3903           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3904         }
3905       }
3906       
3907
3908   return Changed ? &I : 0;
3909 }
3910
3911 // XorSelf - Implements: X ^ X --> 0
3912 struct XorSelf {
3913   Value *RHS;
3914   XorSelf(Value *rhs) : RHS(rhs) {}
3915   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3916   Instruction *apply(BinaryOperator &Xor) const {
3917     return &Xor;
3918   }
3919 };
3920
3921
3922 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3923   bool Changed = SimplifyCommutative(I);
3924   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3925
3926   if (isa<UndefValue>(Op1))
3927     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3928
3929   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3930   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3931     assert(Result == &I && "AssociativeOpt didn't work?");
3932     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3933   }
3934   
3935   // See if we can simplify any instructions used by the instruction whose sole 
3936   // purpose is to compute bits we don't care about.
3937   uint64_t KnownZero, KnownOne;
3938   if (!isa<VectorType>(I.getType()) &&
3939       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3940                            KnownZero, KnownOne))
3941     return &I;
3942
3943   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3944     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3945     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3946       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3947         return new ICmpInst(ICI->getInversePredicate(),
3948                             ICI->getOperand(0), ICI->getOperand(1));
3949
3950     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3951       // ~(c-X) == X-c-1 == X+(-c-1)
3952       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3953         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3954           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3955           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3956                                               ConstantInt::get(I.getType(), 1));
3957           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3958         }
3959
3960       // ~(~X & Y) --> (X | ~Y)
3961       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3962         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3963         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3964           Instruction *NotY =
3965             BinaryOperator::createNot(Op0I->getOperand(1),
3966                                       Op0I->getOperand(1)->getName()+".not");
3967           InsertNewInstBefore(NotY, I);
3968           return BinaryOperator::createOr(Op0NotVal, NotY);
3969         }
3970       }
3971
3972       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3973         if (Op0I->getOpcode() == Instruction::Add) {
3974           // ~(X-c) --> (-c-1)-X
3975           if (RHS->isAllOnesValue()) {
3976             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3977             return BinaryOperator::createSub(
3978                            ConstantExpr::getSub(NegOp0CI,
3979                                              ConstantInt::get(I.getType(), 1)),
3980                                           Op0I->getOperand(0));
3981           }
3982         } else if (Op0I->getOpcode() == Instruction::Or) {
3983           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3984           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3985             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3986             // Anything in both C1 and C2 is known to be zero, remove it from
3987             // NewRHS.
3988             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3989             NewRHS = ConstantExpr::getAnd(NewRHS, 
3990                                           ConstantExpr::getNot(CommonBits));
3991             AddToWorkList(Op0I);
3992             I.setOperand(0, Op0I->getOperand(0));
3993             I.setOperand(1, NewRHS);
3994             return &I;
3995           }
3996         }
3997     }
3998
3999     // Try to fold constant and into select arguments.
4000     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4001       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4002         return R;
4003     if (isa<PHINode>(Op0))
4004       if (Instruction *NV = FoldOpIntoPhi(I))
4005         return NV;
4006   }
4007
4008   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4009     if (X == Op1)
4010       return ReplaceInstUsesWith(I,
4011                                 ConstantInt::getAllOnesValue(I.getType()));
4012
4013   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4014     if (X == Op0)
4015       return ReplaceInstUsesWith(I,
4016                                 ConstantInt::getAllOnesValue(I.getType()));
4017
4018   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
4019     if (Op1I->getOpcode() == Instruction::Or) {
4020       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
4021         Op1I->swapOperands();
4022         I.swapOperands();
4023         std::swap(Op0, Op1);
4024       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
4025         I.swapOperands();     // Simplified below.
4026         std::swap(Op0, Op1);
4027       }
4028     } else if (Op1I->getOpcode() == Instruction::Xor) {
4029       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
4030         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4031       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
4032         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4033     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4034       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4035         Op1I->swapOperands();
4036       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4037         I.swapOperands();     // Simplified below.
4038         std::swap(Op0, Op1);
4039       }
4040     }
4041
4042   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4043     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4044       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4045         Op0I->swapOperands();
4046       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4047         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4048         InsertNewInstBefore(NotB, I);
4049         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4050       }
4051     } else if (Op0I->getOpcode() == Instruction::Xor) {
4052       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4053         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4054       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4055         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4056     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4057       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4058         Op0I->swapOperands();
4059       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4060           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4061         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4062         InsertNewInstBefore(N, I);
4063         return BinaryOperator::createAnd(N, Op1);
4064       }
4065     }
4066
4067   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4068   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4069     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4070       return R;
4071
4072   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4073   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4074     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4075       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4076         const Type *SrcTy = Op0C->getOperand(0)->getType();
4077         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4078             // Only do this if the casts both really cause code to be generated.
4079             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4080                               I.getType(), TD) &&
4081             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4082                               I.getType(), TD)) {
4083           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4084                                                          Op1C->getOperand(0),
4085                                                          I.getName());
4086           InsertNewInstBefore(NewOp, I);
4087           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4088         }
4089       }
4090
4091   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4092   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4093     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4094       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4095           SI0->getOperand(1) == SI1->getOperand(1) &&
4096           (SI0->hasOneUse() || SI1->hasOneUse())) {
4097         Instruction *NewOp =
4098         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4099                                                       SI1->getOperand(0),
4100                                                       SI0->getName()), I);
4101         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4102                                       SI1->getOperand(1));
4103       }
4104   }
4105     
4106   return Changed ? &I : 0;
4107 }
4108
4109 static bool isPositive(ConstantInt *C) {
4110   return C->getSExtValue() >= 0;
4111 }
4112
4113 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4114 /// overflowed for this type.
4115 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4116                             ConstantInt *In2) {
4117   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4118
4119   return cast<ConstantInt>(Result)->getZExtValue() <
4120          cast<ConstantInt>(In1)->getZExtValue();
4121 }
4122
4123 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4124 /// code necessary to compute the offset from the base pointer (without adding
4125 /// in the base pointer).  Return the result as a signed integer of intptr size.
4126 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4127   TargetData &TD = IC.getTargetData();
4128   gep_type_iterator GTI = gep_type_begin(GEP);
4129   const Type *IntPtrTy = TD.getIntPtrType();
4130   Value *Result = Constant::getNullValue(IntPtrTy);
4131
4132   // Build a mask for high order bits.
4133   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4134
4135   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4136     Value *Op = GEP->getOperand(i);
4137     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4138     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4139     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4140       if (!OpC->isNullValue()) {
4141         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4142         Scale = ConstantExpr::getMul(OpC, Scale);
4143         if (Constant *RC = dyn_cast<Constant>(Result))
4144           Result = ConstantExpr::getAdd(RC, Scale);
4145         else {
4146           // Emit an add instruction.
4147           Result = IC.InsertNewInstBefore(
4148              BinaryOperator::createAdd(Result, Scale,
4149                                        GEP->getName()+".offs"), I);
4150         }
4151       }
4152     } else {
4153       // Convert to correct type.
4154       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4155                                                Op->getName()+".c"), I);
4156       if (Size != 1)
4157         // We'll let instcombine(mul) convert this to a shl if possible.
4158         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4159                                                     GEP->getName()+".idx"), I);
4160
4161       // Emit an add instruction.
4162       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4163                                                     GEP->getName()+".offs"), I);
4164     }
4165   }
4166   return Result;
4167 }
4168
4169 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4170 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4171 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4172                                        ICmpInst::Predicate Cond,
4173                                        Instruction &I) {
4174   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4175
4176   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4177     if (isa<PointerType>(CI->getOperand(0)->getType()))
4178       RHS = CI->getOperand(0);
4179
4180   Value *PtrBase = GEPLHS->getOperand(0);
4181   if (PtrBase == RHS) {
4182     // As an optimization, we don't actually have to compute the actual value of
4183     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4184     // each index is zero or not.
4185     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4186       Instruction *InVal = 0;
4187       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4188       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4189         bool EmitIt = true;
4190         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4191           if (isa<UndefValue>(C))  // undef index -> undef.
4192             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4193           if (C->isNullValue())
4194             EmitIt = false;
4195           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4196             EmitIt = false;  // This is indexing into a zero sized array?
4197           } else if (isa<ConstantInt>(C))
4198             return ReplaceInstUsesWith(I, // No comparison is needed here.
4199                                  ConstantInt::get(Type::Int1Ty, 
4200                                                   Cond == ICmpInst::ICMP_NE));
4201         }
4202
4203         if (EmitIt) {
4204           Instruction *Comp =
4205             new ICmpInst(Cond, GEPLHS->getOperand(i),
4206                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4207           if (InVal == 0)
4208             InVal = Comp;
4209           else {
4210             InVal = InsertNewInstBefore(InVal, I);
4211             InsertNewInstBefore(Comp, I);
4212             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4213               InVal = BinaryOperator::createOr(InVal, Comp);
4214             else                              // True if all are equal
4215               InVal = BinaryOperator::createAnd(InVal, Comp);
4216           }
4217         }
4218       }
4219
4220       if (InVal)
4221         return InVal;
4222       else
4223         // No comparison is needed here, all indexes = 0
4224         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4225                                                 Cond == ICmpInst::ICMP_EQ));
4226     }
4227
4228     // Only lower this if the icmp is the only user of the GEP or if we expect
4229     // the result to fold to a constant!
4230     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4231       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4232       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4233       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4234                           Constant::getNullValue(Offset->getType()));
4235     }
4236   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4237     // If the base pointers are different, but the indices are the same, just
4238     // compare the base pointer.
4239     if (PtrBase != GEPRHS->getOperand(0)) {
4240       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4241       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4242                         GEPRHS->getOperand(0)->getType();
4243       if (IndicesTheSame)
4244         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4245           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4246             IndicesTheSame = false;
4247             break;
4248           }
4249
4250       // If all indices are the same, just compare the base pointers.
4251       if (IndicesTheSame)
4252         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4253                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4254
4255       // Otherwise, the base pointers are different and the indices are
4256       // different, bail out.
4257       return 0;
4258     }
4259
4260     // If one of the GEPs has all zero indices, recurse.
4261     bool AllZeros = true;
4262     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4263       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4264           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4265         AllZeros = false;
4266         break;
4267       }
4268     if (AllZeros)
4269       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4270                           ICmpInst::getSwappedPredicate(Cond), I);
4271
4272     // If the other GEP has all zero indices, recurse.
4273     AllZeros = true;
4274     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4275       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4276           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4277         AllZeros = false;
4278         break;
4279       }
4280     if (AllZeros)
4281       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4282
4283     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4284       // If the GEPs only differ by one index, compare it.
4285       unsigned NumDifferences = 0;  // Keep track of # differences.
4286       unsigned DiffOperand = 0;     // The operand that differs.
4287       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4288         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4289           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4290                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4291             // Irreconcilable differences.
4292             NumDifferences = 2;
4293             break;
4294           } else {
4295             if (NumDifferences++) break;
4296             DiffOperand = i;
4297           }
4298         }
4299
4300       if (NumDifferences == 0)   // SAME GEP?
4301         return ReplaceInstUsesWith(I, // No comparison is needed here.
4302                                    ConstantInt::get(Type::Int1Ty, 
4303                                                     Cond == ICmpInst::ICMP_EQ));
4304       else if (NumDifferences == 1) {
4305         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4306         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4307         // Make sure we do a signed comparison here.
4308         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4309       }
4310     }
4311
4312     // Only lower this if the icmp is the only user of the GEP or if we expect
4313     // the result to fold to a constant!
4314     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4315         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4316       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4317       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4318       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4319       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4320     }
4321   }
4322   return 0;
4323 }
4324
4325 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4326   bool Changed = SimplifyCompare(I);
4327   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4328
4329   // Fold trivial predicates.
4330   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4331     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4332   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4333     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4334   
4335   // Simplify 'fcmp pred X, X'
4336   if (Op0 == Op1) {
4337     switch (I.getPredicate()) {
4338     default: assert(0 && "Unknown predicate!");
4339     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4340     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4341     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4342       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4343     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4344     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4345     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4346       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4347       
4348     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4349     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4350     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4351     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4352       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4353       I.setPredicate(FCmpInst::FCMP_UNO);
4354       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4355       return &I;
4356       
4357     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4358     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4359     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4360     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4361       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4362       I.setPredicate(FCmpInst::FCMP_ORD);
4363       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4364       return &I;
4365     }
4366   }
4367     
4368   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4369     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4370
4371   // Handle fcmp with constant RHS
4372   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4373     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4374       switch (LHSI->getOpcode()) {
4375       case Instruction::PHI:
4376         if (Instruction *NV = FoldOpIntoPhi(I))
4377           return NV;
4378         break;
4379       case Instruction::Select:
4380         // If either operand of the select is a constant, we can fold the
4381         // comparison into the select arms, which will cause one to be
4382         // constant folded and the select turned into a bitwise or.
4383         Value *Op1 = 0, *Op2 = 0;
4384         if (LHSI->hasOneUse()) {
4385           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4386             // Fold the known value into the constant operand.
4387             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4388             // Insert a new FCmp of the other select operand.
4389             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4390                                                       LHSI->getOperand(2), RHSC,
4391                                                       I.getName()), I);
4392           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4393             // Fold the known value into the constant operand.
4394             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4395             // Insert a new FCmp of the other select operand.
4396             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4397                                                       LHSI->getOperand(1), RHSC,
4398                                                       I.getName()), I);
4399           }
4400         }
4401
4402         if (Op1)
4403           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4404         break;
4405       }
4406   }
4407
4408   return Changed ? &I : 0;
4409 }
4410
4411 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4412   bool Changed = SimplifyCompare(I);
4413   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4414   const Type *Ty = Op0->getType();
4415
4416   // icmp X, X
4417   if (Op0 == Op1)
4418     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4419                                                    isTrueWhenEqual(I)));
4420
4421   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4422     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4423
4424   // icmp of GlobalValues can never equal each other as long as they aren't
4425   // external weak linkage type.
4426   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4427     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4428       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4429         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4430                                                        !isTrueWhenEqual(I)));
4431
4432   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4433   // addresses never equal each other!  We already know that Op0 != Op1.
4434   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4435        isa<ConstantPointerNull>(Op0)) &&
4436       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4437        isa<ConstantPointerNull>(Op1)))
4438     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4439                                                    !isTrueWhenEqual(I)));
4440
4441   // icmp's with boolean values can always be turned into bitwise operations
4442   if (Ty == Type::Int1Ty) {
4443     switch (I.getPredicate()) {
4444     default: assert(0 && "Invalid icmp instruction!");
4445     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4446       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4447       InsertNewInstBefore(Xor, I);
4448       return BinaryOperator::createNot(Xor);
4449     }
4450     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4451       return BinaryOperator::createXor(Op0, Op1);
4452
4453     case ICmpInst::ICMP_UGT:
4454     case ICmpInst::ICMP_SGT:
4455       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4456       // FALL THROUGH
4457     case ICmpInst::ICMP_ULT:
4458     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4459       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4460       InsertNewInstBefore(Not, I);
4461       return BinaryOperator::createAnd(Not, Op1);
4462     }
4463     case ICmpInst::ICMP_UGE:
4464     case ICmpInst::ICMP_SGE:
4465       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4466       // FALL THROUGH
4467     case ICmpInst::ICMP_ULE:
4468     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4469       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4470       InsertNewInstBefore(Not, I);
4471       return BinaryOperator::createOr(Not, Op1);
4472     }
4473     }
4474   }
4475
4476   // See if we are doing a comparison between a constant and an instruction that
4477   // can be folded into the comparison.
4478   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4479     switch (I.getPredicate()) {
4480     default: break;
4481     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4482       if (CI->isMinValue(false))
4483         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4484       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4485         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4486       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4487         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4488       break;
4489
4490     case ICmpInst::ICMP_SLT:
4491       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4492         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4493       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4494         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4495       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4496         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4497       break;
4498
4499     case ICmpInst::ICMP_UGT:
4500       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4501         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4502       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4503         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4504       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4505         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4506       break;
4507
4508     case ICmpInst::ICMP_SGT:
4509       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4510         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4511       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4512         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4513       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4514         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4515       break;
4516
4517     case ICmpInst::ICMP_ULE:
4518       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4519         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4520       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4521         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4522       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4523         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4524       break;
4525
4526     case ICmpInst::ICMP_SLE:
4527       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4528         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4529       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4530         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4531       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4532         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4533       break;
4534
4535     case ICmpInst::ICMP_UGE:
4536       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4537         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4538       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4539         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4540       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4541         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4542       break;
4543
4544     case ICmpInst::ICMP_SGE:
4545       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4546         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4547       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4548         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4549       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4550         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4551       break;
4552     }
4553
4554     // If we still have a icmp le or icmp ge instruction, turn it into the
4555     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4556     // already been handled above, this requires little checking.
4557     //
4558     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4559       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4560     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4561       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4562     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4563       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4564     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4565       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4566     
4567     // See if we can fold the comparison based on bits known to be zero or one
4568     // in the input.
4569     uint64_t KnownZero, KnownOne;
4570     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4571                              KnownZero, KnownOne, 0))
4572       return &I;
4573         
4574     // Given the known and unknown bits, compute a range that the LHS could be
4575     // in.
4576     if (KnownOne | KnownZero) {
4577       // Compute the Min, Max and RHS values based on the known bits. For the
4578       // EQ and NE we use unsigned values.
4579       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4580       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4581       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4582         SRHSVal = CI->getSExtValue();
4583         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4584                                                SMax);
4585       } else {
4586         URHSVal = CI->getZExtValue();
4587         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4588                                                  UMax);
4589       }
4590       switch (I.getPredicate()) {  // LE/GE have been folded already.
4591       default: assert(0 && "Unknown icmp opcode!");
4592       case ICmpInst::ICMP_EQ:
4593         if (UMax < URHSVal || UMin > URHSVal)
4594           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4595         break;
4596       case ICmpInst::ICMP_NE:
4597         if (UMax < URHSVal || UMin > URHSVal)
4598           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4599         break;
4600       case ICmpInst::ICMP_ULT:
4601         if (UMax < URHSVal)
4602           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4603         if (UMin > URHSVal)
4604           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4605         break;
4606       case ICmpInst::ICMP_UGT:
4607         if (UMin > URHSVal)
4608           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4609         if (UMax < URHSVal)
4610           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4611         break;
4612       case ICmpInst::ICMP_SLT:
4613         if (SMax < SRHSVal)
4614           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4615         if (SMin > SRHSVal)
4616           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4617         break;
4618       case ICmpInst::ICMP_SGT: 
4619         if (SMin > SRHSVal)
4620           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4621         if (SMax < SRHSVal)
4622           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4623         break;
4624       }
4625     }
4626           
4627     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4628     // instruction, see if that instruction also has constants so that the 
4629     // instruction can be folded into the icmp 
4630     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4631       switch (LHSI->getOpcode()) {
4632       case Instruction::And:
4633         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4634             LHSI->getOperand(0)->hasOneUse()) {
4635           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4636
4637           // If the LHS is an AND of a truncating cast, we can widen the
4638           // and/compare to be the input width without changing the value
4639           // produced, eliminating a cast.
4640           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4641             // We can do this transformation if either the AND constant does not
4642             // have its sign bit set or if it is an equality comparison. 
4643             // Extending a relational comparison when we're checking the sign
4644             // bit would not work.
4645             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4646                 (I.isEquality() ||
4647                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4648                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4649               ConstantInt *NewCST;
4650               ConstantInt *NewCI;
4651               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4652                                          AndCST->getZExtValue());
4653               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4654                                         CI->getZExtValue());
4655               Instruction *NewAnd = 
4656                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4657                                           LHSI->getName());
4658               InsertNewInstBefore(NewAnd, I);
4659               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4660             }
4661           }
4662           
4663           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4664           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4665           // happens a LOT in code produced by the C front-end, for bitfield
4666           // access.
4667           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4668           if (Shift && !Shift->isShift())
4669             Shift = 0;
4670
4671           ConstantInt *ShAmt;
4672           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4673           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4674           const Type *AndTy = AndCST->getType();          // Type of the and.
4675
4676           // We can fold this as long as we can't shift unknown bits
4677           // into the mask.  This can only happen with signed shift
4678           // rights, as they sign-extend.
4679           if (ShAmt) {
4680             bool CanFold = Shift->isLogicalShift();
4681             if (!CanFold) {
4682               // To test for the bad case of the signed shr, see if any
4683               // of the bits shifted in could be tested after the mask.
4684               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4685               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4686
4687               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
4688               Constant *ShVal =
4689                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4690                                      OShAmt);
4691               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4692                 CanFold = true;
4693             }
4694
4695             if (CanFold) {
4696               Constant *NewCst;
4697               if (Shift->getOpcode() == Instruction::Shl)
4698                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4699               else
4700                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4701
4702               // Check to see if we are shifting out any of the bits being
4703               // compared.
4704               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4705                 // If we shifted bits out, the fold is not going to work out.
4706                 // As a special case, check to see if this means that the
4707                 // result is always true or false now.
4708                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4709                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4710                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4711                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4712               } else {
4713                 I.setOperand(1, NewCst);
4714                 Constant *NewAndCST;
4715                 if (Shift->getOpcode() == Instruction::Shl)
4716                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4717                 else
4718                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4719                 LHSI->setOperand(1, NewAndCST);
4720                 LHSI->setOperand(0, Shift->getOperand(0));
4721                 AddToWorkList(Shift); // Shift is dead.
4722                 AddUsesToWorkList(I);
4723                 return &I;
4724               }
4725             }
4726           }
4727           
4728           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4729           // preferable because it allows the C<<Y expression to be hoisted out
4730           // of a loop if Y is invariant and X is not.
4731           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4732               I.isEquality() && !Shift->isArithmeticShift() &&
4733               isa<Instruction>(Shift->getOperand(0))) {
4734             // Compute C << Y.
4735             Value *NS;
4736             if (Shift->getOpcode() == Instruction::LShr) {
4737               NS = BinaryOperator::createShl(AndCST, 
4738                                           Shift->getOperand(1), "tmp");
4739             } else {
4740               // Insert a logical shift.
4741               NS = BinaryOperator::createLShr(AndCST,
4742                                           Shift->getOperand(1), "tmp");
4743             }
4744             InsertNewInstBefore(cast<Instruction>(NS), I);
4745
4746             // Compute X & (C << Y).
4747             Instruction *NewAnd = BinaryOperator::createAnd(
4748                 Shift->getOperand(0), NS, LHSI->getName());
4749             InsertNewInstBefore(NewAnd, I);
4750             
4751             I.setOperand(0, NewAnd);
4752             return &I;
4753           }
4754         }
4755         break;
4756
4757       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4758         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4759           if (I.isEquality()) {
4760             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4761
4762             // Check that the shift amount is in range.  If not, don't perform
4763             // undefined shifts.  When the shift is visited it will be
4764             // simplified.
4765             if (ShAmt->getZExtValue() >= TypeBits)
4766               break;
4767
4768             // If we are comparing against bits always shifted out, the
4769             // comparison cannot succeed.
4770             Constant *Comp =
4771               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4772             if (Comp != CI) {// Comparing against a bit that we know is zero.
4773               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4774               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4775               return ReplaceInstUsesWith(I, Cst);
4776             }
4777
4778             if (LHSI->hasOneUse()) {
4779               // Otherwise strength reduce the shift into an and.
4780               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4781               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4782               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4783
4784               Instruction *AndI =
4785                 BinaryOperator::createAnd(LHSI->getOperand(0),
4786                                           Mask, LHSI->getName()+".mask");
4787               Value *And = InsertNewInstBefore(AndI, I);
4788               return new ICmpInst(I.getPredicate(), And,
4789                                      ConstantExpr::getLShr(CI, ShAmt));
4790             }
4791           }
4792         }
4793         break;
4794
4795       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4796       case Instruction::AShr:
4797         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4798           if (I.isEquality()) {
4799             // Check that the shift amount is in range.  If not, don't perform
4800             // undefined shifts.  When the shift is visited it will be
4801             // simplified.
4802             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4803             if (ShAmt->getZExtValue() >= TypeBits)
4804               break;
4805
4806             // If we are comparing against bits always shifted out, the
4807             // comparison cannot succeed.
4808             Constant *Comp;
4809             if (LHSI->getOpcode() == Instruction::LShr) 
4810               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4811                                            ShAmt);
4812             else
4813               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4814                                            ShAmt);
4815
4816             if (Comp != CI) {// Comparing against a bit that we know is zero.
4817               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4818               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4819               return ReplaceInstUsesWith(I, Cst);
4820             }
4821
4822             if (LHSI->hasOneUse() || CI->isNullValue()) {
4823               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4824
4825               // Otherwise strength reduce the shift into an and.
4826               uint64_t Val = ~0ULL;          // All ones.
4827               Val <<= ShAmtVal;              // Shift over to the right spot.
4828               Val &= ~0ULL >> (64-TypeBits);
4829               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4830
4831               Instruction *AndI =
4832                 BinaryOperator::createAnd(LHSI->getOperand(0),
4833                                           Mask, LHSI->getName()+".mask");
4834               Value *And = InsertNewInstBefore(AndI, I);
4835               return new ICmpInst(I.getPredicate(), And,
4836                                      ConstantExpr::getShl(CI, ShAmt));
4837             }
4838           }
4839         }
4840         break;
4841
4842       case Instruction::SDiv:
4843       case Instruction::UDiv:
4844         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4845         // Fold this div into the comparison, producing a range check. 
4846         // Determine, based on the divide type, what the range is being 
4847         // checked.  If there is an overflow on the low or high side, remember 
4848         // it, otherwise compute the range [low, hi) bounding the new value.
4849         // See: InsertRangeTest above for the kinds of replacements possible.
4850         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4851           // FIXME: If the operand types don't match the type of the divide 
4852           // then don't attempt this transform. The code below doesn't have the
4853           // logic to deal with a signed divide and an unsigned compare (and
4854           // vice versa). This is because (x /s C1) <s C2  produces different 
4855           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4856           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4857           // work. :(  The if statement below tests that condition and bails 
4858           // if it finds it. 
4859           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4860           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4861             break;
4862
4863           // Initialize the variables that will indicate the nature of the
4864           // range check.
4865           bool LoOverflow = false, HiOverflow = false;
4866           ConstantInt *LoBound = 0, *HiBound = 0;
4867
4868           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4869           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4870           // C2 (CI). By solving for X we can turn this into a range check 
4871           // instead of computing a divide. 
4872           ConstantInt *Prod = 
4873             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4874
4875           // Determine if the product overflows by seeing if the product is
4876           // not equal to the divide. Make sure we do the same kind of divide
4877           // as in the LHS instruction that we're folding. 
4878           bool ProdOV = !DivRHS->isNullValue() && 
4879             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4880               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4881
4882           // Get the ICmp opcode
4883           ICmpInst::Predicate predicate = I.getPredicate();
4884
4885           if (DivRHS->isNullValue()) {  
4886             // Don't hack on divide by zeros!
4887           } else if (!DivIsSigned) {  // udiv
4888             LoBound = Prod;
4889             LoOverflow = ProdOV;
4890             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4891           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4892             if (CI->isNullValue()) {       // (X / pos) op 0
4893               // Can't overflow.
4894               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4895               HiBound = DivRHS;
4896             } else if (isPositive(CI)) {   // (X / pos) op pos
4897               LoBound = Prod;
4898               LoOverflow = ProdOV;
4899               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4900             } else {                       // (X / pos) op neg
4901               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4902               LoOverflow = AddWithOverflow(LoBound, Prod,
4903                                            cast<ConstantInt>(DivRHSH));
4904               HiBound = Prod;
4905               HiOverflow = ProdOV;
4906             }
4907           } else {                         // Divisor is < 0.
4908             if (CI->isNullValue()) {       // (X / neg) op 0
4909               LoBound = AddOne(DivRHS);
4910               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4911               if (HiBound == DivRHS)
4912                 LoBound = 0;               // - INTMIN = INTMIN
4913             } else if (isPositive(CI)) {   // (X / neg) op pos
4914               HiOverflow = LoOverflow = ProdOV;
4915               if (!LoOverflow)
4916                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4917               HiBound = AddOne(Prod);
4918             } else {                       // (X / neg) op neg
4919               LoBound = Prod;
4920               LoOverflow = HiOverflow = ProdOV;
4921               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4922             }
4923
4924             // Dividing by a negate swaps the condition.
4925             predicate = ICmpInst::getSwappedPredicate(predicate);
4926           }
4927
4928           if (LoBound) {
4929             Value *X = LHSI->getOperand(0);
4930             switch (predicate) {
4931             default: assert(0 && "Unhandled icmp opcode!");
4932             case ICmpInst::ICMP_EQ:
4933               if (LoOverflow && HiOverflow)
4934                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4935               else if (HiOverflow)
4936                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4937                                     ICmpInst::ICMP_UGE, X, LoBound);
4938               else if (LoOverflow)
4939                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4940                                     ICmpInst::ICMP_ULT, X, HiBound);
4941               else
4942                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4943                                        true, I);
4944             case ICmpInst::ICMP_NE:
4945               if (LoOverflow && HiOverflow)
4946                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4947               else if (HiOverflow)
4948                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4949                                     ICmpInst::ICMP_ULT, X, LoBound);
4950               else if (LoOverflow)
4951                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4952                                     ICmpInst::ICMP_UGE, X, HiBound);
4953               else
4954                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4955                                        false, I);
4956             case ICmpInst::ICMP_ULT:
4957             case ICmpInst::ICMP_SLT:
4958               if (LoOverflow)
4959                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4960               return new ICmpInst(predicate, X, LoBound);
4961             case ICmpInst::ICMP_UGT:
4962             case ICmpInst::ICMP_SGT:
4963               if (HiOverflow)
4964                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4965               if (predicate == ICmpInst::ICMP_UGT)
4966                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4967               else
4968                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4969             }
4970           }
4971         }
4972         break;
4973       }
4974
4975     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4976     if (I.isEquality()) {
4977       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4978
4979       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4980       // the second operand is a constant, simplify a bit.
4981       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4982         switch (BO->getOpcode()) {
4983         case Instruction::SRem:
4984           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4985           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4986               BO->hasOneUse()) {
4987             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4988             if (V > 1 && isPowerOf2_64(V)) {
4989               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4990                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4991               return new ICmpInst(I.getPredicate(), NewRem, 
4992                                   Constant::getNullValue(BO->getType()));
4993             }
4994           }
4995           break;
4996         case Instruction::Add:
4997           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4998           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4999             if (BO->hasOneUse())
5000               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5001                                   ConstantExpr::getSub(CI, BOp1C));
5002           } else if (CI->isNullValue()) {
5003             // Replace ((add A, B) != 0) with (A != -B) if A or B is
5004             // efficiently invertible, or if the add has just this one use.
5005             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5006
5007             if (Value *NegVal = dyn_castNegVal(BOp1))
5008               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5009             else if (Value *NegVal = dyn_castNegVal(BOp0))
5010               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5011             else if (BO->hasOneUse()) {
5012               Instruction *Neg = BinaryOperator::createNeg(BOp1);
5013               InsertNewInstBefore(Neg, I);
5014               Neg->takeName(BO);
5015               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5016             }
5017           }
5018           break;
5019         case Instruction::Xor:
5020           // For the xor case, we can xor two constants together, eliminating
5021           // the explicit xor.
5022           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5023             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5024                                 ConstantExpr::getXor(CI, BOC));
5025
5026           // FALLTHROUGH
5027         case Instruction::Sub:
5028           // Replace (([sub|xor] A, B) != 0) with (A != B)
5029           if (CI->isNullValue())
5030             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5031                                 BO->getOperand(1));
5032           break;
5033
5034         case Instruction::Or:
5035           // If bits are being or'd in that are not present in the constant we
5036           // are comparing against, then the comparison could never succeed!
5037           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5038             Constant *NotCI = ConstantExpr::getNot(CI);
5039             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5040               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5041                                                              isICMP_NE));
5042           }
5043           break;
5044
5045         case Instruction::And:
5046           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5047             // If bits are being compared against that are and'd out, then the
5048             // comparison can never succeed!
5049             if (!ConstantExpr::getAnd(CI,
5050                                       ConstantExpr::getNot(BOC))->isNullValue())
5051               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5052                                                              isICMP_NE));
5053
5054             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5055             if (CI == BOC && isOneBitSet(CI))
5056               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5057                                   ICmpInst::ICMP_NE, Op0,
5058                                   Constant::getNullValue(CI->getType()));
5059
5060             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5061             if (isSignBit(BOC)) {
5062               Value *X = BO->getOperand(0);
5063               Constant *Zero = Constant::getNullValue(X->getType());
5064               ICmpInst::Predicate pred = isICMP_NE ? 
5065                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5066               return new ICmpInst(pred, X, Zero);
5067             }
5068
5069             // ((X & ~7) == 0) --> X < 8
5070             if (CI->isNullValue() && isHighOnes(BOC)) {
5071               Value *X = BO->getOperand(0);
5072               Constant *NegX = ConstantExpr::getNeg(BOC);
5073               ICmpInst::Predicate pred = isICMP_NE ? 
5074                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5075               return new ICmpInst(pred, X, NegX);
5076             }
5077
5078           }
5079         default: break;
5080         }
5081       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5082         // Handle set{eq|ne} <intrinsic>, intcst.
5083         switch (II->getIntrinsicID()) {
5084         default: break;
5085         case Intrinsic::bswap_i16: 
5086           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5087           AddToWorkList(II);  // Dead?
5088           I.setOperand(0, II->getOperand(1));
5089           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5090                                            ByteSwap_16(CI->getZExtValue())));
5091           return &I;
5092         case Intrinsic::bswap_i32:   
5093           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5094           AddToWorkList(II);  // Dead?
5095           I.setOperand(0, II->getOperand(1));
5096           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5097                                            ByteSwap_32(CI->getZExtValue())));
5098           return &I;
5099         case Intrinsic::bswap_i64:   
5100           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5101           AddToWorkList(II);  // Dead?
5102           I.setOperand(0, II->getOperand(1));
5103           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5104                                            ByteSwap_64(CI->getZExtValue())));
5105           return &I;
5106         }
5107       }
5108     } else {  // Not a ICMP_EQ/ICMP_NE
5109       // If the LHS is a cast from an integral value of the same size, then 
5110       // since we know the RHS is a constant, try to simlify.
5111       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5112         Value *CastOp = Cast->getOperand(0);
5113         const Type *SrcTy = CastOp->getType();
5114         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5115         if (SrcTy->isInteger() && 
5116             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5117           // If this is an unsigned comparison, try to make the comparison use
5118           // smaller constant values.
5119           switch (I.getPredicate()) {
5120             default: break;
5121             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5122               ConstantInt *CUI = cast<ConstantInt>(CI);
5123               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5124                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5125                                     ConstantInt::get(SrcTy, -1ULL));
5126               break;
5127             }
5128             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5129               ConstantInt *CUI = cast<ConstantInt>(CI);
5130               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5131                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5132                                     Constant::getNullValue(SrcTy));
5133               break;
5134             }
5135           }
5136
5137         }
5138       }
5139     }
5140   }
5141
5142   // Handle icmp with constant RHS
5143   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5144     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5145       switch (LHSI->getOpcode()) {
5146       case Instruction::GetElementPtr:
5147         if (RHSC->isNullValue()) {
5148           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5149           bool isAllZeros = true;
5150           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5151             if (!isa<Constant>(LHSI->getOperand(i)) ||
5152                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5153               isAllZeros = false;
5154               break;
5155             }
5156           if (isAllZeros)
5157             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5158                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5159         }
5160         break;
5161
5162       case Instruction::PHI:
5163         if (Instruction *NV = FoldOpIntoPhi(I))
5164           return NV;
5165         break;
5166       case Instruction::Select:
5167         // If either operand of the select is a constant, we can fold the
5168         // comparison into the select arms, which will cause one to be
5169         // constant folded and the select turned into a bitwise or.
5170         Value *Op1 = 0, *Op2 = 0;
5171         if (LHSI->hasOneUse()) {
5172           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5173             // Fold the known value into the constant operand.
5174             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5175             // Insert a new ICmp of the other select operand.
5176             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5177                                                    LHSI->getOperand(2), RHSC,
5178                                                    I.getName()), I);
5179           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5180             // Fold the known value into the constant operand.
5181             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5182             // Insert a new ICmp of the other select operand.
5183             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5184                                                    LHSI->getOperand(1), RHSC,
5185                                                    I.getName()), I);
5186           }
5187         }
5188
5189         if (Op1)
5190           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5191         break;
5192       }
5193   }
5194
5195   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5196   if (User *GEP = dyn_castGetElementPtr(Op0))
5197     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5198       return NI;
5199   if (User *GEP = dyn_castGetElementPtr(Op1))
5200     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5201                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5202       return NI;
5203
5204   // Test to see if the operands of the icmp are casted versions of other
5205   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5206   // now.
5207   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5208     if (isa<PointerType>(Op0->getType()) && 
5209         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5210       // We keep moving the cast from the left operand over to the right
5211       // operand, where it can often be eliminated completely.
5212       Op0 = CI->getOperand(0);
5213
5214       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5215       // so eliminate it as well.
5216       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5217         Op1 = CI2->getOperand(0);
5218
5219       // If Op1 is a constant, we can fold the cast into the constant.
5220       if (Op0->getType() != Op1->getType())
5221         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5222           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5223         } else {
5224           // Otherwise, cast the RHS right before the icmp
5225           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5226         }
5227       return new ICmpInst(I.getPredicate(), Op0, Op1);
5228     }
5229   }
5230   
5231   if (isa<CastInst>(Op0)) {
5232     // Handle the special case of: icmp (cast bool to X), <cst>
5233     // This comes up when you have code like
5234     //   int X = A < B;
5235     //   if (X) ...
5236     // For generality, we handle any zero-extension of any operand comparison
5237     // with a constant or another cast from the same type.
5238     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5239       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5240         return R;
5241   }
5242   
5243   if (I.isEquality()) {
5244     Value *A, *B, *C, *D;
5245     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5246       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5247         Value *OtherVal = A == Op1 ? B : A;
5248         return new ICmpInst(I.getPredicate(), OtherVal,
5249                             Constant::getNullValue(A->getType()));
5250       }
5251
5252       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5253         // A^c1 == C^c2 --> A == C^(c1^c2)
5254         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5255           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5256             if (Op1->hasOneUse()) {
5257               Constant *NC = ConstantExpr::getXor(C1, C2);
5258               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5259               return new ICmpInst(I.getPredicate(), A,
5260                                   InsertNewInstBefore(Xor, I));
5261             }
5262         
5263         // A^B == A^D -> B == D
5264         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5265         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5266         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5267         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5268       }
5269     }
5270     
5271     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5272         (A == Op0 || B == Op0)) {
5273       // A == (A^B)  ->  B == 0
5274       Value *OtherVal = A == Op0 ? B : A;
5275       return new ICmpInst(I.getPredicate(), OtherVal,
5276                           Constant::getNullValue(A->getType()));
5277     }
5278     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5279       // (A-B) == A  ->  B == 0
5280       return new ICmpInst(I.getPredicate(), B,
5281                           Constant::getNullValue(B->getType()));
5282     }
5283     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5284       // A == (A-B)  ->  B == 0
5285       return new ICmpInst(I.getPredicate(), B,
5286                           Constant::getNullValue(B->getType()));
5287     }
5288     
5289     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5290     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5291         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5292         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5293       Value *X = 0, *Y = 0, *Z = 0;
5294       
5295       if (A == C) {
5296         X = B; Y = D; Z = A;
5297       } else if (A == D) {
5298         X = B; Y = C; Z = A;
5299       } else if (B == C) {
5300         X = A; Y = D; Z = B;
5301       } else if (B == D) {
5302         X = A; Y = C; Z = B;
5303       }
5304       
5305       if (X) {   // Build (X^Y) & Z
5306         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5307         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5308         I.setOperand(0, Op1);
5309         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5310         return &I;
5311       }
5312     }
5313   }
5314   return Changed ? &I : 0;
5315 }
5316
5317 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5318 // We only handle extending casts so far.
5319 //
5320 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5321   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5322   Value *LHSCIOp        = LHSCI->getOperand(0);
5323   const Type *SrcTy     = LHSCIOp->getType();
5324   const Type *DestTy    = LHSCI->getType();
5325   Value *RHSCIOp;
5326
5327   // We only handle extension cast instructions, so far. Enforce this.
5328   if (LHSCI->getOpcode() != Instruction::ZExt &&
5329       LHSCI->getOpcode() != Instruction::SExt)
5330     return 0;
5331
5332   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5333   bool isSignedCmp = ICI.isSignedPredicate();
5334
5335   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5336     // Not an extension from the same type?
5337     RHSCIOp = CI->getOperand(0);
5338     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5339       return 0;
5340     
5341     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5342     // and the other is a zext), then we can't handle this.
5343     if (CI->getOpcode() != LHSCI->getOpcode())
5344       return 0;
5345
5346     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5347     // then we can't handle this.
5348     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5349       return 0;
5350     
5351     // Okay, just insert a compare of the reduced operands now!
5352     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5353   }
5354
5355   // If we aren't dealing with a constant on the RHS, exit early
5356   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5357   if (!CI)
5358     return 0;
5359
5360   // Compute the constant that would happen if we truncated to SrcTy then
5361   // reextended to DestTy.
5362   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5363   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5364
5365   // If the re-extended constant didn't change...
5366   if (Res2 == CI) {
5367     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5368     // For example, we might have:
5369     //    %A = sext short %X to uint
5370     //    %B = icmp ugt uint %A, 1330
5371     // It is incorrect to transform this into 
5372     //    %B = icmp ugt short %X, 1330 
5373     // because %A may have negative value. 
5374     //
5375     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5376     // OR operation is EQ/NE.
5377     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5378       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5379     else
5380       return 0;
5381   }
5382
5383   // The re-extended constant changed so the constant cannot be represented 
5384   // in the shorter type. Consequently, we cannot emit a simple comparison.
5385
5386   // First, handle some easy cases. We know the result cannot be equal at this
5387   // point so handle the ICI.isEquality() cases
5388   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5389     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5390   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5391     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5392
5393   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5394   // should have been folded away previously and not enter in here.
5395   Value *Result;
5396   if (isSignedCmp) {
5397     // We're performing a signed comparison.
5398     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5399       Result = ConstantInt::getFalse();          // X < (small) --> false
5400     else
5401       Result = ConstantInt::getTrue();           // X < (large) --> true
5402   } else {
5403     // We're performing an unsigned comparison.
5404     if (isSignedExt) {
5405       // We're performing an unsigned comp with a sign extended value.
5406       // This is true if the input is >= 0. [aka >s -1]
5407       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5408       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5409                                    NegOne, ICI.getName()), ICI);
5410     } else {
5411       // Unsigned extend & unsigned compare -> always true.
5412       Result = ConstantInt::getTrue();
5413     }
5414   }
5415
5416   // Finally, return the value computed.
5417   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5418       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5419     return ReplaceInstUsesWith(ICI, Result);
5420   } else {
5421     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5422             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5423            "ICmp should be folded!");
5424     if (Constant *CI = dyn_cast<Constant>(Result))
5425       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5426     else
5427       return BinaryOperator::createNot(Result);
5428   }
5429 }
5430
5431 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5432   return commonShiftTransforms(I);
5433 }
5434
5435 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5436   return commonShiftTransforms(I);
5437 }
5438
5439 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5440   return commonShiftTransforms(I);
5441 }
5442
5443 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5444   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5445   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5446
5447   // shl X, 0 == X and shr X, 0 == X
5448   // shl 0, X == 0 and shr 0, X == 0
5449   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5450       Op0 == Constant::getNullValue(Op0->getType()))
5451     return ReplaceInstUsesWith(I, Op0);
5452   
5453   if (isa<UndefValue>(Op0)) {            
5454     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5455       return ReplaceInstUsesWith(I, Op0);
5456     else                                    // undef << X -> 0, undef >>u X -> 0
5457       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5458   }
5459   if (isa<UndefValue>(Op1)) {
5460     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5461       return ReplaceInstUsesWith(I, Op0);          
5462     else                                     // X << undef, X >>u undef -> 0
5463       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5464   }
5465
5466   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5467   if (I.getOpcode() == Instruction::AShr)
5468     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5469       if (CSI->isAllOnesValue())
5470         return ReplaceInstUsesWith(I, CSI);
5471
5472   // Try to fold constant and into select arguments.
5473   if (isa<Constant>(Op0))
5474     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5475       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5476         return R;
5477
5478   // See if we can turn a signed shr into an unsigned shr.
5479   if (I.isArithmeticShift()) {
5480     if (MaskedValueIsZero(Op0,
5481                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5482       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5483     }
5484   }
5485
5486   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5487     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5488       return Res;
5489   return 0;
5490 }
5491
5492 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5493                                                BinaryOperator &I) {
5494   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5495
5496   // See if we can simplify any instructions used by the instruction whose sole 
5497   // purpose is to compute bits we don't care about.
5498   uint64_t KnownZero, KnownOne;
5499   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5500                            KnownZero, KnownOne))
5501     return &I;
5502   
5503   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5504   // of a signed value.
5505   //
5506   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5507   if (Op1->getZExtValue() >= TypeBits) {
5508     if (I.getOpcode() != Instruction::AShr)
5509       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5510     else {
5511       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5512       return &I;
5513     }
5514   }
5515   
5516   // ((X*C1) << C2) == (X * (C1 << C2))
5517   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5518     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5519       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5520         return BinaryOperator::createMul(BO->getOperand(0),
5521                                          ConstantExpr::getShl(BOOp, Op1));
5522   
5523   // Try to fold constant and into select arguments.
5524   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5525     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5526       return R;
5527   if (isa<PHINode>(Op0))
5528     if (Instruction *NV = FoldOpIntoPhi(I))
5529       return NV;
5530   
5531   if (Op0->hasOneUse()) {
5532     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5533       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5534       Value *V1, *V2;
5535       ConstantInt *CC;
5536       switch (Op0BO->getOpcode()) {
5537         default: break;
5538         case Instruction::Add:
5539         case Instruction::And:
5540         case Instruction::Or:
5541         case Instruction::Xor: {
5542           // These operators commute.
5543           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5544           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5545               match(Op0BO->getOperand(1),
5546                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5547             Instruction *YS = BinaryOperator::createShl(
5548                                             Op0BO->getOperand(0), Op1,
5549                                             Op0BO->getName());
5550             InsertNewInstBefore(YS, I); // (Y << C)
5551             Instruction *X = 
5552               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5553                                      Op0BO->getOperand(1)->getName());
5554             InsertNewInstBefore(X, I);  // (X + (Y << C))
5555             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5556             C2 = ConstantExpr::getShl(C2, Op1);
5557             return BinaryOperator::createAnd(X, C2);
5558           }
5559           
5560           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5561           Value *Op0BOOp1 = Op0BO->getOperand(1);
5562           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5563               match(Op0BOOp1, 
5564                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5565               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5566               V2 == Op1) {
5567             Instruction *YS = BinaryOperator::createShl(
5568                                                      Op0BO->getOperand(0), Op1,
5569                                                      Op0BO->getName());
5570             InsertNewInstBefore(YS, I); // (Y << C)
5571             Instruction *XM =
5572               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5573                                         V1->getName()+".mask");
5574             InsertNewInstBefore(XM, I); // X & (CC << C)
5575             
5576             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5577           }
5578         }
5579           
5580         // FALL THROUGH.
5581         case Instruction::Sub: {
5582           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5583           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5584               match(Op0BO->getOperand(0),
5585                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5586             Instruction *YS = BinaryOperator::createShl(
5587                                                      Op0BO->getOperand(1), Op1,
5588                                                      Op0BO->getName());
5589             InsertNewInstBefore(YS, I); // (Y << C)
5590             Instruction *X =
5591               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5592                                      Op0BO->getOperand(0)->getName());
5593             InsertNewInstBefore(X, I);  // (X + (Y << C))
5594             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5595             C2 = ConstantExpr::getShl(C2, Op1);
5596             return BinaryOperator::createAnd(X, C2);
5597           }
5598           
5599           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5600           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5601               match(Op0BO->getOperand(0),
5602                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5603                           m_ConstantInt(CC))) && V2 == Op1 &&
5604               cast<BinaryOperator>(Op0BO->getOperand(0))
5605                   ->getOperand(0)->hasOneUse()) {
5606             Instruction *YS = BinaryOperator::createShl(
5607                                                      Op0BO->getOperand(1), Op1,
5608                                                      Op0BO->getName());
5609             InsertNewInstBefore(YS, I); // (Y << C)
5610             Instruction *XM =
5611               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5612                                         V1->getName()+".mask");
5613             InsertNewInstBefore(XM, I); // X & (CC << C)
5614             
5615             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5616           }
5617           
5618           break;
5619         }
5620       }
5621       
5622       
5623       // If the operand is an bitwise operator with a constant RHS, and the
5624       // shift is the only use, we can pull it out of the shift.
5625       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5626         bool isValid = true;     // Valid only for And, Or, Xor
5627         bool highBitSet = false; // Transform if high bit of constant set?
5628         
5629         switch (Op0BO->getOpcode()) {
5630           default: isValid = false; break;   // Do not perform transform!
5631           case Instruction::Add:
5632             isValid = isLeftShift;
5633             break;
5634           case Instruction::Or:
5635           case Instruction::Xor:
5636             highBitSet = false;
5637             break;
5638           case Instruction::And:
5639             highBitSet = true;
5640             break;
5641         }
5642         
5643         // If this is a signed shift right, and the high bit is modified
5644         // by the logical operation, do not perform the transformation.
5645         // The highBitSet boolean indicates the value of the high bit of
5646         // the constant which would cause it to be modified for this
5647         // operation.
5648         //
5649         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5650           uint64_t Val = Op0C->getZExtValue();
5651           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5652         }
5653         
5654         if (isValid) {
5655           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5656           
5657           Instruction *NewShift =
5658             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5659           InsertNewInstBefore(NewShift, I);
5660           NewShift->takeName(Op0BO);
5661           
5662           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5663                                         NewRHS);
5664         }
5665       }
5666     }
5667   }
5668   
5669   // Find out if this is a shift of a shift by a constant.
5670   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5671   if (ShiftOp && !ShiftOp->isShift())
5672     ShiftOp = 0;
5673   
5674   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5675     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5676     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5677     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5678     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5679     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5680     Value *X = ShiftOp->getOperand(0);
5681     
5682     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5683     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5684       AmtSum = I.getType()->getPrimitiveSizeInBits();
5685     
5686     const IntegerType *Ty = cast<IntegerType>(I.getType());
5687     
5688     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5689     if (I.getOpcode() == ShiftOp->getOpcode()) {
5690       return BinaryOperator::create(I.getOpcode(), X,
5691                                     ConstantInt::get(Ty, AmtSum));
5692     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5693                I.getOpcode() == Instruction::AShr) {
5694       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5695       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5696     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5697                I.getOpcode() == Instruction::LShr) {
5698       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5699       Instruction *Shift =
5700         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5701       InsertNewInstBefore(Shift, I);
5702
5703       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5704       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5705     }
5706     
5707     // Okay, if we get here, one shift must be left, and the other shift must be
5708     // right.  See if the amounts are equal.
5709     if (ShiftAmt1 == ShiftAmt2) {
5710       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5711       if (I.getOpcode() == Instruction::Shl) {
5712         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
5713         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5714       }
5715       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5716       if (I.getOpcode() == Instruction::LShr) {
5717         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
5718         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5719       }
5720       // We can simplify ((X << C) >>s C) into a trunc + sext.
5721       // NOTE: we could do this for any C, but that would make 'unusual' integer
5722       // types.  For now, just stick to ones well-supported by the code
5723       // generators.
5724       const Type *SExtType = 0;
5725       switch (Ty->getBitWidth() - ShiftAmt1) {
5726       case 8 : SExtType = Type::Int8Ty; break;
5727       case 16: SExtType = Type::Int16Ty; break;
5728       case 32: SExtType = Type::Int32Ty; break;
5729       default: break;
5730       }
5731       if (SExtType) {
5732         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5733         InsertNewInstBefore(NewTrunc, I);
5734         return new SExtInst(NewTrunc, Ty);
5735       }
5736       // Otherwise, we can't handle it yet.
5737     } else if (ShiftAmt1 < ShiftAmt2) {
5738       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
5739       
5740       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5741       if (I.getOpcode() == Instruction::Shl) {
5742         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5743                ShiftOp->getOpcode() == Instruction::AShr);
5744         Instruction *Shift =
5745           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5746         InsertNewInstBefore(Shift, I);
5747         
5748         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5749         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5750       }
5751       
5752       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
5753       if (I.getOpcode() == Instruction::LShr) {
5754         assert(ShiftOp->getOpcode() == Instruction::Shl);
5755         Instruction *Shift =
5756           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5757         InsertNewInstBefore(Shift, I);
5758         
5759         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5760         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5761       }
5762       
5763       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5764     } else {
5765       assert(ShiftAmt2 < ShiftAmt1);
5766       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5767
5768       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
5769       if (I.getOpcode() == Instruction::Shl) {
5770         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5771                ShiftOp->getOpcode() == Instruction::AShr);
5772         Instruction *Shift =
5773           BinaryOperator::create(ShiftOp->getOpcode(), X,
5774                                  ConstantInt::get(Ty, ShiftDiff));
5775         InsertNewInstBefore(Shift, I);
5776         
5777         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5778         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5779       }
5780       
5781       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
5782       if (I.getOpcode() == Instruction::LShr) {
5783         assert(ShiftOp->getOpcode() == Instruction::Shl);
5784         Instruction *Shift =
5785           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5786         InsertNewInstBefore(Shift, I);
5787         
5788         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5789         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5790       }
5791       
5792       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
5793     }
5794   }
5795   return 0;
5796 }
5797
5798
5799 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5800 /// expression.  If so, decompose it, returning some value X, such that Val is
5801 /// X*Scale+Offset.
5802 ///
5803 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5804                                         unsigned &Offset) {
5805   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5806   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5807     Offset = CI->getZExtValue();
5808     Scale  = 1;
5809     return ConstantInt::get(Type::Int32Ty, 0);
5810   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5811     if (I->getNumOperands() == 2) {
5812       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5813         if (I->getOpcode() == Instruction::Shl) {
5814           // This is a value scaled by '1 << the shift amt'.
5815           Scale = 1U << CUI->getZExtValue();
5816           Offset = 0;
5817           return I->getOperand(0);
5818         } else if (I->getOpcode() == Instruction::Mul) {
5819           // This value is scaled by 'CUI'.
5820           Scale = CUI->getZExtValue();
5821           Offset = 0;
5822           return I->getOperand(0);
5823         } else if (I->getOpcode() == Instruction::Add) {
5824           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5825           // where C1 is divisible by C2.
5826           unsigned SubScale;
5827           Value *SubVal = 
5828             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5829           Offset += CUI->getZExtValue();
5830           if (SubScale > 1 && (Offset % SubScale == 0)) {
5831             Scale = SubScale;
5832             return SubVal;
5833           }
5834         }
5835       }
5836     }
5837   }
5838
5839   // Otherwise, we can't look past this.
5840   Scale = 1;
5841   Offset = 0;
5842   return Val;
5843 }
5844
5845
5846 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5847 /// try to eliminate the cast by moving the type information into the alloc.
5848 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5849                                                    AllocationInst &AI) {
5850   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5851   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5852   
5853   // Remove any uses of AI that are dead.
5854   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5855   
5856   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5857     Instruction *User = cast<Instruction>(*UI++);
5858     if (isInstructionTriviallyDead(User)) {
5859       while (UI != E && *UI == User)
5860         ++UI; // If this instruction uses AI more than once, don't break UI.
5861       
5862       ++NumDeadInst;
5863       DOUT << "IC: DCE: " << *User;
5864       EraseInstFromFunction(*User);
5865     }
5866   }
5867   
5868   // Get the type really allocated and the type casted to.
5869   const Type *AllocElTy = AI.getAllocatedType();
5870   const Type *CastElTy = PTy->getElementType();
5871   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5872
5873   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5874   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
5875   if (CastElTyAlign < AllocElTyAlign) return 0;
5876
5877   // If the allocation has multiple uses, only promote it if we are strictly
5878   // increasing the alignment of the resultant allocation.  If we keep it the
5879   // same, we open the door to infinite loops of various kinds.
5880   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5881
5882   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5883   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5884   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5885
5886   // See if we can satisfy the modulus by pulling a scale out of the array
5887   // size argument.
5888   unsigned ArraySizeScale, ArrayOffset;
5889   Value *NumElements = // See if the array size is a decomposable linear expr.
5890     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5891  
5892   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5893   // do the xform.
5894   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5895       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5896
5897   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5898   Value *Amt = 0;
5899   if (Scale == 1) {
5900     Amt = NumElements;
5901   } else {
5902     // If the allocation size is constant, form a constant mul expression
5903     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5904     if (isa<ConstantInt>(NumElements))
5905       Amt = ConstantExpr::getMul(
5906               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5907     // otherwise multiply the amount and the number of elements
5908     else if (Scale != 1) {
5909       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5910       Amt = InsertNewInstBefore(Tmp, AI);
5911     }
5912   }
5913   
5914   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5915     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5916     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5917     Amt = InsertNewInstBefore(Tmp, AI);
5918   }
5919   
5920   AllocationInst *New;
5921   if (isa<MallocInst>(AI))
5922     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
5923   else
5924     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
5925   InsertNewInstBefore(New, AI);
5926   New->takeName(&AI);
5927   
5928   // If the allocation has multiple uses, insert a cast and change all things
5929   // that used it to use the new cast.  This will also hack on CI, but it will
5930   // die soon.
5931   if (!AI.hasOneUse()) {
5932     AddUsesToWorkList(AI);
5933     // New is the allocation instruction, pointer typed. AI is the original
5934     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5935     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5936     InsertNewInstBefore(NewCast, AI);
5937     AI.replaceAllUsesWith(NewCast);
5938   }
5939   return ReplaceInstUsesWith(CI, New);
5940 }
5941
5942 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5943 /// and return it as type Ty without inserting any new casts and without
5944 /// changing the computed value.  This is used by code that tries to decide
5945 /// whether promoting or shrinking integer operations to wider or smaller types
5946 /// will allow us to eliminate a truncate or extend.
5947 ///
5948 /// This is a truncation operation if Ty is smaller than V->getType(), or an
5949 /// extension operation if Ty is larger.
5950 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
5951                                        int &NumCastsRemoved) {
5952   // We can always evaluate constants in another type.
5953   if (isa<ConstantInt>(V))
5954     return true;
5955   
5956   Instruction *I = dyn_cast<Instruction>(V);
5957   if (!I) return false;
5958   
5959   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
5960   
5961   switch (I->getOpcode()) {
5962   case Instruction::Add:
5963   case Instruction::Sub:
5964   case Instruction::And:
5965   case Instruction::Or:
5966   case Instruction::Xor:
5967     if (!I->hasOneUse()) return false;
5968     // These operators can all arbitrarily be extended or truncated.
5969     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5970            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5971
5972   case Instruction::Shl:
5973     if (!I->hasOneUse()) return false;
5974     // If we are truncating the result of this SHL, and if it's a shift of a
5975     // constant amount, we can always perform a SHL in a smaller type.
5976     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5977       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5978           CI->getZExtValue() < Ty->getBitWidth())
5979         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
5980     }
5981     break;
5982   case Instruction::LShr:
5983     if (!I->hasOneUse()) return false;
5984     // If this is a truncate of a logical shr, we can truncate it to a smaller
5985     // lshr iff we know that the bits we would otherwise be shifting in are
5986     // already zeros.
5987     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5988       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5989           MaskedValueIsZero(I->getOperand(0),
5990                             OrigTy->getBitMask() & ~Ty->getBitMask()) &&
5991           CI->getZExtValue() < Ty->getBitWidth()) {
5992         return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5993       }
5994     }
5995     break;
5996   case Instruction::Trunc:
5997   case Instruction::ZExt:
5998   case Instruction::SExt:
5999     // If this is a cast from the destination type, we can trivially eliminate
6000     // it, and this will remove a cast overall.
6001     if (I->getOperand(0)->getType() == Ty) {
6002       // If the first operand is itself a cast, and is eliminable, do not count
6003       // this as an eliminable cast.  We would prefer to eliminate those two
6004       // casts first.
6005       if (isa<CastInst>(I->getOperand(0)))
6006         return true;
6007       
6008       ++NumCastsRemoved;
6009       return true;
6010     }
6011     break;
6012   default:
6013     // TODO: Can handle more cases here.
6014     break;
6015   }
6016   
6017   return false;
6018 }
6019
6020 /// EvaluateInDifferentType - Given an expression that 
6021 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6022 /// evaluate the expression.
6023 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6024                                              bool isSigned) {
6025   if (Constant *C = dyn_cast<Constant>(V))
6026     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6027
6028   // Otherwise, it must be an instruction.
6029   Instruction *I = cast<Instruction>(V);
6030   Instruction *Res = 0;
6031   switch (I->getOpcode()) {
6032   case Instruction::Add:
6033   case Instruction::Sub:
6034   case Instruction::And:
6035   case Instruction::Or:
6036   case Instruction::Xor:
6037   case Instruction::AShr:
6038   case Instruction::LShr:
6039   case Instruction::Shl: {
6040     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6041     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6042     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6043                                  LHS, RHS, I->getName());
6044     break;
6045   }    
6046   case Instruction::Trunc:
6047   case Instruction::ZExt:
6048   case Instruction::SExt:
6049   case Instruction::BitCast:
6050     // If the source type of the cast is the type we're trying for then we can
6051     // just return the source. There's no need to insert it because its not new.
6052     if (I->getOperand(0)->getType() == Ty)
6053       return I->getOperand(0);
6054     
6055     // Some other kind of cast, which shouldn't happen, so just ..
6056     // FALL THROUGH
6057   default: 
6058     // TODO: Can handle more cases here.
6059     assert(0 && "Unreachable!");
6060     break;
6061   }
6062   
6063   return InsertNewInstBefore(Res, *I);
6064 }
6065
6066 /// @brief Implement the transforms common to all CastInst visitors.
6067 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6068   Value *Src = CI.getOperand(0);
6069
6070   // Casting undef to anything results in undef so might as just replace it and
6071   // get rid of the cast.
6072   if (isa<UndefValue>(Src))   // cast undef -> undef
6073     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6074
6075   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6076   // eliminate it now.
6077   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6078     if (Instruction::CastOps opc = 
6079         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6080       // The first cast (CSrc) is eliminable so we need to fix up or replace
6081       // the second cast (CI). CSrc will then have a good chance of being dead.
6082       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6083     }
6084   }
6085
6086   // If casting the result of a getelementptr instruction with no offset, turn
6087   // this into a cast of the original pointer!
6088   //
6089   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6090     bool AllZeroOperands = true;
6091     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6092       if (!isa<Constant>(GEP->getOperand(i)) ||
6093           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6094         AllZeroOperands = false;
6095         break;
6096       }
6097     if (AllZeroOperands) {
6098       // Changing the cast operand is usually not a good idea but it is safe
6099       // here because the pointer operand is being replaced with another 
6100       // pointer operand so the opcode doesn't need to change.
6101       CI.setOperand(0, GEP->getOperand(0));
6102       return &CI;
6103     }
6104   }
6105     
6106   // If we are casting a malloc or alloca to a pointer to a type of the same
6107   // size, rewrite the allocation instruction to allocate the "right" type.
6108   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6109     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6110       return V;
6111
6112   // If we are casting a select then fold the cast into the select
6113   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6114     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6115       return NV;
6116
6117   // If we are casting a PHI then fold the cast into the PHI
6118   if (isa<PHINode>(Src))
6119     if (Instruction *NV = FoldOpIntoPhi(CI))
6120       return NV;
6121   
6122   return 0;
6123 }
6124
6125 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6126 /// integer types. This function implements the common transforms for all those
6127 /// cases.
6128 /// @brief Implement the transforms common to CastInst with integer operands
6129 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6130   if (Instruction *Result = commonCastTransforms(CI))
6131     return Result;
6132
6133   Value *Src = CI.getOperand(0);
6134   const Type *SrcTy = Src->getType();
6135   const Type *DestTy = CI.getType();
6136   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6137   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6138
6139   // See if we can simplify any instructions used by the LHS whose sole 
6140   // purpose is to compute bits we don't care about.
6141   uint64_t KnownZero = 0, KnownOne = 0;
6142   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6143                            KnownZero, KnownOne))
6144     return &CI;
6145
6146   // If the source isn't an instruction or has more than one use then we
6147   // can't do anything more. 
6148   Instruction *SrcI = dyn_cast<Instruction>(Src);
6149   if (!SrcI || !Src->hasOneUse())
6150     return 0;
6151
6152   // Attempt to propagate the cast into the instruction for int->int casts.
6153   int NumCastsRemoved = 0;
6154   if (!isa<BitCastInst>(CI) &&
6155       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6156                                  NumCastsRemoved)) {
6157     // If this cast is a truncate, evaluting in a different type always
6158     // eliminates the cast, so it is always a win.  If this is a noop-cast
6159     // this just removes a noop cast which isn't pointful, but simplifies
6160     // the code.  If this is a zero-extension, we need to do an AND to
6161     // maintain the clear top-part of the computation, so we require that
6162     // the input have eliminated at least one cast.  If this is a sign
6163     // extension, we insert two new casts (to do the extension) so we
6164     // require that two casts have been eliminated.
6165     bool DoXForm;
6166     switch (CI.getOpcode()) {
6167     default:
6168       // All the others use floating point so we shouldn't actually 
6169       // get here because of the check above.
6170       assert(0 && "Unknown cast type");
6171     case Instruction::Trunc:
6172       DoXForm = true;
6173       break;
6174     case Instruction::ZExt:
6175       DoXForm = NumCastsRemoved >= 1;
6176       break;
6177     case Instruction::SExt:
6178       DoXForm = NumCastsRemoved >= 2;
6179       break;
6180     case Instruction::BitCast:
6181       DoXForm = false;
6182       break;
6183     }
6184     
6185     if (DoXForm) {
6186       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6187                                            CI.getOpcode() == Instruction::SExt);
6188       assert(Res->getType() == DestTy);
6189       switch (CI.getOpcode()) {
6190       default: assert(0 && "Unknown cast type!");
6191       case Instruction::Trunc:
6192       case Instruction::BitCast:
6193         // Just replace this cast with the result.
6194         return ReplaceInstUsesWith(CI, Res);
6195       case Instruction::ZExt: {
6196         // We need to emit an AND to clear the high bits.
6197         assert(SrcBitSize < DestBitSize && "Not a zext?");
6198         Constant *C = 
6199           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6200         if (DestBitSize < 64)
6201           C = ConstantExpr::getTrunc(C, DestTy);
6202         return BinaryOperator::createAnd(Res, C);
6203       }
6204       case Instruction::SExt:
6205         // We need to emit a cast to truncate, then a cast to sext.
6206         return CastInst::create(Instruction::SExt,
6207             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6208                              CI), DestTy);
6209       }
6210     }
6211   }
6212   
6213   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6214   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6215
6216   switch (SrcI->getOpcode()) {
6217   case Instruction::Add:
6218   case Instruction::Mul:
6219   case Instruction::And:
6220   case Instruction::Or:
6221   case Instruction::Xor:
6222     // If we are discarding information, or just changing the sign, 
6223     // rewrite.
6224     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6225       // Don't insert two casts if they cannot be eliminated.  We allow 
6226       // two casts to be inserted if the sizes are the same.  This could 
6227       // only be converting signedness, which is a noop.
6228       if (DestBitSize == SrcBitSize || 
6229           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6230           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6231         Instruction::CastOps opcode = CI.getOpcode();
6232         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6233         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6234         return BinaryOperator::create(
6235             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6236       }
6237     }
6238
6239     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6240     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6241         SrcI->getOpcode() == Instruction::Xor &&
6242         Op1 == ConstantInt::getTrue() &&
6243         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6244       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6245       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6246     }
6247     break;
6248   case Instruction::SDiv:
6249   case Instruction::UDiv:
6250   case Instruction::SRem:
6251   case Instruction::URem:
6252     // If we are just changing the sign, rewrite.
6253     if (DestBitSize == SrcBitSize) {
6254       // Don't insert two casts if they cannot be eliminated.  We allow 
6255       // two casts to be inserted if the sizes are the same.  This could 
6256       // only be converting signedness, which is a noop.
6257       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6258           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6259         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6260                                               Op0, DestTy, SrcI);
6261         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6262                                               Op1, DestTy, SrcI);
6263         return BinaryOperator::create(
6264           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6265       }
6266     }
6267     break;
6268
6269   case Instruction::Shl:
6270     // Allow changing the sign of the source operand.  Do not allow 
6271     // changing the size of the shift, UNLESS the shift amount is a 
6272     // constant.  We must not change variable sized shifts to a smaller 
6273     // size, because it is undefined to shift more bits out than exist 
6274     // in the value.
6275     if (DestBitSize == SrcBitSize ||
6276         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6277       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6278           Instruction::BitCast : Instruction::Trunc);
6279       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6280       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6281       return BinaryOperator::createShl(Op0c, Op1c);
6282     }
6283     break;
6284   case Instruction::AShr:
6285     // If this is a signed shr, and if all bits shifted in are about to be
6286     // truncated off, turn it into an unsigned shr to allow greater
6287     // simplifications.
6288     if (DestBitSize < SrcBitSize &&
6289         isa<ConstantInt>(Op1)) {
6290       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6291       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6292         // Insert the new logical shift right.
6293         return BinaryOperator::createLShr(Op0, Op1);
6294       }
6295     }
6296     break;
6297
6298   case Instruction::ICmp:
6299     // If we are just checking for a icmp eq of a single bit and casting it
6300     // to an integer, then shift the bit to the appropriate place and then
6301     // cast to integer to avoid the comparison.
6302     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6303       uint64_t Op1CV = Op1C->getZExtValue();
6304       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6305       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6306       // cast (X == 1) to int --> X        iff X has only the low bit set.
6307       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6308       // cast (X != 0) to int --> X        iff X has only the low bit set.
6309       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6310       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6311       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6312       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6313         // If Op1C some other power of two, convert:
6314         uint64_t KnownZero, KnownOne;
6315         uint64_t TypeMask = Op1C->getType()->getBitMask();
6316         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6317
6318         // This only works for EQ and NE
6319         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6320         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6321           break;
6322         
6323         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6324           bool isNE = pred == ICmpInst::ICMP_NE;
6325           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6326             // (X&4) == 2 --> false
6327             // (X&4) != 2 --> true
6328             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6329             Res = ConstantExpr::getZExt(Res, CI.getType());
6330             return ReplaceInstUsesWith(CI, Res);
6331           }
6332           
6333           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6334           Value *In = Op0;
6335           if (ShiftAmt) {
6336             // Perform a logical shr by shiftamt.
6337             // Insert the shift to put the result in the low bit.
6338             In = InsertNewInstBefore(
6339               BinaryOperator::createLShr(In,
6340                                      ConstantInt::get(In->getType(), ShiftAmt),
6341                                      In->getName()+".lobit"), CI);
6342           }
6343           
6344           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6345             Constant *One = ConstantInt::get(In->getType(), 1);
6346             In = BinaryOperator::createXor(In, One, "tmp");
6347             InsertNewInstBefore(cast<Instruction>(In), CI);
6348           }
6349           
6350           if (CI.getType() == In->getType())
6351             return ReplaceInstUsesWith(CI, In);
6352           else
6353             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6354         }
6355       }
6356     }
6357     break;
6358   }
6359   return 0;
6360 }
6361
6362 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6363   if (Instruction *Result = commonIntCastTransforms(CI))
6364     return Result;
6365   
6366   Value *Src = CI.getOperand(0);
6367   const Type *Ty = CI.getType();
6368   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6369   
6370   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6371     switch (SrcI->getOpcode()) {
6372     default: break;
6373     case Instruction::LShr:
6374       // We can shrink lshr to something smaller if we know the bits shifted in
6375       // are already zeros.
6376       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6377         unsigned ShAmt = ShAmtV->getZExtValue();
6378         
6379         // Get a mask for the bits shifting in.
6380         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6381         Value* SrcIOp0 = SrcI->getOperand(0);
6382         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6383           if (ShAmt >= DestBitWidth)        // All zeros.
6384             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6385
6386           // Okay, we can shrink this.  Truncate the input, then return a new
6387           // shift.
6388           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6389           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6390                                        Ty, CI);
6391           return BinaryOperator::createLShr(V1, V2);
6392         }
6393       } else {     // This is a variable shr.
6394         
6395         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6396         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6397         // loop-invariant and CSE'd.
6398         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6399           Value *One = ConstantInt::get(SrcI->getType(), 1);
6400
6401           Value *V = InsertNewInstBefore(
6402               BinaryOperator::createShl(One, SrcI->getOperand(1),
6403                                      "tmp"), CI);
6404           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6405                                                             SrcI->getOperand(0),
6406                                                             "tmp"), CI);
6407           Value *Zero = Constant::getNullValue(V->getType());
6408           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6409         }
6410       }
6411       break;
6412     }
6413   }
6414   
6415   return 0;
6416 }
6417
6418 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6419   // If one of the common conversion will work ..
6420   if (Instruction *Result = commonIntCastTransforms(CI))
6421     return Result;
6422
6423   Value *Src = CI.getOperand(0);
6424
6425   // If this is a cast of a cast
6426   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6427     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6428     // types and if the sizes are just right we can convert this into a logical
6429     // 'and' which will be much cheaper than the pair of casts.
6430     if (isa<TruncInst>(CSrc)) {
6431       // Get the sizes of the types involved
6432       Value *A = CSrc->getOperand(0);
6433       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6434       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6435       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6436       // If we're actually extending zero bits and the trunc is a no-op
6437       if (MidSize < DstSize && SrcSize == DstSize) {
6438         // Replace both of the casts with an And of the type mask.
6439         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6440         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6441         Instruction *And = 
6442           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6443         // Unfortunately, if the type changed, we need to cast it back.
6444         if (And->getType() != CI.getType()) {
6445           And->setName(CSrc->getName()+".mask");
6446           InsertNewInstBefore(And, CI);
6447           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6448         }
6449         return And;
6450       }
6451     }
6452   }
6453
6454   return 0;
6455 }
6456
6457 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6458   return commonIntCastTransforms(CI);
6459 }
6460
6461 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6462   return commonCastTransforms(CI);
6463 }
6464
6465 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6466   return commonCastTransforms(CI);
6467 }
6468
6469 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6470   return commonCastTransforms(CI);
6471 }
6472
6473 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6474   return commonCastTransforms(CI);
6475 }
6476
6477 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6478   return commonCastTransforms(CI);
6479 }
6480
6481 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6482   return commonCastTransforms(CI);
6483 }
6484
6485 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6486   return commonCastTransforms(CI);
6487 }
6488
6489 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6490   return commonCastTransforms(CI);
6491 }
6492
6493 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6494
6495   // If the operands are integer typed then apply the integer transforms,
6496   // otherwise just apply the common ones.
6497   Value *Src = CI.getOperand(0);
6498   const Type *SrcTy = Src->getType();
6499   const Type *DestTy = CI.getType();
6500
6501   if (SrcTy->isInteger() && DestTy->isInteger()) {
6502     if (Instruction *Result = commonIntCastTransforms(CI))
6503       return Result;
6504   } else {
6505     if (Instruction *Result = commonCastTransforms(CI))
6506       return Result;
6507   }
6508
6509
6510   // Get rid of casts from one type to the same type. These are useless and can
6511   // be replaced by the operand.
6512   if (DestTy == Src->getType())
6513     return ReplaceInstUsesWith(CI, Src);
6514
6515   // If the source and destination are pointers, and this cast is equivalent to
6516   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6517   // This can enhance SROA and other transforms that want type-safe pointers.
6518   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6519     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6520       const Type *DstElTy = DstPTy->getElementType();
6521       const Type *SrcElTy = SrcPTy->getElementType();
6522       
6523       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6524       unsigned NumZeros = 0;
6525       while (SrcElTy != DstElTy && 
6526              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6527              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6528         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6529         ++NumZeros;
6530       }
6531
6532       // If we found a path from the src to dest, create the getelementptr now.
6533       if (SrcElTy == DstElTy) {
6534         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6535         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6536       }
6537     }
6538   }
6539
6540   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6541     if (SVI->hasOneUse()) {
6542       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6543       // a bitconvert to a vector with the same # elts.
6544       if (isa<VectorType>(DestTy) && 
6545           cast<VectorType>(DestTy)->getNumElements() == 
6546                 SVI->getType()->getNumElements()) {
6547         CastInst *Tmp;
6548         // If either of the operands is a cast from CI.getType(), then
6549         // evaluating the shuffle in the casted destination's type will allow
6550         // us to eliminate at least one cast.
6551         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6552              Tmp->getOperand(0)->getType() == DestTy) ||
6553             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6554              Tmp->getOperand(0)->getType() == DestTy)) {
6555           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6556                                                SVI->getOperand(0), DestTy, &CI);
6557           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6558                                                SVI->getOperand(1), DestTy, &CI);
6559           // Return a new shuffle vector.  Use the same element ID's, as we
6560           // know the vector types match #elts.
6561           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6562         }
6563       }
6564     }
6565   }
6566   return 0;
6567 }
6568
6569 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6570 ///   %C = or %A, %B
6571 ///   %D = select %cond, %C, %A
6572 /// into:
6573 ///   %C = select %cond, %B, 0
6574 ///   %D = or %A, %C
6575 ///
6576 /// Assuming that the specified instruction is an operand to the select, return
6577 /// a bitmask indicating which operands of this instruction are foldable if they
6578 /// equal the other incoming value of the select.
6579 ///
6580 static unsigned GetSelectFoldableOperands(Instruction *I) {
6581   switch (I->getOpcode()) {
6582   case Instruction::Add:
6583   case Instruction::Mul:
6584   case Instruction::And:
6585   case Instruction::Or:
6586   case Instruction::Xor:
6587     return 3;              // Can fold through either operand.
6588   case Instruction::Sub:   // Can only fold on the amount subtracted.
6589   case Instruction::Shl:   // Can only fold on the shift amount.
6590   case Instruction::LShr:
6591   case Instruction::AShr:
6592     return 1;
6593   default:
6594     return 0;              // Cannot fold
6595   }
6596 }
6597
6598 /// GetSelectFoldableConstant - For the same transformation as the previous
6599 /// function, return the identity constant that goes into the select.
6600 static Constant *GetSelectFoldableConstant(Instruction *I) {
6601   switch (I->getOpcode()) {
6602   default: assert(0 && "This cannot happen!"); abort();
6603   case Instruction::Add:
6604   case Instruction::Sub:
6605   case Instruction::Or:
6606   case Instruction::Xor:
6607   case Instruction::Shl:
6608   case Instruction::LShr:
6609   case Instruction::AShr:
6610     return Constant::getNullValue(I->getType());
6611   case Instruction::And:
6612     return ConstantInt::getAllOnesValue(I->getType());
6613   case Instruction::Mul:
6614     return ConstantInt::get(I->getType(), 1);
6615   }
6616 }
6617
6618 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6619 /// have the same opcode and only one use each.  Try to simplify this.
6620 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6621                                           Instruction *FI) {
6622   if (TI->getNumOperands() == 1) {
6623     // If this is a non-volatile load or a cast from the same type,
6624     // merge.
6625     if (TI->isCast()) {
6626       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6627         return 0;
6628     } else {
6629       return 0;  // unknown unary op.
6630     }
6631
6632     // Fold this by inserting a select from the input values.
6633     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6634                                        FI->getOperand(0), SI.getName()+".v");
6635     InsertNewInstBefore(NewSI, SI);
6636     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6637                             TI->getType());
6638   }
6639
6640   // Only handle binary operators here.
6641   if (!isa<BinaryOperator>(TI))
6642     return 0;
6643
6644   // Figure out if the operations have any operands in common.
6645   Value *MatchOp, *OtherOpT, *OtherOpF;
6646   bool MatchIsOpZero;
6647   if (TI->getOperand(0) == FI->getOperand(0)) {
6648     MatchOp  = TI->getOperand(0);
6649     OtherOpT = TI->getOperand(1);
6650     OtherOpF = FI->getOperand(1);
6651     MatchIsOpZero = true;
6652   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6653     MatchOp  = TI->getOperand(1);
6654     OtherOpT = TI->getOperand(0);
6655     OtherOpF = FI->getOperand(0);
6656     MatchIsOpZero = false;
6657   } else if (!TI->isCommutative()) {
6658     return 0;
6659   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6660     MatchOp  = TI->getOperand(0);
6661     OtherOpT = TI->getOperand(1);
6662     OtherOpF = FI->getOperand(0);
6663     MatchIsOpZero = true;
6664   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6665     MatchOp  = TI->getOperand(1);
6666     OtherOpT = TI->getOperand(0);
6667     OtherOpF = FI->getOperand(1);
6668     MatchIsOpZero = true;
6669   } else {
6670     return 0;
6671   }
6672
6673   // If we reach here, they do have operations in common.
6674   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6675                                      OtherOpF, SI.getName()+".v");
6676   InsertNewInstBefore(NewSI, SI);
6677
6678   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6679     if (MatchIsOpZero)
6680       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6681     else
6682       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6683   }
6684   assert(0 && "Shouldn't get here");
6685   return 0;
6686 }
6687
6688 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6689   Value *CondVal = SI.getCondition();
6690   Value *TrueVal = SI.getTrueValue();
6691   Value *FalseVal = SI.getFalseValue();
6692
6693   // select true, X, Y  -> X
6694   // select false, X, Y -> Y
6695   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6696     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6697
6698   // select C, X, X -> X
6699   if (TrueVal == FalseVal)
6700     return ReplaceInstUsesWith(SI, TrueVal);
6701
6702   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6703     return ReplaceInstUsesWith(SI, FalseVal);
6704   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6705     return ReplaceInstUsesWith(SI, TrueVal);
6706   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6707     if (isa<Constant>(TrueVal))
6708       return ReplaceInstUsesWith(SI, TrueVal);
6709     else
6710       return ReplaceInstUsesWith(SI, FalseVal);
6711   }
6712
6713   if (SI.getType() == Type::Int1Ty) {
6714     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6715       if (C->getZExtValue()) {
6716         // Change: A = select B, true, C --> A = or B, C
6717         return BinaryOperator::createOr(CondVal, FalseVal);
6718       } else {
6719         // Change: A = select B, false, C --> A = and !B, C
6720         Value *NotCond =
6721           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6722                                              "not."+CondVal->getName()), SI);
6723         return BinaryOperator::createAnd(NotCond, FalseVal);
6724       }
6725     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6726       if (C->getZExtValue() == false) {
6727         // Change: A = select B, C, false --> A = and B, C
6728         return BinaryOperator::createAnd(CondVal, TrueVal);
6729       } else {
6730         // Change: A = select B, C, true --> A = or !B, C
6731         Value *NotCond =
6732           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6733                                              "not."+CondVal->getName()), SI);
6734         return BinaryOperator::createOr(NotCond, TrueVal);
6735       }
6736     }
6737   }
6738
6739   // Selecting between two integer constants?
6740   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6741     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6742       // select C, 1, 0 -> cast C to int
6743       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6744         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6745       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6746         // select C, 0, 1 -> cast !C to int
6747         Value *NotCond =
6748           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6749                                                "not."+CondVal->getName()), SI);
6750         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6751       }
6752
6753       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6754
6755         // (x <s 0) ? -1 : 0 -> ashr x, 31
6756         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6757         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6758           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6759             bool CanXForm = false;
6760             if (IC->isSignedPredicate())
6761               CanXForm = CmpCst->isNullValue() && 
6762                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6763             else {
6764               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6765               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6766                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6767             }
6768             
6769             if (CanXForm) {
6770               // The comparison constant and the result are not neccessarily the
6771               // same width. Make an all-ones value by inserting a AShr.
6772               Value *X = IC->getOperand(0);
6773               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6774               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6775               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6776                                                         ShAmt, "ones");
6777               InsertNewInstBefore(SRA, SI);
6778               
6779               // Finally, convert to the type of the select RHS.  We figure out
6780               // if this requires a SExt, Trunc or BitCast based on the sizes.
6781               Instruction::CastOps opc = Instruction::BitCast;
6782               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6783               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6784               if (SRASize < SISize)
6785                 opc = Instruction::SExt;
6786               else if (SRASize > SISize)
6787                 opc = Instruction::Trunc;
6788               return CastInst::create(opc, SRA, SI.getType());
6789             }
6790           }
6791
6792
6793         // If one of the constants is zero (we know they can't both be) and we
6794         // have a fcmp instruction with zero, and we have an 'and' with the
6795         // non-constant value, eliminate this whole mess.  This corresponds to
6796         // cases like this: ((X & 27) ? 27 : 0)
6797         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6798           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6799               cast<Constant>(IC->getOperand(1))->isNullValue())
6800             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6801               if (ICA->getOpcode() == Instruction::And &&
6802                   isa<ConstantInt>(ICA->getOperand(1)) &&
6803                   (ICA->getOperand(1) == TrueValC ||
6804                    ICA->getOperand(1) == FalseValC) &&
6805                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6806                 // Okay, now we know that everything is set up, we just don't
6807                 // know whether we have a icmp_ne or icmp_eq and whether the 
6808                 // true or false val is the zero.
6809                 bool ShouldNotVal = !TrueValC->isNullValue();
6810                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6811                 Value *V = ICA;
6812                 if (ShouldNotVal)
6813                   V = InsertNewInstBefore(BinaryOperator::create(
6814                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6815                 return ReplaceInstUsesWith(SI, V);
6816               }
6817       }
6818     }
6819
6820   // See if we are selecting two values based on a comparison of the two values.
6821   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6822     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6823       // Transform (X == Y) ? X : Y  -> Y
6824       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6825         return ReplaceInstUsesWith(SI, FalseVal);
6826       // Transform (X != Y) ? X : Y  -> X
6827       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6828         return ReplaceInstUsesWith(SI, TrueVal);
6829       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6830
6831     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6832       // Transform (X == Y) ? Y : X  -> X
6833       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6834         return ReplaceInstUsesWith(SI, FalseVal);
6835       // Transform (X != Y) ? Y : X  -> Y
6836       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6837         return ReplaceInstUsesWith(SI, TrueVal);
6838       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6839     }
6840   }
6841
6842   // See if we are selecting two values based on a comparison of the two values.
6843   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6844     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6845       // Transform (X == Y) ? X : Y  -> Y
6846       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6847         return ReplaceInstUsesWith(SI, FalseVal);
6848       // Transform (X != Y) ? X : Y  -> X
6849       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6850         return ReplaceInstUsesWith(SI, TrueVal);
6851       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6852
6853     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6854       // Transform (X == Y) ? Y : X  -> X
6855       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6856         return ReplaceInstUsesWith(SI, FalseVal);
6857       // Transform (X != Y) ? Y : X  -> Y
6858       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6859         return ReplaceInstUsesWith(SI, TrueVal);
6860       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6861     }
6862   }
6863
6864   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6865     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6866       if (TI->hasOneUse() && FI->hasOneUse()) {
6867         Instruction *AddOp = 0, *SubOp = 0;
6868
6869         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6870         if (TI->getOpcode() == FI->getOpcode())
6871           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6872             return IV;
6873
6874         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6875         // even legal for FP.
6876         if (TI->getOpcode() == Instruction::Sub &&
6877             FI->getOpcode() == Instruction::Add) {
6878           AddOp = FI; SubOp = TI;
6879         } else if (FI->getOpcode() == Instruction::Sub &&
6880                    TI->getOpcode() == Instruction::Add) {
6881           AddOp = TI; SubOp = FI;
6882         }
6883
6884         if (AddOp) {
6885           Value *OtherAddOp = 0;
6886           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6887             OtherAddOp = AddOp->getOperand(1);
6888           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6889             OtherAddOp = AddOp->getOperand(0);
6890           }
6891
6892           if (OtherAddOp) {
6893             // So at this point we know we have (Y -> OtherAddOp):
6894             //        select C, (add X, Y), (sub X, Z)
6895             Value *NegVal;  // Compute -Z
6896             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6897               NegVal = ConstantExpr::getNeg(C);
6898             } else {
6899               NegVal = InsertNewInstBefore(
6900                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6901             }
6902
6903             Value *NewTrueOp = OtherAddOp;
6904             Value *NewFalseOp = NegVal;
6905             if (AddOp != TI)
6906               std::swap(NewTrueOp, NewFalseOp);
6907             Instruction *NewSel =
6908               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6909
6910             NewSel = InsertNewInstBefore(NewSel, SI);
6911             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6912           }
6913         }
6914       }
6915
6916   // See if we can fold the select into one of our operands.
6917   if (SI.getType()->isInteger()) {
6918     // See the comment above GetSelectFoldableOperands for a description of the
6919     // transformation we are doing here.
6920     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6921       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6922           !isa<Constant>(FalseVal))
6923         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6924           unsigned OpToFold = 0;
6925           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6926             OpToFold = 1;
6927           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6928             OpToFold = 2;
6929           }
6930
6931           if (OpToFold) {
6932             Constant *C = GetSelectFoldableConstant(TVI);
6933             Instruction *NewSel =
6934               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
6935             InsertNewInstBefore(NewSel, SI);
6936             NewSel->takeName(TVI);
6937             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6938               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6939             else {
6940               assert(0 && "Unknown instruction!!");
6941             }
6942           }
6943         }
6944
6945     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6946       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6947           !isa<Constant>(TrueVal))
6948         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6949           unsigned OpToFold = 0;
6950           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6951             OpToFold = 1;
6952           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6953             OpToFold = 2;
6954           }
6955
6956           if (OpToFold) {
6957             Constant *C = GetSelectFoldableConstant(FVI);
6958             Instruction *NewSel =
6959               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
6960             InsertNewInstBefore(NewSel, SI);
6961             NewSel->takeName(FVI);
6962             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6963               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6964             else
6965               assert(0 && "Unknown instruction!!");
6966           }
6967         }
6968   }
6969
6970   if (BinaryOperator::isNot(CondVal)) {
6971     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6972     SI.setOperand(1, FalseVal);
6973     SI.setOperand(2, TrueVal);
6974     return &SI;
6975   }
6976
6977   return 0;
6978 }
6979
6980 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6981 /// determine, return it, otherwise return 0.
6982 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6983   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6984     unsigned Align = GV->getAlignment();
6985     if (Align == 0 && TD) 
6986       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
6987     return Align;
6988   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6989     unsigned Align = AI->getAlignment();
6990     if (Align == 0 && TD) {
6991       if (isa<AllocaInst>(AI))
6992         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
6993       else if (isa<MallocInst>(AI)) {
6994         // Malloc returns maximally aligned memory.
6995         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
6996         Align =
6997           std::max(Align,
6998                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
6999         Align =
7000           std::max(Align,
7001                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7002       }
7003     }
7004     return Align;
7005   } else if (isa<BitCastInst>(V) ||
7006              (isa<ConstantExpr>(V) && 
7007               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7008     User *CI = cast<User>(V);
7009     if (isa<PointerType>(CI->getOperand(0)->getType()))
7010       return GetKnownAlignment(CI->getOperand(0), TD);
7011     return 0;
7012   } else if (isa<GetElementPtrInst>(V) ||
7013              (isa<ConstantExpr>(V) && 
7014               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7015     User *GEPI = cast<User>(V);
7016     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7017     if (BaseAlignment == 0) return 0;
7018     
7019     // If all indexes are zero, it is just the alignment of the base pointer.
7020     bool AllZeroOperands = true;
7021     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7022       if (!isa<Constant>(GEPI->getOperand(i)) ||
7023           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7024         AllZeroOperands = false;
7025         break;
7026       }
7027     if (AllZeroOperands)
7028       return BaseAlignment;
7029     
7030     // Otherwise, if the base alignment is >= the alignment we expect for the
7031     // base pointer type, then we know that the resultant pointer is aligned at
7032     // least as much as its type requires.
7033     if (!TD) return 0;
7034
7035     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7036     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7037     if (TD->getABITypeAlignment(PtrTy->getElementType())
7038         <= BaseAlignment) {
7039       const Type *GEPTy = GEPI->getType();
7040       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7041       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7042     }
7043     return 0;
7044   }
7045   return 0;
7046 }
7047
7048
7049 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7050 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7051 /// the heavy lifting.
7052 ///
7053 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7054   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7055   if (!II) return visitCallSite(&CI);
7056   
7057   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7058   // visitCallSite.
7059   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7060     bool Changed = false;
7061
7062     // memmove/cpy/set of zero bytes is a noop.
7063     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7064       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7065
7066       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7067         if (CI->getZExtValue() == 1) {
7068           // Replace the instruction with just byte operations.  We would
7069           // transform other cases to loads/stores, but we don't know if
7070           // alignment is sufficient.
7071         }
7072     }
7073
7074     // If we have a memmove and the source operation is a constant global,
7075     // then the source and dest pointers can't alias, so we can change this
7076     // into a call to memcpy.
7077     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7078       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7079         if (GVSrc->isConstant()) {
7080           Module *M = CI.getParent()->getParent()->getParent();
7081           const char *Name;
7082           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7083               Type::Int32Ty)
7084             Name = "llvm.memcpy.i32";
7085           else
7086             Name = "llvm.memcpy.i64";
7087           Constant *MemCpy = M->getOrInsertFunction(Name,
7088                                      CI.getCalledFunction()->getFunctionType());
7089           CI.setOperand(0, MemCpy);
7090           Changed = true;
7091         }
7092     }
7093
7094     // If we can determine a pointer alignment that is bigger than currently
7095     // set, update the alignment.
7096     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7097       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7098       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7099       unsigned Align = std::min(Alignment1, Alignment2);
7100       if (MI->getAlignment()->getZExtValue() < Align) {
7101         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7102         Changed = true;
7103       }
7104     } else if (isa<MemSetInst>(MI)) {
7105       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7106       if (MI->getAlignment()->getZExtValue() < Alignment) {
7107         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7108         Changed = true;
7109       }
7110     }
7111           
7112     if (Changed) return II;
7113   } else {
7114     switch (II->getIntrinsicID()) {
7115     default: break;
7116     case Intrinsic::ppc_altivec_lvx:
7117     case Intrinsic::ppc_altivec_lvxl:
7118     case Intrinsic::x86_sse_loadu_ps:
7119     case Intrinsic::x86_sse2_loadu_pd:
7120     case Intrinsic::x86_sse2_loadu_dq:
7121       // Turn PPC lvx     -> load if the pointer is known aligned.
7122       // Turn X86 loadups -> load if the pointer is known aligned.
7123       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7124         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7125                                       PointerType::get(II->getType()), CI);
7126         return new LoadInst(Ptr);
7127       }
7128       break;
7129     case Intrinsic::ppc_altivec_stvx:
7130     case Intrinsic::ppc_altivec_stvxl:
7131       // Turn stvx -> store if the pointer is known aligned.
7132       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7133         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7134         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7135                                       OpPtrTy, CI);
7136         return new StoreInst(II->getOperand(1), Ptr);
7137       }
7138       break;
7139     case Intrinsic::x86_sse_storeu_ps:
7140     case Intrinsic::x86_sse2_storeu_pd:
7141     case Intrinsic::x86_sse2_storeu_dq:
7142     case Intrinsic::x86_sse2_storel_dq:
7143       // Turn X86 storeu -> store if the pointer is known aligned.
7144       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7145         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7146         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7147                                       OpPtrTy, CI);
7148         return new StoreInst(II->getOperand(2), Ptr);
7149       }
7150       break;
7151       
7152     case Intrinsic::x86_sse_cvttss2si: {
7153       // These intrinsics only demands the 0th element of its input vector.  If
7154       // we can simplify the input based on that, do so now.
7155       uint64_t UndefElts;
7156       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7157                                                 UndefElts)) {
7158         II->setOperand(1, V);
7159         return II;
7160       }
7161       break;
7162     }
7163       
7164     case Intrinsic::ppc_altivec_vperm:
7165       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7166       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7167         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7168         
7169         // Check that all of the elements are integer constants or undefs.
7170         bool AllEltsOk = true;
7171         for (unsigned i = 0; i != 16; ++i) {
7172           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7173               !isa<UndefValue>(Mask->getOperand(i))) {
7174             AllEltsOk = false;
7175             break;
7176           }
7177         }
7178         
7179         if (AllEltsOk) {
7180           // Cast the input vectors to byte vectors.
7181           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7182                                         II->getOperand(1), Mask->getType(), CI);
7183           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7184                                         II->getOperand(2), Mask->getType(), CI);
7185           Value *Result = UndefValue::get(Op0->getType());
7186           
7187           // Only extract each element once.
7188           Value *ExtractedElts[32];
7189           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7190           
7191           for (unsigned i = 0; i != 16; ++i) {
7192             if (isa<UndefValue>(Mask->getOperand(i)))
7193               continue;
7194             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7195             Idx &= 31;  // Match the hardware behavior.
7196             
7197             if (ExtractedElts[Idx] == 0) {
7198               Instruction *Elt = 
7199                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7200               InsertNewInstBefore(Elt, CI);
7201               ExtractedElts[Idx] = Elt;
7202             }
7203           
7204             // Insert this value into the result vector.
7205             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7206             InsertNewInstBefore(cast<Instruction>(Result), CI);
7207           }
7208           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7209         }
7210       }
7211       break;
7212
7213     case Intrinsic::stackrestore: {
7214       // If the save is right next to the restore, remove the restore.  This can
7215       // happen when variable allocas are DCE'd.
7216       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7217         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7218           BasicBlock::iterator BI = SS;
7219           if (&*++BI == II)
7220             return EraseInstFromFunction(CI);
7221         }
7222       }
7223       
7224       // If the stack restore is in a return/unwind block and if there are no
7225       // allocas or calls between the restore and the return, nuke the restore.
7226       TerminatorInst *TI = II->getParent()->getTerminator();
7227       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7228         BasicBlock::iterator BI = II;
7229         bool CannotRemove = false;
7230         for (++BI; &*BI != TI; ++BI) {
7231           if (isa<AllocaInst>(BI) ||
7232               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7233             CannotRemove = true;
7234             break;
7235           }
7236         }
7237         if (!CannotRemove)
7238           return EraseInstFromFunction(CI);
7239       }
7240       break;
7241     }
7242     }
7243   }
7244
7245   return visitCallSite(II);
7246 }
7247
7248 // InvokeInst simplification
7249 //
7250 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7251   return visitCallSite(&II);
7252 }
7253
7254 // visitCallSite - Improvements for call and invoke instructions.
7255 //
7256 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7257   bool Changed = false;
7258
7259   // If the callee is a constexpr cast of a function, attempt to move the cast
7260   // to the arguments of the call/invoke.
7261   if (transformConstExprCastCall(CS)) return 0;
7262
7263   Value *Callee = CS.getCalledValue();
7264
7265   if (Function *CalleeF = dyn_cast<Function>(Callee))
7266     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7267       Instruction *OldCall = CS.getInstruction();
7268       // If the call and callee calling conventions don't match, this call must
7269       // be unreachable, as the call is undefined.
7270       new StoreInst(ConstantInt::getTrue(),
7271                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7272       if (!OldCall->use_empty())
7273         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7274       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7275         return EraseInstFromFunction(*OldCall);
7276       return 0;
7277     }
7278
7279   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7280     // This instruction is not reachable, just remove it.  We insert a store to
7281     // undef so that we know that this code is not reachable, despite the fact
7282     // that we can't modify the CFG here.
7283     new StoreInst(ConstantInt::getTrue(),
7284                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7285                   CS.getInstruction());
7286
7287     if (!CS.getInstruction()->use_empty())
7288       CS.getInstruction()->
7289         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7290
7291     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7292       // Don't break the CFG, insert a dummy cond branch.
7293       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7294                      ConstantInt::getTrue(), II);
7295     }
7296     return EraseInstFromFunction(*CS.getInstruction());
7297   }
7298
7299   const PointerType *PTy = cast<PointerType>(Callee->getType());
7300   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7301   if (FTy->isVarArg()) {
7302     // See if we can optimize any arguments passed through the varargs area of
7303     // the call.
7304     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7305            E = CS.arg_end(); I != E; ++I)
7306       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7307         // If this cast does not effect the value passed through the varargs
7308         // area, we can eliminate the use of the cast.
7309         Value *Op = CI->getOperand(0);
7310         if (CI->isLosslessCast()) {
7311           *I = Op;
7312           Changed = true;
7313         }
7314       }
7315   }
7316
7317   return Changed ? CS.getInstruction() : 0;
7318 }
7319
7320 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7321 // attempt to move the cast to the arguments of the call/invoke.
7322 //
7323 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7324   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7325   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7326   if (CE->getOpcode() != Instruction::BitCast || 
7327       !isa<Function>(CE->getOperand(0)))
7328     return false;
7329   Function *Callee = cast<Function>(CE->getOperand(0));
7330   Instruction *Caller = CS.getInstruction();
7331
7332   // Okay, this is a cast from a function to a different type.  Unless doing so
7333   // would cause a type conversion of one of our arguments, change this call to
7334   // be a direct call with arguments casted to the appropriate types.
7335   //
7336   const FunctionType *FT = Callee->getFunctionType();
7337   const Type *OldRetTy = Caller->getType();
7338
7339   // Check to see if we are changing the return type...
7340   if (OldRetTy != FT->getReturnType()) {
7341     if (Callee->isDeclaration() && !Caller->use_empty() && 
7342         OldRetTy != FT->getReturnType() &&
7343         // Conversion is ok if changing from pointer to int of same size.
7344         !(isa<PointerType>(FT->getReturnType()) &&
7345           TD->getIntPtrType() == OldRetTy))
7346       return false;   // Cannot transform this return value.
7347
7348     // If the callsite is an invoke instruction, and the return value is used by
7349     // a PHI node in a successor, we cannot change the return type of the call
7350     // because there is no place to put the cast instruction (without breaking
7351     // the critical edge).  Bail out in this case.
7352     if (!Caller->use_empty())
7353       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7354         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7355              UI != E; ++UI)
7356           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7357             if (PN->getParent() == II->getNormalDest() ||
7358                 PN->getParent() == II->getUnwindDest())
7359               return false;
7360   }
7361
7362   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7363   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7364
7365   CallSite::arg_iterator AI = CS.arg_begin();
7366   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7367     const Type *ParamTy = FT->getParamType(i);
7368     const Type *ActTy = (*AI)->getType();
7369     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7370     //Either we can cast directly, or we can upconvert the argument
7371     bool isConvertible = ActTy == ParamTy ||
7372       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7373       (ParamTy->isInteger() && ActTy->isInteger() &&
7374        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7375       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7376        && c->getSExtValue() > 0);
7377     if (Callee->isDeclaration() && !isConvertible) return false;
7378   }
7379
7380   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7381       Callee->isDeclaration())
7382     return false;   // Do not delete arguments unless we have a function body...
7383
7384   // Okay, we decided that this is a safe thing to do: go ahead and start
7385   // inserting cast instructions as necessary...
7386   std::vector<Value*> Args;
7387   Args.reserve(NumActualArgs);
7388
7389   AI = CS.arg_begin();
7390   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7391     const Type *ParamTy = FT->getParamType(i);
7392     if ((*AI)->getType() == ParamTy) {
7393       Args.push_back(*AI);
7394     } else {
7395       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7396           false, ParamTy, false);
7397       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7398       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7399     }
7400   }
7401
7402   // If the function takes more arguments than the call was taking, add them
7403   // now...
7404   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7405     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7406
7407   // If we are removing arguments to the function, emit an obnoxious warning...
7408   if (FT->getNumParams() < NumActualArgs)
7409     if (!FT->isVarArg()) {
7410       cerr << "WARNING: While resolving call to function '"
7411            << Callee->getName() << "' arguments were dropped!\n";
7412     } else {
7413       // Add all of the arguments in their promoted form to the arg list...
7414       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7415         const Type *PTy = getPromotedType((*AI)->getType());
7416         if (PTy != (*AI)->getType()) {
7417           // Must promote to pass through va_arg area!
7418           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7419                                                                 PTy, false);
7420           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7421           InsertNewInstBefore(Cast, *Caller);
7422           Args.push_back(Cast);
7423         } else {
7424           Args.push_back(*AI);
7425         }
7426       }
7427     }
7428
7429   if (FT->getReturnType() == Type::VoidTy)
7430     Caller->setName("");   // Void type should not have a name.
7431
7432   Instruction *NC;
7433   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7434     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7435                         &Args[0], Args.size(), Caller->getName(), Caller);
7436     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7437   } else {
7438     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7439     if (cast<CallInst>(Caller)->isTailCall())
7440       cast<CallInst>(NC)->setTailCall();
7441    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7442   }
7443
7444   // Insert a cast of the return type as necessary.
7445   Value *NV = NC;
7446   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7447     if (NV->getType() != Type::VoidTy) {
7448       const Type *CallerTy = Caller->getType();
7449       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7450                                                             CallerTy, false);
7451       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7452
7453       // If this is an invoke instruction, we should insert it after the first
7454       // non-phi, instruction in the normal successor block.
7455       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7456         BasicBlock::iterator I = II->getNormalDest()->begin();
7457         while (isa<PHINode>(I)) ++I;
7458         InsertNewInstBefore(NC, *I);
7459       } else {
7460         // Otherwise, it's a call, just insert cast right after the call instr
7461         InsertNewInstBefore(NC, *Caller);
7462       }
7463       AddUsersToWorkList(*Caller);
7464     } else {
7465       NV = UndefValue::get(Caller->getType());
7466     }
7467   }
7468
7469   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7470     Caller->replaceAllUsesWith(NV);
7471   Caller->eraseFromParent();
7472   RemoveFromWorkList(Caller);
7473   return true;
7474 }
7475
7476 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7477 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7478 /// and a single binop.
7479 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7480   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7481   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7482          isa<CmpInst>(FirstInst));
7483   unsigned Opc = FirstInst->getOpcode();
7484   Value *LHSVal = FirstInst->getOperand(0);
7485   Value *RHSVal = FirstInst->getOperand(1);
7486     
7487   const Type *LHSType = LHSVal->getType();
7488   const Type *RHSType = RHSVal->getType();
7489   
7490   // Scan to see if all operands are the same opcode, all have one use, and all
7491   // kill their operands (i.e. the operands have one use).
7492   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7493     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7494     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7495         // Verify type of the LHS matches so we don't fold cmp's of different
7496         // types or GEP's with different index types.
7497         I->getOperand(0)->getType() != LHSType ||
7498         I->getOperand(1)->getType() != RHSType)
7499       return 0;
7500
7501     // If they are CmpInst instructions, check their predicates
7502     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7503       if (cast<CmpInst>(I)->getPredicate() !=
7504           cast<CmpInst>(FirstInst)->getPredicate())
7505         return 0;
7506     
7507     // Keep track of which operand needs a phi node.
7508     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7509     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7510   }
7511   
7512   // Otherwise, this is safe to transform, determine if it is profitable.
7513
7514   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7515   // Indexes are often folded into load/store instructions, so we don't want to
7516   // hide them behind a phi.
7517   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7518     return 0;
7519   
7520   Value *InLHS = FirstInst->getOperand(0);
7521   Value *InRHS = FirstInst->getOperand(1);
7522   PHINode *NewLHS = 0, *NewRHS = 0;
7523   if (LHSVal == 0) {
7524     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7525     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7526     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7527     InsertNewInstBefore(NewLHS, PN);
7528     LHSVal = NewLHS;
7529   }
7530   
7531   if (RHSVal == 0) {
7532     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7533     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7534     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7535     InsertNewInstBefore(NewRHS, PN);
7536     RHSVal = NewRHS;
7537   }
7538   
7539   // Add all operands to the new PHIs.
7540   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7541     if (NewLHS) {
7542       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7543       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7544     }
7545     if (NewRHS) {
7546       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7547       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7548     }
7549   }
7550     
7551   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7552     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7553   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7554     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7555                            RHSVal);
7556   else {
7557     assert(isa<GetElementPtrInst>(FirstInst));
7558     return new GetElementPtrInst(LHSVal, RHSVal);
7559   }
7560 }
7561
7562 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7563 /// of the block that defines it.  This means that it must be obvious the value
7564 /// of the load is not changed from the point of the load to the end of the
7565 /// block it is in.
7566 ///
7567 /// Finally, it is safe, but not profitable, to sink a load targetting a
7568 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7569 /// to a register.
7570 static bool isSafeToSinkLoad(LoadInst *L) {
7571   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7572   
7573   for (++BBI; BBI != E; ++BBI)
7574     if (BBI->mayWriteToMemory())
7575       return false;
7576   
7577   // Check for non-address taken alloca.  If not address-taken already, it isn't
7578   // profitable to do this xform.
7579   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7580     bool isAddressTaken = false;
7581     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7582          UI != E; ++UI) {
7583       if (isa<LoadInst>(UI)) continue;
7584       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7585         // If storing TO the alloca, then the address isn't taken.
7586         if (SI->getOperand(1) == AI) continue;
7587       }
7588       isAddressTaken = true;
7589       break;
7590     }
7591     
7592     if (!isAddressTaken)
7593       return false;
7594   }
7595   
7596   return true;
7597 }
7598
7599
7600 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7601 // operator and they all are only used by the PHI, PHI together their
7602 // inputs, and do the operation once, to the result of the PHI.
7603 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7604   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7605
7606   // Scan the instruction, looking for input operations that can be folded away.
7607   // If all input operands to the phi are the same instruction (e.g. a cast from
7608   // the same type or "+42") we can pull the operation through the PHI, reducing
7609   // code size and simplifying code.
7610   Constant *ConstantOp = 0;
7611   const Type *CastSrcTy = 0;
7612   bool isVolatile = false;
7613   if (isa<CastInst>(FirstInst)) {
7614     CastSrcTy = FirstInst->getOperand(0)->getType();
7615   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7616     // Can fold binop, compare or shift here if the RHS is a constant, 
7617     // otherwise call FoldPHIArgBinOpIntoPHI.
7618     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7619     if (ConstantOp == 0)
7620       return FoldPHIArgBinOpIntoPHI(PN);
7621   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7622     isVolatile = LI->isVolatile();
7623     // We can't sink the load if the loaded value could be modified between the
7624     // load and the PHI.
7625     if (LI->getParent() != PN.getIncomingBlock(0) ||
7626         !isSafeToSinkLoad(LI))
7627       return 0;
7628   } else if (isa<GetElementPtrInst>(FirstInst)) {
7629     if (FirstInst->getNumOperands() == 2)
7630       return FoldPHIArgBinOpIntoPHI(PN);
7631     // Can't handle general GEPs yet.
7632     return 0;
7633   } else {
7634     return 0;  // Cannot fold this operation.
7635   }
7636
7637   // Check to see if all arguments are the same operation.
7638   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7639     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7640     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7641     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7642       return 0;
7643     if (CastSrcTy) {
7644       if (I->getOperand(0)->getType() != CastSrcTy)
7645         return 0;  // Cast operation must match.
7646     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7647       // We can't sink the load if the loaded value could be modified between 
7648       // the load and the PHI.
7649       if (LI->isVolatile() != isVolatile ||
7650           LI->getParent() != PN.getIncomingBlock(i) ||
7651           !isSafeToSinkLoad(LI))
7652         return 0;
7653     } else if (I->getOperand(1) != ConstantOp) {
7654       return 0;
7655     }
7656   }
7657
7658   // Okay, they are all the same operation.  Create a new PHI node of the
7659   // correct type, and PHI together all of the LHS's of the instructions.
7660   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7661                                PN.getName()+".in");
7662   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7663
7664   Value *InVal = FirstInst->getOperand(0);
7665   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7666
7667   // Add all operands to the new PHI.
7668   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7669     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7670     if (NewInVal != InVal)
7671       InVal = 0;
7672     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7673   }
7674
7675   Value *PhiVal;
7676   if (InVal) {
7677     // The new PHI unions all of the same values together.  This is really
7678     // common, so we handle it intelligently here for compile-time speed.
7679     PhiVal = InVal;
7680     delete NewPN;
7681   } else {
7682     InsertNewInstBefore(NewPN, PN);
7683     PhiVal = NewPN;
7684   }
7685
7686   // Insert and return the new operation.
7687   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7688     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7689   else if (isa<LoadInst>(FirstInst))
7690     return new LoadInst(PhiVal, "", isVolatile);
7691   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7692     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7693   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7694     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7695                            PhiVal, ConstantOp);
7696   else
7697     assert(0 && "Unknown operation");
7698   return 0;
7699 }
7700
7701 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7702 /// that is dead.
7703 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7704   if (PN->use_empty()) return true;
7705   if (!PN->hasOneUse()) return false;
7706
7707   // Remember this node, and if we find the cycle, return.
7708   if (!PotentiallyDeadPHIs.insert(PN).second)
7709     return true;
7710
7711   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7712     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7713
7714   return false;
7715 }
7716
7717 // PHINode simplification
7718 //
7719 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7720   // If LCSSA is around, don't mess with Phi nodes
7721   if (MustPreserveLCSSA) return 0;
7722   
7723   if (Value *V = PN.hasConstantValue())
7724     return ReplaceInstUsesWith(PN, V);
7725
7726   // If all PHI operands are the same operation, pull them through the PHI,
7727   // reducing code size.
7728   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7729       PN.getIncomingValue(0)->hasOneUse())
7730     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7731       return Result;
7732
7733   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7734   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7735   // PHI)... break the cycle.
7736   if (PN.hasOneUse()) {
7737     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7738     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7739       std::set<PHINode*> PotentiallyDeadPHIs;
7740       PotentiallyDeadPHIs.insert(&PN);
7741       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7742         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7743     }
7744    
7745     // If this phi has a single use, and if that use just computes a value for
7746     // the next iteration of a loop, delete the phi.  This occurs with unused
7747     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7748     // common case here is good because the only other things that catch this
7749     // are induction variable analysis (sometimes) and ADCE, which is only run
7750     // late.
7751     if (PHIUser->hasOneUse() &&
7752         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7753         PHIUser->use_back() == &PN) {
7754       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7755     }
7756   }
7757
7758   return 0;
7759 }
7760
7761 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7762                                    Instruction *InsertPoint,
7763                                    InstCombiner *IC) {
7764   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7765   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7766   // We must cast correctly to the pointer type. Ensure that we
7767   // sign extend the integer value if it is smaller as this is
7768   // used for address computation.
7769   Instruction::CastOps opcode = 
7770      (VTySize < PtrSize ? Instruction::SExt :
7771       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7772   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7773 }
7774
7775
7776 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7777   Value *PtrOp = GEP.getOperand(0);
7778   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7779   // If so, eliminate the noop.
7780   if (GEP.getNumOperands() == 1)
7781     return ReplaceInstUsesWith(GEP, PtrOp);
7782
7783   if (isa<UndefValue>(GEP.getOperand(0)))
7784     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7785
7786   bool HasZeroPointerIndex = false;
7787   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7788     HasZeroPointerIndex = C->isNullValue();
7789
7790   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7791     return ReplaceInstUsesWith(GEP, PtrOp);
7792
7793   // Eliminate unneeded casts for indices.
7794   bool MadeChange = false;
7795   gep_type_iterator GTI = gep_type_begin(GEP);
7796   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7797     if (isa<SequentialType>(*GTI)) {
7798       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7799         if (CI->getOpcode() == Instruction::ZExt ||
7800             CI->getOpcode() == Instruction::SExt) {
7801           const Type *SrcTy = CI->getOperand(0)->getType();
7802           // We can eliminate a cast from i32 to i64 iff the target 
7803           // is a 32-bit pointer target.
7804           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7805             MadeChange = true;
7806             GEP.setOperand(i, CI->getOperand(0));
7807           }
7808         }
7809       }
7810       // If we are using a wider index than needed for this platform, shrink it
7811       // to what we need.  If the incoming value needs a cast instruction,
7812       // insert it.  This explicit cast can make subsequent optimizations more
7813       // obvious.
7814       Value *Op = GEP.getOperand(i);
7815       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7816         if (Constant *C = dyn_cast<Constant>(Op)) {
7817           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7818           MadeChange = true;
7819         } else {
7820           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7821                                 GEP);
7822           GEP.setOperand(i, Op);
7823           MadeChange = true;
7824         }
7825     }
7826   if (MadeChange) return &GEP;
7827
7828   // Combine Indices - If the source pointer to this getelementptr instruction
7829   // is a getelementptr instruction, combine the indices of the two
7830   // getelementptr instructions into a single instruction.
7831   //
7832   SmallVector<Value*, 8> SrcGEPOperands;
7833   if (User *Src = dyn_castGetElementPtr(PtrOp))
7834     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
7835
7836   if (!SrcGEPOperands.empty()) {
7837     // Note that if our source is a gep chain itself that we wait for that
7838     // chain to be resolved before we perform this transformation.  This
7839     // avoids us creating a TON of code in some cases.
7840     //
7841     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7842         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7843       return 0;   // Wait until our source is folded to completion.
7844
7845     SmallVector<Value*, 8> Indices;
7846
7847     // Find out whether the last index in the source GEP is a sequential idx.
7848     bool EndsWithSequential = false;
7849     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7850            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7851       EndsWithSequential = !isa<StructType>(*I);
7852
7853     // Can we combine the two pointer arithmetics offsets?
7854     if (EndsWithSequential) {
7855       // Replace: gep (gep %P, long B), long A, ...
7856       // With:    T = long A+B; gep %P, T, ...
7857       //
7858       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7859       if (SO1 == Constant::getNullValue(SO1->getType())) {
7860         Sum = GO1;
7861       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7862         Sum = SO1;
7863       } else {
7864         // If they aren't the same type, convert both to an integer of the
7865         // target's pointer size.
7866         if (SO1->getType() != GO1->getType()) {
7867           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7868             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7869           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7870             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7871           } else {
7872             unsigned PS = TD->getPointerSize();
7873             if (TD->getTypeSize(SO1->getType()) == PS) {
7874               // Convert GO1 to SO1's type.
7875               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7876
7877             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7878               // Convert SO1 to GO1's type.
7879               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7880             } else {
7881               const Type *PT = TD->getIntPtrType();
7882               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7883               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7884             }
7885           }
7886         }
7887         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7888           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7889         else {
7890           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7891           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7892         }
7893       }
7894
7895       // Recycle the GEP we already have if possible.
7896       if (SrcGEPOperands.size() == 2) {
7897         GEP.setOperand(0, SrcGEPOperands[0]);
7898         GEP.setOperand(1, Sum);
7899         return &GEP;
7900       } else {
7901         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7902                        SrcGEPOperands.end()-1);
7903         Indices.push_back(Sum);
7904         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7905       }
7906     } else if (isa<Constant>(*GEP.idx_begin()) &&
7907                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7908                SrcGEPOperands.size() != 1) {
7909       // Otherwise we can do the fold if the first index of the GEP is a zero
7910       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7911                      SrcGEPOperands.end());
7912       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7913     }
7914
7915     if (!Indices.empty())
7916       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7917                                    Indices.size(), GEP.getName());
7918
7919   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7920     // GEP of global variable.  If all of the indices for this GEP are
7921     // constants, we can promote this to a constexpr instead of an instruction.
7922
7923     // Scan for nonconstants...
7924     SmallVector<Constant*, 8> Indices;
7925     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7926     for (; I != E && isa<Constant>(*I); ++I)
7927       Indices.push_back(cast<Constant>(*I));
7928
7929     if (I == E) {  // If they are all constants...
7930       Constant *CE = ConstantExpr::getGetElementPtr(GV,
7931                                                     &Indices[0],Indices.size());
7932
7933       // Replace all uses of the GEP with the new constexpr...
7934       return ReplaceInstUsesWith(GEP, CE);
7935     }
7936   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7937     if (!isa<PointerType>(X->getType())) {
7938       // Not interesting.  Source pointer must be a cast from pointer.
7939     } else if (HasZeroPointerIndex) {
7940       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7941       // into     : GEP [10 x ubyte]* X, long 0, ...
7942       //
7943       // This occurs when the program declares an array extern like "int X[];"
7944       //
7945       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7946       const PointerType *XTy = cast<PointerType>(X->getType());
7947       if (const ArrayType *XATy =
7948           dyn_cast<ArrayType>(XTy->getElementType()))
7949         if (const ArrayType *CATy =
7950             dyn_cast<ArrayType>(CPTy->getElementType()))
7951           if (CATy->getElementType() == XATy->getElementType()) {
7952             // At this point, we know that the cast source type is a pointer
7953             // to an array of the same type as the destination pointer
7954             // array.  Because the array type is never stepped over (there
7955             // is a leading zero) we can fold the cast into this GEP.
7956             GEP.setOperand(0, X);
7957             return &GEP;
7958           }
7959     } else if (GEP.getNumOperands() == 2) {
7960       // Transform things like:
7961       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7962       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7963       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7964       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7965       if (isa<ArrayType>(SrcElTy) &&
7966           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7967           TD->getTypeSize(ResElTy)) {
7968         Value *V = InsertNewInstBefore(
7969                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7970                                      GEP.getOperand(1), GEP.getName()), GEP);
7971         // V and GEP are both pointer types --> BitCast
7972         return new BitCastInst(V, GEP.getType());
7973       }
7974       
7975       // Transform things like:
7976       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7977       //   (where tmp = 8*tmp2) into:
7978       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7979       
7980       if (isa<ArrayType>(SrcElTy) &&
7981           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7982         uint64_t ArrayEltSize =
7983             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7984         
7985         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7986         // allow either a mul, shift, or constant here.
7987         Value *NewIdx = 0;
7988         ConstantInt *Scale = 0;
7989         if (ArrayEltSize == 1) {
7990           NewIdx = GEP.getOperand(1);
7991           Scale = ConstantInt::get(NewIdx->getType(), 1);
7992         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7993           NewIdx = ConstantInt::get(CI->getType(), 1);
7994           Scale = CI;
7995         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7996           if (Inst->getOpcode() == Instruction::Shl &&
7997               isa<ConstantInt>(Inst->getOperand(1))) {
7998             unsigned ShAmt =
7999               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8000             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8001             NewIdx = Inst->getOperand(0);
8002           } else if (Inst->getOpcode() == Instruction::Mul &&
8003                      isa<ConstantInt>(Inst->getOperand(1))) {
8004             Scale = cast<ConstantInt>(Inst->getOperand(1));
8005             NewIdx = Inst->getOperand(0);
8006           }
8007         }
8008
8009         // If the index will be to exactly the right offset with the scale taken
8010         // out, perform the transformation.
8011         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8012           if (isa<ConstantInt>(Scale))
8013             Scale = ConstantInt::get(Scale->getType(),
8014                                       Scale->getZExtValue() / ArrayEltSize);
8015           if (Scale->getZExtValue() != 1) {
8016             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8017                                                        true /*SExt*/);
8018             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8019             NewIdx = InsertNewInstBefore(Sc, GEP);
8020           }
8021
8022           // Insert the new GEP instruction.
8023           Instruction *NewGEP =
8024             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8025                                   NewIdx, GEP.getName());
8026           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8027           // The NewGEP must be pointer typed, so must the old one -> BitCast
8028           return new BitCastInst(NewGEP, GEP.getType());
8029         }
8030       }
8031     }
8032   }
8033
8034   return 0;
8035 }
8036
8037 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8038   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8039   if (AI.isArrayAllocation())    // Check C != 1
8040     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8041       const Type *NewTy = 
8042         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8043       AllocationInst *New = 0;
8044
8045       // Create and insert the replacement instruction...
8046       if (isa<MallocInst>(AI))
8047         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8048       else {
8049         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8050         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8051       }
8052
8053       InsertNewInstBefore(New, AI);
8054
8055       // Scan to the end of the allocation instructions, to skip over a block of
8056       // allocas if possible...
8057       //
8058       BasicBlock::iterator It = New;
8059       while (isa<AllocationInst>(*It)) ++It;
8060
8061       // Now that I is pointing to the first non-allocation-inst in the block,
8062       // insert our getelementptr instruction...
8063       //
8064       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8065       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8066                                        New->getName()+".sub", It);
8067
8068       // Now make everything use the getelementptr instead of the original
8069       // allocation.
8070       return ReplaceInstUsesWith(AI, V);
8071     } else if (isa<UndefValue>(AI.getArraySize())) {
8072       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8073     }
8074
8075   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8076   // Note that we only do this for alloca's, because malloc should allocate and
8077   // return a unique pointer, even for a zero byte allocation.
8078   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8079       TD->getTypeSize(AI.getAllocatedType()) == 0)
8080     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8081
8082   return 0;
8083 }
8084
8085 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8086   Value *Op = FI.getOperand(0);
8087
8088   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8089   if (CastInst *CI = dyn_cast<CastInst>(Op))
8090     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8091       FI.setOperand(0, CI->getOperand(0));
8092       return &FI;
8093     }
8094
8095   // free undef -> unreachable.
8096   if (isa<UndefValue>(Op)) {
8097     // Insert a new store to null because we cannot modify the CFG here.
8098     new StoreInst(ConstantInt::getTrue(),
8099                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8100     return EraseInstFromFunction(FI);
8101   }
8102
8103   // If we have 'free null' delete the instruction.  This can happen in stl code
8104   // when lots of inlining happens.
8105   if (isa<ConstantPointerNull>(Op))
8106     return EraseInstFromFunction(FI);
8107
8108   return 0;
8109 }
8110
8111
8112 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8113 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8114   User *CI = cast<User>(LI.getOperand(0));
8115   Value *CastOp = CI->getOperand(0);
8116
8117   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8118   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8119     const Type *SrcPTy = SrcTy->getElementType();
8120
8121     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8122          isa<VectorType>(DestPTy)) {
8123       // If the source is an array, the code below will not succeed.  Check to
8124       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8125       // constants.
8126       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8127         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8128           if (ASrcTy->getNumElements() != 0) {
8129             Value *Idxs[2];
8130             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8131             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8132             SrcTy = cast<PointerType>(CastOp->getType());
8133             SrcPTy = SrcTy->getElementType();
8134           }
8135
8136       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8137             isa<VectorType>(SrcPTy)) &&
8138           // Do not allow turning this into a load of an integer, which is then
8139           // casted to a pointer, this pessimizes pointer analysis a lot.
8140           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8141           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8142                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8143
8144         // Okay, we are casting from one integer or pointer type to another of
8145         // the same size.  Instead of casting the pointer before the load, cast
8146         // the result of the loaded value.
8147         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8148                                                              CI->getName(),
8149                                                          LI.isVolatile()),LI);
8150         // Now cast the result of the load.
8151         return new BitCastInst(NewLoad, LI.getType());
8152       }
8153     }
8154   }
8155   return 0;
8156 }
8157
8158 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8159 /// from this value cannot trap.  If it is not obviously safe to load from the
8160 /// specified pointer, we do a quick local scan of the basic block containing
8161 /// ScanFrom, to determine if the address is already accessed.
8162 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8163   // If it is an alloca or global variable, it is always safe to load from.
8164   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8165
8166   // Otherwise, be a little bit agressive by scanning the local block where we
8167   // want to check to see if the pointer is already being loaded or stored
8168   // from/to.  If so, the previous load or store would have already trapped,
8169   // so there is no harm doing an extra load (also, CSE will later eliminate
8170   // the load entirely).
8171   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8172
8173   while (BBI != E) {
8174     --BBI;
8175
8176     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8177       if (LI->getOperand(0) == V) return true;
8178     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8179       if (SI->getOperand(1) == V) return true;
8180
8181   }
8182   return false;
8183 }
8184
8185 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8186   Value *Op = LI.getOperand(0);
8187
8188   // load (cast X) --> cast (load X) iff safe
8189   if (isa<CastInst>(Op))
8190     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8191       return Res;
8192
8193   // None of the following transforms are legal for volatile loads.
8194   if (LI.isVolatile()) return 0;
8195   
8196   if (&LI.getParent()->front() != &LI) {
8197     BasicBlock::iterator BBI = &LI; --BBI;
8198     // If the instruction immediately before this is a store to the same
8199     // address, do a simple form of store->load forwarding.
8200     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8201       if (SI->getOperand(1) == LI.getOperand(0))
8202         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8203     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8204       if (LIB->getOperand(0) == LI.getOperand(0))
8205         return ReplaceInstUsesWith(LI, LIB);
8206   }
8207
8208   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8209     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8210         isa<UndefValue>(GEPI->getOperand(0))) {
8211       // Insert a new store to null instruction before the load to indicate
8212       // that this code is not reachable.  We do this instead of inserting
8213       // an unreachable instruction directly because we cannot modify the
8214       // CFG.
8215       new StoreInst(UndefValue::get(LI.getType()),
8216                     Constant::getNullValue(Op->getType()), &LI);
8217       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8218     }
8219
8220   if (Constant *C = dyn_cast<Constant>(Op)) {
8221     // load null/undef -> undef
8222     if ((C->isNullValue() || isa<UndefValue>(C))) {
8223       // Insert a new store to null instruction before the load to indicate that
8224       // this code is not reachable.  We do this instead of inserting an
8225       // unreachable instruction directly because we cannot modify the CFG.
8226       new StoreInst(UndefValue::get(LI.getType()),
8227                     Constant::getNullValue(Op->getType()), &LI);
8228       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8229     }
8230
8231     // Instcombine load (constant global) into the value loaded.
8232     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8233       if (GV->isConstant() && !GV->isDeclaration())
8234         return ReplaceInstUsesWith(LI, GV->getInitializer());
8235
8236     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8237     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8238       if (CE->getOpcode() == Instruction::GetElementPtr) {
8239         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8240           if (GV->isConstant() && !GV->isDeclaration())
8241             if (Constant *V = 
8242                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8243               return ReplaceInstUsesWith(LI, V);
8244         if (CE->getOperand(0)->isNullValue()) {
8245           // Insert a new store to null instruction before the load to indicate
8246           // that this code is not reachable.  We do this instead of inserting
8247           // an unreachable instruction directly because we cannot modify the
8248           // CFG.
8249           new StoreInst(UndefValue::get(LI.getType()),
8250                         Constant::getNullValue(Op->getType()), &LI);
8251           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8252         }
8253
8254       } else if (CE->isCast()) {
8255         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8256           return Res;
8257       }
8258   }
8259
8260   if (Op->hasOneUse()) {
8261     // Change select and PHI nodes to select values instead of addresses: this
8262     // helps alias analysis out a lot, allows many others simplifications, and
8263     // exposes redundancy in the code.
8264     //
8265     // Note that we cannot do the transformation unless we know that the
8266     // introduced loads cannot trap!  Something like this is valid as long as
8267     // the condition is always false: load (select bool %C, int* null, int* %G),
8268     // but it would not be valid if we transformed it to load from null
8269     // unconditionally.
8270     //
8271     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8272       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8273       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8274           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8275         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8276                                      SI->getOperand(1)->getName()+".val"), LI);
8277         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8278                                      SI->getOperand(2)->getName()+".val"), LI);
8279         return new SelectInst(SI->getCondition(), V1, V2);
8280       }
8281
8282       // load (select (cond, null, P)) -> load P
8283       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8284         if (C->isNullValue()) {
8285           LI.setOperand(0, SI->getOperand(2));
8286           return &LI;
8287         }
8288
8289       // load (select (cond, P, null)) -> load P
8290       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8291         if (C->isNullValue()) {
8292           LI.setOperand(0, SI->getOperand(1));
8293           return &LI;
8294         }
8295     }
8296   }
8297   return 0;
8298 }
8299
8300 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8301 /// when possible.
8302 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8303   User *CI = cast<User>(SI.getOperand(1));
8304   Value *CastOp = CI->getOperand(0);
8305
8306   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8307   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8308     const Type *SrcPTy = SrcTy->getElementType();
8309
8310     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8311       // If the source is an array, the code below will not succeed.  Check to
8312       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8313       // constants.
8314       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8315         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8316           if (ASrcTy->getNumElements() != 0) {
8317             Value* Idxs[2];
8318             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8319             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8320             SrcTy = cast<PointerType>(CastOp->getType());
8321             SrcPTy = SrcTy->getElementType();
8322           }
8323
8324       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8325           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8326                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8327
8328         // Okay, we are casting from one integer or pointer type to another of
8329         // the same size.  Instead of casting the pointer before 
8330         // the store, cast the value to be stored.
8331         Value *NewCast;
8332         Value *SIOp0 = SI.getOperand(0);
8333         Instruction::CastOps opcode = Instruction::BitCast;
8334         const Type* CastSrcTy = SIOp0->getType();
8335         const Type* CastDstTy = SrcPTy;
8336         if (isa<PointerType>(CastDstTy)) {
8337           if (CastSrcTy->isInteger())
8338             opcode = Instruction::IntToPtr;
8339         } else if (isa<IntegerType>(CastDstTy)) {
8340           if (isa<PointerType>(SIOp0->getType()))
8341             opcode = Instruction::PtrToInt;
8342         }
8343         if (Constant *C = dyn_cast<Constant>(SIOp0))
8344           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8345         else
8346           NewCast = IC.InsertNewInstBefore(
8347             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8348             SI);
8349         return new StoreInst(NewCast, CastOp);
8350       }
8351     }
8352   }
8353   return 0;
8354 }
8355
8356 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8357   Value *Val = SI.getOperand(0);
8358   Value *Ptr = SI.getOperand(1);
8359
8360   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8361     EraseInstFromFunction(SI);
8362     ++NumCombined;
8363     return 0;
8364   }
8365   
8366   // If the RHS is an alloca with a single use, zapify the store, making the
8367   // alloca dead.
8368   if (Ptr->hasOneUse()) {
8369     if (isa<AllocaInst>(Ptr)) {
8370       EraseInstFromFunction(SI);
8371       ++NumCombined;
8372       return 0;
8373     }
8374     
8375     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8376       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8377           GEP->getOperand(0)->hasOneUse()) {
8378         EraseInstFromFunction(SI);
8379         ++NumCombined;
8380         return 0;
8381       }
8382   }
8383
8384   // Do really simple DSE, to catch cases where there are several consequtive
8385   // stores to the same location, separated by a few arithmetic operations. This
8386   // situation often occurs with bitfield accesses.
8387   BasicBlock::iterator BBI = &SI;
8388   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8389        --ScanInsts) {
8390     --BBI;
8391     
8392     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8393       // Prev store isn't volatile, and stores to the same location?
8394       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8395         ++NumDeadStore;
8396         ++BBI;
8397         EraseInstFromFunction(*PrevSI);
8398         continue;
8399       }
8400       break;
8401     }
8402     
8403     // If this is a load, we have to stop.  However, if the loaded value is from
8404     // the pointer we're loading and is producing the pointer we're storing,
8405     // then *this* store is dead (X = load P; store X -> P).
8406     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8407       if (LI == Val && LI->getOperand(0) == Ptr) {
8408         EraseInstFromFunction(SI);
8409         ++NumCombined;
8410         return 0;
8411       }
8412       // Otherwise, this is a load from some other location.  Stores before it
8413       // may not be dead.
8414       break;
8415     }
8416     
8417     // Don't skip over loads or things that can modify memory.
8418     if (BBI->mayWriteToMemory())
8419       break;
8420   }
8421   
8422   
8423   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8424
8425   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8426   if (isa<ConstantPointerNull>(Ptr)) {
8427     if (!isa<UndefValue>(Val)) {
8428       SI.setOperand(0, UndefValue::get(Val->getType()));
8429       if (Instruction *U = dyn_cast<Instruction>(Val))
8430         AddToWorkList(U);  // Dropped a use.
8431       ++NumCombined;
8432     }
8433     return 0;  // Do not modify these!
8434   }
8435
8436   // store undef, Ptr -> noop
8437   if (isa<UndefValue>(Val)) {
8438     EraseInstFromFunction(SI);
8439     ++NumCombined;
8440     return 0;
8441   }
8442
8443   // If the pointer destination is a cast, see if we can fold the cast into the
8444   // source instead.
8445   if (isa<CastInst>(Ptr))
8446     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8447       return Res;
8448   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8449     if (CE->isCast())
8450       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8451         return Res;
8452
8453   
8454   // If this store is the last instruction in the basic block, and if the block
8455   // ends with an unconditional branch, try to move it to the successor block.
8456   BBI = &SI; ++BBI;
8457   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8458     if (BI->isUnconditional()) {
8459       // Check to see if the successor block has exactly two incoming edges.  If
8460       // so, see if the other predecessor contains a store to the same location.
8461       // if so, insert a PHI node (if needed) and move the stores down.
8462       BasicBlock *Dest = BI->getSuccessor(0);
8463
8464       pred_iterator PI = pred_begin(Dest);
8465       BasicBlock *Other = 0;
8466       if (*PI != BI->getParent())
8467         Other = *PI;
8468       ++PI;
8469       if (PI != pred_end(Dest)) {
8470         if (*PI != BI->getParent())
8471           if (Other)
8472             Other = 0;
8473           else
8474             Other = *PI;
8475         if (++PI != pred_end(Dest))
8476           Other = 0;
8477       }
8478       if (Other) {  // If only one other pred...
8479         BBI = Other->getTerminator();
8480         // Make sure this other block ends in an unconditional branch and that
8481         // there is an instruction before the branch.
8482         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8483             BBI != Other->begin()) {
8484           --BBI;
8485           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8486           
8487           // If this instruction is a store to the same location.
8488           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8489             // Okay, we know we can perform this transformation.  Insert a PHI
8490             // node now if we need it.
8491             Value *MergedVal = OtherStore->getOperand(0);
8492             if (MergedVal != SI.getOperand(0)) {
8493               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8494               PN->reserveOperandSpace(2);
8495               PN->addIncoming(SI.getOperand(0), SI.getParent());
8496               PN->addIncoming(OtherStore->getOperand(0), Other);
8497               MergedVal = InsertNewInstBefore(PN, Dest->front());
8498             }
8499             
8500             // Advance to a place where it is safe to insert the new store and
8501             // insert it.
8502             BBI = Dest->begin();
8503             while (isa<PHINode>(BBI)) ++BBI;
8504             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8505                                               OtherStore->isVolatile()), *BBI);
8506
8507             // Nuke the old stores.
8508             EraseInstFromFunction(SI);
8509             EraseInstFromFunction(*OtherStore);
8510             ++NumCombined;
8511             return 0;
8512           }
8513         }
8514       }
8515     }
8516   
8517   return 0;
8518 }
8519
8520
8521 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8522   // Change br (not X), label True, label False to: br X, label False, True
8523   Value *X = 0;
8524   BasicBlock *TrueDest;
8525   BasicBlock *FalseDest;
8526   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8527       !isa<Constant>(X)) {
8528     // Swap Destinations and condition...
8529     BI.setCondition(X);
8530     BI.setSuccessor(0, FalseDest);
8531     BI.setSuccessor(1, TrueDest);
8532     return &BI;
8533   }
8534
8535   // Cannonicalize fcmp_one -> fcmp_oeq
8536   FCmpInst::Predicate FPred; Value *Y;
8537   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8538                              TrueDest, FalseDest)))
8539     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8540          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8541       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8542       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8543       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8544       NewSCC->takeName(I);
8545       // Swap Destinations and condition...
8546       BI.setCondition(NewSCC);
8547       BI.setSuccessor(0, FalseDest);
8548       BI.setSuccessor(1, TrueDest);
8549       RemoveFromWorkList(I);
8550       I->eraseFromParent();
8551       AddToWorkList(NewSCC);
8552       return &BI;
8553     }
8554
8555   // Cannonicalize icmp_ne -> icmp_eq
8556   ICmpInst::Predicate IPred;
8557   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8558                       TrueDest, FalseDest)))
8559     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8560          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8561          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8562       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8563       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8564       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8565       NewSCC->takeName(I);
8566       // Swap Destinations and condition...
8567       BI.setCondition(NewSCC);
8568       BI.setSuccessor(0, FalseDest);
8569       BI.setSuccessor(1, TrueDest);
8570       RemoveFromWorkList(I);
8571       I->eraseFromParent();;
8572       AddToWorkList(NewSCC);
8573       return &BI;
8574     }
8575
8576   return 0;
8577 }
8578
8579 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8580   Value *Cond = SI.getCondition();
8581   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8582     if (I->getOpcode() == Instruction::Add)
8583       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8584         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8585         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8586           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8587                                                 AddRHS));
8588         SI.setOperand(0, I->getOperand(0));
8589         AddToWorkList(I);
8590         return &SI;
8591       }
8592   }
8593   return 0;
8594 }
8595
8596 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8597 /// is to leave as a vector operation.
8598 static bool CheapToScalarize(Value *V, bool isConstant) {
8599   if (isa<ConstantAggregateZero>(V)) 
8600     return true;
8601   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
8602     if (isConstant) return true;
8603     // If all elts are the same, we can extract.
8604     Constant *Op0 = C->getOperand(0);
8605     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8606       if (C->getOperand(i) != Op0)
8607         return false;
8608     return true;
8609   }
8610   Instruction *I = dyn_cast<Instruction>(V);
8611   if (!I) return false;
8612   
8613   // Insert element gets simplified to the inserted element or is deleted if
8614   // this is constant idx extract element and its a constant idx insertelt.
8615   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8616       isa<ConstantInt>(I->getOperand(2)))
8617     return true;
8618   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8619     return true;
8620   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8621     if (BO->hasOneUse() &&
8622         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8623          CheapToScalarize(BO->getOperand(1), isConstant)))
8624       return true;
8625   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8626     if (CI->hasOneUse() &&
8627         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8628          CheapToScalarize(CI->getOperand(1), isConstant)))
8629       return true;
8630   
8631   return false;
8632 }
8633
8634 /// Read and decode a shufflevector mask.
8635 ///
8636 /// It turns undef elements into values that are larger than the number of
8637 /// elements in the input.
8638 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8639   unsigned NElts = SVI->getType()->getNumElements();
8640   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8641     return std::vector<unsigned>(NElts, 0);
8642   if (isa<UndefValue>(SVI->getOperand(2)))
8643     return std::vector<unsigned>(NElts, 2*NElts);
8644
8645   std::vector<unsigned> Result;
8646   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
8647   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8648     if (isa<UndefValue>(CP->getOperand(i)))
8649       Result.push_back(NElts*2);  // undef -> 8
8650     else
8651       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8652   return Result;
8653 }
8654
8655 /// FindScalarElement - Given a vector and an element number, see if the scalar
8656 /// value is already around as a register, for example if it were inserted then
8657 /// extracted from the vector.
8658 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8659   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8660   const VectorType *PTy = cast<VectorType>(V->getType());
8661   unsigned Width = PTy->getNumElements();
8662   if (EltNo >= Width)  // Out of range access.
8663     return UndefValue::get(PTy->getElementType());
8664   
8665   if (isa<UndefValue>(V))
8666     return UndefValue::get(PTy->getElementType());
8667   else if (isa<ConstantAggregateZero>(V))
8668     return Constant::getNullValue(PTy->getElementType());
8669   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
8670     return CP->getOperand(EltNo);
8671   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8672     // If this is an insert to a variable element, we don't know what it is.
8673     if (!isa<ConstantInt>(III->getOperand(2))) 
8674       return 0;
8675     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8676     
8677     // If this is an insert to the element we are looking for, return the
8678     // inserted value.
8679     if (EltNo == IIElt) 
8680       return III->getOperand(1);
8681     
8682     // Otherwise, the insertelement doesn't modify the value, recurse on its
8683     // vector input.
8684     return FindScalarElement(III->getOperand(0), EltNo);
8685   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8686     unsigned InEl = getShuffleMask(SVI)[EltNo];
8687     if (InEl < Width)
8688       return FindScalarElement(SVI->getOperand(0), InEl);
8689     else if (InEl < Width*2)
8690       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8691     else
8692       return UndefValue::get(PTy->getElementType());
8693   }
8694   
8695   // Otherwise, we don't know.
8696   return 0;
8697 }
8698
8699 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8700
8701   // If packed val is undef, replace extract with scalar undef.
8702   if (isa<UndefValue>(EI.getOperand(0)))
8703     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8704
8705   // If packed val is constant 0, replace extract with scalar 0.
8706   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8707     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8708   
8709   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
8710     // If packed val is constant with uniform operands, replace EI
8711     // with that operand
8712     Constant *op0 = C->getOperand(0);
8713     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8714       if (C->getOperand(i) != op0) {
8715         op0 = 0; 
8716         break;
8717       }
8718     if (op0)
8719       return ReplaceInstUsesWith(EI, op0);
8720   }
8721   
8722   // If extracting a specified index from the vector, see if we can recursively
8723   // find a previously computed scalar that was inserted into the vector.
8724   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8725     // This instruction only demands the single element from the input vector.
8726     // If the input vector has a single use, simplify it based on this use
8727     // property.
8728     uint64_t IndexVal = IdxC->getZExtValue();
8729     if (EI.getOperand(0)->hasOneUse()) {
8730       uint64_t UndefElts;
8731       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8732                                                 1 << IndexVal,
8733                                                 UndefElts)) {
8734         EI.setOperand(0, V);
8735         return &EI;
8736       }
8737     }
8738     
8739     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8740       return ReplaceInstUsesWith(EI, Elt);
8741   }
8742   
8743   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8744     if (I->hasOneUse()) {
8745       // Push extractelement into predecessor operation if legal and
8746       // profitable to do so
8747       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8748         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8749         if (CheapToScalarize(BO, isConstantElt)) {
8750           ExtractElementInst *newEI0 = 
8751             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8752                                    EI.getName()+".lhs");
8753           ExtractElementInst *newEI1 =
8754             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8755                                    EI.getName()+".rhs");
8756           InsertNewInstBefore(newEI0, EI);
8757           InsertNewInstBefore(newEI1, EI);
8758           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8759         }
8760       } else if (isa<LoadInst>(I)) {
8761         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8762                                       PointerType::get(EI.getType()), EI);
8763         GetElementPtrInst *GEP = 
8764           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8765         InsertNewInstBefore(GEP, EI);
8766         return new LoadInst(GEP);
8767       }
8768     }
8769     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8770       // Extracting the inserted element?
8771       if (IE->getOperand(2) == EI.getOperand(1))
8772         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8773       // If the inserted and extracted elements are constants, they must not
8774       // be the same value, extract from the pre-inserted value instead.
8775       if (isa<Constant>(IE->getOperand(2)) &&
8776           isa<Constant>(EI.getOperand(1))) {
8777         AddUsesToWorkList(EI);
8778         EI.setOperand(0, IE->getOperand(0));
8779         return &EI;
8780       }
8781     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8782       // If this is extracting an element from a shufflevector, figure out where
8783       // it came from and extract from the appropriate input element instead.
8784       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8785         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8786         Value *Src;
8787         if (SrcIdx < SVI->getType()->getNumElements())
8788           Src = SVI->getOperand(0);
8789         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8790           SrcIdx -= SVI->getType()->getNumElements();
8791           Src = SVI->getOperand(1);
8792         } else {
8793           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8794         }
8795         return new ExtractElementInst(Src, SrcIdx);
8796       }
8797     }
8798   }
8799   return 0;
8800 }
8801
8802 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8803 /// elements from either LHS or RHS, return the shuffle mask and true. 
8804 /// Otherwise, return false.
8805 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8806                                          std::vector<Constant*> &Mask) {
8807   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8808          "Invalid CollectSingleShuffleElements");
8809   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8810
8811   if (isa<UndefValue>(V)) {
8812     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8813     return true;
8814   } else if (V == LHS) {
8815     for (unsigned i = 0; i != NumElts; ++i)
8816       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8817     return true;
8818   } else if (V == RHS) {
8819     for (unsigned i = 0; i != NumElts; ++i)
8820       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8821     return true;
8822   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8823     // If this is an insert of an extract from some other vector, include it.
8824     Value *VecOp    = IEI->getOperand(0);
8825     Value *ScalarOp = IEI->getOperand(1);
8826     Value *IdxOp    = IEI->getOperand(2);
8827     
8828     if (!isa<ConstantInt>(IdxOp))
8829       return false;
8830     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8831     
8832     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8833       // Okay, we can handle this if the vector we are insertinting into is
8834       // transitively ok.
8835       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8836         // If so, update the mask to reflect the inserted undef.
8837         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8838         return true;
8839       }      
8840     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8841       if (isa<ConstantInt>(EI->getOperand(1)) &&
8842           EI->getOperand(0)->getType() == V->getType()) {
8843         unsigned ExtractedIdx =
8844           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8845         
8846         // This must be extracting from either LHS or RHS.
8847         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8848           // Okay, we can handle this if the vector we are insertinting into is
8849           // transitively ok.
8850           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8851             // If so, update the mask to reflect the inserted value.
8852             if (EI->getOperand(0) == LHS) {
8853               Mask[InsertedIdx & (NumElts-1)] = 
8854                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8855             } else {
8856               assert(EI->getOperand(0) == RHS);
8857               Mask[InsertedIdx & (NumElts-1)] = 
8858                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8859               
8860             }
8861             return true;
8862           }
8863         }
8864       }
8865     }
8866   }
8867   // TODO: Handle shufflevector here!
8868   
8869   return false;
8870 }
8871
8872 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8873 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8874 /// that computes V and the LHS value of the shuffle.
8875 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8876                                      Value *&RHS) {
8877   assert(isa<VectorType>(V->getType()) && 
8878          (RHS == 0 || V->getType() == RHS->getType()) &&
8879          "Invalid shuffle!");
8880   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8881
8882   if (isa<UndefValue>(V)) {
8883     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8884     return V;
8885   } else if (isa<ConstantAggregateZero>(V)) {
8886     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8887     return V;
8888   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8889     // If this is an insert of an extract from some other vector, include it.
8890     Value *VecOp    = IEI->getOperand(0);
8891     Value *ScalarOp = IEI->getOperand(1);
8892     Value *IdxOp    = IEI->getOperand(2);
8893     
8894     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8895       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8896           EI->getOperand(0)->getType() == V->getType()) {
8897         unsigned ExtractedIdx =
8898           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8899         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8900         
8901         // Either the extracted from or inserted into vector must be RHSVec,
8902         // otherwise we'd end up with a shuffle of three inputs.
8903         if (EI->getOperand(0) == RHS || RHS == 0) {
8904           RHS = EI->getOperand(0);
8905           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8906           Mask[InsertedIdx & (NumElts-1)] = 
8907             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8908           return V;
8909         }
8910         
8911         if (VecOp == RHS) {
8912           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8913           // Everything but the extracted element is replaced with the RHS.
8914           for (unsigned i = 0; i != NumElts; ++i) {
8915             if (i != InsertedIdx)
8916               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8917           }
8918           return V;
8919         }
8920         
8921         // If this insertelement is a chain that comes from exactly these two
8922         // vectors, return the vector and the effective shuffle.
8923         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8924           return EI->getOperand(0);
8925         
8926       }
8927     }
8928   }
8929   // TODO: Handle shufflevector here!
8930   
8931   // Otherwise, can't do anything fancy.  Return an identity vector.
8932   for (unsigned i = 0; i != NumElts; ++i)
8933     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8934   return V;
8935 }
8936
8937 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8938   Value *VecOp    = IE.getOperand(0);
8939   Value *ScalarOp = IE.getOperand(1);
8940   Value *IdxOp    = IE.getOperand(2);
8941   
8942   // If the inserted element was extracted from some other vector, and if the 
8943   // indexes are constant, try to turn this into a shufflevector operation.
8944   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8945     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8946         EI->getOperand(0)->getType() == IE.getType()) {
8947       unsigned NumVectorElts = IE.getType()->getNumElements();
8948       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8949       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8950       
8951       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8952         return ReplaceInstUsesWith(IE, VecOp);
8953       
8954       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8955         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8956       
8957       // If we are extracting a value from a vector, then inserting it right
8958       // back into the same place, just use the input vector.
8959       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8960         return ReplaceInstUsesWith(IE, VecOp);      
8961       
8962       // We could theoretically do this for ANY input.  However, doing so could
8963       // turn chains of insertelement instructions into a chain of shufflevector
8964       // instructions, and right now we do not merge shufflevectors.  As such,
8965       // only do this in a situation where it is clear that there is benefit.
8966       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8967         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8968         // the values of VecOp, except then one read from EIOp0.
8969         // Build a new shuffle mask.
8970         std::vector<Constant*> Mask;
8971         if (isa<UndefValue>(VecOp))
8972           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8973         else {
8974           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8975           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8976                                                        NumVectorElts));
8977         } 
8978         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8979         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8980                                      ConstantVector::get(Mask));
8981       }
8982       
8983       // If this insertelement isn't used by some other insertelement, turn it
8984       // (and any insertelements it points to), into one big shuffle.
8985       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8986         std::vector<Constant*> Mask;
8987         Value *RHS = 0;
8988         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8989         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8990         // We now have a shuffle of LHS, RHS, Mask.
8991         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
8992       }
8993     }
8994   }
8995
8996   return 0;
8997 }
8998
8999
9000 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9001   Value *LHS = SVI.getOperand(0);
9002   Value *RHS = SVI.getOperand(1);
9003   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9004
9005   bool MadeChange = false;
9006   
9007   // Undefined shuffle mask -> undefined value.
9008   if (isa<UndefValue>(SVI.getOperand(2)))
9009     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9010   
9011   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9012   // the undef, change them to undefs.
9013   if (isa<UndefValue>(SVI.getOperand(1))) {
9014     // Scan to see if there are any references to the RHS.  If so, replace them
9015     // with undef element refs and set MadeChange to true.
9016     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9017       if (Mask[i] >= e && Mask[i] != 2*e) {
9018         Mask[i] = 2*e;
9019         MadeChange = true;
9020       }
9021     }
9022     
9023     if (MadeChange) {
9024       // Remap any references to RHS to use LHS.
9025       std::vector<Constant*> Elts;
9026       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9027         if (Mask[i] == 2*e)
9028           Elts.push_back(UndefValue::get(Type::Int32Ty));
9029         else
9030           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9031       }
9032       SVI.setOperand(2, ConstantVector::get(Elts));
9033     }
9034   }
9035   
9036   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9037   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9038   if (LHS == RHS || isa<UndefValue>(LHS)) {
9039     if (isa<UndefValue>(LHS) && LHS == RHS) {
9040       // shuffle(undef,undef,mask) -> undef.
9041       return ReplaceInstUsesWith(SVI, LHS);
9042     }
9043     
9044     // Remap any references to RHS to use LHS.
9045     std::vector<Constant*> Elts;
9046     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9047       if (Mask[i] >= 2*e)
9048         Elts.push_back(UndefValue::get(Type::Int32Ty));
9049       else {
9050         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9051             (Mask[i] <  e && isa<UndefValue>(LHS)))
9052           Mask[i] = 2*e;     // Turn into undef.
9053         else
9054           Mask[i] &= (e-1);  // Force to LHS.
9055         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9056       }
9057     }
9058     SVI.setOperand(0, SVI.getOperand(1));
9059     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9060     SVI.setOperand(2, ConstantVector::get(Elts));
9061     LHS = SVI.getOperand(0);
9062     RHS = SVI.getOperand(1);
9063     MadeChange = true;
9064   }
9065   
9066   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9067   bool isLHSID = true, isRHSID = true;
9068     
9069   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9070     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9071     // Is this an identity shuffle of the LHS value?
9072     isLHSID &= (Mask[i] == i);
9073       
9074     // Is this an identity shuffle of the RHS value?
9075     isRHSID &= (Mask[i]-e == i);
9076   }
9077
9078   // Eliminate identity shuffles.
9079   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9080   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9081   
9082   // If the LHS is a shufflevector itself, see if we can combine it with this
9083   // one without producing an unusual shuffle.  Here we are really conservative:
9084   // we are absolutely afraid of producing a shuffle mask not in the input
9085   // program, because the code gen may not be smart enough to turn a merged
9086   // shuffle into two specific shuffles: it may produce worse code.  As such,
9087   // we only merge two shuffles if the result is one of the two input shuffle
9088   // masks.  In this case, merging the shuffles just removes one instruction,
9089   // which we know is safe.  This is good for things like turning:
9090   // (splat(splat)) -> splat.
9091   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9092     if (isa<UndefValue>(RHS)) {
9093       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9094
9095       std::vector<unsigned> NewMask;
9096       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9097         if (Mask[i] >= 2*e)
9098           NewMask.push_back(2*e);
9099         else
9100           NewMask.push_back(LHSMask[Mask[i]]);
9101       
9102       // If the result mask is equal to the src shuffle or this shuffle mask, do
9103       // the replacement.
9104       if (NewMask == LHSMask || NewMask == Mask) {
9105         std::vector<Constant*> Elts;
9106         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9107           if (NewMask[i] >= e*2) {
9108             Elts.push_back(UndefValue::get(Type::Int32Ty));
9109           } else {
9110             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9111           }
9112         }
9113         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9114                                      LHSSVI->getOperand(1),
9115                                      ConstantVector::get(Elts));
9116       }
9117     }
9118   }
9119
9120   return MadeChange ? &SVI : 0;
9121 }
9122
9123
9124
9125
9126 /// TryToSinkInstruction - Try to move the specified instruction from its
9127 /// current block into the beginning of DestBlock, which can only happen if it's
9128 /// safe to move the instruction past all of the instructions between it and the
9129 /// end of its block.
9130 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9131   assert(I->hasOneUse() && "Invariants didn't hold!");
9132
9133   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9134   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9135
9136   // Do not sink alloca instructions out of the entry block.
9137   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9138     return false;
9139
9140   // We can only sink load instructions if there is nothing between the load and
9141   // the end of block that could change the value.
9142   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9143     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9144          Scan != E; ++Scan)
9145       if (Scan->mayWriteToMemory())
9146         return false;
9147   }
9148
9149   BasicBlock::iterator InsertPos = DestBlock->begin();
9150   while (isa<PHINode>(InsertPos)) ++InsertPos;
9151
9152   I->moveBefore(InsertPos);
9153   ++NumSunkInst;
9154   return true;
9155 }
9156
9157
9158 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9159 /// all reachable code to the worklist.
9160 ///
9161 /// This has a couple of tricks to make the code faster and more powerful.  In
9162 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9163 /// them to the worklist (this significantly speeds up instcombine on code where
9164 /// many instructions are dead or constant).  Additionally, if we find a branch
9165 /// whose condition is a known constant, we only visit the reachable successors.
9166 ///
9167 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9168                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9169                                        InstCombiner &IC,
9170                                        const TargetData *TD) {
9171   // We have now visited this block!  If we've already been here, bail out.
9172   if (!Visited.insert(BB)) return;
9173     
9174   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9175     Instruction *Inst = BBI++;
9176     
9177     // DCE instruction if trivially dead.
9178     if (isInstructionTriviallyDead(Inst)) {
9179       ++NumDeadInst;
9180       DOUT << "IC: DCE: " << *Inst;
9181       Inst->eraseFromParent();
9182       continue;
9183     }
9184     
9185     // ConstantProp instruction if trivially constant.
9186     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9187       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9188       Inst->replaceAllUsesWith(C);
9189       ++NumConstProp;
9190       Inst->eraseFromParent();
9191       continue;
9192     }
9193     
9194     IC.AddToWorkList(Inst);
9195   }
9196
9197   // Recursively visit successors.  If this is a branch or switch on a constant,
9198   // only visit the reachable successor.
9199   TerminatorInst *TI = BB->getTerminator();
9200   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9201     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9202       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9203       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
9204       return;
9205     }
9206   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9207     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9208       // See if this is an explicit destination.
9209       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9210         if (SI->getCaseValue(i) == Cond) {
9211           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
9212           return;
9213         }
9214       
9215       // Otherwise it is the default destination.
9216       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
9217       return;
9218     }
9219   }
9220   
9221   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9222     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
9223 }
9224
9225 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9226   bool Changed = false;
9227   TD = &getAnalysis<TargetData>();
9228   
9229   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9230              << F.getNameStr() << "\n");
9231
9232   {
9233     // Do a depth-first traversal of the function, populate the worklist with
9234     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9235     // track of which blocks we visit.
9236     SmallPtrSet<BasicBlock*, 64> Visited;
9237     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9238
9239     // Do a quick scan over the function.  If we find any blocks that are
9240     // unreachable, remove any instructions inside of them.  This prevents
9241     // the instcombine code from having to deal with some bad special cases.
9242     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9243       if (!Visited.count(BB)) {
9244         Instruction *Term = BB->getTerminator();
9245         while (Term != BB->begin()) {   // Remove instrs bottom-up
9246           BasicBlock::iterator I = Term; --I;
9247
9248           DOUT << "IC: DCE: " << *I;
9249           ++NumDeadInst;
9250
9251           if (!I->use_empty())
9252             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9253           I->eraseFromParent();
9254         }
9255       }
9256   }
9257
9258   while (!Worklist.empty()) {
9259     Instruction *I = RemoveOneFromWorkList();
9260     if (I == 0) continue;  // skip null values.
9261
9262     // Check to see if we can DCE the instruction.
9263     if (isInstructionTriviallyDead(I)) {
9264       // Add operands to the worklist.
9265       if (I->getNumOperands() < 4)
9266         AddUsesToWorkList(*I);
9267       ++NumDeadInst;
9268
9269       DOUT << "IC: DCE: " << *I;
9270
9271       I->eraseFromParent();
9272       RemoveFromWorkList(I);
9273       continue;
9274     }
9275
9276     // Instruction isn't dead, see if we can constant propagate it.
9277     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9278       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9279
9280       // Add operands to the worklist.
9281       AddUsesToWorkList(*I);
9282       ReplaceInstUsesWith(*I, C);
9283
9284       ++NumConstProp;
9285       I->eraseFromParent();
9286       RemoveFromWorkList(I);
9287       continue;
9288     }
9289
9290     // See if we can trivially sink this instruction to a successor basic block.
9291     if (I->hasOneUse()) {
9292       BasicBlock *BB = I->getParent();
9293       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9294       if (UserParent != BB) {
9295         bool UserIsSuccessor = false;
9296         // See if the user is one of our successors.
9297         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9298           if (*SI == UserParent) {
9299             UserIsSuccessor = true;
9300             break;
9301           }
9302
9303         // If the user is one of our immediate successors, and if that successor
9304         // only has us as a predecessors (we'd have to split the critical edge
9305         // otherwise), we can keep going.
9306         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9307             next(pred_begin(UserParent)) == pred_end(UserParent))
9308           // Okay, the CFG is simple enough, try to sink this instruction.
9309           Changed |= TryToSinkInstruction(I, UserParent);
9310       }
9311     }
9312
9313     // Now that we have an instruction, try combining it to simplify it...
9314     if (Instruction *Result = visit(*I)) {
9315       ++NumCombined;
9316       // Should we replace the old instruction with a new one?
9317       if (Result != I) {
9318         DOUT << "IC: Old = " << *I
9319              << "    New = " << *Result;
9320
9321         // Everything uses the new instruction now.
9322         I->replaceAllUsesWith(Result);
9323
9324         // Push the new instruction and any users onto the worklist.
9325         AddToWorkList(Result);
9326         AddUsersToWorkList(*Result);
9327
9328         // Move the name to the new instruction first.
9329         Result->takeName(I);
9330
9331         // Insert the new instruction into the basic block...
9332         BasicBlock *InstParent = I->getParent();
9333         BasicBlock::iterator InsertPos = I;
9334
9335         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9336           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9337             ++InsertPos;
9338
9339         InstParent->getInstList().insert(InsertPos, Result);
9340
9341         // Make sure that we reprocess all operands now that we reduced their
9342         // use counts.
9343         AddUsesToWorkList(*I);
9344
9345         // Instructions can end up on the worklist more than once.  Make sure
9346         // we do not process an instruction that has been deleted.
9347         RemoveFromWorkList(I);
9348
9349         // Erase the old instruction.
9350         InstParent->getInstList().erase(I);
9351       } else {
9352         DOUT << "IC: MOD = " << *I;
9353
9354         // If the instruction was modified, it's possible that it is now dead.
9355         // if so, remove it.
9356         if (isInstructionTriviallyDead(I)) {
9357           // Make sure we process all operands now that we are reducing their
9358           // use counts.
9359           AddUsesToWorkList(*I);
9360
9361           // Instructions may end up in the worklist more than once.  Erase all
9362           // occurrences of this instruction.
9363           RemoveFromWorkList(I);
9364           I->eraseFromParent();
9365         } else {
9366           AddToWorkList(I);
9367           AddUsersToWorkList(*I);
9368         }
9369       }
9370       Changed = true;
9371     }
9372   }
9373
9374   assert(WorklistMap.empty() && "Worklist empty, but map not?");
9375   return Changed;
9376 }
9377
9378
9379 bool InstCombiner::runOnFunction(Function &F) {
9380   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9381   
9382   bool EverMadeChange = false;
9383
9384   // Iterate while there is work to do.
9385   unsigned Iteration = 0;
9386   while (DoOneIteration(F, Iteration++)) 
9387     EverMadeChange = true;
9388   return EverMadeChange;
9389 }
9390
9391 FunctionPass *llvm::createInstructionCombiningPass() {
9392   return new InstCombiner();
9393 }
9394