Fix whitespace in whitespace-significant pseudocode in a comment.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     std::vector<Instruction*> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           I.setOperand(i, UndefValue::get(Op->getType()));
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235
236     // visitInstruction - Specify what to return for unhandled instructions...
237     Instruction *visitInstruction(Instruction &I) { return 0; }
238
239   private:
240     Instruction *visitCallSite(CallSite CS);
241     bool transformConstExprCastCall(CallSite CS);
242     Instruction *transformCallThroughTrampoline(CallSite CS);
243     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
244                                    bool DoXform = true);
245     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
246
247   public:
248     // InsertNewInstBefore - insert an instruction New before instruction Old
249     // in the program.  Add the new instruction to the worklist.
250     //
251     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
252       assert(New && New->getParent() == 0 &&
253              "New instruction already inserted into a basic block!");
254       BasicBlock *BB = Old.getParent();
255       BB->getInstList().insert(&Old, New);  // Insert inst
256       AddToWorkList(New);
257       return New;
258     }
259
260     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
261     /// This also adds the cast to the worklist.  Finally, this returns the
262     /// cast.
263     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
264                             Instruction &Pos) {
265       if (V->getType() == Ty) return V;
266
267       if (Constant *CV = dyn_cast<Constant>(V))
268         return ConstantExpr::getCast(opc, CV, Ty);
269       
270       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
271       AddToWorkList(C);
272       return C;
273     }
274         
275     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
276       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
277     }
278
279
280     // ReplaceInstUsesWith - This method is to be used when an instruction is
281     // found to be dead, replacable with another preexisting expression.  Here
282     // we add all uses of I to the worklist, replace all uses of I with the new
283     // value, then return I, so that the inst combiner will know that I was
284     // modified.
285     //
286     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
287       AddUsersToWorkList(I);         // Add all modified instrs to worklist
288       if (&I != V) {
289         I.replaceAllUsesWith(V);
290         return &I;
291       } else {
292         // If we are replacing the instruction with itself, this must be in a
293         // segment of unreachable code, so just clobber the instruction.
294         I.replaceAllUsesWith(UndefValue::get(I.getType()));
295         return &I;
296       }
297     }
298
299     // UpdateValueUsesWith - This method is to be used when an value is
300     // found to be replacable with another preexisting expression or was
301     // updated.  Here we add all uses of I to the worklist, replace all uses of
302     // I with the new value (unless the instruction was just updated), then
303     // return true, so that the inst combiner will know that I was modified.
304     //
305     bool UpdateValueUsesWith(Value *Old, Value *New) {
306       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
307       if (Old != New)
308         Old->replaceAllUsesWith(New);
309       if (Instruction *I = dyn_cast<Instruction>(Old))
310         AddToWorkList(I);
311       if (Instruction *I = dyn_cast<Instruction>(New))
312         AddToWorkList(I);
313       return true;
314     }
315     
316     // EraseInstFromFunction - When dealing with an instruction that has side
317     // effects or produces a void value, we can't rely on DCE to delete the
318     // instruction.  Instead, visit methods should return the value returned by
319     // this function.
320     Instruction *EraseInstFromFunction(Instruction &I) {
321       assert(I.use_empty() && "Cannot erase instruction that is used!");
322       AddUsesToWorkList(I);
323       RemoveFromWorkList(&I);
324       I.eraseFromParent();
325       return 0;  // Don't do anything with FI
326     }
327         
328     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329                            APInt &KnownOne, unsigned Depth = 0) const {
330       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331     }
332     
333     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
334                            unsigned Depth = 0) const {
335       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336     }
337     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338       return llvm::ComputeNumSignBits(Op, TD, Depth);
339     }
340
341   private:
342     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
343     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
344     /// casts that are known to not do anything...
345     ///
346     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
347                                    Value *V, const Type *DestTy,
348                                    Instruction *InsertBefore);
349
350     /// SimplifyCommutative - This performs a few simplifications for 
351     /// commutative operators.
352     bool SimplifyCommutative(BinaryOperator &I);
353
354     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355     /// most-complex to least-complex order.
356     bool SimplifyCompare(CmpInst &I);
357
358     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359     /// on the demanded bits.
360     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth = 0);
363
364     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365                                       uint64_t &UndefElts, unsigned Depth = 0);
366       
367     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368     // PHI node as operand #0, see if we can fold the instruction into the PHI
369     // (which is only possible if all operands to the PHI are constants).
370     Instruction *FoldOpIntoPhi(Instruction &I);
371
372     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373     // operator and they all are only used by the PHI, PHI together their
374     // inputs, and do the operation once, to the result of the PHI.
375     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377     
378     
379     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
380                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
381     
382     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
383                               bool isSub, Instruction &I);
384     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
385                                  bool isSigned, bool Inside, Instruction &IB);
386     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
387     Instruction *MatchBSwap(BinaryOperator &I);
388     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
389     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
390     Instruction *SimplifyMemSet(MemSetInst *MI);
391
392
393     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
394
395     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
396                                     unsigned CastOpc,
397                                     int &NumCastsRemoved);
398     unsigned GetOrEnforceKnownAlignment(Value *V,
399                                         unsigned PrefAlign = 0);
400   };
401 }
402
403 char InstCombiner::ID = 0;
404 static RegisterPass<InstCombiner>
405 X("instcombine", "Combine redundant instructions");
406
407 // getComplexity:  Assign a complexity or rank value to LLVM Values...
408 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
409 static unsigned getComplexity(Value *V) {
410   if (isa<Instruction>(V)) {
411     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
412       return 3;
413     return 4;
414   }
415   if (isa<Argument>(V)) return 3;
416   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
417 }
418
419 // isOnlyUse - Return true if this instruction will be deleted if we stop using
420 // it.
421 static bool isOnlyUse(Value *V) {
422   return V->hasOneUse() || isa<Constant>(V);
423 }
424
425 // getPromotedType - Return the specified type promoted as it would be to pass
426 // though a va_arg area...
427 static const Type *getPromotedType(const Type *Ty) {
428   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
429     if (ITy->getBitWidth() < 32)
430       return Type::Int32Ty;
431   }
432   return Ty;
433 }
434
435 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
436 /// expression bitcast,  return the operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439     return I->getOperand(0);
440   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
441     if (CE->getOpcode() == Instruction::BitCast)
442       return CE->getOperand(0);
443   return 0;
444 }
445
446 /// This function is a wrapper around CastInst::isEliminableCastPair. It
447 /// simply extracts arguments and returns what that function returns.
448 static Instruction::CastOps 
449 isEliminableCastPair(
450   const CastInst *CI, ///< The first cast instruction
451   unsigned opcode,       ///< The opcode of the second cast instruction
452   const Type *DstTy,     ///< The target type for the second cast instruction
453   TargetData *TD         ///< The target data for pointer size
454 ) {
455   
456   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
457   const Type *MidTy = CI->getType();                  // B from above
458
459   // Get the opcodes of the two Cast instructions
460   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
461   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
462
463   return Instruction::CastOps(
464       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
465                                      DstTy, TD->getIntPtrType()));
466 }
467
468 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
469 /// in any code being generated.  It does not require codegen if V is simple
470 /// enough or if the cast can be folded into other casts.
471 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
472                               const Type *Ty, TargetData *TD) {
473   if (V->getType() == Ty || isa<Constant>(V)) return false;
474   
475   // If this is another cast that can be eliminated, it isn't codegen either.
476   if (const CastInst *CI = dyn_cast<CastInst>(V))
477     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
478       return false;
479   return true;
480 }
481
482 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
483 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
484 /// casts that are known to not do anything...
485 ///
486 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
487                                              Value *V, const Type *DestTy,
488                                              Instruction *InsertBefore) {
489   if (V->getType() == DestTy) return V;
490   if (Constant *C = dyn_cast<Constant>(V))
491     return ConstantExpr::getCast(opcode, C, DestTy);
492   
493   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
494 }
495
496 // SimplifyCommutative - This performs a few simplifications for commutative
497 // operators:
498 //
499 //  1. Order operands such that they are listed from right (least complex) to
500 //     left (most complex).  This puts constants before unary operators before
501 //     binary operators.
502 //
503 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505 //
506 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
507   bool Changed = false;
508   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509     Changed = !I.swapOperands();
510
511   if (!I.isAssociative()) return Changed;
512   Instruction::BinaryOps Opcode = I.getOpcode();
513   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515       if (isa<Constant>(I.getOperand(1))) {
516         Constant *Folded = ConstantExpr::get(I.getOpcode(),
517                                              cast<Constant>(I.getOperand(1)),
518                                              cast<Constant>(Op->getOperand(1)));
519         I.setOperand(0, Op->getOperand(0));
520         I.setOperand(1, Folded);
521         return true;
522       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524             isOnlyUse(Op) && isOnlyUse(Op1)) {
525           Constant *C1 = cast<Constant>(Op->getOperand(1));
526           Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
529           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
530           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
531                                                     Op1->getOperand(0),
532                                                     Op1->getName(), &I);
533           AddToWorkList(New);
534           I.setOperand(0, New);
535           I.setOperand(1, Folded);
536           return true;
537         }
538     }
539   return Changed;
540 }
541
542 /// SimplifyCompare - For a CmpInst this function just orders the operands
543 /// so that theyare listed from right (least complex) to left (most complex).
544 /// This puts constants before unary operators before binary operators.
545 bool InstCombiner::SimplifyCompare(CmpInst &I) {
546   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547     return false;
548   I.swapOperands();
549   // Compare instructions are not associative so there's nothing else we can do.
550   return true;
551 }
552
553 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554 // if the LHS is a constant zero (which is the 'negate' form).
555 //
556 static inline Value *dyn_castNegVal(Value *V) {
557   if (BinaryOperator::isNeg(V))
558     return BinaryOperator::getNegArgument(V);
559
560   // Constants can be considered to be negated values if they can be folded.
561   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562     return ConstantExpr::getNeg(C);
563
564   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
565     if (C->getType()->getElementType()->isInteger())
566       return ConstantExpr::getNeg(C);
567
568   return 0;
569 }
570
571 static inline Value *dyn_castNotVal(Value *V) {
572   if (BinaryOperator::isNot(V))
573     return BinaryOperator::getNotArgument(V);
574
575   // Constants can be considered to be not'ed values...
576   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577     return ConstantInt::get(~C->getValue());
578   return 0;
579 }
580
581 // dyn_castFoldableMul - If this value is a multiply that can be folded into
582 // other computations (because it has a constant operand), return the
583 // non-constant operand of the multiply, and set CST to point to the multiplier.
584 // Otherwise, return null.
585 //
586 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
587   if (V->hasOneUse() && V->getType()->isInteger())
588     if (Instruction *I = dyn_cast<Instruction>(V)) {
589       if (I->getOpcode() == Instruction::Mul)
590         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
591           return I->getOperand(0);
592       if (I->getOpcode() == Instruction::Shl)
593         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
594           // The multiplier is really 1 << CST.
595           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
596           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
597           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
598           return I->getOperand(0);
599         }
600     }
601   return 0;
602 }
603
604 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
605 /// expression, return it.
606 static User *dyn_castGetElementPtr(Value *V) {
607   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
608   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
609     if (CE->getOpcode() == Instruction::GetElementPtr)
610       return cast<User>(V);
611   return false;
612 }
613
614 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
615 /// opcode value. Otherwise return UserOp1.
616 static unsigned getOpcode(const Value *V) {
617   if (const Instruction *I = dyn_cast<Instruction>(V))
618     return I->getOpcode();
619   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
620     return CE->getOpcode();
621   // Use UserOp1 to mean there's no opcode.
622   return Instruction::UserOp1;
623 }
624
625 /// AddOne - Add one to a ConstantInt
626 static ConstantInt *AddOne(ConstantInt *C) {
627   APInt Val(C->getValue());
628   return ConstantInt::get(++Val);
629 }
630 /// SubOne - Subtract one from a ConstantInt
631 static ConstantInt *SubOne(ConstantInt *C) {
632   APInt Val(C->getValue());
633   return ConstantInt::get(--Val);
634 }
635 /// Add - Add two ConstantInts together
636 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
637   return ConstantInt::get(C1->getValue() + C2->getValue());
638 }
639 /// And - Bitwise AND two ConstantInts together
640 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
641   return ConstantInt::get(C1->getValue() & C2->getValue());
642 }
643 /// Subtract - Subtract one ConstantInt from another
644 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() - C2->getValue());
646 }
647 /// Multiply - Multiply two ConstantInts together
648 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() * C2->getValue());
650 }
651 /// MultiplyOverflows - True if the multiply can not be expressed in an int
652 /// this size.
653 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
654   uint32_t W = C1->getBitWidth();
655   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656   if (sign) {
657     LHSExt.sext(W * 2);
658     RHSExt.sext(W * 2);
659   } else {
660     LHSExt.zext(W * 2);
661     RHSExt.zext(W * 2);
662   }
663
664   APInt MulExt = LHSExt * RHSExt;
665
666   if (sign) {
667     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669     return MulExt.slt(Min) || MulExt.sgt(Max);
670   } else 
671     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672 }
673
674
675 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
676 /// specified instruction is a constant integer.  If so, check to see if there
677 /// are any bits set in the constant that are not demanded.  If so, shrink the
678 /// constant and return true.
679 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
680                                    APInt Demanded) {
681   assert(I && "No instruction?");
682   assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684   // If the operand is not a constant integer, nothing to do.
685   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686   if (!OpC) return false;
687
688   // If there are no bits set that aren't demanded, nothing to do.
689   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690   if ((~Demanded & OpC->getValue()) == 0)
691     return false;
692
693   // This instruction is producing bits that are not demanded. Shrink the RHS.
694   Demanded &= OpC->getValue();
695   I->setOperand(OpNo, ConstantInt::get(Demanded));
696   return true;
697 }
698
699 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
700 // set of known zero and one bits, compute the maximum and minimum values that
701 // could have the specified known zero and known one bits, returning them in
702 // min/max.
703 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
704                                                    const APInt& KnownZero,
705                                                    const APInt& KnownOne,
706                                                    APInt& Min, APInt& Max) {
707   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
708   assert(KnownZero.getBitWidth() == BitWidth && 
709          KnownOne.getBitWidth() == BitWidth &&
710          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
711          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
712   APInt UnknownBits = ~(KnownZero|KnownOne);
713
714   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
715   // bit if it is unknown.
716   Min = KnownOne;
717   Max = KnownOne|UnknownBits;
718   
719   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
720     Min.set(BitWidth-1);
721     Max.clear(BitWidth-1);
722   }
723 }
724
725 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
726 // a set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
730                                                      const APInt &KnownZero,
731                                                      const APInt &KnownOne,
732                                                      APInt &Min, APInt &Max) {
733   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
734   assert(KnownZero.getBitWidth() == BitWidth && 
735          KnownOne.getBitWidth() == BitWidth &&
736          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
737          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
738   APInt UnknownBits = ~(KnownZero|KnownOne);
739   
740   // The minimum value is when the unknown bits are all zeros.
741   Min = KnownOne;
742   // The maximum value is when the unknown bits are all ones.
743   Max = KnownOne|UnknownBits;
744 }
745
746 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
747 /// value based on the demanded bits. When this function is called, it is known
748 /// that only the bits set in DemandedMask of the result of V are ever used
749 /// downstream. Consequently, depending on the mask and V, it may be possible
750 /// to replace V with a constant or one of its operands. In such cases, this
751 /// function does the replacement and returns true. In all other cases, it
752 /// returns false after analyzing the expression and setting KnownOne and known
753 /// to be one in the expression. KnownZero contains all the bits that are known
754 /// to be zero in the expression. These are provided to potentially allow the
755 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
756 /// the expression. KnownOne and KnownZero always follow the invariant that 
757 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
758 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
759 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
760 /// and KnownOne must all be the same.
761 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
762                                         APInt& KnownZero, APInt& KnownOne,
763                                         unsigned Depth) {
764   assert(V != 0 && "Null pointer of Value???");
765   assert(Depth <= 6 && "Limit Search Depth");
766   uint32_t BitWidth = DemandedMask.getBitWidth();
767   const IntegerType *VTy = cast<IntegerType>(V->getType());
768   assert(VTy->getBitWidth() == BitWidth && 
769          KnownZero.getBitWidth() == BitWidth && 
770          KnownOne.getBitWidth() == BitWidth &&
771          "Value *V, DemandedMask, KnownZero and KnownOne \
772           must have same BitWidth");
773   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
774     // We know all of the bits for a constant!
775     KnownOne = CI->getValue() & DemandedMask;
776     KnownZero = ~KnownOne & DemandedMask;
777     return false;
778   }
779   
780   KnownZero.clear(); 
781   KnownOne.clear();
782   if (!V->hasOneUse()) {    // Other users may use these bits.
783     if (Depth != 0) {       // Not at the root.
784       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
785       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
786       return false;
787     }
788     // If this is the root being simplified, allow it to have multiple uses,
789     // just set the DemandedMask to all bits.
790     DemandedMask = APInt::getAllOnesValue(BitWidth);
791   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
792     if (V != UndefValue::get(VTy))
793       return UpdateValueUsesWith(V, UndefValue::get(VTy));
794     return false;
795   } else if (Depth == 6) {        // Limit search depth.
796     return false;
797   }
798   
799   Instruction *I = dyn_cast<Instruction>(V);
800   if (!I) return false;        // Only analyze instructions.
801
802   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
803   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
804   switch (I->getOpcode()) {
805   default:
806     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
807     break;
808   case Instruction::And:
809     // If either the LHS or the RHS are Zero, the result is zero.
810     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
811                              RHSKnownZero, RHSKnownOne, Depth+1))
812       return true;
813     assert((RHSKnownZero & RHSKnownOne) == 0 && 
814            "Bits known to be one AND zero?"); 
815
816     // If something is known zero on the RHS, the bits aren't demanded on the
817     // LHS.
818     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
819                              LHSKnownZero, LHSKnownOne, Depth+1))
820       return true;
821     assert((LHSKnownZero & LHSKnownOne) == 0 && 
822            "Bits known to be one AND zero?"); 
823
824     // If all of the demanded bits are known 1 on one side, return the other.
825     // These bits cannot contribute to the result of the 'and'.
826     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
827         (DemandedMask & ~LHSKnownZero))
828       return UpdateValueUsesWith(I, I->getOperand(0));
829     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
830         (DemandedMask & ~RHSKnownZero))
831       return UpdateValueUsesWith(I, I->getOperand(1));
832     
833     // If all of the demanded bits in the inputs are known zeros, return zero.
834     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
835       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
836       
837     // If the RHS is a constant, see if we can simplify it.
838     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
839       return UpdateValueUsesWith(I, I);
840       
841     // Output known-1 bits are only known if set in both the LHS & RHS.
842     RHSKnownOne &= LHSKnownOne;
843     // Output known-0 are known to be clear if zero in either the LHS | RHS.
844     RHSKnownZero |= LHSKnownZero;
845     break;
846   case Instruction::Or:
847     // If either the LHS or the RHS are One, the result is One.
848     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
849                              RHSKnownZero, RHSKnownOne, Depth+1))
850       return true;
851     assert((RHSKnownZero & RHSKnownOne) == 0 && 
852            "Bits known to be one AND zero?"); 
853     // If something is known one on the RHS, the bits aren't demanded on the
854     // LHS.
855     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
856                              LHSKnownZero, LHSKnownOne, Depth+1))
857       return true;
858     assert((LHSKnownZero & LHSKnownOne) == 0 && 
859            "Bits known to be one AND zero?"); 
860     
861     // If all of the demanded bits are known zero on one side, return the other.
862     // These bits cannot contribute to the result of the 'or'.
863     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
864         (DemandedMask & ~LHSKnownOne))
865       return UpdateValueUsesWith(I, I->getOperand(0));
866     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
867         (DemandedMask & ~RHSKnownOne))
868       return UpdateValueUsesWith(I, I->getOperand(1));
869
870     // If all of the potentially set bits on one side are known to be set on
871     // the other side, just use the 'other' side.
872     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
873         (DemandedMask & (~RHSKnownZero)))
874       return UpdateValueUsesWith(I, I->getOperand(0));
875     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
876         (DemandedMask & (~LHSKnownZero)))
877       return UpdateValueUsesWith(I, I->getOperand(1));
878         
879     // If the RHS is a constant, see if we can simplify it.
880     if (ShrinkDemandedConstant(I, 1, DemandedMask))
881       return UpdateValueUsesWith(I, I);
882           
883     // Output known-0 bits are only known if clear in both the LHS & RHS.
884     RHSKnownZero &= LHSKnownZero;
885     // Output known-1 are known to be set if set in either the LHS | RHS.
886     RHSKnownOne |= LHSKnownOne;
887     break;
888   case Instruction::Xor: {
889     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890                              RHSKnownZero, RHSKnownOne, Depth+1))
891       return true;
892     assert((RHSKnownZero & RHSKnownOne) == 0 && 
893            "Bits known to be one AND zero?"); 
894     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
895                              LHSKnownZero, LHSKnownOne, Depth+1))
896       return true;
897     assert((LHSKnownZero & LHSKnownOne) == 0 && 
898            "Bits known to be one AND zero?"); 
899     
900     // If all of the demanded bits are known zero on one side, return the other.
901     // These bits cannot contribute to the result of the 'xor'.
902     if ((DemandedMask & RHSKnownZero) == DemandedMask)
903       return UpdateValueUsesWith(I, I->getOperand(0));
904     if ((DemandedMask & LHSKnownZero) == DemandedMask)
905       return UpdateValueUsesWith(I, I->getOperand(1));
906     
907     // Output known-0 bits are known if clear or set in both the LHS & RHS.
908     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
909                          (RHSKnownOne & LHSKnownOne);
910     // Output known-1 are known to be set if set in only one of the LHS, RHS.
911     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
912                         (RHSKnownOne & LHSKnownZero);
913     
914     // If all of the demanded bits are known to be zero on one side or the
915     // other, turn this into an *inclusive* or.
916     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
917     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
918       Instruction *Or =
919         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
920                                  I->getName());
921       InsertNewInstBefore(Or, *I);
922       return UpdateValueUsesWith(I, Or);
923     }
924     
925     // If all of the demanded bits on one side are known, and all of the set
926     // bits on that side are also known to be set on the other side, turn this
927     // into an AND, as we know the bits will be cleared.
928     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
929     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
930       // all known
931       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
932         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
933         Instruction *And = 
934           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
935         InsertNewInstBefore(And, *I);
936         return UpdateValueUsesWith(I, And);
937       }
938     }
939     
940     // If the RHS is a constant, see if we can simplify it.
941     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
942     if (ShrinkDemandedConstant(I, 1, DemandedMask))
943       return UpdateValueUsesWith(I, I);
944     
945     RHSKnownZero = KnownZeroOut;
946     RHSKnownOne  = KnownOneOut;
947     break;
948   }
949   case Instruction::Select:
950     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
951                              RHSKnownZero, RHSKnownOne, Depth+1))
952       return true;
953     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
954                              LHSKnownZero, LHSKnownOne, Depth+1))
955       return true;
956     assert((RHSKnownZero & RHSKnownOne) == 0 && 
957            "Bits known to be one AND zero?"); 
958     assert((LHSKnownZero & LHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960     
961     // If the operands are constants, see if we can simplify them.
962     if (ShrinkDemandedConstant(I, 1, DemandedMask))
963       return UpdateValueUsesWith(I, I);
964     if (ShrinkDemandedConstant(I, 2, DemandedMask))
965       return UpdateValueUsesWith(I, I);
966     
967     // Only known if known in both the LHS and RHS.
968     RHSKnownOne &= LHSKnownOne;
969     RHSKnownZero &= LHSKnownZero;
970     break;
971   case Instruction::Trunc: {
972     uint32_t truncBf = 
973       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
974     DemandedMask.zext(truncBf);
975     RHSKnownZero.zext(truncBf);
976     RHSKnownOne.zext(truncBf);
977     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
978                              RHSKnownZero, RHSKnownOne, Depth+1))
979       return true;
980     DemandedMask.trunc(BitWidth);
981     RHSKnownZero.trunc(BitWidth);
982     RHSKnownOne.trunc(BitWidth);
983     assert((RHSKnownZero & RHSKnownOne) == 0 && 
984            "Bits known to be one AND zero?"); 
985     break;
986   }
987   case Instruction::BitCast:
988     if (!I->getOperand(0)->getType()->isInteger())
989       return false;
990       
991     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
992                              RHSKnownZero, RHSKnownOne, Depth+1))
993       return true;
994     assert((RHSKnownZero & RHSKnownOne) == 0 && 
995            "Bits known to be one AND zero?"); 
996     break;
997   case Instruction::ZExt: {
998     // Compute the bits in the result that are not present in the input.
999     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1000     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1001     
1002     DemandedMask.trunc(SrcBitWidth);
1003     RHSKnownZero.trunc(SrcBitWidth);
1004     RHSKnownOne.trunc(SrcBitWidth);
1005     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1006                              RHSKnownZero, RHSKnownOne, Depth+1))
1007       return true;
1008     DemandedMask.zext(BitWidth);
1009     RHSKnownZero.zext(BitWidth);
1010     RHSKnownOne.zext(BitWidth);
1011     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1012            "Bits known to be one AND zero?"); 
1013     // The top bits are known to be zero.
1014     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1015     break;
1016   }
1017   case Instruction::SExt: {
1018     // Compute the bits in the result that are not present in the input.
1019     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1020     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1021     
1022     APInt InputDemandedBits = DemandedMask & 
1023                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1024
1025     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1026     // If any of the sign extended bits are demanded, we know that the sign
1027     // bit is demanded.
1028     if ((NewBits & DemandedMask) != 0)
1029       InputDemandedBits.set(SrcBitWidth-1);
1030       
1031     InputDemandedBits.trunc(SrcBitWidth);
1032     RHSKnownZero.trunc(SrcBitWidth);
1033     RHSKnownOne.trunc(SrcBitWidth);
1034     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1035                              RHSKnownZero, RHSKnownOne, Depth+1))
1036       return true;
1037     InputDemandedBits.zext(BitWidth);
1038     RHSKnownZero.zext(BitWidth);
1039     RHSKnownOne.zext(BitWidth);
1040     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1041            "Bits known to be one AND zero?"); 
1042       
1043     // If the sign bit of the input is known set or clear, then we know the
1044     // top bits of the result.
1045
1046     // If the input sign bit is known zero, or if the NewBits are not demanded
1047     // convert this into a zero extension.
1048     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1049     {
1050       // Convert to ZExt cast
1051       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1052       return UpdateValueUsesWith(I, NewCast);
1053     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1054       RHSKnownOne |= NewBits;
1055     }
1056     break;
1057   }
1058   case Instruction::Add: {
1059     // Figure out what the input bits are.  If the top bits of the and result
1060     // are not demanded, then the add doesn't demand them from its input
1061     // either.
1062     uint32_t NLZ = DemandedMask.countLeadingZeros();
1063       
1064     // If there is a constant on the RHS, there are a variety of xformations
1065     // we can do.
1066     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1067       // If null, this should be simplified elsewhere.  Some of the xforms here
1068       // won't work if the RHS is zero.
1069       if (RHS->isZero())
1070         break;
1071       
1072       // If the top bit of the output is demanded, demand everything from the
1073       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1074       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1075
1076       // Find information about known zero/one bits in the input.
1077       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1078                                LHSKnownZero, LHSKnownOne, Depth+1))
1079         return true;
1080
1081       // If the RHS of the add has bits set that can't affect the input, reduce
1082       // the constant.
1083       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1084         return UpdateValueUsesWith(I, I);
1085       
1086       // Avoid excess work.
1087       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1088         break;
1089       
1090       // Turn it into OR if input bits are zero.
1091       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1092         Instruction *Or =
1093           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1094                                    I->getName());
1095         InsertNewInstBefore(Or, *I);
1096         return UpdateValueUsesWith(I, Or);
1097       }
1098       
1099       // We can say something about the output known-zero and known-one bits,
1100       // depending on potential carries from the input constant and the
1101       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1102       // bits set and the RHS constant is 0x01001, then we know we have a known
1103       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1104       
1105       // To compute this, we first compute the potential carry bits.  These are
1106       // the bits which may be modified.  I'm not aware of a better way to do
1107       // this scan.
1108       const APInt& RHSVal = RHS->getValue();
1109       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1110       
1111       // Now that we know which bits have carries, compute the known-1/0 sets.
1112       
1113       // Bits are known one if they are known zero in one operand and one in the
1114       // other, and there is no input carry.
1115       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1116                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1117       
1118       // Bits are known zero if they are known zero in both operands and there
1119       // is no input carry.
1120       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1121     } else {
1122       // If the high-bits of this ADD are not demanded, then it does not demand
1123       // the high bits of its LHS or RHS.
1124       if (DemandedMask[BitWidth-1] == 0) {
1125         // Right fill the mask of bits for this ADD to demand the most
1126         // significant bit and all those below it.
1127         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1128         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1129                                  LHSKnownZero, LHSKnownOne, Depth+1))
1130           return true;
1131         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1132                                  LHSKnownZero, LHSKnownOne, Depth+1))
1133           return true;
1134       }
1135     }
1136     break;
1137   }
1138   case Instruction::Sub:
1139     // If the high-bits of this SUB are not demanded, then it does not demand
1140     // the high bits of its LHS or RHS.
1141     if (DemandedMask[BitWidth-1] == 0) {
1142       // Right fill the mask of bits for this SUB to demand the most
1143       // significant bit and all those below it.
1144       uint32_t NLZ = DemandedMask.countLeadingZeros();
1145       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1146       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1147                                LHSKnownZero, LHSKnownOne, Depth+1))
1148         return true;
1149       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1150                                LHSKnownZero, LHSKnownOne, Depth+1))
1151         return true;
1152     }
1153     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1154     // the known zeros and ones.
1155     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1156     break;
1157   case Instruction::Shl:
1158     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1160       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1161       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1162                                RHSKnownZero, RHSKnownOne, Depth+1))
1163         return true;
1164       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1165              "Bits known to be one AND zero?"); 
1166       RHSKnownZero <<= ShiftAmt;
1167       RHSKnownOne  <<= ShiftAmt;
1168       // low bits known zero.
1169       if (ShiftAmt)
1170         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1171     }
1172     break;
1173   case Instruction::LShr:
1174     // For a logical shift right
1175     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1177       
1178       // Unsigned shift right.
1179       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1180       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1181                                RHSKnownZero, RHSKnownOne, Depth+1))
1182         return true;
1183       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1184              "Bits known to be one AND zero?"); 
1185       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1186       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1187       if (ShiftAmt) {
1188         // Compute the new bits that are at the top now.
1189         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1190         RHSKnownZero |= HighBits;  // high bits known zero.
1191       }
1192     }
1193     break;
1194   case Instruction::AShr:
1195     // If this is an arithmetic shift right and only the low-bit is set, we can
1196     // always convert this into a logical shr, even if the shift amount is
1197     // variable.  The low bit of the shift cannot be an input sign bit unless
1198     // the shift amount is >= the size of the datatype, which is undefined.
1199     if (DemandedMask == 1) {
1200       // Perform the logical shift right.
1201       Value *NewVal = BinaryOperator::CreateLShr(
1202                         I->getOperand(0), I->getOperand(1), I->getName());
1203       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1204       return UpdateValueUsesWith(I, NewVal);
1205     }    
1206
1207     // If the sign bit is the only bit demanded by this ashr, then there is no
1208     // need to do it, the shift doesn't change the high bit.
1209     if (DemandedMask.isSignBit())
1210       return UpdateValueUsesWith(I, I->getOperand(0));
1211     
1212     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1213       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1214       
1215       // Signed shift right.
1216       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1217       // If any of the "high bits" are demanded, we should set the sign bit as
1218       // demanded.
1219       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1220         DemandedMaskIn.set(BitWidth-1);
1221       if (SimplifyDemandedBits(I->getOperand(0),
1222                                DemandedMaskIn,
1223                                RHSKnownZero, RHSKnownOne, Depth+1))
1224         return true;
1225       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1226              "Bits known to be one AND zero?"); 
1227       // Compute the new bits that are at the top now.
1228       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1229       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1230       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1231         
1232       // Handle the sign bits.
1233       APInt SignBit(APInt::getSignBit(BitWidth));
1234       // Adjust to where it is now in the mask.
1235       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1236         
1237       // If the input sign bit is known to be zero, or if none of the top bits
1238       // are demanded, turn this into an unsigned shift right.
1239       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1240           (HighBits & ~DemandedMask) == HighBits) {
1241         // Perform the logical shift right.
1242         Value *NewVal = BinaryOperator::CreateLShr(
1243                           I->getOperand(0), SA, I->getName());
1244         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1245         return UpdateValueUsesWith(I, NewVal);
1246       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1247         RHSKnownOne |= HighBits;
1248       }
1249     }
1250     break;
1251   case Instruction::SRem:
1252     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1253       APInt RA = Rem->getValue();
1254       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1255         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1256         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1257         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1258                                  LHSKnownZero, LHSKnownOne, Depth+1))
1259           return true;
1260
1261         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1262           LHSKnownZero |= ~LowBits;
1263         else if (LHSKnownOne[BitWidth-1])
1264           LHSKnownOne |= ~LowBits;
1265
1266         KnownZero |= LHSKnownZero & DemandedMask;
1267         KnownOne |= LHSKnownOne & DemandedMask;
1268
1269         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1270       }
1271     }
1272     break;
1273   case Instruction::URem: {
1274     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1275       APInt RA = Rem->getValue();
1276       if (RA.isPowerOf2()) {
1277         APInt LowBits = (RA - 1);
1278         APInt Mask2 = LowBits & DemandedMask;
1279         KnownZero |= ~LowBits & DemandedMask;
1280         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1281                                  KnownZero, KnownOne, Depth+1))
1282           return true;
1283
1284         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1285         break;
1286       }
1287     }
1288
1289     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1290     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1291     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1292                              KnownZero2, KnownOne2, Depth+1))
1293       return true;
1294
1295     uint32_t Leaders = KnownZero2.countLeadingOnes();
1296     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1297                              KnownZero2, KnownOne2, Depth+1))
1298       return true;
1299
1300     Leaders = std::max(Leaders,
1301                        KnownZero2.countLeadingOnes());
1302     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1303     break;
1304   }
1305   }
1306   
1307   // If the client is only demanding bits that we know, return the known
1308   // constant.
1309   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1310     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1311   return false;
1312 }
1313
1314
1315 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1316 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1317 /// actually used by the caller.  This method analyzes which elements of the
1318 /// operand are undef and returns that information in UndefElts.
1319 ///
1320 /// If the information about demanded elements can be used to simplify the
1321 /// operation, the operation is simplified, then the resultant value is
1322 /// returned.  This returns null if no change was made.
1323 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1324                                                 uint64_t &UndefElts,
1325                                                 unsigned Depth) {
1326   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1327   assert(VWidth <= 64 && "Vector too wide to analyze!");
1328   uint64_t EltMask = ~0ULL >> (64-VWidth);
1329   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1330          "Invalid DemandedElts!");
1331
1332   if (isa<UndefValue>(V)) {
1333     // If the entire vector is undefined, just return this info.
1334     UndefElts = EltMask;
1335     return 0;
1336   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1337     UndefElts = EltMask;
1338     return UndefValue::get(V->getType());
1339   }
1340   
1341   UndefElts = 0;
1342   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1343     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1344     Constant *Undef = UndefValue::get(EltTy);
1345
1346     std::vector<Constant*> Elts;
1347     for (unsigned i = 0; i != VWidth; ++i)
1348       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1349         Elts.push_back(Undef);
1350         UndefElts |= (1ULL << i);
1351       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1352         Elts.push_back(Undef);
1353         UndefElts |= (1ULL << i);
1354       } else {                               // Otherwise, defined.
1355         Elts.push_back(CP->getOperand(i));
1356       }
1357         
1358     // If we changed the constant, return it.
1359     Constant *NewCP = ConstantVector::get(Elts);
1360     return NewCP != CP ? NewCP : 0;
1361   } else if (isa<ConstantAggregateZero>(V)) {
1362     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1363     // set to undef.
1364     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1365     Constant *Zero = Constant::getNullValue(EltTy);
1366     Constant *Undef = UndefValue::get(EltTy);
1367     std::vector<Constant*> Elts;
1368     for (unsigned i = 0; i != VWidth; ++i)
1369       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1370     UndefElts = DemandedElts ^ EltMask;
1371     return ConstantVector::get(Elts);
1372   }
1373   
1374   if (!V->hasOneUse()) {    // Other users may use these bits.
1375     if (Depth != 0) {       // Not at the root.
1376       // TODO: Just compute the UndefElts information recursively.
1377       return false;
1378     }
1379     return false;
1380   } else if (Depth == 10) {        // Limit search depth.
1381     return false;
1382   }
1383   
1384   Instruction *I = dyn_cast<Instruction>(V);
1385   if (!I) return false;        // Only analyze instructions.
1386   
1387   bool MadeChange = false;
1388   uint64_t UndefElts2;
1389   Value *TmpV;
1390   switch (I->getOpcode()) {
1391   default: break;
1392     
1393   case Instruction::InsertElement: {
1394     // If this is a variable index, we don't know which element it overwrites.
1395     // demand exactly the same input as we produce.
1396     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1397     if (Idx == 0) {
1398       // Note that we can't propagate undef elt info, because we don't know
1399       // which elt is getting updated.
1400       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1401                                         UndefElts2, Depth+1);
1402       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1403       break;
1404     }
1405     
1406     // If this is inserting an element that isn't demanded, remove this
1407     // insertelement.
1408     unsigned IdxNo = Idx->getZExtValue();
1409     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1410       return AddSoonDeadInstToWorklist(*I, 0);
1411     
1412     // Otherwise, the element inserted overwrites whatever was there, so the
1413     // input demanded set is simpler than the output set.
1414     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1415                                       DemandedElts & ~(1ULL << IdxNo),
1416                                       UndefElts, Depth+1);
1417     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1418
1419     // The inserted element is defined.
1420     UndefElts |= 1ULL << IdxNo;
1421     break;
1422   }
1423   case Instruction::BitCast: {
1424     // Vector->vector casts only.
1425     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1426     if (!VTy) break;
1427     unsigned InVWidth = VTy->getNumElements();
1428     uint64_t InputDemandedElts = 0;
1429     unsigned Ratio;
1430
1431     if (VWidth == InVWidth) {
1432       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1433       // elements as are demanded of us.
1434       Ratio = 1;
1435       InputDemandedElts = DemandedElts;
1436     } else if (VWidth > InVWidth) {
1437       // Untested so far.
1438       break;
1439       
1440       // If there are more elements in the result than there are in the source,
1441       // then an input element is live if any of the corresponding output
1442       // elements are live.
1443       Ratio = VWidth/InVWidth;
1444       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1445         if (DemandedElts & (1ULL << OutIdx))
1446           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1447       }
1448     } else {
1449       // Untested so far.
1450       break;
1451       
1452       // If there are more elements in the source than there are in the result,
1453       // then an input element is live if the corresponding output element is
1454       // live.
1455       Ratio = InVWidth/VWidth;
1456       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1457         if (DemandedElts & (1ULL << InIdx/Ratio))
1458           InputDemandedElts |= 1ULL << InIdx;
1459     }
1460     
1461     // div/rem demand all inputs, because they don't want divide by zero.
1462     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1463                                       UndefElts2, Depth+1);
1464     if (TmpV) {
1465       I->setOperand(0, TmpV);
1466       MadeChange = true;
1467     }
1468     
1469     UndefElts = UndefElts2;
1470     if (VWidth > InVWidth) {
1471       assert(0 && "Unimp");
1472       // If there are more elements in the result than there are in the source,
1473       // then an output element is undef if the corresponding input element is
1474       // undef.
1475       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1476         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1477           UndefElts |= 1ULL << OutIdx;
1478     } else if (VWidth < InVWidth) {
1479       assert(0 && "Unimp");
1480       // If there are more elements in the source than there are in the result,
1481       // then a result element is undef if all of the corresponding input
1482       // elements are undef.
1483       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1484       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1485         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1486           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1487     }
1488     break;
1489   }
1490   case Instruction::And:
1491   case Instruction::Or:
1492   case Instruction::Xor:
1493   case Instruction::Add:
1494   case Instruction::Sub:
1495   case Instruction::Mul:
1496     // div/rem demand all inputs, because they don't want divide by zero.
1497     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1498                                       UndefElts, Depth+1);
1499     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1500     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1501                                       UndefElts2, Depth+1);
1502     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
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   case Instruction::Call: {
1510     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1511     if (!II) break;
1512     switch (II->getIntrinsicID()) {
1513     default: break;
1514       
1515     // Binary vector operations that work column-wise.  A dest element is a
1516     // function of the corresponding input elements from the two inputs.
1517     case Intrinsic::x86_sse_sub_ss:
1518     case Intrinsic::x86_sse_mul_ss:
1519     case Intrinsic::x86_sse_min_ss:
1520     case Intrinsic::x86_sse_max_ss:
1521     case Intrinsic::x86_sse2_sub_sd:
1522     case Intrinsic::x86_sse2_mul_sd:
1523     case Intrinsic::x86_sse2_min_sd:
1524     case Intrinsic::x86_sse2_max_sd:
1525       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1526                                         UndefElts, Depth+1);
1527       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1528       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1529                                         UndefElts2, Depth+1);
1530       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1531
1532       // If only the low elt is demanded and this is a scalarizable intrinsic,
1533       // scalarize it now.
1534       if (DemandedElts == 1) {
1535         switch (II->getIntrinsicID()) {
1536         default: break;
1537         case Intrinsic::x86_sse_sub_ss:
1538         case Intrinsic::x86_sse_mul_ss:
1539         case Intrinsic::x86_sse2_sub_sd:
1540         case Intrinsic::x86_sse2_mul_sd:
1541           // TODO: Lower MIN/MAX/ABS/etc
1542           Value *LHS = II->getOperand(1);
1543           Value *RHS = II->getOperand(2);
1544           // Extract the element as scalars.
1545           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1546           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1547           
1548           switch (II->getIntrinsicID()) {
1549           default: assert(0 && "Case stmts out of sync!");
1550           case Intrinsic::x86_sse_sub_ss:
1551           case Intrinsic::x86_sse2_sub_sd:
1552             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1553                                                         II->getName()), *II);
1554             break;
1555           case Intrinsic::x86_sse_mul_ss:
1556           case Intrinsic::x86_sse2_mul_sd:
1557             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1558                                                          II->getName()), *II);
1559             break;
1560           }
1561           
1562           Instruction *New =
1563             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1564                                       II->getName());
1565           InsertNewInstBefore(New, *II);
1566           AddSoonDeadInstToWorklist(*II, 0);
1567           return New;
1568         }            
1569       }
1570         
1571       // Output elements are undefined if both are undefined.  Consider things
1572       // like undef&0.  The result is known zero, not undef.
1573       UndefElts &= UndefElts2;
1574       break;
1575     }
1576     break;
1577   }
1578   }
1579   return MadeChange ? I : 0;
1580 }
1581
1582
1583 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1584 /// function is designed to check a chain of associative operators for a
1585 /// potential to apply a certain optimization.  Since the optimization may be
1586 /// applicable if the expression was reassociated, this checks the chain, then
1587 /// reassociates the expression as necessary to expose the optimization
1588 /// opportunity.  This makes use of a special Functor, which must define
1589 /// 'shouldApply' and 'apply' methods.
1590 ///
1591 template<typename Functor>
1592 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1593   unsigned Opcode = Root.getOpcode();
1594   Value *LHS = Root.getOperand(0);
1595
1596   // Quick check, see if the immediate LHS matches...
1597   if (F.shouldApply(LHS))
1598     return F.apply(Root);
1599
1600   // Otherwise, if the LHS is not of the same opcode as the root, return.
1601   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1602   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1603     // Should we apply this transform to the RHS?
1604     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1605
1606     // If not to the RHS, check to see if we should apply to the LHS...
1607     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1608       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1609       ShouldApply = true;
1610     }
1611
1612     // If the functor wants to apply the optimization to the RHS of LHSI,
1613     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1614     if (ShouldApply) {
1615       BasicBlock *BB = Root.getParent();
1616
1617       // Now all of the instructions are in the current basic block, go ahead
1618       // and perform the reassociation.
1619       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1620
1621       // First move the selected RHS to the LHS of the root...
1622       Root.setOperand(0, LHSI->getOperand(1));
1623
1624       // Make what used to be the LHS of the root be the user of the root...
1625       Value *ExtraOperand = TmpLHSI->getOperand(1);
1626       if (&Root == TmpLHSI) {
1627         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1628         return 0;
1629       }
1630       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1631       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1632       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1633       BasicBlock::iterator ARI = &Root; ++ARI;
1634       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1635       ARI = Root;
1636
1637       // Now propagate the ExtraOperand down the chain of instructions until we
1638       // get to LHSI.
1639       while (TmpLHSI != LHSI) {
1640         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1641         // Move the instruction to immediately before the chain we are
1642         // constructing to avoid breaking dominance properties.
1643         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1644         BB->getInstList().insert(ARI, NextLHSI);
1645         ARI = NextLHSI;
1646
1647         Value *NextOp = NextLHSI->getOperand(1);
1648         NextLHSI->setOperand(1, ExtraOperand);
1649         TmpLHSI = NextLHSI;
1650         ExtraOperand = NextOp;
1651       }
1652
1653       // Now that the instructions are reassociated, have the functor perform
1654       // the transformation...
1655       return F.apply(Root);
1656     }
1657
1658     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1659   }
1660   return 0;
1661 }
1662
1663 namespace {
1664
1665 // AddRHS - Implements: X + X --> X << 1
1666 struct AddRHS {
1667   Value *RHS;
1668   AddRHS(Value *rhs) : RHS(rhs) {}
1669   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1670   Instruction *apply(BinaryOperator &Add) const {
1671     return BinaryOperator::CreateShl(Add.getOperand(0),
1672                                      ConstantInt::get(Add.getType(), 1));
1673   }
1674 };
1675
1676 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1677 //                 iff C1&C2 == 0
1678 struct AddMaskingAnd {
1679   Constant *C2;
1680   AddMaskingAnd(Constant *c) : C2(c) {}
1681   bool shouldApply(Value *LHS) const {
1682     ConstantInt *C1;
1683     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1684            ConstantExpr::getAnd(C1, C2)->isNullValue();
1685   }
1686   Instruction *apply(BinaryOperator &Add) const {
1687     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1688   }
1689 };
1690
1691 }
1692
1693 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1694                                              InstCombiner *IC) {
1695   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1696     if (Constant *SOC = dyn_cast<Constant>(SO))
1697       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1698
1699     return IC->InsertNewInstBefore(CastInst::Create(
1700           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1701   }
1702
1703   // Figure out if the constant is the left or the right argument.
1704   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1705   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1706
1707   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1708     if (ConstIsRHS)
1709       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1710     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1711   }
1712
1713   Value *Op0 = SO, *Op1 = ConstOperand;
1714   if (!ConstIsRHS)
1715     std::swap(Op0, Op1);
1716   Instruction *New;
1717   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1718     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1719   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1720     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1721                           SO->getName()+".cmp");
1722   else {
1723     assert(0 && "Unknown binary instruction type!");
1724     abort();
1725   }
1726   return IC->InsertNewInstBefore(New, I);
1727 }
1728
1729 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1730 // constant as the other operand, try to fold the binary operator into the
1731 // select arguments.  This also works for Cast instructions, which obviously do
1732 // not have a second operand.
1733 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1734                                      InstCombiner *IC) {
1735   // Don't modify shared select instructions
1736   if (!SI->hasOneUse()) return 0;
1737   Value *TV = SI->getOperand(1);
1738   Value *FV = SI->getOperand(2);
1739
1740   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1741     // Bool selects with constant operands can be folded to logical ops.
1742     if (SI->getType() == Type::Int1Ty) return 0;
1743
1744     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1745     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1746
1747     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1748                               SelectFalseVal);
1749   }
1750   return 0;
1751 }
1752
1753
1754 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1755 /// node as operand #0, see if we can fold the instruction into the PHI (which
1756 /// is only possible if all operands to the PHI are constants).
1757 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1758   PHINode *PN = cast<PHINode>(I.getOperand(0));
1759   unsigned NumPHIValues = PN->getNumIncomingValues();
1760   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1761
1762   // Check to see if all of the operands of the PHI are constants.  If there is
1763   // one non-constant value, remember the BB it is.  If there is more than one
1764   // or if *it* is a PHI, bail out.
1765   BasicBlock *NonConstBB = 0;
1766   for (unsigned i = 0; i != NumPHIValues; ++i)
1767     if (!isa<Constant>(PN->getIncomingValue(i))) {
1768       if (NonConstBB) return 0;  // More than one non-const value.
1769       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1770       NonConstBB = PN->getIncomingBlock(i);
1771       
1772       // If the incoming non-constant value is in I's block, we have an infinite
1773       // loop.
1774       if (NonConstBB == I.getParent())
1775         return 0;
1776     }
1777   
1778   // If there is exactly one non-constant value, we can insert a copy of the
1779   // operation in that block.  However, if this is a critical edge, we would be
1780   // inserting the computation one some other paths (e.g. inside a loop).  Only
1781   // do this if the pred block is unconditionally branching into the phi block.
1782   if (NonConstBB) {
1783     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1784     if (!BI || !BI->isUnconditional()) return 0;
1785   }
1786
1787   // Okay, we can do the transformation: create the new PHI node.
1788   PHINode *NewPN = PHINode::Create(I.getType(), "");
1789   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1790   InsertNewInstBefore(NewPN, *PN);
1791   NewPN->takeName(PN);
1792
1793   // Next, add all of the operands to the PHI.
1794   if (I.getNumOperands() == 2) {
1795     Constant *C = cast<Constant>(I.getOperand(1));
1796     for (unsigned i = 0; i != NumPHIValues; ++i) {
1797       Value *InV = 0;
1798       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1799         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1800           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1801         else
1802           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1803       } else {
1804         assert(PN->getIncomingBlock(i) == NonConstBB);
1805         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1806           InV = BinaryOperator::Create(BO->getOpcode(),
1807                                        PN->getIncomingValue(i), C, "phitmp",
1808                                        NonConstBB->getTerminator());
1809         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1810           InV = CmpInst::Create(CI->getOpcode(), 
1811                                 CI->getPredicate(),
1812                                 PN->getIncomingValue(i), C, "phitmp",
1813                                 NonConstBB->getTerminator());
1814         else
1815           assert(0 && "Unknown binop!");
1816         
1817         AddToWorkList(cast<Instruction>(InV));
1818       }
1819       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1820     }
1821   } else { 
1822     CastInst *CI = cast<CastInst>(&I);
1823     const Type *RetTy = CI->getType();
1824     for (unsigned i = 0; i != NumPHIValues; ++i) {
1825       Value *InV;
1826       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1827         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1828       } else {
1829         assert(PN->getIncomingBlock(i) == NonConstBB);
1830         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1831                                I.getType(), "phitmp", 
1832                                NonConstBB->getTerminator());
1833         AddToWorkList(cast<Instruction>(InV));
1834       }
1835       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1836     }
1837   }
1838   return ReplaceInstUsesWith(I, NewPN);
1839 }
1840
1841
1842 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1843 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1844 /// This basically requires proving that the add in the original type would not
1845 /// overflow to change the sign bit or have a carry out.
1846 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1847   // There are different heuristics we can use for this.  Here are some simple
1848   // ones.
1849   
1850   // Add has the property that adding any two 2's complement numbers can only 
1851   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1852   // have at least two sign bits, we know that the addition of the two values will
1853   // sign extend fine.
1854   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1855     return true;
1856   
1857   
1858   // If one of the operands only has one non-zero bit, and if the other operand
1859   // has a known-zero bit in a more significant place than it (not including the
1860   // sign bit) the ripple may go up to and fill the zero, but won't change the
1861   // sign.  For example, (X & ~4) + 1.
1862   
1863   // TODO: Implement.
1864   
1865   return false;
1866 }
1867
1868
1869 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1870   bool Changed = SimplifyCommutative(I);
1871   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1872
1873   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1874     // X + undef -> undef
1875     if (isa<UndefValue>(RHS))
1876       return ReplaceInstUsesWith(I, RHS);
1877
1878     // X + 0 --> X
1879     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1880       if (RHSC->isNullValue())
1881         return ReplaceInstUsesWith(I, LHS);
1882     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1883       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1884                               (I.getType())->getValueAPF()))
1885         return ReplaceInstUsesWith(I, LHS);
1886     }
1887
1888     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1889       // X + (signbit) --> X ^ signbit
1890       const APInt& Val = CI->getValue();
1891       uint32_t BitWidth = Val.getBitWidth();
1892       if (Val == APInt::getSignBit(BitWidth))
1893         return BinaryOperator::CreateXor(LHS, RHS);
1894       
1895       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1896       // (X & 254)+1 -> (X&254)|1
1897       if (!isa<VectorType>(I.getType())) {
1898         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1899         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1900                                  KnownZero, KnownOne))
1901           return &I;
1902       }
1903     }
1904
1905     if (isa<PHINode>(LHS))
1906       if (Instruction *NV = FoldOpIntoPhi(I))
1907         return NV;
1908     
1909     ConstantInt *XorRHS = 0;
1910     Value *XorLHS = 0;
1911     if (isa<ConstantInt>(RHSC) &&
1912         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1913       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1914       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1915       
1916       uint32_t Size = TySizeBits / 2;
1917       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1918       APInt CFF80Val(-C0080Val);
1919       do {
1920         if (TySizeBits > Size) {
1921           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1922           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1923           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1924               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1925             // This is a sign extend if the top bits are known zero.
1926             if (!MaskedValueIsZero(XorLHS, 
1927                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1928               Size = 0;  // Not a sign ext, but can't be any others either.
1929             break;
1930           }
1931         }
1932         Size >>= 1;
1933         C0080Val = APIntOps::lshr(C0080Val, Size);
1934         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1935       } while (Size >= 1);
1936       
1937       // FIXME: This shouldn't be necessary. When the backends can handle types
1938       // with funny bit widths then this switch statement should be removed. It
1939       // is just here to get the size of the "middle" type back up to something
1940       // that the back ends can handle.
1941       const Type *MiddleType = 0;
1942       switch (Size) {
1943         default: break;
1944         case 32: MiddleType = Type::Int32Ty; break;
1945         case 16: MiddleType = Type::Int16Ty; break;
1946         case  8: MiddleType = Type::Int8Ty; break;
1947       }
1948       if (MiddleType) {
1949         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1950         InsertNewInstBefore(NewTrunc, I);
1951         return new SExtInst(NewTrunc, I.getType(), I.getName());
1952       }
1953     }
1954   }
1955
1956   if (I.getType() == Type::Int1Ty)
1957     return BinaryOperator::CreateXor(LHS, RHS);
1958
1959   // X + X --> X << 1
1960   if (I.getType()->isInteger()) {
1961     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1962
1963     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1964       if (RHSI->getOpcode() == Instruction::Sub)
1965         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1966           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1967     }
1968     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1969       if (LHSI->getOpcode() == Instruction::Sub)
1970         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1971           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1972     }
1973   }
1974
1975   // -A + B  -->  B - A
1976   // -A + -B  -->  -(A + B)
1977   if (Value *LHSV = dyn_castNegVal(LHS)) {
1978     if (LHS->getType()->isIntOrIntVector()) {
1979       if (Value *RHSV = dyn_castNegVal(RHS)) {
1980         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
1981         InsertNewInstBefore(NewAdd, I);
1982         return BinaryOperator::CreateNeg(NewAdd);
1983       }
1984     }
1985     
1986     return BinaryOperator::CreateSub(RHS, LHSV);
1987   }
1988
1989   // A + -B  -->  A - B
1990   if (!isa<Constant>(RHS))
1991     if (Value *V = dyn_castNegVal(RHS))
1992       return BinaryOperator::CreateSub(LHS, V);
1993
1994
1995   ConstantInt *C2;
1996   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1997     if (X == RHS)   // X*C + X --> X * (C+1)
1998       return BinaryOperator::CreateMul(RHS, AddOne(C2));
1999
2000     // X*C1 + X*C2 --> X * (C1+C2)
2001     ConstantInt *C1;
2002     if (X == dyn_castFoldableMul(RHS, C1))
2003       return BinaryOperator::CreateMul(X, Add(C1, C2));
2004   }
2005
2006   // X + X*C --> X * (C+1)
2007   if (dyn_castFoldableMul(RHS, C2) == LHS)
2008     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2009
2010   // X + ~X --> -1   since   ~X = -X-1
2011   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2012     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2013   
2014
2015   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2016   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2017     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2018       return R;
2019   
2020   // A+B --> A|B iff A and B have no bits set in common.
2021   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2022     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2023     APInt LHSKnownOne(IT->getBitWidth(), 0);
2024     APInt LHSKnownZero(IT->getBitWidth(), 0);
2025     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2026     if (LHSKnownZero != 0) {
2027       APInt RHSKnownOne(IT->getBitWidth(), 0);
2028       APInt RHSKnownZero(IT->getBitWidth(), 0);
2029       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2030       
2031       // No bits in common -> bitwise or.
2032       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2033         return BinaryOperator::CreateOr(LHS, RHS);
2034     }
2035   }
2036
2037   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2038   if (I.getType()->isIntOrIntVector()) {
2039     Value *W, *X, *Y, *Z;
2040     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2041         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2042       if (W != Y) {
2043         if (W == Z) {
2044           std::swap(Y, Z);
2045         } else if (Y == X) {
2046           std::swap(W, X);
2047         } else if (X == Z) {
2048           std::swap(Y, Z);
2049           std::swap(W, X);
2050         }
2051       }
2052
2053       if (W == Y) {
2054         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2055                                                             LHS->getName()), I);
2056         return BinaryOperator::CreateMul(W, NewAdd);
2057       }
2058     }
2059   }
2060
2061   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2062     Value *X = 0;
2063     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2064       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2065
2066     // (X & FF00) + xx00  -> (X+xx00) & FF00
2067     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2068       Constant *Anded = And(CRHS, C2);
2069       if (Anded == CRHS) {
2070         // See if all bits from the first bit set in the Add RHS up are included
2071         // in the mask.  First, get the rightmost bit.
2072         const APInt& AddRHSV = CRHS->getValue();
2073
2074         // Form a mask of all bits from the lowest bit added through the top.
2075         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2076
2077         // See if the and mask includes all of these bits.
2078         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2079
2080         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2081           // Okay, the xform is safe.  Insert the new add pronto.
2082           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2083                                                             LHS->getName()), I);
2084           return BinaryOperator::CreateAnd(NewAdd, C2);
2085         }
2086       }
2087     }
2088
2089     // Try to fold constant add into select arguments.
2090     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2091       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2092         return R;
2093   }
2094
2095   // add (cast *A to intptrtype) B -> 
2096   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2097   {
2098     CastInst *CI = dyn_cast<CastInst>(LHS);
2099     Value *Other = RHS;
2100     if (!CI) {
2101       CI = dyn_cast<CastInst>(RHS);
2102       Other = LHS;
2103     }
2104     if (CI && CI->getType()->isSized() && 
2105         (CI->getType()->getPrimitiveSizeInBits() == 
2106          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2107         && isa<PointerType>(CI->getOperand(0)->getType())) {
2108       unsigned AS =
2109         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2110       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2111                                       PointerType::get(Type::Int8Ty, AS), I);
2112       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2113       return new PtrToIntInst(I2, CI->getType());
2114     }
2115   }
2116   
2117   // add (select X 0 (sub n A)) A  -->  select X A n
2118   {
2119     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2120     Value *Other = RHS;
2121     if (!SI) {
2122       SI = dyn_cast<SelectInst>(RHS);
2123       Other = LHS;
2124     }
2125     if (SI && SI->hasOneUse()) {
2126       Value *TV = SI->getTrueValue();
2127       Value *FV = SI->getFalseValue();
2128       Value *A, *N;
2129
2130       // Can we fold the add into the argument of the select?
2131       // We check both true and false select arguments for a matching subtract.
2132       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2133           A == Other)  // Fold the add into the true select value.
2134         return SelectInst::Create(SI->getCondition(), N, A);
2135       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2136           A == Other)  // Fold the add into the false select value.
2137         return SelectInst::Create(SI->getCondition(), A, N);
2138     }
2139   }
2140   
2141   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2142   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2143     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2144       return ReplaceInstUsesWith(I, LHS);
2145
2146   // Check for (add (sext x), y), see if we can merge this into an
2147   // integer add followed by a sext.
2148   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2149     // (add (sext x), cst) --> (sext (add x, cst'))
2150     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2151       Constant *CI = 
2152         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2153       if (LHSConv->hasOneUse() &&
2154           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2155           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2156         // Insert the new, smaller add.
2157         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2158                                                         CI, "addconv");
2159         InsertNewInstBefore(NewAdd, I);
2160         return new SExtInst(NewAdd, I.getType());
2161       }
2162     }
2163     
2164     // (add (sext x), (sext y)) --> (sext (add int x, y))
2165     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2166       // Only do this if x/y have the same type, if at last one of them has a
2167       // single use (so we don't increase the number of sexts), and if the
2168       // integer add will not overflow.
2169       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2170           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2171           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2172                                    RHSConv->getOperand(0))) {
2173         // Insert the new integer add.
2174         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2175                                                         RHSConv->getOperand(0),
2176                                                         "addconv");
2177         InsertNewInstBefore(NewAdd, I);
2178         return new SExtInst(NewAdd, I.getType());
2179       }
2180     }
2181   }
2182   
2183   // Check for (add double (sitofp x), y), see if we can merge this into an
2184   // integer add followed by a promotion.
2185   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2186     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2187     // ... if the constant fits in the integer value.  This is useful for things
2188     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2189     // requires a constant pool load, and generally allows the add to be better
2190     // instcombined.
2191     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2192       Constant *CI = 
2193       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2194       if (LHSConv->hasOneUse() &&
2195           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2196           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2197         // Insert the new integer add.
2198         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2199                                                         CI, "addconv");
2200         InsertNewInstBefore(NewAdd, I);
2201         return new SIToFPInst(NewAdd, I.getType());
2202       }
2203     }
2204     
2205     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2206     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2207       // Only do this if x/y have the same type, if at last one of them has a
2208       // single use (so we don't increase the number of int->fp conversions),
2209       // and if the integer add will not overflow.
2210       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2211           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2212           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2213                                    RHSConv->getOperand(0))) {
2214         // Insert the new integer add.
2215         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2216                                                         RHSConv->getOperand(0),
2217                                                         "addconv");
2218         InsertNewInstBefore(NewAdd, I);
2219         return new SIToFPInst(NewAdd, I.getType());
2220       }
2221     }
2222   }
2223   
2224   return Changed ? &I : 0;
2225 }
2226
2227 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2228   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2229
2230   if (Op0 == Op1)         // sub X, X  -> 0
2231     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2232
2233   // If this is a 'B = x-(-A)', change to B = x+A...
2234   if (Value *V = dyn_castNegVal(Op1))
2235     return BinaryOperator::CreateAdd(Op0, V);
2236
2237   if (isa<UndefValue>(Op0))
2238     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2239   if (isa<UndefValue>(Op1))
2240     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2241
2242   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2243     // Replace (-1 - A) with (~A)...
2244     if (C->isAllOnesValue())
2245       return BinaryOperator::CreateNot(Op1);
2246
2247     // C - ~X == X + (1+C)
2248     Value *X = 0;
2249     if (match(Op1, m_Not(m_Value(X))))
2250       return BinaryOperator::CreateAdd(X, AddOne(C));
2251
2252     // -(X >>u 31) -> (X >>s 31)
2253     // -(X >>s 31) -> (X >>u 31)
2254     if (C->isZero()) {
2255       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2256         if (SI->getOpcode() == Instruction::LShr) {
2257           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2258             // Check to see if we are shifting out everything but the sign bit.
2259             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2260                 SI->getType()->getPrimitiveSizeInBits()-1) {
2261               // Ok, the transformation is safe.  Insert AShr.
2262               return BinaryOperator::Create(Instruction::AShr, 
2263                                           SI->getOperand(0), CU, SI->getName());
2264             }
2265           }
2266         }
2267         else if (SI->getOpcode() == Instruction::AShr) {
2268           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2269             // Check to see if we are shifting out everything but the sign bit.
2270             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2271                 SI->getType()->getPrimitiveSizeInBits()-1) {
2272               // Ok, the transformation is safe.  Insert LShr. 
2273               return BinaryOperator::CreateLShr(
2274                                           SI->getOperand(0), CU, SI->getName());
2275             }
2276           }
2277         }
2278       }
2279     }
2280
2281     // Try to fold constant sub into select arguments.
2282     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2283       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2284         return R;
2285
2286     if (isa<PHINode>(Op0))
2287       if (Instruction *NV = FoldOpIntoPhi(I))
2288         return NV;
2289   }
2290
2291   if (I.getType() == Type::Int1Ty)
2292     return BinaryOperator::CreateXor(Op0, Op1);
2293
2294   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2295     if (Op1I->getOpcode() == Instruction::Add &&
2296         !Op0->getType()->isFPOrFPVector()) {
2297       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2298         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2299       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2300         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2301       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2302         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2303           // C1-(X+C2) --> (C1-C2)-X
2304           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2305                                            Op1I->getOperand(0));
2306       }
2307     }
2308
2309     if (Op1I->hasOneUse()) {
2310       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2311       // is not used by anyone else...
2312       //
2313       if (Op1I->getOpcode() == Instruction::Sub &&
2314           !Op1I->getType()->isFPOrFPVector()) {
2315         // Swap the two operands of the subexpr...
2316         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2317         Op1I->setOperand(0, IIOp1);
2318         Op1I->setOperand(1, IIOp0);
2319
2320         // Create the new top level add instruction...
2321         return BinaryOperator::CreateAdd(Op0, Op1);
2322       }
2323
2324       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2325       //
2326       if (Op1I->getOpcode() == Instruction::And &&
2327           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2328         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2329
2330         Value *NewNot =
2331           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2332         return BinaryOperator::CreateAnd(Op0, NewNot);
2333       }
2334
2335       // 0 - (X sdiv C)  -> (X sdiv -C)
2336       if (Op1I->getOpcode() == Instruction::SDiv)
2337         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2338           if (CSI->isZero())
2339             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2340               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2341                                                ConstantExpr::getNeg(DivRHS));
2342
2343       // X - X*C --> X * (1-C)
2344       ConstantInt *C2 = 0;
2345       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2346         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2347         return BinaryOperator::CreateMul(Op0, CP1);
2348       }
2349
2350       // X - ((X / Y) * Y) --> X % Y
2351       if (Op1I->getOpcode() == Instruction::Mul)
2352         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2353           if (Op0 == I->getOperand(0) &&
2354               Op1I->getOperand(1) == I->getOperand(1)) {
2355             if (I->getOpcode() == Instruction::SDiv)
2356               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2357             if (I->getOpcode() == Instruction::UDiv)
2358               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2359           }
2360     }
2361   }
2362
2363   if (!Op0->getType()->isFPOrFPVector())
2364     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2365       if (Op0I->getOpcode() == Instruction::Add) {
2366         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2367           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2368         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2369           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2370       } else if (Op0I->getOpcode() == Instruction::Sub) {
2371         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2372           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2373       }
2374     }
2375
2376   ConstantInt *C1;
2377   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2378     if (X == Op1)  // X*C - X --> X * (C-1)
2379       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2380
2381     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2382     if (X == dyn_castFoldableMul(Op1, C2))
2383       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2384   }
2385   return 0;
2386 }
2387
2388 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2389 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2390 /// TrueIfSigned if the result of the comparison is true when the input value is
2391 /// signed.
2392 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2393                            bool &TrueIfSigned) {
2394   switch (pred) {
2395   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2396     TrueIfSigned = true;
2397     return RHS->isZero();
2398   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2399     TrueIfSigned = true;
2400     return RHS->isAllOnesValue();
2401   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2402     TrueIfSigned = false;
2403     return RHS->isAllOnesValue();
2404   case ICmpInst::ICMP_UGT:
2405     // True if LHS u> RHS and RHS == high-bit-mask - 1
2406     TrueIfSigned = true;
2407     return RHS->getValue() ==
2408       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2409   case ICmpInst::ICMP_UGE: 
2410     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2411     TrueIfSigned = true;
2412     return RHS->getValue().isSignBit();
2413   default:
2414     return false;
2415   }
2416 }
2417
2418 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2419   bool Changed = SimplifyCommutative(I);
2420   Value *Op0 = I.getOperand(0);
2421
2422   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2423     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2424
2425   // Simplify mul instructions with a constant RHS...
2426   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2427     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2428
2429       // ((X << C1)*C2) == (X * (C2 << C1))
2430       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2431         if (SI->getOpcode() == Instruction::Shl)
2432           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2433             return BinaryOperator::CreateMul(SI->getOperand(0),
2434                                              ConstantExpr::getShl(CI, ShOp));
2435
2436       if (CI->isZero())
2437         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2438       if (CI->equalsInt(1))                  // X * 1  == X
2439         return ReplaceInstUsesWith(I, Op0);
2440       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2441         return BinaryOperator::CreateNeg(Op0, I.getName());
2442
2443       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2444       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2445         return BinaryOperator::CreateShl(Op0,
2446                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2447       }
2448     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2449       if (Op1F->isNullValue())
2450         return ReplaceInstUsesWith(I, Op1);
2451
2452       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2453       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2454       // We need a better interface for long double here.
2455       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2456         if (Op1F->isExactlyValue(1.0))
2457           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2458     }
2459     
2460     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2461       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2462           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2463         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2464         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2465                                                      Op1, "tmp");
2466         InsertNewInstBefore(Add, I);
2467         Value *C1C2 = ConstantExpr::getMul(Op1, 
2468                                            cast<Constant>(Op0I->getOperand(1)));
2469         return BinaryOperator::CreateAdd(Add, C1C2);
2470         
2471       }
2472
2473     // Try to fold constant mul into select arguments.
2474     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2475       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2476         return R;
2477
2478     if (isa<PHINode>(Op0))
2479       if (Instruction *NV = FoldOpIntoPhi(I))
2480         return NV;
2481   }
2482
2483   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2484     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2485       return BinaryOperator::CreateMul(Op0v, Op1v);
2486
2487   if (I.getType() == Type::Int1Ty)
2488     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2489
2490   // If one of the operands of the multiply is a cast from a boolean value, then
2491   // we know the bool is either zero or one, so this is a 'masking' multiply.
2492   // See if we can simplify things based on how the boolean was originally
2493   // formed.
2494   CastInst *BoolCast = 0;
2495   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2496     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2497       BoolCast = CI;
2498   if (!BoolCast)
2499     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2500       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2501         BoolCast = CI;
2502   if (BoolCast) {
2503     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2504       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2505       const Type *SCOpTy = SCIOp0->getType();
2506       bool TIS = false;
2507       
2508       // If the icmp is true iff the sign bit of X is set, then convert this
2509       // multiply into a shift/and combination.
2510       if (isa<ConstantInt>(SCIOp1) &&
2511           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2512           TIS) {
2513         // Shift the X value right to turn it into "all signbits".
2514         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2515                                           SCOpTy->getPrimitiveSizeInBits()-1);
2516         Value *V =
2517           InsertNewInstBefore(
2518             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2519                                             BoolCast->getOperand(0)->getName()+
2520                                             ".mask"), I);
2521
2522         // If the multiply type is not the same as the source type, sign extend
2523         // or truncate to the multiply type.
2524         if (I.getType() != V->getType()) {
2525           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2526           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2527           Instruction::CastOps opcode = 
2528             (SrcBits == DstBits ? Instruction::BitCast : 
2529              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2530           V = InsertCastBefore(opcode, V, I.getType(), I);
2531         }
2532
2533         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2534         return BinaryOperator::CreateAnd(V, OtherOp);
2535       }
2536     }
2537   }
2538
2539   return Changed ? &I : 0;
2540 }
2541
2542 /// This function implements the transforms on div instructions that work
2543 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2544 /// used by the visitors to those instructions.
2545 /// @brief Transforms common to all three div instructions
2546 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2547   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2548
2549   // undef / X -> 0        for integer.
2550   // undef / X -> undef    for FP (the undef could be a snan).
2551   if (isa<UndefValue>(Op0)) {
2552     if (Op0->getType()->isFPOrFPVector())
2553       return ReplaceInstUsesWith(I, Op0);
2554     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2555   }
2556
2557   // X / undef -> undef
2558   if (isa<UndefValue>(Op1))
2559     return ReplaceInstUsesWith(I, Op1);
2560
2561   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2562   // This does not apply for fdiv.
2563   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2564     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2565     // the same basic block, then we replace the select with Y, and the
2566     // condition of the select with false (if the cond value is in the same BB).
2567     // If the select has uses other than the div, this allows them to be
2568     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2569     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2570       if (ST->isNullValue()) {
2571         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2572         if (CondI && CondI->getParent() == I.getParent())
2573           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2574         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2575           I.setOperand(1, SI->getOperand(2));
2576         else
2577           UpdateValueUsesWith(SI, SI->getOperand(2));
2578         return &I;
2579       }
2580
2581     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2582     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2583       if (ST->isNullValue()) {
2584         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2585         if (CondI && CondI->getParent() == I.getParent())
2586           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2587         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2588           I.setOperand(1, SI->getOperand(1));
2589         else
2590           UpdateValueUsesWith(SI, SI->getOperand(1));
2591         return &I;
2592       }
2593   }
2594
2595   return 0;
2596 }
2597
2598 /// This function implements the transforms common to both integer division
2599 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2600 /// division instructions.
2601 /// @brief Common integer divide transforms
2602 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2603   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2604
2605   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2606   if (Op0 == Op1) {
2607     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2608       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2609       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2610       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2611     }
2612
2613     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2614     return ReplaceInstUsesWith(I, CI);
2615   }
2616   
2617   if (Instruction *Common = commonDivTransforms(I))
2618     return Common;
2619
2620   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2621     // div X, 1 == X
2622     if (RHS->equalsInt(1))
2623       return ReplaceInstUsesWith(I, Op0);
2624
2625     // (X / C1) / C2  -> X / (C1*C2)
2626     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2627       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2628         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2629           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2630             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2631           else 
2632             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2633                                           Multiply(RHS, LHSRHS));
2634         }
2635
2636     if (!RHS->isZero()) { // avoid X udiv 0
2637       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2638         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2639           return R;
2640       if (isa<PHINode>(Op0))
2641         if (Instruction *NV = FoldOpIntoPhi(I))
2642           return NV;
2643     }
2644   }
2645
2646   // 0 / X == 0, we don't need to preserve faults!
2647   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2648     if (LHS->equalsInt(0))
2649       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
2651   // It can't be division by zero, hence it must be division by one.
2652   if (I.getType() == Type::Int1Ty)
2653     return ReplaceInstUsesWith(I, Op0);
2654
2655   return 0;
2656 }
2657
2658 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2659   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2660
2661   // Handle the integer div common cases
2662   if (Instruction *Common = commonIDivTransforms(I))
2663     return Common;
2664
2665   // X udiv C^2 -> X >> C
2666   // Check to see if this is an unsigned division with an exact power of 2,
2667   // if so, convert to a right shift.
2668   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2669     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2670       return BinaryOperator::CreateLShr(Op0, 
2671                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2672   }
2673
2674   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2675   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2676     if (RHSI->getOpcode() == Instruction::Shl &&
2677         isa<ConstantInt>(RHSI->getOperand(0))) {
2678       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2679       if (C1.isPowerOf2()) {
2680         Value *N = RHSI->getOperand(1);
2681         const Type *NTy = N->getType();
2682         if (uint32_t C2 = C1.logBase2()) {
2683           Constant *C2V = ConstantInt::get(NTy, C2);
2684           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2685         }
2686         return BinaryOperator::CreateLShr(Op0, N);
2687       }
2688     }
2689   }
2690   
2691   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2692   // where C1&C2 are powers of two.
2693   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2694     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2695       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2696         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2697         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2698           // Compute the shift amounts
2699           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2700           // Construct the "on true" case of the select
2701           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2702           Instruction *TSI = BinaryOperator::CreateLShr(
2703                                                  Op0, TC, SI->getName()+".t");
2704           TSI = InsertNewInstBefore(TSI, I);
2705   
2706           // Construct the "on false" case of the select
2707           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2708           Instruction *FSI = BinaryOperator::CreateLShr(
2709                                                  Op0, FC, SI->getName()+".f");
2710           FSI = InsertNewInstBefore(FSI, I);
2711
2712           // construct the select instruction and return it.
2713           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2714         }
2715       }
2716   return 0;
2717 }
2718
2719 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2720   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2721
2722   // Handle the integer div common cases
2723   if (Instruction *Common = commonIDivTransforms(I))
2724     return Common;
2725
2726   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2727     // sdiv X, -1 == -X
2728     if (RHS->isAllOnesValue())
2729       return BinaryOperator::CreateNeg(Op0);
2730
2731     // -X/C -> X/-C
2732     if (Value *LHSNeg = dyn_castNegVal(Op0))
2733       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2734   }
2735
2736   // If the sign bits of both operands are zero (i.e. we can prove they are
2737   // unsigned inputs), turn this into a udiv.
2738   if (I.getType()->isInteger()) {
2739     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2740     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2741       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2742       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2743     }
2744   }      
2745   
2746   return 0;
2747 }
2748
2749 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2750   return commonDivTransforms(I);
2751 }
2752
2753 /// This function implements the transforms on rem instructions that work
2754 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2755 /// is used by the visitors to those instructions.
2756 /// @brief Transforms common to all three rem instructions
2757 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2758   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2759
2760   // 0 % X == 0 for integer, we don't need to preserve faults!
2761   if (Constant *LHS = dyn_cast<Constant>(Op0))
2762     if (LHS->isNullValue())
2763       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2764
2765   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2766     if (I.getType()->isFPOrFPVector())
2767       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2768     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2769   }
2770   if (isa<UndefValue>(Op1))
2771     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2772
2773   // Handle cases involving: rem X, (select Cond, Y, Z)
2774   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2775     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2776     // the same basic block, then we replace the select with Y, and the
2777     // condition of the select with false (if the cond value is in the same
2778     // BB).  If the select has uses other than the div, this allows them to be
2779     // simplified also.
2780     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2781       if (ST->isNullValue()) {
2782         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2783         if (CondI && CondI->getParent() == I.getParent())
2784           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2785         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2786           I.setOperand(1, SI->getOperand(2));
2787         else
2788           UpdateValueUsesWith(SI, SI->getOperand(2));
2789         return &I;
2790       }
2791     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2792     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2793       if (ST->isNullValue()) {
2794         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2795         if (CondI && CondI->getParent() == I.getParent())
2796           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2797         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2798           I.setOperand(1, SI->getOperand(1));
2799         else
2800           UpdateValueUsesWith(SI, SI->getOperand(1));
2801         return &I;
2802       }
2803   }
2804
2805   return 0;
2806 }
2807
2808 /// This function implements the transforms common to both integer remainder
2809 /// instructions (urem and srem). It is called by the visitors to those integer
2810 /// remainder instructions.
2811 /// @brief Common integer remainder transforms
2812 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2813   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2814
2815   if (Instruction *common = commonRemTransforms(I))
2816     return common;
2817
2818   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2819     // X % 0 == undef, we don't need to preserve faults!
2820     if (RHS->equalsInt(0))
2821       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2822     
2823     if (RHS->equalsInt(1))  // X % 1 == 0
2824       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2825
2826     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2827       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2828         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2829           return R;
2830       } else if (isa<PHINode>(Op0I)) {
2831         if (Instruction *NV = FoldOpIntoPhi(I))
2832           return NV;
2833       }
2834
2835       // See if we can fold away this rem instruction.
2836       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2837       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2838       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2839                                KnownZero, KnownOne))
2840         return &I;
2841     }
2842   }
2843
2844   return 0;
2845 }
2846
2847 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2848   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2849
2850   if (Instruction *common = commonIRemTransforms(I))
2851     return common;
2852   
2853   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2854     // X urem C^2 -> X and C
2855     // Check to see if this is an unsigned remainder with an exact power of 2,
2856     // if so, convert to a bitwise and.
2857     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2858       if (C->getValue().isPowerOf2())
2859         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2860   }
2861
2862   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2863     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2864     if (RHSI->getOpcode() == Instruction::Shl &&
2865         isa<ConstantInt>(RHSI->getOperand(0))) {
2866       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2867         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2868         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2869                                                                    "tmp"), I);
2870         return BinaryOperator::CreateAnd(Op0, Add);
2871       }
2872     }
2873   }
2874
2875   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2876   // where C1&C2 are powers of two.
2877   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2878     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2879       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2880         // STO == 0 and SFO == 0 handled above.
2881         if ((STO->getValue().isPowerOf2()) && 
2882             (SFO->getValue().isPowerOf2())) {
2883           Value *TrueAnd = InsertNewInstBefore(
2884             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2885           Value *FalseAnd = InsertNewInstBefore(
2886             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2887           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2888         }
2889       }
2890   }
2891   
2892   return 0;
2893 }
2894
2895 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898   // Handle the integer rem common cases
2899   if (Instruction *common = commonIRemTransforms(I))
2900     return common;
2901   
2902   if (Value *RHSNeg = dyn_castNegVal(Op1))
2903     if (!isa<ConstantInt>(RHSNeg) || 
2904         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2905       // X % -Y -> X % Y
2906       AddUsesToWorkList(I);
2907       I.setOperand(1, RHSNeg);
2908       return &I;
2909     }
2910  
2911   // If the sign bits of both operands are zero (i.e. we can prove they are
2912   // unsigned inputs), turn this into a urem.
2913   if (I.getType()->isInteger()) {
2914     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2915     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2916       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2917       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2918     }
2919   }
2920
2921   return 0;
2922 }
2923
2924 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2925   return commonRemTransforms(I);
2926 }
2927
2928 // isMaxValueMinusOne - return true if this is Max-1
2929 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2930   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2931   if (!isSigned)
2932     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2933   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2934 }
2935
2936 // isMinValuePlusOne - return true if this is Min+1
2937 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2938   if (!isSigned)
2939     return C->getValue() == 1; // unsigned
2940     
2941   // Calculate 1111111111000000000000
2942   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2943   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2944 }
2945
2946 // isOneBitSet - Return true if there is exactly one bit set in the specified
2947 // constant.
2948 static bool isOneBitSet(const ConstantInt *CI) {
2949   return CI->getValue().isPowerOf2();
2950 }
2951
2952 // isHighOnes - Return true if the constant is of the form 1+0+.
2953 // This is the same as lowones(~X).
2954 static bool isHighOnes(const ConstantInt *CI) {
2955   return (~CI->getValue() + 1).isPowerOf2();
2956 }
2957
2958 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2959 /// are carefully arranged to allow folding of expressions such as:
2960 ///
2961 ///      (A < B) | (A > B) --> (A != B)
2962 ///
2963 /// Note that this is only valid if the first and second predicates have the
2964 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2965 ///
2966 /// Three bits are used to represent the condition, as follows:
2967 ///   0  A > B
2968 ///   1  A == B
2969 ///   2  A < B
2970 ///
2971 /// <=>  Value  Definition
2972 /// 000     0   Always false
2973 /// 001     1   A >  B
2974 /// 010     2   A == B
2975 /// 011     3   A >= B
2976 /// 100     4   A <  B
2977 /// 101     5   A != B
2978 /// 110     6   A <= B
2979 /// 111     7   Always true
2980 ///  
2981 static unsigned getICmpCode(const ICmpInst *ICI) {
2982   switch (ICI->getPredicate()) {
2983     // False -> 0
2984   case ICmpInst::ICMP_UGT: return 1;  // 001
2985   case ICmpInst::ICMP_SGT: return 1;  // 001
2986   case ICmpInst::ICMP_EQ:  return 2;  // 010
2987   case ICmpInst::ICMP_UGE: return 3;  // 011
2988   case ICmpInst::ICMP_SGE: return 3;  // 011
2989   case ICmpInst::ICMP_ULT: return 4;  // 100
2990   case ICmpInst::ICMP_SLT: return 4;  // 100
2991   case ICmpInst::ICMP_NE:  return 5;  // 101
2992   case ICmpInst::ICMP_ULE: return 6;  // 110
2993   case ICmpInst::ICMP_SLE: return 6;  // 110
2994     // True -> 7
2995   default:
2996     assert(0 && "Invalid ICmp predicate!");
2997     return 0;
2998   }
2999 }
3000
3001 /// getICmpValue - This is the complement of getICmpCode, which turns an
3002 /// opcode and two operands into either a constant true or false, or a brand 
3003 /// new ICmp instruction. The sign is passed in to determine which kind
3004 /// of predicate to use in new icmp instructions.
3005 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3006   switch (code) {
3007   default: assert(0 && "Illegal ICmp code!");
3008   case  0: return ConstantInt::getFalse();
3009   case  1: 
3010     if (sign)
3011       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3012     else
3013       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3014   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3015   case  3: 
3016     if (sign)
3017       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3018     else
3019       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3020   case  4: 
3021     if (sign)
3022       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3023     else
3024       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3025   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3026   case  6: 
3027     if (sign)
3028       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3029     else
3030       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3031   case  7: return ConstantInt::getTrue();
3032   }
3033 }
3034
3035 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3036   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3037     (ICmpInst::isSignedPredicate(p1) && 
3038      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3039     (ICmpInst::isSignedPredicate(p2) && 
3040      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3041 }
3042
3043 namespace { 
3044 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3045 struct FoldICmpLogical {
3046   InstCombiner &IC;
3047   Value *LHS, *RHS;
3048   ICmpInst::Predicate pred;
3049   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3050     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3051       pred(ICI->getPredicate()) {}
3052   bool shouldApply(Value *V) const {
3053     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3054       if (PredicatesFoldable(pred, ICI->getPredicate()))
3055         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3056                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3057     return false;
3058   }
3059   Instruction *apply(Instruction &Log) const {
3060     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3061     if (ICI->getOperand(0) != LHS) {
3062       assert(ICI->getOperand(1) == LHS);
3063       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3064     }
3065
3066     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3067     unsigned LHSCode = getICmpCode(ICI);
3068     unsigned RHSCode = getICmpCode(RHSICI);
3069     unsigned Code;
3070     switch (Log.getOpcode()) {
3071     case Instruction::And: Code = LHSCode & RHSCode; break;
3072     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3073     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3074     default: assert(0 && "Illegal logical opcode!"); return 0;
3075     }
3076
3077     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3078                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3079       
3080     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3081     if (Instruction *I = dyn_cast<Instruction>(RV))
3082       return I;
3083     // Otherwise, it's a constant boolean value...
3084     return IC.ReplaceInstUsesWith(Log, RV);
3085   }
3086 };
3087 } // end anonymous namespace
3088
3089 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3090 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3091 // guaranteed to be a binary operator.
3092 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3093                                     ConstantInt *OpRHS,
3094                                     ConstantInt *AndRHS,
3095                                     BinaryOperator &TheAnd) {
3096   Value *X = Op->getOperand(0);
3097   Constant *Together = 0;
3098   if (!Op->isShift())
3099     Together = And(AndRHS, OpRHS);
3100
3101   switch (Op->getOpcode()) {
3102   case Instruction::Xor:
3103     if (Op->hasOneUse()) {
3104       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3105       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3106       InsertNewInstBefore(And, TheAnd);
3107       And->takeName(Op);
3108       return BinaryOperator::CreateXor(And, Together);
3109     }
3110     break;
3111   case Instruction::Or:
3112     if (Together == AndRHS) // (X | C) & C --> C
3113       return ReplaceInstUsesWith(TheAnd, AndRHS);
3114
3115     if (Op->hasOneUse() && Together != OpRHS) {
3116       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3117       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3118       InsertNewInstBefore(Or, TheAnd);
3119       Or->takeName(Op);
3120       return BinaryOperator::CreateAnd(Or, AndRHS);
3121     }
3122     break;
3123   case Instruction::Add:
3124     if (Op->hasOneUse()) {
3125       // Adding a one to a single bit bit-field should be turned into an XOR
3126       // of the bit.  First thing to check is to see if this AND is with a
3127       // single bit constant.
3128       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3129
3130       // If there is only one bit set...
3131       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3132         // Ok, at this point, we know that we are masking the result of the
3133         // ADD down to exactly one bit.  If the constant we are adding has
3134         // no bits set below this bit, then we can eliminate the ADD.
3135         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3136
3137         // Check to see if any bits below the one bit set in AndRHSV are set.
3138         if ((AddRHS & (AndRHSV-1)) == 0) {
3139           // If not, the only thing that can effect the output of the AND is
3140           // the bit specified by AndRHSV.  If that bit is set, the effect of
3141           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3142           // no effect.
3143           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3144             TheAnd.setOperand(0, X);
3145             return &TheAnd;
3146           } else {
3147             // Pull the XOR out of the AND.
3148             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3149             InsertNewInstBefore(NewAnd, TheAnd);
3150             NewAnd->takeName(Op);
3151             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3152           }
3153         }
3154       }
3155     }
3156     break;
3157
3158   case Instruction::Shl: {
3159     // We know that the AND will not produce any of the bits shifted in, so if
3160     // the anded constant includes them, clear them now!
3161     //
3162     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3163     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3164     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3165     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3166
3167     if (CI->getValue() == ShlMask) { 
3168     // Masking out bits that the shift already masks
3169       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3170     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3171       TheAnd.setOperand(1, CI);
3172       return &TheAnd;
3173     }
3174     break;
3175   }
3176   case Instruction::LShr:
3177   {
3178     // We know that the AND will not produce any of the bits shifted in, so if
3179     // the anded constant includes them, clear them now!  This only applies to
3180     // unsigned shifts, because a signed shr may bring in set bits!
3181     //
3182     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3183     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3184     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3185     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3186
3187     if (CI->getValue() == ShrMask) {   
3188     // Masking out bits that the shift already masks.
3189       return ReplaceInstUsesWith(TheAnd, Op);
3190     } else if (CI != AndRHS) {
3191       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3192       return &TheAnd;
3193     }
3194     break;
3195   }
3196   case Instruction::AShr:
3197     // Signed shr.
3198     // See if this is shifting in some sign extension, then masking it out
3199     // with an and.
3200     if (Op->hasOneUse()) {
3201       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3202       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3203       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3204       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3205       if (C == AndRHS) {          // Masking out bits shifted in.
3206         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3207         // Make the argument unsigned.
3208         Value *ShVal = Op->getOperand(0);
3209         ShVal = InsertNewInstBefore(
3210             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3211                                    Op->getName()), TheAnd);
3212         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3213       }
3214     }
3215     break;
3216   }
3217   return 0;
3218 }
3219
3220
3221 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3222 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3223 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3224 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3225 /// insert new instructions.
3226 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3227                                            bool isSigned, bool Inside, 
3228                                            Instruction &IB) {
3229   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3230             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3231          "Lo is not <= Hi in range emission code!");
3232     
3233   if (Inside) {
3234     if (Lo == Hi)  // Trivially false.
3235       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3236
3237     // V >= Min && V < Hi --> V < Hi
3238     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3239       ICmpInst::Predicate pred = (isSigned ? 
3240         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3241       return new ICmpInst(pred, V, Hi);
3242     }
3243
3244     // Emit V-Lo <u Hi-Lo
3245     Constant *NegLo = ConstantExpr::getNeg(Lo);
3246     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3247     InsertNewInstBefore(Add, IB);
3248     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3249     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3250   }
3251
3252   if (Lo == Hi)  // Trivially true.
3253     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3254
3255   // V < Min || V >= Hi -> V > Hi-1
3256   Hi = SubOne(cast<ConstantInt>(Hi));
3257   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3258     ICmpInst::Predicate pred = (isSigned ? 
3259         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3260     return new ICmpInst(pred, V, Hi);
3261   }
3262
3263   // Emit V-Lo >u Hi-1-Lo
3264   // Note that Hi has already had one subtracted from it, above.
3265   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3266   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3267   InsertNewInstBefore(Add, IB);
3268   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3269   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3270 }
3271
3272 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3273 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3274 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3275 // not, since all 1s are not contiguous.
3276 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3277   const APInt& V = Val->getValue();
3278   uint32_t BitWidth = Val->getType()->getBitWidth();
3279   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3280
3281   // look for the first zero bit after the run of ones
3282   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3283   // look for the first non-zero bit
3284   ME = V.getActiveBits(); 
3285   return true;
3286 }
3287
3288 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3289 /// where isSub determines whether the operator is a sub.  If we can fold one of
3290 /// the following xforms:
3291 /// 
3292 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3293 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3294 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3295 ///
3296 /// return (A +/- B).
3297 ///
3298 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3299                                         ConstantInt *Mask, bool isSub,
3300                                         Instruction &I) {
3301   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3302   if (!LHSI || LHSI->getNumOperands() != 2 ||
3303       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3304
3305   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3306
3307   switch (LHSI->getOpcode()) {
3308   default: return 0;
3309   case Instruction::And:
3310     if (And(N, Mask) == Mask) {
3311       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3312       if ((Mask->getValue().countLeadingZeros() + 
3313            Mask->getValue().countPopulation()) == 
3314           Mask->getValue().getBitWidth())
3315         break;
3316
3317       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3318       // part, we don't need any explicit masks to take them out of A.  If that
3319       // is all N is, ignore it.
3320       uint32_t MB = 0, ME = 0;
3321       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3322         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3323         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3324         if (MaskedValueIsZero(RHS, Mask))
3325           break;
3326       }
3327     }
3328     return 0;
3329   case Instruction::Or:
3330   case Instruction::Xor:
3331     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3332     if ((Mask->getValue().countLeadingZeros() + 
3333          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3334         && And(N, Mask)->isZero())
3335       break;
3336     return 0;
3337   }
3338   
3339   Instruction *New;
3340   if (isSub)
3341     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3342   else
3343     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3344   return InsertNewInstBefore(New, I);
3345 }
3346
3347 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3348   bool Changed = SimplifyCommutative(I);
3349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3350
3351   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3352     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3353
3354   // and X, X = X
3355   if (Op0 == Op1)
3356     return ReplaceInstUsesWith(I, Op1);
3357
3358   // See if we can simplify any instructions used by the instruction whose sole 
3359   // purpose is to compute bits we don't care about.
3360   if (!isa<VectorType>(I.getType())) {
3361     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3362     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3363     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3364                              KnownZero, KnownOne))
3365       return &I;
3366   } else {
3367     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3368       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3369         return ReplaceInstUsesWith(I, I.getOperand(0));
3370     } else if (isa<ConstantAggregateZero>(Op1)) {
3371       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3372     }
3373   }
3374   
3375   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3376     const APInt& AndRHSMask = AndRHS->getValue();
3377     APInt NotAndRHS(~AndRHSMask);
3378
3379     // Optimize a variety of ((val OP C1) & C2) combinations...
3380     if (isa<BinaryOperator>(Op0)) {
3381       Instruction *Op0I = cast<Instruction>(Op0);
3382       Value *Op0LHS = Op0I->getOperand(0);
3383       Value *Op0RHS = Op0I->getOperand(1);
3384       switch (Op0I->getOpcode()) {
3385       case Instruction::Xor:
3386       case Instruction::Or:
3387         // If the mask is only needed on one incoming arm, push it up.
3388         if (Op0I->hasOneUse()) {
3389           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3390             // Not masking anything out for the LHS, move to RHS.
3391             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3392                                                    Op0RHS->getName()+".masked");
3393             InsertNewInstBefore(NewRHS, I);
3394             return BinaryOperator::Create(
3395                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3396           }
3397           if (!isa<Constant>(Op0RHS) &&
3398               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3399             // Not masking anything out for the RHS, move to LHS.
3400             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3401                                                    Op0LHS->getName()+".masked");
3402             InsertNewInstBefore(NewLHS, I);
3403             return BinaryOperator::Create(
3404                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3405           }
3406         }
3407
3408         break;
3409       case Instruction::Add:
3410         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3411         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3412         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3413         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3414           return BinaryOperator::CreateAnd(V, AndRHS);
3415         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3416           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3417         break;
3418
3419       case Instruction::Sub:
3420         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3421         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3422         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3423         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3424           return BinaryOperator::CreateAnd(V, AndRHS);
3425         break;
3426       }
3427
3428       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3429         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3430           return Res;
3431     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3432       // If this is an integer truncation or change from signed-to-unsigned, and
3433       // if the source is an and/or with immediate, transform it.  This
3434       // frequently occurs for bitfield accesses.
3435       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3436         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3437             CastOp->getNumOperands() == 2)
3438           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3439             if (CastOp->getOpcode() == Instruction::And) {
3440               // Change: and (cast (and X, C1) to T), C2
3441               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3442               // This will fold the two constants together, which may allow 
3443               // other simplifications.
3444               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3445                 CastOp->getOperand(0), I.getType(), 
3446                 CastOp->getName()+".shrunk");
3447               NewCast = InsertNewInstBefore(NewCast, I);
3448               // trunc_or_bitcast(C1)&C2
3449               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3450               C3 = ConstantExpr::getAnd(C3, AndRHS);
3451               return BinaryOperator::CreateAnd(NewCast, C3);
3452             } else if (CastOp->getOpcode() == Instruction::Or) {
3453               // Change: and (cast (or X, C1) to T), C2
3454               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3455               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3456               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3457                 return ReplaceInstUsesWith(I, AndRHS);
3458             }
3459           }
3460       }
3461     }
3462
3463     // Try to fold constant and into select arguments.
3464     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3465       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3466         return R;
3467     if (isa<PHINode>(Op0))
3468       if (Instruction *NV = FoldOpIntoPhi(I))
3469         return NV;
3470   }
3471
3472   Value *Op0NotVal = dyn_castNotVal(Op0);
3473   Value *Op1NotVal = dyn_castNotVal(Op1);
3474
3475   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3476     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3477
3478   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3479   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3480     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3481                                                I.getName()+".demorgan");
3482     InsertNewInstBefore(Or, I);
3483     return BinaryOperator::CreateNot(Or);
3484   }
3485   
3486   {
3487     Value *A = 0, *B = 0, *C = 0, *D = 0;
3488     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3489       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3490         return ReplaceInstUsesWith(I, Op1);
3491     
3492       // (A|B) & ~(A&B) -> A^B
3493       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3494         if ((A == C && B == D) || (A == D && B == C))
3495           return BinaryOperator::CreateXor(A, B);
3496       }
3497     }
3498     
3499     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3500       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3501         return ReplaceInstUsesWith(I, Op0);
3502
3503       // ~(A&B) & (A|B) -> A^B
3504       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3505         if ((A == C && B == D) || (A == D && B == C))
3506           return BinaryOperator::CreateXor(A, B);
3507       }
3508     }
3509     
3510     if (Op0->hasOneUse() &&
3511         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3512       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3513         I.swapOperands();     // Simplify below
3514         std::swap(Op0, Op1);
3515       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3516         cast<BinaryOperator>(Op0)->swapOperands();
3517         I.swapOperands();     // Simplify below
3518         std::swap(Op0, Op1);
3519       }
3520     }
3521     if (Op1->hasOneUse() &&
3522         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3523       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3524         cast<BinaryOperator>(Op1)->swapOperands();
3525         std::swap(A, B);
3526       }
3527       if (A == Op0) {                                // A&(A^B) -> A & ~B
3528         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3529         InsertNewInstBefore(NotB, I);
3530         return BinaryOperator::CreateAnd(A, NotB);
3531       }
3532     }
3533   }
3534   
3535   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3536     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3537     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3538       return R;
3539
3540     Value *LHSVal, *RHSVal;
3541     ConstantInt *LHSCst, *RHSCst;
3542     ICmpInst::Predicate LHSCC, RHSCC;
3543     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3544       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3545         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3546             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3547             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3548             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3549             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3550             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3551             
3552             // Don't try to fold ICMP_SLT + ICMP_ULT.
3553             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3554              ICmpInst::isSignedPredicate(LHSCC) == 
3555                  ICmpInst::isSignedPredicate(RHSCC))) {
3556           // Ensure that the larger constant is on the RHS.
3557           ICmpInst::Predicate GT;
3558           if (ICmpInst::isSignedPredicate(LHSCC) ||
3559               (ICmpInst::isEquality(LHSCC) && 
3560                ICmpInst::isSignedPredicate(RHSCC)))
3561             GT = ICmpInst::ICMP_SGT;
3562           else
3563             GT = ICmpInst::ICMP_UGT;
3564           
3565           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3566           ICmpInst *LHS = cast<ICmpInst>(Op0);
3567           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3568             std::swap(LHS, RHS);
3569             std::swap(LHSCst, RHSCst);
3570             std::swap(LHSCC, RHSCC);
3571           }
3572
3573           // At this point, we know we have have two icmp instructions
3574           // comparing a value against two constants and and'ing the result
3575           // together.  Because of the above check, we know that we only have
3576           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3577           // (from the FoldICmpLogical check above), that the two constants 
3578           // are not equal and that the larger constant is on the RHS
3579           assert(LHSCst != RHSCst && "Compares not folded above?");
3580
3581           switch (LHSCC) {
3582           default: assert(0 && "Unknown integer condition code!");
3583           case ICmpInst::ICMP_EQ:
3584             switch (RHSCC) {
3585             default: assert(0 && "Unknown integer condition code!");
3586             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3587             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3588             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3589               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3590             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3591             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3592             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3593               return ReplaceInstUsesWith(I, LHS);
3594             }
3595           case ICmpInst::ICMP_NE:
3596             switch (RHSCC) {
3597             default: assert(0 && "Unknown integer condition code!");
3598             case ICmpInst::ICMP_ULT:
3599               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3600                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3601               break;                        // (X != 13 & X u< 15) -> no change
3602             case ICmpInst::ICMP_SLT:
3603               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3604                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3605               break;                        // (X != 13 & X s< 15) -> no change
3606             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3607             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3608             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3609               return ReplaceInstUsesWith(I, RHS);
3610             case ICmpInst::ICMP_NE:
3611               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3612                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3613                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3614                                                       LHSVal->getName()+".off");
3615                 InsertNewInstBefore(Add, I);
3616                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3617                                     ConstantInt::get(Add->getType(), 1));
3618               }
3619               break;                        // (X != 13 & X != 15) -> no change
3620             }
3621             break;
3622           case ICmpInst::ICMP_ULT:
3623             switch (RHSCC) {
3624             default: assert(0 && "Unknown integer condition code!");
3625             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3626             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3627               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3628             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3629               break;
3630             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3631             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3632               return ReplaceInstUsesWith(I, LHS);
3633             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3634               break;
3635             }
3636             break;
3637           case ICmpInst::ICMP_SLT:
3638             switch (RHSCC) {
3639             default: assert(0 && "Unknown integer condition code!");
3640             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3641             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3642               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3643             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3644               break;
3645             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3646             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3647               return ReplaceInstUsesWith(I, LHS);
3648             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3649               break;
3650             }
3651             break;
3652           case ICmpInst::ICMP_UGT:
3653             switch (RHSCC) {
3654             default: assert(0 && "Unknown integer condition code!");
3655             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3656               return ReplaceInstUsesWith(I, LHS);
3657             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3658               return ReplaceInstUsesWith(I, RHS);
3659             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3660               break;
3661             case ICmpInst::ICMP_NE:
3662               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3663                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3664               break;                        // (X u> 13 & X != 15) -> no change
3665             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3666               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3667                                      true, I);
3668             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3669               break;
3670             }
3671             break;
3672           case ICmpInst::ICMP_SGT:
3673             switch (RHSCC) {
3674             default: assert(0 && "Unknown integer condition code!");
3675             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3676             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3677               return ReplaceInstUsesWith(I, RHS);
3678             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3679               break;
3680             case ICmpInst::ICMP_NE:
3681               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3682                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3683               break;                        // (X s> 13 & X != 15) -> no change
3684             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3685               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3686                                      true, I);
3687             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3688               break;
3689             }
3690             break;
3691           }
3692         }
3693   }
3694
3695   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3696   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3697     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3698       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3699         const Type *SrcTy = Op0C->getOperand(0)->getType();
3700         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3701             // Only do this if the casts both really cause code to be generated.
3702             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3703                               I.getType(), TD) &&
3704             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3705                               I.getType(), TD)) {
3706           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3707                                                          Op1C->getOperand(0),
3708                                                          I.getName());
3709           InsertNewInstBefore(NewOp, I);
3710           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3711         }
3712       }
3713     
3714   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3715   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3716     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3717       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3718           SI0->getOperand(1) == SI1->getOperand(1) &&
3719           (SI0->hasOneUse() || SI1->hasOneUse())) {
3720         Instruction *NewOp =
3721           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3722                                                         SI1->getOperand(0),
3723                                                         SI0->getName()), I);
3724         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3725                                       SI1->getOperand(1));
3726       }
3727   }
3728
3729   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3730   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3731     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3732       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3733           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3734         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3735           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3736             // If either of the constants are nans, then the whole thing returns
3737             // false.
3738             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3739               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3740             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3741                                 RHS->getOperand(0));
3742           }
3743     }
3744   }
3745       
3746   return Changed ? &I : 0;
3747 }
3748
3749 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3750 /// in the result.  If it does, and if the specified byte hasn't been filled in
3751 /// yet, fill it in and return false.
3752 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3753   Instruction *I = dyn_cast<Instruction>(V);
3754   if (I == 0) return true;
3755
3756   // If this is an or instruction, it is an inner node of the bswap.
3757   if (I->getOpcode() == Instruction::Or)
3758     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3759            CollectBSwapParts(I->getOperand(1), ByteValues);
3760   
3761   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3762   // If this is a shift by a constant int, and it is "24", then its operand
3763   // defines a byte.  We only handle unsigned types here.
3764   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3765     // Not shifting the entire input by N-1 bytes?
3766     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3767         8*(ByteValues.size()-1))
3768       return true;
3769     
3770     unsigned DestNo;
3771     if (I->getOpcode() == Instruction::Shl) {
3772       // X << 24 defines the top byte with the lowest of the input bytes.
3773       DestNo = ByteValues.size()-1;
3774     } else {
3775       // X >>u 24 defines the low byte with the highest of the input bytes.
3776       DestNo = 0;
3777     }
3778     
3779     // If the destination byte value is already defined, the values are or'd
3780     // together, which isn't a bswap (unless it's an or of the same bits).
3781     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3782       return true;
3783     ByteValues[DestNo] = I->getOperand(0);
3784     return false;
3785   }
3786   
3787   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3788   // don't have this.
3789   Value *Shift = 0, *ShiftLHS = 0;
3790   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3791   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3792       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3793     return true;
3794   Instruction *SI = cast<Instruction>(Shift);
3795
3796   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3797   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3798       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3799     return true;
3800   
3801   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3802   unsigned DestByte;
3803   if (AndAmt->getValue().getActiveBits() > 64)
3804     return true;
3805   uint64_t AndAmtVal = AndAmt->getZExtValue();
3806   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3807     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3808       break;
3809   // Unknown mask for bswap.
3810   if (DestByte == ByteValues.size()) return true;
3811   
3812   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3813   unsigned SrcByte;
3814   if (SI->getOpcode() == Instruction::Shl)
3815     SrcByte = DestByte - ShiftBytes;
3816   else
3817     SrcByte = DestByte + ShiftBytes;
3818   
3819   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3820   if (SrcByte != ByteValues.size()-DestByte-1)
3821     return true;
3822   
3823   // If the destination byte value is already defined, the values are or'd
3824   // together, which isn't a bswap (unless it's an or of the same bits).
3825   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3826     return true;
3827   ByteValues[DestByte] = SI->getOperand(0);
3828   return false;
3829 }
3830
3831 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3832 /// If so, insert the new bswap intrinsic and return it.
3833 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3834   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3835   if (!ITy || ITy->getBitWidth() % 16) 
3836     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3837   
3838   /// ByteValues - For each byte of the result, we keep track of which value
3839   /// defines each byte.
3840   SmallVector<Value*, 8> ByteValues;
3841   ByteValues.resize(ITy->getBitWidth()/8);
3842     
3843   // Try to find all the pieces corresponding to the bswap.
3844   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3845       CollectBSwapParts(I.getOperand(1), ByteValues))
3846     return 0;
3847   
3848   // Check to see if all of the bytes come from the same value.
3849   Value *V = ByteValues[0];
3850   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3851   
3852   // Check to make sure that all of the bytes come from the same value.
3853   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3854     if (ByteValues[i] != V)
3855       return 0;
3856   const Type *Tys[] = { ITy };
3857   Module *M = I.getParent()->getParent()->getParent();
3858   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3859   return CallInst::Create(F, V);
3860 }
3861
3862
3863 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3864   bool Changed = SimplifyCommutative(I);
3865   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3866
3867   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3868     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3869
3870   // or X, X = X
3871   if (Op0 == Op1)
3872     return ReplaceInstUsesWith(I, Op0);
3873
3874   // See if we can simplify any instructions used by the instruction whose sole 
3875   // purpose is to compute bits we don't care about.
3876   if (!isa<VectorType>(I.getType())) {
3877     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3878     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3879     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3880                              KnownZero, KnownOne))
3881       return &I;
3882   } else if (isa<ConstantAggregateZero>(Op1)) {
3883     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3884   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3885     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3886       return ReplaceInstUsesWith(I, I.getOperand(1));
3887   }
3888     
3889
3890   
3891   // or X, -1 == -1
3892   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3893     ConstantInt *C1 = 0; Value *X = 0;
3894     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3895     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3896       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3897       InsertNewInstBefore(Or, I);
3898       Or->takeName(Op0);
3899       return BinaryOperator::CreateAnd(Or, 
3900                ConstantInt::get(RHS->getValue() | C1->getValue()));
3901     }
3902
3903     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3904     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3905       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3906       InsertNewInstBefore(Or, I);
3907       Or->takeName(Op0);
3908       return BinaryOperator::CreateXor(Or,
3909                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3910     }
3911
3912     // Try to fold constant and into select arguments.
3913     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3914       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3915         return R;
3916     if (isa<PHINode>(Op0))
3917       if (Instruction *NV = FoldOpIntoPhi(I))
3918         return NV;
3919   }
3920
3921   Value *A = 0, *B = 0;
3922   ConstantInt *C1 = 0, *C2 = 0;
3923
3924   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3925     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3926       return ReplaceInstUsesWith(I, Op1);
3927   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3928     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3929       return ReplaceInstUsesWith(I, Op0);
3930
3931   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3932   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3933   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3934       match(Op1, m_Or(m_Value(), m_Value())) ||
3935       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3936        match(Op1, m_Shift(m_Value(), m_Value())))) {
3937     if (Instruction *BSwap = MatchBSwap(I))
3938       return BSwap;
3939   }
3940   
3941   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3942   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3943       MaskedValueIsZero(Op1, C1->getValue())) {
3944     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3945     InsertNewInstBefore(NOr, I);
3946     NOr->takeName(Op0);
3947     return BinaryOperator::CreateXor(NOr, C1);
3948   }
3949
3950   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3951   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3952       MaskedValueIsZero(Op0, C1->getValue())) {
3953     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
3954     InsertNewInstBefore(NOr, I);
3955     NOr->takeName(Op0);
3956     return BinaryOperator::CreateXor(NOr, C1);
3957   }
3958
3959   // (A & C)|(B & D)
3960   Value *C = 0, *D = 0;
3961   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3962       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3963     Value *V1 = 0, *V2 = 0, *V3 = 0;
3964     C1 = dyn_cast<ConstantInt>(C);
3965     C2 = dyn_cast<ConstantInt>(D);
3966     if (C1 && C2) {  // (A & C1)|(B & C2)
3967       // If we have: ((V + N) & C1) | (V & C2)
3968       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3969       // replace with V+N.
3970       if (C1->getValue() == ~C2->getValue()) {
3971         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3972             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3973           // Add commutes, try both ways.
3974           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3975             return ReplaceInstUsesWith(I, A);
3976           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3977             return ReplaceInstUsesWith(I, A);
3978         }
3979         // Or commutes, try both ways.
3980         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3981             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3982           // Add commutes, try both ways.
3983           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3984             return ReplaceInstUsesWith(I, B);
3985           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3986             return ReplaceInstUsesWith(I, B);
3987         }
3988       }
3989       V1 = 0; V2 = 0; V3 = 0;
3990     }
3991     
3992     // Check to see if we have any common things being and'ed.  If so, find the
3993     // terms for V1 & (V2|V3).
3994     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3995       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3996         V1 = A, V2 = C, V3 = D;
3997       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3998         V1 = A, V2 = B, V3 = C;
3999       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4000         V1 = C, V2 = A, V3 = D;
4001       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4002         V1 = C, V2 = A, V3 = B;
4003       
4004       if (V1) {
4005         Value *Or =
4006           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4007         return BinaryOperator::CreateAnd(V1, Or);
4008       }
4009     }
4010   }
4011   
4012   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4013   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4014     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4015       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4016           SI0->getOperand(1) == SI1->getOperand(1) &&
4017           (SI0->hasOneUse() || SI1->hasOneUse())) {
4018         Instruction *NewOp =
4019         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4020                                                      SI1->getOperand(0),
4021                                                      SI0->getName()), I);
4022         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4023                                       SI1->getOperand(1));
4024       }
4025   }
4026
4027   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4028     if (A == Op1)   // ~A | A == -1
4029       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4030   } else {
4031     A = 0;
4032   }
4033   // Note, A is still live here!
4034   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4035     if (Op0 == B)
4036       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4037
4038     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4039     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4040       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4041                                               I.getName()+".demorgan"), I);
4042       return BinaryOperator::CreateNot(And);
4043     }
4044   }
4045
4046   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4047   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4048     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4049       return R;
4050
4051     Value *LHSVal, *RHSVal;
4052     ConstantInt *LHSCst, *RHSCst;
4053     ICmpInst::Predicate LHSCC, RHSCC;
4054     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4055       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4056         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4057             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4058             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4059             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4060             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4061             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4062             // We can't fold (ugt x, C) | (sgt x, C2).
4063             PredicatesFoldable(LHSCC, RHSCC)) {
4064           // Ensure that the larger constant is on the RHS.
4065           ICmpInst *LHS = cast<ICmpInst>(Op0);
4066           bool NeedsSwap;
4067           if (ICmpInst::isSignedPredicate(LHSCC))
4068             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4069           else
4070             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4071             
4072           if (NeedsSwap) {
4073             std::swap(LHS, RHS);
4074             std::swap(LHSCst, RHSCst);
4075             std::swap(LHSCC, RHSCC);
4076           }
4077
4078           // At this point, we know we have have two icmp instructions
4079           // comparing a value against two constants and or'ing the result
4080           // together.  Because of the above check, we know that we only have
4081           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4082           // FoldICmpLogical check above), that the two constants are not
4083           // equal.
4084           assert(LHSCst != RHSCst && "Compares not folded above?");
4085
4086           switch (LHSCC) {
4087           default: assert(0 && "Unknown integer condition code!");
4088           case ICmpInst::ICMP_EQ:
4089             switch (RHSCC) {
4090             default: assert(0 && "Unknown integer condition code!");
4091             case ICmpInst::ICMP_EQ:
4092               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4093                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4094                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4095                                                       LHSVal->getName()+".off");
4096                 InsertNewInstBefore(Add, I);
4097                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4098                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4099               }
4100               break;                         // (X == 13 | X == 15) -> no change
4101             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4102             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4103               break;
4104             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4105             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4106             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4107               return ReplaceInstUsesWith(I, RHS);
4108             }
4109             break;
4110           case ICmpInst::ICMP_NE:
4111             switch (RHSCC) {
4112             default: assert(0 && "Unknown integer condition code!");
4113             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4114             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4115             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4116               return ReplaceInstUsesWith(I, LHS);
4117             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4118             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4119             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4120               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4121             }
4122             break;
4123           case ICmpInst::ICMP_ULT:
4124             switch (RHSCC) {
4125             default: assert(0 && "Unknown integer condition code!");
4126             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4127               break;
4128             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4129               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4130               // this can cause overflow.
4131               if (RHSCst->isMaxValue(false))
4132                 return ReplaceInstUsesWith(I, LHS);
4133               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4134                                      false, I);
4135             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4136               break;
4137             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4138             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4139               return ReplaceInstUsesWith(I, RHS);
4140             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4141               break;
4142             }
4143             break;
4144           case ICmpInst::ICMP_SLT:
4145             switch (RHSCC) {
4146             default: assert(0 && "Unknown integer condition code!");
4147             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4148               break;
4149             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4150               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4151               // this can cause overflow.
4152               if (RHSCst->isMaxValue(true))
4153                 return ReplaceInstUsesWith(I, LHS);
4154               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4155                                      false, I);
4156             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4157               break;
4158             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4159             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4160               return ReplaceInstUsesWith(I, RHS);
4161             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4162               break;
4163             }
4164             break;
4165           case ICmpInst::ICMP_UGT:
4166             switch (RHSCC) {
4167             default: assert(0 && "Unknown integer condition code!");
4168             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4169             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4170               return ReplaceInstUsesWith(I, LHS);
4171             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4172               break;
4173             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4174             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4175               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4176             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4177               break;
4178             }
4179             break;
4180           case ICmpInst::ICMP_SGT:
4181             switch (RHSCC) {
4182             default: assert(0 && "Unknown integer condition code!");
4183             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4184             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4185               return ReplaceInstUsesWith(I, LHS);
4186             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4187               break;
4188             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4189             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4190               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4191             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4192               break;
4193             }
4194             break;
4195           }
4196         }
4197   }
4198     
4199   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4200   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4201     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4202       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4203         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4204             !isa<ICmpInst>(Op1C->getOperand(0))) {
4205           const Type *SrcTy = Op0C->getOperand(0)->getType();
4206           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4207               // Only do this if the casts both really cause code to be
4208               // generated.
4209               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4210                                 I.getType(), TD) &&
4211               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4212                                 I.getType(), TD)) {
4213             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4214                                                           Op1C->getOperand(0),
4215                                                           I.getName());
4216             InsertNewInstBefore(NewOp, I);
4217             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4218           }
4219         }
4220       }
4221   }
4222   
4223     
4224   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4225   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4226     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4227       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4228           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4229           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4230         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4231           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4232             // If either of the constants are nans, then the whole thing returns
4233             // true.
4234             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4235               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4236             
4237             // Otherwise, no need to compare the two constants, compare the
4238             // rest.
4239             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4240                                 RHS->getOperand(0));
4241           }
4242     }
4243   }
4244
4245   return Changed ? &I : 0;
4246 }
4247
4248 namespace {
4249
4250 // XorSelf - Implements: X ^ X --> 0
4251 struct XorSelf {
4252   Value *RHS;
4253   XorSelf(Value *rhs) : RHS(rhs) {}
4254   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4255   Instruction *apply(BinaryOperator &Xor) const {
4256     return &Xor;
4257   }
4258 };
4259
4260 }
4261
4262 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4263   bool Changed = SimplifyCommutative(I);
4264   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4265
4266   if (isa<UndefValue>(Op1)) {
4267     if (isa<UndefValue>(Op0))
4268       // Handle undef ^ undef -> 0 special case. This is a common
4269       // idiom (misuse).
4270       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4271     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4272   }
4273
4274   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4275   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4276     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4277     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4278   }
4279   
4280   // See if we can simplify any instructions used by the instruction whose sole 
4281   // purpose is to compute bits we don't care about.
4282   if (!isa<VectorType>(I.getType())) {
4283     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4284     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4285     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4286                              KnownZero, KnownOne))
4287       return &I;
4288   } else if (isa<ConstantAggregateZero>(Op1)) {
4289     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4290   }
4291
4292   // Is this a ~ operation?
4293   if (Value *NotOp = dyn_castNotVal(&I)) {
4294     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4295     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4296     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4297       if (Op0I->getOpcode() == Instruction::And || 
4298           Op0I->getOpcode() == Instruction::Or) {
4299         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4300         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4301           Instruction *NotY =
4302             BinaryOperator::CreateNot(Op0I->getOperand(1),
4303                                       Op0I->getOperand(1)->getName()+".not");
4304           InsertNewInstBefore(NotY, I);
4305           if (Op0I->getOpcode() == Instruction::And)
4306             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4307           else
4308             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4309         }
4310       }
4311     }
4312   }
4313   
4314   
4315   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4316     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4317     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4318       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4319         return new ICmpInst(ICI->getInversePredicate(),
4320                             ICI->getOperand(0), ICI->getOperand(1));
4321
4322       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4323         return new FCmpInst(FCI->getInversePredicate(),
4324                             FCI->getOperand(0), FCI->getOperand(1));
4325     }
4326
4327     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4328     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4329       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4330         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4331           Instruction::CastOps Opcode = Op0C->getOpcode();
4332           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4333             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4334                                              Op0C->getDestTy())) {
4335               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4336                                      CI->getOpcode(), CI->getInversePredicate(),
4337                                      CI->getOperand(0), CI->getOperand(1)), I);
4338               NewCI->takeName(CI);
4339               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4340             }
4341           }
4342         }
4343       }
4344     }
4345
4346     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4347       // ~(c-X) == X-c-1 == X+(-c-1)
4348       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4349         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4350           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4351           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4352                                               ConstantInt::get(I.getType(), 1));
4353           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4354         }
4355           
4356       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4357         if (Op0I->getOpcode() == Instruction::Add) {
4358           // ~(X-c) --> (-c-1)-X
4359           if (RHS->isAllOnesValue()) {
4360             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4361             return BinaryOperator::CreateSub(
4362                            ConstantExpr::getSub(NegOp0CI,
4363                                              ConstantInt::get(I.getType(), 1)),
4364                                           Op0I->getOperand(0));
4365           } else if (RHS->getValue().isSignBit()) {
4366             // (X + C) ^ signbit -> (X + C + signbit)
4367             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4368             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4369
4370           }
4371         } else if (Op0I->getOpcode() == Instruction::Or) {
4372           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4373           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4374             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4375             // Anything in both C1 and C2 is known to be zero, remove it from
4376             // NewRHS.
4377             Constant *CommonBits = And(Op0CI, RHS);
4378             NewRHS = ConstantExpr::getAnd(NewRHS, 
4379                                           ConstantExpr::getNot(CommonBits));
4380             AddToWorkList(Op0I);
4381             I.setOperand(0, Op0I->getOperand(0));
4382             I.setOperand(1, NewRHS);
4383             return &I;
4384           }
4385         }
4386       }
4387     }
4388
4389     // Try to fold constant and into select arguments.
4390     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4391       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4392         return R;
4393     if (isa<PHINode>(Op0))
4394       if (Instruction *NV = FoldOpIntoPhi(I))
4395         return NV;
4396   }
4397
4398   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4399     if (X == Op1)
4400       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4401
4402   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4403     if (X == Op0)
4404       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4405
4406   
4407   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4408   if (Op1I) {
4409     Value *A, *B;
4410     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4411       if (A == Op0) {              // B^(B|A) == (A|B)^B
4412         Op1I->swapOperands();
4413         I.swapOperands();
4414         std::swap(Op0, Op1);
4415       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4416         I.swapOperands();     // Simplified below.
4417         std::swap(Op0, Op1);
4418       }
4419     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4420       if (Op0 == A)                                          // A^(A^B) == B
4421         return ReplaceInstUsesWith(I, B);
4422       else if (Op0 == B)                                     // A^(B^A) == B
4423         return ReplaceInstUsesWith(I, A);
4424     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4425       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4426         Op1I->swapOperands();
4427         std::swap(A, B);
4428       }
4429       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4430         I.swapOperands();     // Simplified below.
4431         std::swap(Op0, Op1);
4432       }
4433     }
4434   }
4435   
4436   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4437   if (Op0I) {
4438     Value *A, *B;
4439     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4440       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4441         std::swap(A, B);
4442       if (B == Op1) {                                // (A|B)^B == A & ~B
4443         Instruction *NotB =
4444           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4445         return BinaryOperator::CreateAnd(A, NotB);
4446       }
4447     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4448       if (Op1 == A)                                          // (A^B)^A == B
4449         return ReplaceInstUsesWith(I, B);
4450       else if (Op1 == B)                                     // (B^A)^A == B
4451         return ReplaceInstUsesWith(I, A);
4452     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4453       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4454         std::swap(A, B);
4455       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4456           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4457         Instruction *N =
4458           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4459         return BinaryOperator::CreateAnd(N, Op1);
4460       }
4461     }
4462   }
4463   
4464   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4465   if (Op0I && Op1I && Op0I->isShift() && 
4466       Op0I->getOpcode() == Op1I->getOpcode() && 
4467       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4468       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4469     Instruction *NewOp =
4470       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4471                                                     Op1I->getOperand(0),
4472                                                     Op0I->getName()), I);
4473     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4474                                   Op1I->getOperand(1));
4475   }
4476     
4477   if (Op0I && Op1I) {
4478     Value *A, *B, *C, *D;
4479     // (A & B)^(A | B) -> A ^ B
4480     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4481         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4482       if ((A == C && B == D) || (A == D && B == C)) 
4483         return BinaryOperator::CreateXor(A, B);
4484     }
4485     // (A | B)^(A & B) -> A ^ B
4486     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4487         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4488       if ((A == C && B == D) || (A == D && B == C)) 
4489         return BinaryOperator::CreateXor(A, B);
4490     }
4491     
4492     // (A & B)^(C & D)
4493     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4494         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4495         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4496       // (X & Y)^(X & Y) -> (Y^Z) & X
4497       Value *X = 0, *Y = 0, *Z = 0;
4498       if (A == C)
4499         X = A, Y = B, Z = D;
4500       else if (A == D)
4501         X = A, Y = B, Z = C;
4502       else if (B == C)
4503         X = B, Y = A, Z = D;
4504       else if (B == D)
4505         X = B, Y = A, Z = C;
4506       
4507       if (X) {
4508         Instruction *NewOp =
4509         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4510         return BinaryOperator::CreateAnd(NewOp, X);
4511       }
4512     }
4513   }
4514     
4515   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4516   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4517     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4518       return R;
4519
4520   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4521   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4522     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4523       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4524         const Type *SrcTy = Op0C->getOperand(0)->getType();
4525         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4526             // Only do this if the casts both really cause code to be generated.
4527             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4528                               I.getType(), TD) &&
4529             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4530                               I.getType(), TD)) {
4531           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4532                                                          Op1C->getOperand(0),
4533                                                          I.getName());
4534           InsertNewInstBefore(NewOp, I);
4535           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4536         }
4537       }
4538   }
4539
4540   return Changed ? &I : 0;
4541 }
4542
4543 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4544 /// overflowed for this type.
4545 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4546                             ConstantInt *In2, bool IsSigned = false) {
4547   Result = cast<ConstantInt>(Add(In1, In2));
4548
4549   if (IsSigned)
4550     if (In2->getValue().isNegative())
4551       return Result->getValue().sgt(In1->getValue());
4552     else
4553       return Result->getValue().slt(In1->getValue());
4554   else
4555     return Result->getValue().ult(In1->getValue());
4556 }
4557
4558 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4559 /// code necessary to compute the offset from the base pointer (without adding
4560 /// in the base pointer).  Return the result as a signed integer of intptr size.
4561 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4562   TargetData &TD = IC.getTargetData();
4563   gep_type_iterator GTI = gep_type_begin(GEP);
4564   const Type *IntPtrTy = TD.getIntPtrType();
4565   Value *Result = Constant::getNullValue(IntPtrTy);
4566
4567   // Build a mask for high order bits.
4568   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4569   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4570
4571   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4572     Value *Op = GEP->getOperand(i);
4573     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4574     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4575       if (OpC->isZero()) continue;
4576       
4577       // Handle a struct index, which adds its field offset to the pointer.
4578       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4579         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4580         
4581         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4582           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4583         else
4584           Result = IC.InsertNewInstBefore(
4585                    BinaryOperator::CreateAdd(Result,
4586                                              ConstantInt::get(IntPtrTy, Size),
4587                                              GEP->getName()+".offs"), I);
4588         continue;
4589       }
4590       
4591       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4592       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4593       Scale = ConstantExpr::getMul(OC, Scale);
4594       if (Constant *RC = dyn_cast<Constant>(Result))
4595         Result = ConstantExpr::getAdd(RC, Scale);
4596       else {
4597         // Emit an add instruction.
4598         Result = IC.InsertNewInstBefore(
4599            BinaryOperator::CreateAdd(Result, Scale,
4600                                      GEP->getName()+".offs"), I);
4601       }
4602       continue;
4603     }
4604     // Convert to correct type.
4605     if (Op->getType() != IntPtrTy) {
4606       if (Constant *OpC = dyn_cast<Constant>(Op))
4607         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4608       else
4609         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4610                                                  Op->getName()+".c"), I);
4611     }
4612     if (Size != 1) {
4613       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4614       if (Constant *OpC = dyn_cast<Constant>(Op))
4615         Op = ConstantExpr::getMul(OpC, Scale);
4616       else    // We'll let instcombine(mul) convert this to a shl if possible.
4617         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4618                                                   GEP->getName()+".idx"), I);
4619     }
4620
4621     // Emit an add instruction.
4622     if (isa<Constant>(Op) && isa<Constant>(Result))
4623       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4624                                     cast<Constant>(Result));
4625     else
4626       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4627                                                   GEP->getName()+".offs"), I);
4628   }
4629   return Result;
4630 }
4631
4632
4633 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4634 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4635 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4636 /// complex, and scales are involved.  The above expression would also be legal
4637 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4638 /// later form is less amenable to optimization though, and we are allowed to
4639 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4640 ///
4641 /// If we can't emit an optimized form for this expression, this returns null.
4642 /// 
4643 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4644                                           InstCombiner &IC) {
4645   TargetData &TD = IC.getTargetData();
4646   gep_type_iterator GTI = gep_type_begin(GEP);
4647
4648   // Check to see if this gep only has a single variable index.  If so, and if
4649   // any constant indices are a multiple of its scale, then we can compute this
4650   // in terms of the scale of the variable index.  For example, if the GEP
4651   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4652   // because the expression will cross zero at the same point.
4653   unsigned i, e = GEP->getNumOperands();
4654   int64_t Offset = 0;
4655   for (i = 1; i != e; ++i, ++GTI) {
4656     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4657       // Compute the aggregate offset of constant indices.
4658       if (CI->isZero()) continue;
4659
4660       // Handle a struct index, which adds its field offset to the pointer.
4661       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4662         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4663       } else {
4664         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4665         Offset += Size*CI->getSExtValue();
4666       }
4667     } else {
4668       // Found our variable index.
4669       break;
4670     }
4671   }
4672   
4673   // If there are no variable indices, we must have a constant offset, just
4674   // evaluate it the general way.
4675   if (i == e) return 0;
4676   
4677   Value *VariableIdx = GEP->getOperand(i);
4678   // Determine the scale factor of the variable element.  For example, this is
4679   // 4 if the variable index is into an array of i32.
4680   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4681   
4682   // Verify that there are no other variable indices.  If so, emit the hard way.
4683   for (++i, ++GTI; i != e; ++i, ++GTI) {
4684     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4685     if (!CI) return 0;
4686    
4687     // Compute the aggregate offset of constant indices.
4688     if (CI->isZero()) continue;
4689     
4690     // Handle a struct index, which adds its field offset to the pointer.
4691     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4692       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4693     } else {
4694       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4695       Offset += Size*CI->getSExtValue();
4696     }
4697   }
4698   
4699   // Okay, we know we have a single variable index, which must be a
4700   // pointer/array/vector index.  If there is no offset, life is simple, return
4701   // the index.
4702   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4703   if (Offset == 0) {
4704     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4705     // we don't need to bother extending: the extension won't affect where the
4706     // computation crosses zero.
4707     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4708       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4709                                   VariableIdx->getNameStart(), &I);
4710     return VariableIdx;
4711   }
4712   
4713   // Otherwise, there is an index.  The computation we will do will be modulo
4714   // the pointer size, so get it.
4715   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4716   
4717   Offset &= PtrSizeMask;
4718   VariableScale &= PtrSizeMask;
4719
4720   // To do this transformation, any constant index must be a multiple of the
4721   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4722   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4723   // multiple of the variable scale.
4724   int64_t NewOffs = Offset / (int64_t)VariableScale;
4725   if (Offset != NewOffs*(int64_t)VariableScale)
4726     return 0;
4727
4728   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4729   const Type *IntPtrTy = TD.getIntPtrType();
4730   if (VariableIdx->getType() != IntPtrTy)
4731     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4732                                               true /*SExt*/, 
4733                                               VariableIdx->getNameStart(), &I);
4734   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4735   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4736 }
4737
4738
4739 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4740 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4741 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4742                                        ICmpInst::Predicate Cond,
4743                                        Instruction &I) {
4744   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4745
4746   // Look through bitcasts.
4747   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4748     RHS = BCI->getOperand(0);
4749
4750   Value *PtrBase = GEPLHS->getOperand(0);
4751   if (PtrBase == RHS) {
4752     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4753     // This transformation (ignoring the base and scales) is valid because we
4754     // know pointers can't overflow.  See if we can output an optimized form.
4755     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4756     
4757     // If not, synthesize the offset the hard way.
4758     if (Offset == 0)
4759       Offset = EmitGEPOffset(GEPLHS, I, *this);
4760     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4761                         Constant::getNullValue(Offset->getType()));
4762   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4763     // If the base pointers are different, but the indices are the same, just
4764     // compare the base pointer.
4765     if (PtrBase != GEPRHS->getOperand(0)) {
4766       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4767       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4768                         GEPRHS->getOperand(0)->getType();
4769       if (IndicesTheSame)
4770         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4771           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4772             IndicesTheSame = false;
4773             break;
4774           }
4775
4776       // If all indices are the same, just compare the base pointers.
4777       if (IndicesTheSame)
4778         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4779                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4780
4781       // Otherwise, the base pointers are different and the indices are
4782       // different, bail out.
4783       return 0;
4784     }
4785
4786     // If one of the GEPs has all zero indices, recurse.
4787     bool AllZeros = true;
4788     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4790           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4791         AllZeros = false;
4792         break;
4793       }
4794     if (AllZeros)
4795       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4796                           ICmpInst::getSwappedPredicate(Cond), I);
4797
4798     // If the other GEP has all zero indices, recurse.
4799     AllZeros = true;
4800     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4801       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4802           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4803         AllZeros = false;
4804         break;
4805       }
4806     if (AllZeros)
4807       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4808
4809     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4810       // If the GEPs only differ by one index, compare it.
4811       unsigned NumDifferences = 0;  // Keep track of # differences.
4812       unsigned DiffOperand = 0;     // The operand that differs.
4813       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4814         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4815           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4816                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4817             // Irreconcilable differences.
4818             NumDifferences = 2;
4819             break;
4820           } else {
4821             if (NumDifferences++) break;
4822             DiffOperand = i;
4823           }
4824         }
4825
4826       if (NumDifferences == 0)   // SAME GEP?
4827         return ReplaceInstUsesWith(I, // No comparison is needed here.
4828                                    ConstantInt::get(Type::Int1Ty,
4829                                              ICmpInst::isTrueWhenEqual(Cond)));
4830
4831       else if (NumDifferences == 1) {
4832         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4833         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4834         // Make sure we do a signed comparison here.
4835         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4836       }
4837     }
4838
4839     // Only lower this if the icmp is the only user of the GEP or if we expect
4840     // the result to fold to a constant!
4841     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4842         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4843       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4844       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4845       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4846       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4847     }
4848   }
4849   return 0;
4850 }
4851
4852 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4853 ///
4854 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4855                                                 Instruction *LHSI,
4856                                                 Constant *RHSC) {
4857   if (!isa<ConstantFP>(RHSC)) return 0;
4858   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4859   
4860   // Get the width of the mantissa.  We don't want to hack on conversions that
4861   // might lose information from the integer, e.g. "i64 -> float"
4862   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4863   if (MantissaWidth == -1) return 0;  // Unknown.
4864   
4865   // Check to see that the input is converted from an integer type that is small
4866   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4867   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4868   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4869   
4870   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4871   if (isa<UIToFPInst>(LHSI))
4872     ++InputSize;
4873   
4874   // If the conversion would lose info, don't hack on this.
4875   if ((int)InputSize > MantissaWidth)
4876     return 0;
4877   
4878   // Otherwise, we can potentially simplify the comparison.  We know that it
4879   // will always come through as an integer value and we know the constant is
4880   // not a NAN (it would have been previously simplified).
4881   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4882   
4883   ICmpInst::Predicate Pred;
4884   switch (I.getPredicate()) {
4885   default: assert(0 && "Unexpected predicate!");
4886   case FCmpInst::FCMP_UEQ:
4887   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4888   case FCmpInst::FCMP_UGT:
4889   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4890   case FCmpInst::FCMP_UGE:
4891   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4892   case FCmpInst::FCMP_ULT:
4893   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4894   case FCmpInst::FCMP_ULE:
4895   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4896   case FCmpInst::FCMP_UNE:
4897   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4898   case FCmpInst::FCMP_ORD:
4899     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4900   case FCmpInst::FCMP_UNO:
4901     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4902   }
4903   
4904   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4905   
4906   // Now we know that the APFloat is a normal number, zero or inf.
4907   
4908   // See if the FP constant is too large for the integer.  For example,
4909   // comparing an i8 to 300.0.
4910   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4911   
4912   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4913   // and large values. 
4914   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4915   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4916                         APFloat::rmNearestTiesToEven);
4917   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4918     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4919         Pred == ICmpInst::ICMP_SLE)
4920       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4921     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4922   }
4923   
4924   // See if the RHS value is < SignedMin.
4925   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4926   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4927                         APFloat::rmNearestTiesToEven);
4928   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4929     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4930         Pred == ICmpInst::ICMP_SGE)
4931       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4932     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4933   }
4934
4935   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4936   // it may still be fractional.  See if it is fractional by casting the FP
4937   // value to the integer value and back, checking for equality.  Don't do this
4938   // for zero, because -0.0 is not fractional.
4939   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4940   if (!RHS.isZero() &&
4941       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4942     // If we had a comparison against a fractional value, we have to adjust
4943     // the compare predicate and sometimes the value.  RHSC is rounded towards
4944     // zero at this point.
4945     switch (Pred) {
4946     default: assert(0 && "Unexpected integer comparison!");
4947     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
4948       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4949     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
4950       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4951     case ICmpInst::ICMP_SLE:
4952       // (float)int <= 4.4   --> int <= 4
4953       // (float)int <= -4.4  --> int < -4
4954       if (RHS.isNegative())
4955         Pred = ICmpInst::ICMP_SLT;
4956       break;
4957     case ICmpInst::ICMP_SLT:
4958       // (float)int < -4.4   --> int < -4
4959       // (float)int < 4.4    --> int <= 4
4960       if (!RHS.isNegative())
4961         Pred = ICmpInst::ICMP_SLE;
4962       break;
4963     case ICmpInst::ICMP_SGT:
4964       // (float)int > 4.4    --> int > 4
4965       // (float)int > -4.4   --> int >= -4
4966       if (RHS.isNegative())
4967         Pred = ICmpInst::ICMP_SGE;
4968       break;
4969     case ICmpInst::ICMP_SGE:
4970       // (float)int >= -4.4   --> int >= -4
4971       // (float)int >= 4.4    --> int > 4
4972       if (!RHS.isNegative())
4973         Pred = ICmpInst::ICMP_SGT;
4974       break;
4975     }
4976   }
4977
4978   // Lower this FP comparison into an appropriate integer version of the
4979   // comparison.
4980   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4981 }
4982
4983 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4984   bool Changed = SimplifyCompare(I);
4985   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4986
4987   // Fold trivial predicates.
4988   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4989     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4990   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4991     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4992   
4993   // Simplify 'fcmp pred X, X'
4994   if (Op0 == Op1) {
4995     switch (I.getPredicate()) {
4996     default: assert(0 && "Unknown predicate!");
4997     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4998     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4999     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5000       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5001     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5002     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5003     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5004       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5005       
5006     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5007     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5008     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5009     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5010       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5011       I.setPredicate(FCmpInst::FCMP_UNO);
5012       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5013       return &I;
5014       
5015     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5016     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5017     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5018     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5019       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5020       I.setPredicate(FCmpInst::FCMP_ORD);
5021       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5022       return &I;
5023     }
5024   }
5025     
5026   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5027     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5028
5029   // Handle fcmp with constant RHS
5030   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5031     // If the constant is a nan, see if we can fold the comparison based on it.
5032     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5033       if (CFP->getValueAPF().isNaN()) {
5034         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5035           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5036         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5037                "Comparison must be either ordered or unordered!");
5038         // True if unordered.
5039         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5040       }
5041     }
5042     
5043     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5044       switch (LHSI->getOpcode()) {
5045       case Instruction::PHI:
5046         if (Instruction *NV = FoldOpIntoPhi(I))
5047           return NV;
5048         break;
5049       case Instruction::SIToFP:
5050       case Instruction::UIToFP:
5051         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5052           return NV;
5053         break;
5054       case Instruction::Select:
5055         // If either operand of the select is a constant, we can fold the
5056         // comparison into the select arms, which will cause one to be
5057         // constant folded and the select turned into a bitwise or.
5058         Value *Op1 = 0, *Op2 = 0;
5059         if (LHSI->hasOneUse()) {
5060           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5061             // Fold the known value into the constant operand.
5062             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5063             // Insert a new FCmp of the other select operand.
5064             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5065                                                       LHSI->getOperand(2), RHSC,
5066                                                       I.getName()), I);
5067           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5068             // Fold the known value into the constant operand.
5069             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5070             // Insert a new FCmp of the other select operand.
5071             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5072                                                       LHSI->getOperand(1), RHSC,
5073                                                       I.getName()), I);
5074           }
5075         }
5076
5077         if (Op1)
5078           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5079         break;
5080       }
5081   }
5082
5083   return Changed ? &I : 0;
5084 }
5085
5086 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5087   bool Changed = SimplifyCompare(I);
5088   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5089   const Type *Ty = Op0->getType();
5090
5091   // icmp X, X
5092   if (Op0 == Op1)
5093     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5094                                                    I.isTrueWhenEqual()));
5095
5096   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5097     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5098   
5099   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5100   // addresses never equal each other!  We already know that Op0 != Op1.
5101   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5102        isa<ConstantPointerNull>(Op0)) &&
5103       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5104        isa<ConstantPointerNull>(Op1)))
5105     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5106                                                    !I.isTrueWhenEqual()));
5107
5108   // icmp's with boolean values can always be turned into bitwise operations
5109   if (Ty == Type::Int1Ty) {
5110     switch (I.getPredicate()) {
5111     default: assert(0 && "Invalid icmp instruction!");
5112     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5113       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5114       InsertNewInstBefore(Xor, I);
5115       return BinaryOperator::CreateNot(Xor);
5116     }
5117     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5118       return BinaryOperator::CreateXor(Op0, Op1);
5119
5120     case ICmpInst::ICMP_UGT:
5121     case ICmpInst::ICMP_SGT:
5122       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5123       // FALL THROUGH
5124     case ICmpInst::ICMP_ULT:
5125     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5126       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5127       InsertNewInstBefore(Not, I);
5128       return BinaryOperator::CreateAnd(Not, Op1);
5129     }
5130     case ICmpInst::ICMP_UGE:
5131     case ICmpInst::ICMP_SGE:
5132       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5133       // FALL THROUGH
5134     case ICmpInst::ICMP_ULE:
5135     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5136       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5137       InsertNewInstBefore(Not, I);
5138       return BinaryOperator::CreateOr(Not, Op1);
5139     }
5140     }
5141   }
5142
5143   // See if we are doing a comparison between a constant and an instruction that
5144   // can be folded into the comparison.
5145   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5146       Value *A, *B;
5147     
5148     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5149     if (I.isEquality() && CI->isNullValue() &&
5150         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5151       // (icmp cond A B) if cond is equality
5152       return new ICmpInst(I.getPredicate(), A, B);
5153     }
5154     
5155     switch (I.getPredicate()) {
5156     default: break;
5157     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5158       if (CI->isMinValue(false))
5159         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5160       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5161         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5162       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5163         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5164       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5165       if (CI->isMinValue(true))
5166         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5167                             ConstantInt::getAllOnesValue(Op0->getType()));
5168           
5169       break;
5170
5171     case ICmpInst::ICMP_SLT:
5172       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5173         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5174       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5175         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5176       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5177         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5178       break;
5179
5180     case ICmpInst::ICMP_UGT:
5181       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5182         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5183       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5184         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5185       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5186         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5187         
5188       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5189       if (CI->isMaxValue(true))
5190         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5191                             ConstantInt::getNullValue(Op0->getType()));
5192       break;
5193
5194     case ICmpInst::ICMP_SGT:
5195       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5196         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5197       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5198         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5199       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5200         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5201       break;
5202
5203     case ICmpInst::ICMP_ULE:
5204       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5205         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5206       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5207         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5208       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5209         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5210       break;
5211
5212     case ICmpInst::ICMP_SLE:
5213       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5214         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5215       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5216         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5217       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5218         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5219       break;
5220
5221     case ICmpInst::ICMP_UGE:
5222       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5223         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5224       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5225         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5226       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5227         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5228       break;
5229
5230     case ICmpInst::ICMP_SGE:
5231       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5232         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5233       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5234         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5235       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5236         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5237       break;
5238     }
5239
5240     // If we still have a icmp le or icmp ge instruction, turn it into the
5241     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5242     // already been handled above, this requires little checking.
5243     //
5244     switch (I.getPredicate()) {
5245     default: break;
5246     case ICmpInst::ICMP_ULE: 
5247       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5248     case ICmpInst::ICMP_SLE:
5249       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5250     case ICmpInst::ICMP_UGE:
5251       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5252     case ICmpInst::ICMP_SGE:
5253       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5254     }
5255     
5256     // See if we can fold the comparison based on bits known to be zero or one
5257     // in the input.  If this comparison is a normal comparison, it demands all
5258     // bits, if it is a sign bit comparison, it only demands the sign bit.
5259     
5260     bool UnusedBit;
5261     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5262     
5263     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5264     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5265     if (SimplifyDemandedBits(Op0, 
5266                              isSignBit ? APInt::getSignBit(BitWidth)
5267                                        : APInt::getAllOnesValue(BitWidth),
5268                              KnownZero, KnownOne, 0))
5269       return &I;
5270         
5271     // Given the known and unknown bits, compute a range that the LHS could be
5272     // in.
5273     if ((KnownOne | KnownZero) != 0) {
5274       // Compute the Min, Max and RHS values based on the known bits. For the
5275       // EQ and NE we use unsigned values.
5276       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5277       const APInt& RHSVal = CI->getValue();
5278       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5279         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5280                                                Max);
5281       } else {
5282         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5283                                                  Max);
5284       }
5285       switch (I.getPredicate()) {  // LE/GE have been folded already.
5286       default: assert(0 && "Unknown icmp opcode!");
5287       case ICmpInst::ICMP_EQ:
5288         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5289           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5290         break;
5291       case ICmpInst::ICMP_NE:
5292         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5293           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5294         break;
5295       case ICmpInst::ICMP_ULT:
5296         if (Max.ult(RHSVal))
5297           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5298         if (Min.uge(RHSVal))
5299           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5300         break;
5301       case ICmpInst::ICMP_UGT:
5302         if (Min.ugt(RHSVal))
5303           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5304         if (Max.ule(RHSVal))
5305           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5306         break;
5307       case ICmpInst::ICMP_SLT:
5308         if (Max.slt(RHSVal))
5309           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5310         if (Min.sgt(RHSVal))
5311           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5312         break;
5313       case ICmpInst::ICMP_SGT: 
5314         if (Min.sgt(RHSVal))
5315           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5316         if (Max.sle(RHSVal))
5317           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5318         break;
5319       }
5320     }
5321           
5322     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5323     // instruction, see if that instruction also has constants so that the 
5324     // instruction can be folded into the icmp 
5325     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5326       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5327         return Res;
5328   }
5329
5330   // Handle icmp with constant (but not simple integer constant) RHS
5331   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5332     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5333       switch (LHSI->getOpcode()) {
5334       case Instruction::GetElementPtr:
5335         if (RHSC->isNullValue()) {
5336           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5337           bool isAllZeros = true;
5338           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5339             if (!isa<Constant>(LHSI->getOperand(i)) ||
5340                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5341               isAllZeros = false;
5342               break;
5343             }
5344           if (isAllZeros)
5345             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5346                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5347         }
5348         break;
5349
5350       case Instruction::PHI:
5351         if (Instruction *NV = FoldOpIntoPhi(I))
5352           return NV;
5353         break;
5354       case Instruction::Select: {
5355         // If either operand of the select is a constant, we can fold the
5356         // comparison into the select arms, which will cause one to be
5357         // constant folded and the select turned into a bitwise or.
5358         Value *Op1 = 0, *Op2 = 0;
5359         if (LHSI->hasOneUse()) {
5360           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5361             // Fold the known value into the constant operand.
5362             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5363             // Insert a new ICmp of the other select operand.
5364             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5365                                                    LHSI->getOperand(2), RHSC,
5366                                                    I.getName()), I);
5367           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5368             // Fold the known value into the constant operand.
5369             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5370             // Insert a new ICmp of the other select operand.
5371             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5372                                                    LHSI->getOperand(1), RHSC,
5373                                                    I.getName()), I);
5374           }
5375         }
5376
5377         if (Op1)
5378           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5379         break;
5380       }
5381       case Instruction::Malloc:
5382         // If we have (malloc != null), and if the malloc has a single use, we
5383         // can assume it is successful and remove the malloc.
5384         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5385           AddToWorkList(LHSI);
5386           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5387                                                          !I.isTrueWhenEqual()));
5388         }
5389         break;
5390       }
5391   }
5392
5393   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5394   if (User *GEP = dyn_castGetElementPtr(Op0))
5395     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5396       return NI;
5397   if (User *GEP = dyn_castGetElementPtr(Op1))
5398     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5399                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5400       return NI;
5401
5402   // Test to see if the operands of the icmp are casted versions of other
5403   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5404   // now.
5405   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5406     if (isa<PointerType>(Op0->getType()) && 
5407         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5408       // We keep moving the cast from the left operand over to the right
5409       // operand, where it can often be eliminated completely.
5410       Op0 = CI->getOperand(0);
5411
5412       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5413       // so eliminate it as well.
5414       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5415         Op1 = CI2->getOperand(0);
5416
5417       // If Op1 is a constant, we can fold the cast into the constant.
5418       if (Op0->getType() != Op1->getType()) {
5419         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5420           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5421         } else {
5422           // Otherwise, cast the RHS right before the icmp
5423           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5424         }
5425       }
5426       return new ICmpInst(I.getPredicate(), Op0, Op1);
5427     }
5428   }
5429   
5430   if (isa<CastInst>(Op0)) {
5431     // Handle the special case of: icmp (cast bool to X), <cst>
5432     // This comes up when you have code like
5433     //   int X = A < B;
5434     //   if (X) ...
5435     // For generality, we handle any zero-extension of any operand comparison
5436     // with a constant or another cast from the same type.
5437     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5438       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5439         return R;
5440   }
5441   
5442   // ~x < ~y --> y < x
5443   { Value *A, *B;
5444     if (match(Op0, m_Not(m_Value(A))) &&
5445         match(Op1, m_Not(m_Value(B))))
5446       return new ICmpInst(I.getPredicate(), B, A);
5447   }
5448   
5449   if (I.isEquality()) {
5450     Value *A, *B, *C, *D;
5451     
5452     // -x == -y --> x == y
5453     if (match(Op0, m_Neg(m_Value(A))) &&
5454         match(Op1, m_Neg(m_Value(B))))
5455       return new ICmpInst(I.getPredicate(), A, B);
5456     
5457     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5458       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5459         Value *OtherVal = A == Op1 ? B : A;
5460         return new ICmpInst(I.getPredicate(), OtherVal,
5461                             Constant::getNullValue(A->getType()));
5462       }
5463
5464       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5465         // A^c1 == C^c2 --> A == C^(c1^c2)
5466         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5467           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5468             if (Op1->hasOneUse()) {
5469               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5470               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5471               return new ICmpInst(I.getPredicate(), A,
5472                                   InsertNewInstBefore(Xor, I));
5473             }
5474         
5475         // A^B == A^D -> B == D
5476         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5477         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5478         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5479         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5480       }
5481     }
5482     
5483     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5484         (A == Op0 || B == Op0)) {
5485       // A == (A^B)  ->  B == 0
5486       Value *OtherVal = A == Op0 ? B : A;
5487       return new ICmpInst(I.getPredicate(), OtherVal,
5488                           Constant::getNullValue(A->getType()));
5489     }
5490     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5491       // (A-B) == A  ->  B == 0
5492       return new ICmpInst(I.getPredicate(), B,
5493                           Constant::getNullValue(B->getType()));
5494     }
5495     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5496       // A == (A-B)  ->  B == 0
5497       return new ICmpInst(I.getPredicate(), B,
5498                           Constant::getNullValue(B->getType()));
5499     }
5500     
5501     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5502     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5503         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5504         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5505       Value *X = 0, *Y = 0, *Z = 0;
5506       
5507       if (A == C) {
5508         X = B; Y = D; Z = A;
5509       } else if (A == D) {
5510         X = B; Y = C; Z = A;
5511       } else if (B == C) {
5512         X = A; Y = D; Z = B;
5513       } else if (B == D) {
5514         X = A; Y = C; Z = B;
5515       }
5516       
5517       if (X) {   // Build (X^Y) & Z
5518         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5519         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5520         I.setOperand(0, Op1);
5521         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5522         return &I;
5523       }
5524     }
5525   }
5526   return Changed ? &I : 0;
5527 }
5528
5529
5530 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5531 /// and CmpRHS are both known to be integer constants.
5532 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5533                                           ConstantInt *DivRHS) {
5534   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5535   const APInt &CmpRHSV = CmpRHS->getValue();
5536   
5537   // FIXME: If the operand types don't match the type of the divide 
5538   // then don't attempt this transform. The code below doesn't have the
5539   // logic to deal with a signed divide and an unsigned compare (and
5540   // vice versa). This is because (x /s C1) <s C2  produces different 
5541   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5542   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5543   // work. :(  The if statement below tests that condition and bails 
5544   // if it finds it. 
5545   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5546   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5547     return 0;
5548   if (DivRHS->isZero())
5549     return 0; // The ProdOV computation fails on divide by zero.
5550
5551   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5552   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5553   // C2 (CI). By solving for X we can turn this into a range check 
5554   // instead of computing a divide. 
5555   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5556
5557   // Determine if the product overflows by seeing if the product is
5558   // not equal to the divide. Make sure we do the same kind of divide
5559   // as in the LHS instruction that we're folding. 
5560   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5561                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5562
5563   // Get the ICmp opcode
5564   ICmpInst::Predicate Pred = ICI.getPredicate();
5565
5566   // Figure out the interval that is being checked.  For example, a comparison
5567   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5568   // Compute this interval based on the constants involved and the signedness of
5569   // the compare/divide.  This computes a half-open interval, keeping track of
5570   // whether either value in the interval overflows.  After analysis each
5571   // overflow variable is set to 0 if it's corresponding bound variable is valid
5572   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5573   int LoOverflow = 0, HiOverflow = 0;
5574   ConstantInt *LoBound = 0, *HiBound = 0;
5575   
5576   
5577   if (!DivIsSigned) {  // udiv
5578     // e.g. X/5 op 3  --> [15, 20)
5579     LoBound = Prod;
5580     HiOverflow = LoOverflow = ProdOV;
5581     if (!HiOverflow)
5582       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5583   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5584     if (CmpRHSV == 0) {       // (X / pos) op 0
5585       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5586       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5587       HiBound = DivRHS;
5588     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5589       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5590       HiOverflow = LoOverflow = ProdOV;
5591       if (!HiOverflow)
5592         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5593     } else {                       // (X / pos) op neg
5594       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5595       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5596       LoOverflow = AddWithOverflow(LoBound, Prod,
5597                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5598       HiBound = AddOne(Prod);
5599       HiOverflow = ProdOV ? -1 : 0;
5600     }
5601   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5602     if (CmpRHSV == 0) {       // (X / neg) op 0
5603       // e.g. X/-5 op 0  --> [-4, 5)
5604       LoBound = AddOne(DivRHS);
5605       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5606       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5607         HiOverflow = 1;            // [INTMIN+1, overflow)
5608         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5609       }
5610     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5611       // e.g. X/-5 op 3  --> [-19, -14)
5612       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5613       if (!LoOverflow)
5614         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5615       HiBound = AddOne(Prod);
5616     } else {                       // (X / neg) op neg
5617       // e.g. X/-5 op -3  --> [15, 20)
5618       LoBound = Prod;
5619       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5620       HiBound = Subtract(Prod, DivRHS);
5621     }
5622     
5623     // Dividing by a negative swaps the condition.  LT <-> GT
5624     Pred = ICmpInst::getSwappedPredicate(Pred);
5625   }
5626
5627   Value *X = DivI->getOperand(0);
5628   switch (Pred) {
5629   default: assert(0 && "Unhandled icmp opcode!");
5630   case ICmpInst::ICMP_EQ:
5631     if (LoOverflow && HiOverflow)
5632       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5633     else if (HiOverflow)
5634       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5635                           ICmpInst::ICMP_UGE, X, LoBound);
5636     else if (LoOverflow)
5637       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5638                           ICmpInst::ICMP_ULT, X, HiBound);
5639     else
5640       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5641   case ICmpInst::ICMP_NE:
5642     if (LoOverflow && HiOverflow)
5643       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5644     else if (HiOverflow)
5645       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5646                           ICmpInst::ICMP_ULT, X, LoBound);
5647     else if (LoOverflow)
5648       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5649                           ICmpInst::ICMP_UGE, X, HiBound);
5650     else
5651       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5652   case ICmpInst::ICMP_ULT:
5653   case ICmpInst::ICMP_SLT:
5654     if (LoOverflow == +1)   // Low bound is greater than input range.
5655       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5656     if (LoOverflow == -1)   // Low bound is less than input range.
5657       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5658     return new ICmpInst(Pred, X, LoBound);
5659   case ICmpInst::ICMP_UGT:
5660   case ICmpInst::ICMP_SGT:
5661     if (HiOverflow == +1)       // High bound greater than input range.
5662       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5663     else if (HiOverflow == -1)  // High bound less than input range.
5664       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5665     if (Pred == ICmpInst::ICMP_UGT)
5666       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5667     else
5668       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5669   }
5670 }
5671
5672
5673 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5674 ///
5675 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5676                                                           Instruction *LHSI,
5677                                                           ConstantInt *RHS) {
5678   const APInt &RHSV = RHS->getValue();
5679   
5680   switch (LHSI->getOpcode()) {
5681   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5682     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5683       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5684       // fold the xor.
5685       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5686           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5687         Value *CompareVal = LHSI->getOperand(0);
5688         
5689         // If the sign bit of the XorCST is not set, there is no change to
5690         // the operation, just stop using the Xor.
5691         if (!XorCST->getValue().isNegative()) {
5692           ICI.setOperand(0, CompareVal);
5693           AddToWorkList(LHSI);
5694           return &ICI;
5695         }
5696         
5697         // Was the old condition true if the operand is positive?
5698         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5699         
5700         // If so, the new one isn't.
5701         isTrueIfPositive ^= true;
5702         
5703         if (isTrueIfPositive)
5704           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5705         else
5706           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5707       }
5708     }
5709     break;
5710   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5711     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5712         LHSI->getOperand(0)->hasOneUse()) {
5713       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5714       
5715       // If the LHS is an AND of a truncating cast, we can widen the
5716       // and/compare to be the input width without changing the value
5717       // produced, eliminating a cast.
5718       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5719         // We can do this transformation if either the AND constant does not
5720         // have its sign bit set or if it is an equality comparison. 
5721         // Extending a relational comparison when we're checking the sign
5722         // bit would not work.
5723         if (Cast->hasOneUse() &&
5724             (ICI.isEquality() ||
5725              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5726           uint32_t BitWidth = 
5727             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5728           APInt NewCST = AndCST->getValue();
5729           NewCST.zext(BitWidth);
5730           APInt NewCI = RHSV;
5731           NewCI.zext(BitWidth);
5732           Instruction *NewAnd = 
5733             BinaryOperator::CreateAnd(Cast->getOperand(0),
5734                                       ConstantInt::get(NewCST),LHSI->getName());
5735           InsertNewInstBefore(NewAnd, ICI);
5736           return new ICmpInst(ICI.getPredicate(), NewAnd,
5737                               ConstantInt::get(NewCI));
5738         }
5739       }
5740       
5741       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5742       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5743       // happens a LOT in code produced by the C front-end, for bitfield
5744       // access.
5745       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5746       if (Shift && !Shift->isShift())
5747         Shift = 0;
5748       
5749       ConstantInt *ShAmt;
5750       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5751       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5752       const Type *AndTy = AndCST->getType();          // Type of the and.
5753       
5754       // We can fold this as long as we can't shift unknown bits
5755       // into the mask.  This can only happen with signed shift
5756       // rights, as they sign-extend.
5757       if (ShAmt) {
5758         bool CanFold = Shift->isLogicalShift();
5759         if (!CanFold) {
5760           // To test for the bad case of the signed shr, see if any
5761           // of the bits shifted in could be tested after the mask.
5762           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5763           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5764           
5765           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5766           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5767                AndCST->getValue()) == 0)
5768             CanFold = true;
5769         }
5770         
5771         if (CanFold) {
5772           Constant *NewCst;
5773           if (Shift->getOpcode() == Instruction::Shl)
5774             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5775           else
5776             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5777           
5778           // Check to see if we are shifting out any of the bits being
5779           // compared.
5780           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5781             // If we shifted bits out, the fold is not going to work out.
5782             // As a special case, check to see if this means that the
5783             // result is always true or false now.
5784             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5785               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5786             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5787               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5788           } else {
5789             ICI.setOperand(1, NewCst);
5790             Constant *NewAndCST;
5791             if (Shift->getOpcode() == Instruction::Shl)
5792               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5793             else
5794               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5795             LHSI->setOperand(1, NewAndCST);
5796             LHSI->setOperand(0, Shift->getOperand(0));
5797             AddToWorkList(Shift); // Shift is dead.
5798             AddUsesToWorkList(ICI);
5799             return &ICI;
5800           }
5801         }
5802       }
5803       
5804       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5805       // preferable because it allows the C<<Y expression to be hoisted out
5806       // of a loop if Y is invariant and X is not.
5807       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5808           ICI.isEquality() && !Shift->isArithmeticShift() &&
5809           isa<Instruction>(Shift->getOperand(0))) {
5810         // Compute C << Y.
5811         Value *NS;
5812         if (Shift->getOpcode() == Instruction::LShr) {
5813           NS = BinaryOperator::CreateShl(AndCST, 
5814                                          Shift->getOperand(1), "tmp");
5815         } else {
5816           // Insert a logical shift.
5817           NS = BinaryOperator::CreateLShr(AndCST,
5818                                           Shift->getOperand(1), "tmp");
5819         }
5820         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5821         
5822         // Compute X & (C << Y).
5823         Instruction *NewAnd = 
5824           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5825         InsertNewInstBefore(NewAnd, ICI);
5826         
5827         ICI.setOperand(0, NewAnd);
5828         return &ICI;
5829       }
5830     }
5831     break;
5832     
5833   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5834     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5835     if (!ShAmt) break;
5836     
5837     uint32_t TypeBits = RHSV.getBitWidth();
5838     
5839     // Check that the shift amount is in range.  If not, don't perform
5840     // undefined shifts.  When the shift is visited it will be
5841     // simplified.
5842     if (ShAmt->uge(TypeBits))
5843       break;
5844     
5845     if (ICI.isEquality()) {
5846       // If we are comparing against bits always shifted out, the
5847       // comparison cannot succeed.
5848       Constant *Comp =
5849         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5850       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5851         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5852         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5853         return ReplaceInstUsesWith(ICI, Cst);
5854       }
5855       
5856       if (LHSI->hasOneUse()) {
5857         // Otherwise strength reduce the shift into an and.
5858         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5859         Constant *Mask =
5860           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5861         
5862         Instruction *AndI =
5863           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5864                                     Mask, LHSI->getName()+".mask");
5865         Value *And = InsertNewInstBefore(AndI, ICI);
5866         return new ICmpInst(ICI.getPredicate(), And,
5867                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5868       }
5869     }
5870     
5871     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5872     bool TrueIfSigned = false;
5873     if (LHSI->hasOneUse() &&
5874         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5875       // (X << 31) <s 0  --> (X&1) != 0
5876       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5877                                            (TypeBits-ShAmt->getZExtValue()-1));
5878       Instruction *AndI =
5879         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5880                                   Mask, LHSI->getName()+".mask");
5881       Value *And = InsertNewInstBefore(AndI, ICI);
5882       
5883       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5884                           And, Constant::getNullValue(And->getType()));
5885     }
5886     break;
5887   }
5888     
5889   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5890   case Instruction::AShr: {
5891     // Only handle equality comparisons of shift-by-constant.
5892     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5893     if (!ShAmt || !ICI.isEquality()) break;
5894
5895     // Check that the shift amount is in range.  If not, don't perform
5896     // undefined shifts.  When the shift is visited it will be
5897     // simplified.
5898     uint32_t TypeBits = RHSV.getBitWidth();
5899     if (ShAmt->uge(TypeBits))
5900       break;
5901     
5902     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5903       
5904     // If we are comparing against bits always shifted out, the
5905     // comparison cannot succeed.
5906     APInt Comp = RHSV << ShAmtVal;
5907     if (LHSI->getOpcode() == Instruction::LShr)
5908       Comp = Comp.lshr(ShAmtVal);
5909     else
5910       Comp = Comp.ashr(ShAmtVal);
5911     
5912     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5913       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5914       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5915       return ReplaceInstUsesWith(ICI, Cst);
5916     }
5917     
5918     // Otherwise, check to see if the bits shifted out are known to be zero.
5919     // If so, we can compare against the unshifted value:
5920     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5921     if (LHSI->hasOneUse() &&
5922         MaskedValueIsZero(LHSI->getOperand(0), 
5923                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5924       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5925                           ConstantExpr::getShl(RHS, ShAmt));
5926     }
5927       
5928     if (LHSI->hasOneUse()) {
5929       // Otherwise strength reduce the shift into an and.
5930       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5931       Constant *Mask = ConstantInt::get(Val);
5932       
5933       Instruction *AndI =
5934         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5935                                   Mask, LHSI->getName()+".mask");
5936       Value *And = InsertNewInstBefore(AndI, ICI);
5937       return new ICmpInst(ICI.getPredicate(), And,
5938                           ConstantExpr::getShl(RHS, ShAmt));
5939     }
5940     break;
5941   }
5942     
5943   case Instruction::SDiv:
5944   case Instruction::UDiv:
5945     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5946     // Fold this div into the comparison, producing a range check. 
5947     // Determine, based on the divide type, what the range is being 
5948     // checked.  If there is an overflow on the low or high side, remember 
5949     // it, otherwise compute the range [low, hi) bounding the new value.
5950     // See: InsertRangeTest above for the kinds of replacements possible.
5951     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5952       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5953                                           DivRHS))
5954         return R;
5955     break;
5956
5957   case Instruction::Add:
5958     // Fold: icmp pred (add, X, C1), C2
5959
5960     if (!ICI.isEquality()) {
5961       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5962       if (!LHSC) break;
5963       const APInt &LHSV = LHSC->getValue();
5964
5965       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5966                             .subtract(LHSV);
5967
5968       if (ICI.isSignedPredicate()) {
5969         if (CR.getLower().isSignBit()) {
5970           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5971                               ConstantInt::get(CR.getUpper()));
5972         } else if (CR.getUpper().isSignBit()) {
5973           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5974                               ConstantInt::get(CR.getLower()));
5975         }
5976       } else {
5977         if (CR.getLower().isMinValue()) {
5978           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5979                               ConstantInt::get(CR.getUpper()));
5980         } else if (CR.getUpper().isMinValue()) {
5981           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5982                               ConstantInt::get(CR.getLower()));
5983         }
5984       }
5985     }
5986     break;
5987   }
5988   
5989   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5990   if (ICI.isEquality()) {
5991     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5992     
5993     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5994     // the second operand is a constant, simplify a bit.
5995     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5996       switch (BO->getOpcode()) {
5997       case Instruction::SRem:
5998         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5999         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6000           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6001           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6002             Instruction *NewRem =
6003               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6004                                          BO->getName());
6005             InsertNewInstBefore(NewRem, ICI);
6006             return new ICmpInst(ICI.getPredicate(), NewRem, 
6007                                 Constant::getNullValue(BO->getType()));
6008           }
6009         }
6010         break;
6011       case Instruction::Add:
6012         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6013         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6014           if (BO->hasOneUse())
6015             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6016                                 Subtract(RHS, BOp1C));
6017         } else if (RHSV == 0) {
6018           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6019           // efficiently invertible, or if the add has just this one use.
6020           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6021           
6022           if (Value *NegVal = dyn_castNegVal(BOp1))
6023             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6024           else if (Value *NegVal = dyn_castNegVal(BOp0))
6025             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6026           else if (BO->hasOneUse()) {
6027             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6028             InsertNewInstBefore(Neg, ICI);
6029             Neg->takeName(BO);
6030             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6031           }
6032         }
6033         break;
6034       case Instruction::Xor:
6035         // For the xor case, we can xor two constants together, eliminating
6036         // the explicit xor.
6037         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6038           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6039                               ConstantExpr::getXor(RHS, BOC));
6040         
6041         // FALLTHROUGH
6042       case Instruction::Sub:
6043         // Replace (([sub|xor] A, B) != 0) with (A != B)
6044         if (RHSV == 0)
6045           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6046                               BO->getOperand(1));
6047         break;
6048         
6049       case Instruction::Or:
6050         // If bits are being or'd in that are not present in the constant we
6051         // are comparing against, then the comparison could never succeed!
6052         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6053           Constant *NotCI = ConstantExpr::getNot(RHS);
6054           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6055             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6056                                                              isICMP_NE));
6057         }
6058         break;
6059         
6060       case Instruction::And:
6061         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6062           // If bits are being compared against that are and'd out, then the
6063           // comparison can never succeed!
6064           if ((RHSV & ~BOC->getValue()) != 0)
6065             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6066                                                              isICMP_NE));
6067           
6068           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6069           if (RHS == BOC && RHSV.isPowerOf2())
6070             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6071                                 ICmpInst::ICMP_NE, LHSI,
6072                                 Constant::getNullValue(RHS->getType()));
6073           
6074           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6075           if (BOC->getValue().isSignBit()) {
6076             Value *X = BO->getOperand(0);
6077             Constant *Zero = Constant::getNullValue(X->getType());
6078             ICmpInst::Predicate pred = isICMP_NE ? 
6079               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6080             return new ICmpInst(pred, X, Zero);
6081           }
6082           
6083           // ((X & ~7) == 0) --> X < 8
6084           if (RHSV == 0 && isHighOnes(BOC)) {
6085             Value *X = BO->getOperand(0);
6086             Constant *NegX = ConstantExpr::getNeg(BOC);
6087             ICmpInst::Predicate pred = isICMP_NE ? 
6088               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6089             return new ICmpInst(pred, X, NegX);
6090           }
6091         }
6092       default: break;
6093       }
6094     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6095       // Handle icmp {eq|ne} <intrinsic>, intcst.
6096       if (II->getIntrinsicID() == Intrinsic::bswap) {
6097         AddToWorkList(II);
6098         ICI.setOperand(0, II->getOperand(1));
6099         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6100         return &ICI;
6101       }
6102     }
6103   } else {  // Not a ICMP_EQ/ICMP_NE
6104             // If the LHS is a cast from an integral value of the same size, 
6105             // then since we know the RHS is a constant, try to simlify.
6106     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6107       Value *CastOp = Cast->getOperand(0);
6108       const Type *SrcTy = CastOp->getType();
6109       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6110       if (SrcTy->isInteger() && 
6111           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6112         // If this is an unsigned comparison, try to make the comparison use
6113         // smaller constant values.
6114         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6115           // X u< 128 => X s> -1
6116           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6117                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6118         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6119                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6120           // X u> 127 => X s< 0
6121           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6122                               Constant::getNullValue(SrcTy));
6123         }
6124       }
6125     }
6126   }
6127   return 0;
6128 }
6129
6130 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6131 /// We only handle extending casts so far.
6132 ///
6133 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6134   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6135   Value *LHSCIOp        = LHSCI->getOperand(0);
6136   const Type *SrcTy     = LHSCIOp->getType();
6137   const Type *DestTy    = LHSCI->getType();
6138   Value *RHSCIOp;
6139
6140   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6141   // integer type is the same size as the pointer type.
6142   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6143       getTargetData().getPointerSizeInBits() == 
6144          cast<IntegerType>(DestTy)->getBitWidth()) {
6145     Value *RHSOp = 0;
6146     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6147       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6148     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6149       RHSOp = RHSC->getOperand(0);
6150       // If the pointer types don't match, insert a bitcast.
6151       if (LHSCIOp->getType() != RHSOp->getType())
6152         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6153     }
6154
6155     if (RHSOp)
6156       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6157   }
6158   
6159   // The code below only handles extension cast instructions, so far.
6160   // Enforce this.
6161   if (LHSCI->getOpcode() != Instruction::ZExt &&
6162       LHSCI->getOpcode() != Instruction::SExt)
6163     return 0;
6164
6165   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6166   bool isSignedCmp = ICI.isSignedPredicate();
6167
6168   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6169     // Not an extension from the same type?
6170     RHSCIOp = CI->getOperand(0);
6171     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6172       return 0;
6173     
6174     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6175     // and the other is a zext), then we can't handle this.
6176     if (CI->getOpcode() != LHSCI->getOpcode())
6177       return 0;
6178
6179     // Deal with equality cases early.
6180     if (ICI.isEquality())
6181       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6182
6183     // A signed comparison of sign extended values simplifies into a
6184     // signed comparison.
6185     if (isSignedCmp && isSignedExt)
6186       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6187
6188     // The other three cases all fold into an unsigned comparison.
6189     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6190   }
6191
6192   // If we aren't dealing with a constant on the RHS, exit early
6193   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6194   if (!CI)
6195     return 0;
6196
6197   // Compute the constant that would happen if we truncated to SrcTy then
6198   // reextended to DestTy.
6199   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6200   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6201
6202   // If the re-extended constant didn't change...
6203   if (Res2 == CI) {
6204     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6205     // For example, we might have:
6206     //    %A = sext short %X to uint
6207     //    %B = icmp ugt uint %A, 1330
6208     // It is incorrect to transform this into 
6209     //    %B = icmp ugt short %X, 1330 
6210     // because %A may have negative value. 
6211     //
6212     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6213     // OR operation is EQ/NE.
6214     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6215       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6216     else
6217       return 0;
6218   }
6219
6220   // The re-extended constant changed so the constant cannot be represented 
6221   // in the shorter type. Consequently, we cannot emit a simple comparison.
6222
6223   // First, handle some easy cases. We know the result cannot be equal at this
6224   // point so handle the ICI.isEquality() cases
6225   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6226     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6227   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6228     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6229
6230   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6231   // should have been folded away previously and not enter in here.
6232   Value *Result;
6233   if (isSignedCmp) {
6234     // We're performing a signed comparison.
6235     if (cast<ConstantInt>(CI)->getValue().isNegative())
6236       Result = ConstantInt::getFalse();          // X < (small) --> false
6237     else
6238       Result = ConstantInt::getTrue();           // X < (large) --> true
6239   } else {
6240     // We're performing an unsigned comparison.
6241     if (isSignedExt) {
6242       // We're performing an unsigned comp with a sign extended value.
6243       // This is true if the input is >= 0. [aka >s -1]
6244       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6245       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6246                                    NegOne, ICI.getName()), ICI);
6247     } else {
6248       // Unsigned extend & unsigned compare -> always true.
6249       Result = ConstantInt::getTrue();
6250     }
6251   }
6252
6253   // Finally, return the value computed.
6254   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6255       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6256     return ReplaceInstUsesWith(ICI, Result);
6257   } else {
6258     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6259             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6260            "ICmp should be folded!");
6261     if (Constant *CI = dyn_cast<Constant>(Result))
6262       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6263     else
6264       return BinaryOperator::CreateNot(Result);
6265   }
6266 }
6267
6268 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6269   return commonShiftTransforms(I);
6270 }
6271
6272 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6273   return commonShiftTransforms(I);
6274 }
6275
6276 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6277   if (Instruction *R = commonShiftTransforms(I))
6278     return R;
6279   
6280   Value *Op0 = I.getOperand(0);
6281   
6282   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6283   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6284     if (CSI->isAllOnesValue())
6285       return ReplaceInstUsesWith(I, CSI);
6286   
6287   // See if we can turn a signed shr into an unsigned shr.
6288   if (MaskedValueIsZero(Op0, 
6289                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6290     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6291   
6292   return 0;
6293 }
6294
6295 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6296   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6297   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6298
6299   // shl X, 0 == X and shr X, 0 == X
6300   // shl 0, X == 0 and shr 0, X == 0
6301   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6302       Op0 == Constant::getNullValue(Op0->getType()))
6303     return ReplaceInstUsesWith(I, Op0);
6304   
6305   if (isa<UndefValue>(Op0)) {            
6306     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6307       return ReplaceInstUsesWith(I, Op0);
6308     else                                    // undef << X -> 0, undef >>u X -> 0
6309       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6310   }
6311   if (isa<UndefValue>(Op1)) {
6312     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6313       return ReplaceInstUsesWith(I, Op0);          
6314     else                                     // X << undef, X >>u undef -> 0
6315       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6316   }
6317
6318   // Try to fold constant and into select arguments.
6319   if (isa<Constant>(Op0))
6320     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6321       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6322         return R;
6323
6324   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6325     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6326       return Res;
6327   return 0;
6328 }
6329
6330 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6331                                                BinaryOperator &I) {
6332   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6333
6334   // See if we can simplify any instructions used by the instruction whose sole 
6335   // purpose is to compute bits we don't care about.
6336   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6337   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6338   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6339                            KnownZero, KnownOne))
6340     return &I;
6341   
6342   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6343   // of a signed value.
6344   //
6345   if (Op1->uge(TypeBits)) {
6346     if (I.getOpcode() != Instruction::AShr)
6347       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6348     else {
6349       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6350       return &I;
6351     }
6352   }
6353   
6354   // ((X*C1) << C2) == (X * (C1 << C2))
6355   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6356     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6357       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6358         return BinaryOperator::CreateMul(BO->getOperand(0),
6359                                          ConstantExpr::getShl(BOOp, Op1));
6360   
6361   // Try to fold constant and into select arguments.
6362   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6363     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6364       return R;
6365   if (isa<PHINode>(Op0))
6366     if (Instruction *NV = FoldOpIntoPhi(I))
6367       return NV;
6368   
6369   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6370   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6371     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6372     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6373     // place.  Don't try to do this transformation in this case.  Also, we
6374     // require that the input operand is a shift-by-constant so that we have
6375     // confidence that the shifts will get folded together.  We could do this
6376     // xform in more cases, but it is unlikely to be profitable.
6377     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6378         isa<ConstantInt>(TrOp->getOperand(1))) {
6379       // Okay, we'll do this xform.  Make the shift of shift.
6380       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6381       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6382                                                 I.getName());
6383       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6384
6385       // For logical shifts, the truncation has the effect of making the high
6386       // part of the register be zeros.  Emulate this by inserting an AND to
6387       // clear the top bits as needed.  This 'and' will usually be zapped by
6388       // other xforms later if dead.
6389       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6390       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6391       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6392       
6393       // The mask we constructed says what the trunc would do if occurring
6394       // between the shifts.  We want to know the effect *after* the second
6395       // shift.  We know that it is a logical shift by a constant, so adjust the
6396       // mask as appropriate.
6397       if (I.getOpcode() == Instruction::Shl)
6398         MaskV <<= Op1->getZExtValue();
6399       else {
6400         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6401         MaskV = MaskV.lshr(Op1->getZExtValue());
6402       }
6403
6404       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6405                                                    TI->getName());
6406       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6407
6408       // Return the value truncated to the interesting size.
6409       return new TruncInst(And, I.getType());
6410     }
6411   }
6412   
6413   if (Op0->hasOneUse()) {
6414     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6415       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6416       Value *V1, *V2;
6417       ConstantInt *CC;
6418       switch (Op0BO->getOpcode()) {
6419         default: break;
6420         case Instruction::Add:
6421         case Instruction::And:
6422         case Instruction::Or:
6423         case Instruction::Xor: {
6424           // These operators commute.
6425           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6426           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6427               match(Op0BO->getOperand(1),
6428                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6429             Instruction *YS = BinaryOperator::CreateShl(
6430                                             Op0BO->getOperand(0), Op1,
6431                                             Op0BO->getName());
6432             InsertNewInstBefore(YS, I); // (Y << C)
6433             Instruction *X = 
6434               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6435                                      Op0BO->getOperand(1)->getName());
6436             InsertNewInstBefore(X, I);  // (X + (Y << C))
6437             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6438             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6439                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6440           }
6441           
6442           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6443           Value *Op0BOOp1 = Op0BO->getOperand(1);
6444           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6445               match(Op0BOOp1, 
6446                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6447               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6448               V2 == Op1) {
6449             Instruction *YS = BinaryOperator::CreateShl(
6450                                                      Op0BO->getOperand(0), Op1,
6451                                                      Op0BO->getName());
6452             InsertNewInstBefore(YS, I); // (Y << C)
6453             Instruction *XM =
6454               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6455                                         V1->getName()+".mask");
6456             InsertNewInstBefore(XM, I); // X & (CC << C)
6457             
6458             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6459           }
6460         }
6461           
6462         // FALL THROUGH.
6463         case Instruction::Sub: {
6464           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6465           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6466               match(Op0BO->getOperand(0),
6467                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6468             Instruction *YS = BinaryOperator::CreateShl(
6469                                                      Op0BO->getOperand(1), Op1,
6470                                                      Op0BO->getName());
6471             InsertNewInstBefore(YS, I); // (Y << C)
6472             Instruction *X =
6473               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6474                                      Op0BO->getOperand(0)->getName());
6475             InsertNewInstBefore(X, I);  // (X + (Y << C))
6476             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6477             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6478                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6479           }
6480           
6481           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6482           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6483               match(Op0BO->getOperand(0),
6484                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6485                           m_ConstantInt(CC))) && V2 == Op1 &&
6486               cast<BinaryOperator>(Op0BO->getOperand(0))
6487                   ->getOperand(0)->hasOneUse()) {
6488             Instruction *YS = BinaryOperator::CreateShl(
6489                                                      Op0BO->getOperand(1), Op1,
6490                                                      Op0BO->getName());
6491             InsertNewInstBefore(YS, I); // (Y << C)
6492             Instruction *XM =
6493               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6494                                         V1->getName()+".mask");
6495             InsertNewInstBefore(XM, I); // X & (CC << C)
6496             
6497             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6498           }
6499           
6500           break;
6501         }
6502       }
6503       
6504       
6505       // If the operand is an bitwise operator with a constant RHS, and the
6506       // shift is the only use, we can pull it out of the shift.
6507       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6508         bool isValid = true;     // Valid only for And, Or, Xor
6509         bool highBitSet = false; // Transform if high bit of constant set?
6510         
6511         switch (Op0BO->getOpcode()) {
6512           default: isValid = false; break;   // Do not perform transform!
6513           case Instruction::Add:
6514             isValid = isLeftShift;
6515             break;
6516           case Instruction::Or:
6517           case Instruction::Xor:
6518             highBitSet = false;
6519             break;
6520           case Instruction::And:
6521             highBitSet = true;
6522             break;
6523         }
6524         
6525         // If this is a signed shift right, and the high bit is modified
6526         // by the logical operation, do not perform the transformation.
6527         // The highBitSet boolean indicates the value of the high bit of
6528         // the constant which would cause it to be modified for this
6529         // operation.
6530         //
6531         if (isValid && I.getOpcode() == Instruction::AShr)
6532           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6533         
6534         if (isValid) {
6535           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6536           
6537           Instruction *NewShift =
6538             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6539           InsertNewInstBefore(NewShift, I);
6540           NewShift->takeName(Op0BO);
6541           
6542           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6543                                         NewRHS);
6544         }
6545       }
6546     }
6547   }
6548   
6549   // Find out if this is a shift of a shift by a constant.
6550   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6551   if (ShiftOp && !ShiftOp->isShift())
6552     ShiftOp = 0;
6553   
6554   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6555     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6556     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6557     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6558     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6559     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6560     Value *X = ShiftOp->getOperand(0);
6561     
6562     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6563     if (AmtSum > TypeBits)
6564       AmtSum = TypeBits;
6565     
6566     const IntegerType *Ty = cast<IntegerType>(I.getType());
6567     
6568     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6569     if (I.getOpcode() == ShiftOp->getOpcode()) {
6570       return BinaryOperator::Create(I.getOpcode(), X,
6571                                     ConstantInt::get(Ty, AmtSum));
6572     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6573                I.getOpcode() == Instruction::AShr) {
6574       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6575       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6576     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6577                I.getOpcode() == Instruction::LShr) {
6578       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6579       Instruction *Shift =
6580         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6581       InsertNewInstBefore(Shift, I);
6582
6583       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6584       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6585     }
6586     
6587     // Okay, if we get here, one shift must be left, and the other shift must be
6588     // right.  See if the amounts are equal.
6589     if (ShiftAmt1 == ShiftAmt2) {
6590       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6591       if (I.getOpcode() == Instruction::Shl) {
6592         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6593         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6594       }
6595       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6596       if (I.getOpcode() == Instruction::LShr) {
6597         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6598         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6599       }
6600       // We can simplify ((X << C) >>s C) into a trunc + sext.
6601       // NOTE: we could do this for any C, but that would make 'unusual' integer
6602       // types.  For now, just stick to ones well-supported by the code
6603       // generators.
6604       const Type *SExtType = 0;
6605       switch (Ty->getBitWidth() - ShiftAmt1) {
6606       case 1  :
6607       case 8  :
6608       case 16 :
6609       case 32 :
6610       case 64 :
6611       case 128:
6612         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6613         break;
6614       default: break;
6615       }
6616       if (SExtType) {
6617         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6618         InsertNewInstBefore(NewTrunc, I);
6619         return new SExtInst(NewTrunc, Ty);
6620       }
6621       // Otherwise, we can't handle it yet.
6622     } else if (ShiftAmt1 < ShiftAmt2) {
6623       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6624       
6625       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6626       if (I.getOpcode() == Instruction::Shl) {
6627         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6628                ShiftOp->getOpcode() == Instruction::AShr);
6629         Instruction *Shift =
6630           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6631         InsertNewInstBefore(Shift, I);
6632         
6633         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6634         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6635       }
6636       
6637       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6638       if (I.getOpcode() == Instruction::LShr) {
6639         assert(ShiftOp->getOpcode() == Instruction::Shl);
6640         Instruction *Shift =
6641           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6642         InsertNewInstBefore(Shift, I);
6643         
6644         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6645         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6646       }
6647       
6648       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6649     } else {
6650       assert(ShiftAmt2 < ShiftAmt1);
6651       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6652
6653       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6654       if (I.getOpcode() == Instruction::Shl) {
6655         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6656                ShiftOp->getOpcode() == Instruction::AShr);
6657         Instruction *Shift =
6658           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6659                                  ConstantInt::get(Ty, ShiftDiff));
6660         InsertNewInstBefore(Shift, I);
6661         
6662         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6663         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6664       }
6665       
6666       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6667       if (I.getOpcode() == Instruction::LShr) {
6668         assert(ShiftOp->getOpcode() == Instruction::Shl);
6669         Instruction *Shift =
6670           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6671         InsertNewInstBefore(Shift, I);
6672         
6673         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6674         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6675       }
6676       
6677       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6678     }
6679   }
6680   return 0;
6681 }
6682
6683
6684 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6685 /// expression.  If so, decompose it, returning some value X, such that Val is
6686 /// X*Scale+Offset.
6687 ///
6688 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6689                                         int &Offset) {
6690   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6691   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6692     Offset = CI->getZExtValue();
6693     Scale  = 0;
6694     return ConstantInt::get(Type::Int32Ty, 0);
6695   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6696     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6697       if (I->getOpcode() == Instruction::Shl) {
6698         // This is a value scaled by '1 << the shift amt'.
6699         Scale = 1U << RHS->getZExtValue();
6700         Offset = 0;
6701         return I->getOperand(0);
6702       } else if (I->getOpcode() == Instruction::Mul) {
6703         // This value is scaled by 'RHS'.
6704         Scale = RHS->getZExtValue();
6705         Offset = 0;
6706         return I->getOperand(0);
6707       } else if (I->getOpcode() == Instruction::Add) {
6708         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6709         // where C1 is divisible by C2.
6710         unsigned SubScale;
6711         Value *SubVal = 
6712           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6713         Offset += RHS->getZExtValue();
6714         Scale = SubScale;
6715         return SubVal;
6716       }
6717     }
6718   }
6719
6720   // Otherwise, we can't look past this.
6721   Scale = 1;
6722   Offset = 0;
6723   return Val;
6724 }
6725
6726
6727 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6728 /// try to eliminate the cast by moving the type information into the alloc.
6729 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6730                                                    AllocationInst &AI) {
6731   const PointerType *PTy = cast<PointerType>(CI.getType());
6732   
6733   // Remove any uses of AI that are dead.
6734   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6735   
6736   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6737     Instruction *User = cast<Instruction>(*UI++);
6738     if (isInstructionTriviallyDead(User)) {
6739       while (UI != E && *UI == User)
6740         ++UI; // If this instruction uses AI more than once, don't break UI.
6741       
6742       ++NumDeadInst;
6743       DOUT << "IC: DCE: " << *User;
6744       EraseInstFromFunction(*User);
6745     }
6746   }
6747   
6748   // Get the type really allocated and the type casted to.
6749   const Type *AllocElTy = AI.getAllocatedType();
6750   const Type *CastElTy = PTy->getElementType();
6751   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6752
6753   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6754   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6755   if (CastElTyAlign < AllocElTyAlign) return 0;
6756
6757   // If the allocation has multiple uses, only promote it if we are strictly
6758   // increasing the alignment of the resultant allocation.  If we keep it the
6759   // same, we open the door to infinite loops of various kinds.
6760   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6761
6762   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6763   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6764   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6765
6766   // See if we can satisfy the modulus by pulling a scale out of the array
6767   // size argument.
6768   unsigned ArraySizeScale;
6769   int ArrayOffset;
6770   Value *NumElements = // See if the array size is a decomposable linear expr.
6771     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6772  
6773   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6774   // do the xform.
6775   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6776       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6777
6778   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6779   Value *Amt = 0;
6780   if (Scale == 1) {
6781     Amt = NumElements;
6782   } else {
6783     // If the allocation size is constant, form a constant mul expression
6784     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6785     if (isa<ConstantInt>(NumElements))
6786       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6787     // otherwise multiply the amount and the number of elements
6788     else if (Scale != 1) {
6789       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6790       Amt = InsertNewInstBefore(Tmp, AI);
6791     }
6792   }
6793   
6794   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6795     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6796     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6797     Amt = InsertNewInstBefore(Tmp, AI);
6798   }
6799   
6800   AllocationInst *New;
6801   if (isa<MallocInst>(AI))
6802     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6803   else
6804     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6805   InsertNewInstBefore(New, AI);
6806   New->takeName(&AI);
6807   
6808   // If the allocation has multiple uses, insert a cast and change all things
6809   // that used it to use the new cast.  This will also hack on CI, but it will
6810   // die soon.
6811   if (!AI.hasOneUse()) {
6812     AddUsesToWorkList(AI);
6813     // New is the allocation instruction, pointer typed. AI is the original
6814     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6815     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6816     InsertNewInstBefore(NewCast, AI);
6817     AI.replaceAllUsesWith(NewCast);
6818   }
6819   return ReplaceInstUsesWith(CI, New);
6820 }
6821
6822 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6823 /// and return it as type Ty without inserting any new casts and without
6824 /// changing the computed value.  This is used by code that tries to decide
6825 /// whether promoting or shrinking integer operations to wider or smaller types
6826 /// will allow us to eliminate a truncate or extend.
6827 ///
6828 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6829 /// extension operation if Ty is larger.
6830 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6831                                               unsigned CastOpc,
6832                                               int &NumCastsRemoved) {
6833   // We can always evaluate constants in another type.
6834   if (isa<ConstantInt>(V))
6835     return true;
6836   
6837   Instruction *I = dyn_cast<Instruction>(V);
6838   if (!I) return false;
6839   
6840   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6841   
6842   // If this is an extension or truncate, we can often eliminate it.
6843   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6844     // If this is a cast from the destination type, we can trivially eliminate
6845     // it, and this will remove a cast overall.
6846     if (I->getOperand(0)->getType() == Ty) {
6847       // If the first operand is itself a cast, and is eliminable, do not count
6848       // this as an eliminable cast.  We would prefer to eliminate those two
6849       // casts first.
6850       if (!isa<CastInst>(I->getOperand(0)))
6851         ++NumCastsRemoved;
6852       return true;
6853     }
6854   }
6855
6856   // We can't extend or shrink something that has multiple uses: doing so would
6857   // require duplicating the instruction in general, which isn't profitable.
6858   if (!I->hasOneUse()) return false;
6859
6860   switch (I->getOpcode()) {
6861   case Instruction::Add:
6862   case Instruction::Sub:
6863   case Instruction::And:
6864   case Instruction::Or:
6865   case Instruction::Xor:
6866     // These operators can all arbitrarily be extended or truncated.
6867     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6868                                       NumCastsRemoved) &&
6869            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6870                                       NumCastsRemoved);
6871
6872   case Instruction::Mul:
6873     // A multiply can be truncated by truncating its operands.
6874     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6875            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6876                                       NumCastsRemoved) &&
6877            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6878                                       NumCastsRemoved);
6879
6880   case Instruction::Shl:
6881     // If we are truncating the result of this SHL, and if it's a shift of a
6882     // constant amount, we can always perform a SHL in a smaller type.
6883     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6884       uint32_t BitWidth = Ty->getBitWidth();
6885       if (BitWidth < OrigTy->getBitWidth() && 
6886           CI->getLimitedValue(BitWidth) < BitWidth)
6887         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6888                                           NumCastsRemoved);
6889     }
6890     break;
6891   case Instruction::LShr:
6892     // If this is a truncate of a logical shr, we can truncate it to a smaller
6893     // lshr iff we know that the bits we would otherwise be shifting in are
6894     // already zeros.
6895     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6896       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6897       uint32_t BitWidth = Ty->getBitWidth();
6898       if (BitWidth < OrigBitWidth &&
6899           MaskedValueIsZero(I->getOperand(0),
6900             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6901           CI->getLimitedValue(BitWidth) < BitWidth) {
6902         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6903                                           NumCastsRemoved);
6904       }
6905     }
6906     break;
6907   case Instruction::ZExt:
6908   case Instruction::SExt:
6909   case Instruction::Trunc:
6910     // If this is the same kind of case as our original (e.g. zext+zext), we
6911     // can safely replace it.  Note that replacing it does not reduce the number
6912     // of casts in the input.
6913     if (I->getOpcode() == CastOpc)
6914       return true;
6915     
6916     break;
6917   default:
6918     // TODO: Can handle more cases here.
6919     break;
6920   }
6921   
6922   return false;
6923 }
6924
6925 /// EvaluateInDifferentType - Given an expression that 
6926 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6927 /// evaluate the expression.
6928 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6929                                              bool isSigned) {
6930   if (Constant *C = dyn_cast<Constant>(V))
6931     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6932
6933   // Otherwise, it must be an instruction.
6934   Instruction *I = cast<Instruction>(V);
6935   Instruction *Res = 0;
6936   switch (I->getOpcode()) {
6937   case Instruction::Add:
6938   case Instruction::Sub:
6939   case Instruction::Mul:
6940   case Instruction::And:
6941   case Instruction::Or:
6942   case Instruction::Xor:
6943   case Instruction::AShr:
6944   case Instruction::LShr:
6945   case Instruction::Shl: {
6946     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6947     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6948     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
6949                                  LHS, RHS, I->getName());
6950     break;
6951   }    
6952   case Instruction::Trunc:
6953   case Instruction::ZExt:
6954   case Instruction::SExt:
6955     // If the source type of the cast is the type we're trying for then we can
6956     // just return the source.  There's no need to insert it because it is not
6957     // new.
6958     if (I->getOperand(0)->getType() == Ty)
6959       return I->getOperand(0);
6960     
6961     // Otherwise, must be the same type of case, so just reinsert a new one.
6962     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6963                            Ty, I->getName());
6964     break;
6965   default: 
6966     // TODO: Can handle more cases here.
6967     assert(0 && "Unreachable!");
6968     break;
6969   }
6970   
6971   return InsertNewInstBefore(Res, *I);
6972 }
6973
6974 /// @brief Implement the transforms common to all CastInst visitors.
6975 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6976   Value *Src = CI.getOperand(0);
6977
6978   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6979   // eliminate it now.
6980   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6981     if (Instruction::CastOps opc = 
6982         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6983       // The first cast (CSrc) is eliminable so we need to fix up or replace
6984       // the second cast (CI). CSrc will then have a good chance of being dead.
6985       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
6986     }
6987   }
6988
6989   // If we are casting a select then fold the cast into the select
6990   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6991     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6992       return NV;
6993
6994   // If we are casting a PHI then fold the cast into the PHI
6995   if (isa<PHINode>(Src))
6996     if (Instruction *NV = FoldOpIntoPhi(CI))
6997       return NV;
6998   
6999   return 0;
7000 }
7001
7002 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7003 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7004   Value *Src = CI.getOperand(0);
7005   
7006   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7007     // If casting the result of a getelementptr instruction with no offset, turn
7008     // this into a cast of the original pointer!
7009     if (GEP->hasAllZeroIndices()) {
7010       // Changing the cast operand is usually not a good idea but it is safe
7011       // here because the pointer operand is being replaced with another 
7012       // pointer operand so the opcode doesn't need to change.
7013       AddToWorkList(GEP);
7014       CI.setOperand(0, GEP->getOperand(0));
7015       return &CI;
7016     }
7017     
7018     // If the GEP has a single use, and the base pointer is a bitcast, and the
7019     // GEP computes a constant offset, see if we can convert these three
7020     // instructions into fewer.  This typically happens with unions and other
7021     // non-type-safe code.
7022     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7023       if (GEP->hasAllConstantIndices()) {
7024         // We are guaranteed to get a constant from EmitGEPOffset.
7025         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7026         int64_t Offset = OffsetV->getSExtValue();
7027         
7028         // Get the base pointer input of the bitcast, and the type it points to.
7029         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7030         const Type *GEPIdxTy =
7031           cast<PointerType>(OrigBase->getType())->getElementType();
7032         if (GEPIdxTy->isSized()) {
7033           SmallVector<Value*, 8> NewIndices;
7034           
7035           // Start with the index over the outer type.  Note that the type size
7036           // might be zero (even if the offset isn't zero) if the indexed type
7037           // is something like [0 x {int, int}]
7038           const Type *IntPtrTy = TD->getIntPtrType();
7039           int64_t FirstIdx = 0;
7040           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7041             FirstIdx = Offset/TySize;
7042             Offset %= TySize;
7043           
7044             // Handle silly modulus not returning values values [0..TySize).
7045             if (Offset < 0) {
7046               --FirstIdx;
7047               Offset += TySize;
7048               assert(Offset >= 0);
7049             }
7050             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7051           }
7052           
7053           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7054
7055           // Index into the types.  If we fail, set OrigBase to null.
7056           while (Offset) {
7057             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7058               const StructLayout *SL = TD->getStructLayout(STy);
7059               if (Offset < (int64_t)SL->getSizeInBytes()) {
7060                 unsigned Elt = SL->getElementContainingOffset(Offset);
7061                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7062               
7063                 Offset -= SL->getElementOffset(Elt);
7064                 GEPIdxTy = STy->getElementType(Elt);
7065               } else {
7066                 // Otherwise, we can't index into this, bail out.
7067                 Offset = 0;
7068                 OrigBase = 0;
7069               }
7070             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7071               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7072               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7073                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7074                 Offset %= EltSize;
7075               } else {
7076                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7077               }
7078               GEPIdxTy = STy->getElementType();
7079             } else {
7080               // Otherwise, we can't index into this, bail out.
7081               Offset = 0;
7082               OrigBase = 0;
7083             }
7084           }
7085           if (OrigBase) {
7086             // If we were able to index down into an element, create the GEP
7087             // and bitcast the result.  This eliminates one bitcast, potentially
7088             // two.
7089             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7090                                                           NewIndices.begin(),
7091                                                           NewIndices.end(), "");
7092             InsertNewInstBefore(NGEP, CI);
7093             NGEP->takeName(GEP);
7094             
7095             if (isa<BitCastInst>(CI))
7096               return new BitCastInst(NGEP, CI.getType());
7097             assert(isa<PtrToIntInst>(CI));
7098             return new PtrToIntInst(NGEP, CI.getType());
7099           }
7100         }
7101       }      
7102     }
7103   }
7104     
7105   return commonCastTransforms(CI);
7106 }
7107
7108
7109
7110 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7111 /// integer types. This function implements the common transforms for all those
7112 /// cases.
7113 /// @brief Implement the transforms common to CastInst with integer operands
7114 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7115   if (Instruction *Result = commonCastTransforms(CI))
7116     return Result;
7117
7118   Value *Src = CI.getOperand(0);
7119   const Type *SrcTy = Src->getType();
7120   const Type *DestTy = CI.getType();
7121   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7122   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7123
7124   // See if we can simplify any instructions used by the LHS whose sole 
7125   // purpose is to compute bits we don't care about.
7126   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7127   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7128                            KnownZero, KnownOne))
7129     return &CI;
7130
7131   // If the source isn't an instruction or has more than one use then we
7132   // can't do anything more. 
7133   Instruction *SrcI = dyn_cast<Instruction>(Src);
7134   if (!SrcI || !Src->hasOneUse())
7135     return 0;
7136
7137   // Attempt to propagate the cast into the instruction for int->int casts.
7138   int NumCastsRemoved = 0;
7139   if (!isa<BitCastInst>(CI) &&
7140       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7141                                  CI.getOpcode(), NumCastsRemoved)) {
7142     // If this cast is a truncate, evaluting in a different type always
7143     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7144     // we need to do an AND to maintain the clear top-part of the computation,
7145     // so we require that the input have eliminated at least one cast.  If this
7146     // is a sign extension, we insert two new casts (to do the extension) so we
7147     // require that two casts have been eliminated.
7148     bool DoXForm;
7149     switch (CI.getOpcode()) {
7150     default:
7151       // All the others use floating point so we shouldn't actually 
7152       // get here because of the check above.
7153       assert(0 && "Unknown cast type");
7154     case Instruction::Trunc:
7155       DoXForm = true;
7156       break;
7157     case Instruction::ZExt:
7158       DoXForm = NumCastsRemoved >= 1;
7159       break;
7160     case Instruction::SExt:
7161       DoXForm = NumCastsRemoved >= 2;
7162       break;
7163     }
7164     
7165     if (DoXForm) {
7166       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7167                                            CI.getOpcode() == Instruction::SExt);
7168       assert(Res->getType() == DestTy);
7169       switch (CI.getOpcode()) {
7170       default: assert(0 && "Unknown cast type!");
7171       case Instruction::Trunc:
7172       case Instruction::BitCast:
7173         // Just replace this cast with the result.
7174         return ReplaceInstUsesWith(CI, Res);
7175       case Instruction::ZExt: {
7176         // We need to emit an AND to clear the high bits.
7177         assert(SrcBitSize < DestBitSize && "Not a zext?");
7178         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7179                                                             SrcBitSize));
7180         return BinaryOperator::CreateAnd(Res, C);
7181       }
7182       case Instruction::SExt:
7183         // We need to emit a cast to truncate, then a cast to sext.
7184         return CastInst::Create(Instruction::SExt,
7185             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7186                              CI), DestTy);
7187       }
7188     }
7189   }
7190   
7191   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7192   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7193
7194   switch (SrcI->getOpcode()) {
7195   case Instruction::Add:
7196   case Instruction::Mul:
7197   case Instruction::And:
7198   case Instruction::Or:
7199   case Instruction::Xor:
7200     // If we are discarding information, rewrite.
7201     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7202       // Don't insert two casts if they cannot be eliminated.  We allow 
7203       // two casts to be inserted if the sizes are the same.  This could 
7204       // only be converting signedness, which is a noop.
7205       if (DestBitSize == SrcBitSize || 
7206           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7207           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7208         Instruction::CastOps opcode = CI.getOpcode();
7209         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7210         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7211         return BinaryOperator::Create(
7212             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7213       }
7214     }
7215
7216     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7217     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7218         SrcI->getOpcode() == Instruction::Xor &&
7219         Op1 == ConstantInt::getTrue() &&
7220         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7221       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7222       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7223     }
7224     break;
7225   case Instruction::SDiv:
7226   case Instruction::UDiv:
7227   case Instruction::SRem:
7228   case Instruction::URem:
7229     // If we are just changing the sign, rewrite.
7230     if (DestBitSize == SrcBitSize) {
7231       // Don't insert two casts if they cannot be eliminated.  We allow 
7232       // two casts to be inserted if the sizes are the same.  This could 
7233       // only be converting signedness, which is a noop.
7234       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7235           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7236         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7237                                               Op0, DestTy, SrcI);
7238         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7239                                               Op1, DestTy, SrcI);
7240         return BinaryOperator::Create(
7241           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7242       }
7243     }
7244     break;
7245
7246   case Instruction::Shl:
7247     // Allow changing the sign of the source operand.  Do not allow 
7248     // changing the size of the shift, UNLESS the shift amount is a 
7249     // constant.  We must not change variable sized shifts to a smaller 
7250     // size, because it is undefined to shift more bits out than exist 
7251     // in the value.
7252     if (DestBitSize == SrcBitSize ||
7253         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7254       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7255           Instruction::BitCast : Instruction::Trunc);
7256       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7257       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7258       return BinaryOperator::CreateShl(Op0c, Op1c);
7259     }
7260     break;
7261   case Instruction::AShr:
7262     // If this is a signed shr, and if all bits shifted in are about to be
7263     // truncated off, turn it into an unsigned shr to allow greater
7264     // simplifications.
7265     if (DestBitSize < SrcBitSize &&
7266         isa<ConstantInt>(Op1)) {
7267       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7268       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7269         // Insert the new logical shift right.
7270         return BinaryOperator::CreateLShr(Op0, Op1);
7271       }
7272     }
7273     break;
7274   }
7275   return 0;
7276 }
7277
7278 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7279   if (Instruction *Result = commonIntCastTransforms(CI))
7280     return Result;
7281   
7282   Value *Src = CI.getOperand(0);
7283   const Type *Ty = CI.getType();
7284   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7285   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7286   
7287   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7288     switch (SrcI->getOpcode()) {
7289     default: break;
7290     case Instruction::LShr:
7291       // We can shrink lshr to something smaller if we know the bits shifted in
7292       // are already zeros.
7293       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7294         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7295         
7296         // Get a mask for the bits shifting in.
7297         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7298         Value* SrcIOp0 = SrcI->getOperand(0);
7299         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7300           if (ShAmt >= DestBitWidth)        // All zeros.
7301             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7302
7303           // Okay, we can shrink this.  Truncate the input, then return a new
7304           // shift.
7305           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7306           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7307                                        Ty, CI);
7308           return BinaryOperator::CreateLShr(V1, V2);
7309         }
7310       } else {     // This is a variable shr.
7311         
7312         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7313         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7314         // loop-invariant and CSE'd.
7315         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7316           Value *One = ConstantInt::get(SrcI->getType(), 1);
7317
7318           Value *V = InsertNewInstBefore(
7319               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7320                                      "tmp"), CI);
7321           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7322                                                             SrcI->getOperand(0),
7323                                                             "tmp"), CI);
7324           Value *Zero = Constant::getNullValue(V->getType());
7325           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7326         }
7327       }
7328       break;
7329     }
7330   }
7331   
7332   return 0;
7333 }
7334
7335 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7336 /// in order to eliminate the icmp.
7337 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7338                                              bool DoXform) {
7339   // If we are just checking for a icmp eq of a single bit and zext'ing it
7340   // to an integer, then shift the bit to the appropriate place and then
7341   // cast to integer to avoid the comparison.
7342   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7343     const APInt &Op1CV = Op1C->getValue();
7344       
7345     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7346     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7347     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7348         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7349       if (!DoXform) return ICI;
7350
7351       Value *In = ICI->getOperand(0);
7352       Value *Sh = ConstantInt::get(In->getType(),
7353                                    In->getType()->getPrimitiveSizeInBits()-1);
7354       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7355                                                         In->getName()+".lobit"),
7356                                CI);
7357       if (In->getType() != CI.getType())
7358         In = CastInst::CreateIntegerCast(In, CI.getType(),
7359                                          false/*ZExt*/, "tmp", &CI);
7360
7361       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7362         Constant *One = ConstantInt::get(In->getType(), 1);
7363         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7364                                                          In->getName()+".not"),
7365                                  CI);
7366       }
7367
7368       return ReplaceInstUsesWith(CI, In);
7369     }
7370       
7371       
7372       
7373     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7374     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7375     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7376     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7377     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7378     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7379     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7380     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7381     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7382         // This only works for EQ and NE
7383         ICI->isEquality()) {
7384       // If Op1C some other power of two, convert:
7385       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7386       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7387       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7388       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7389         
7390       APInt KnownZeroMask(~KnownZero);
7391       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7392         if (!DoXform) return ICI;
7393
7394         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7395         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7396           // (X&4) == 2 --> false
7397           // (X&4) != 2 --> true
7398           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7399           Res = ConstantExpr::getZExt(Res, CI.getType());
7400           return ReplaceInstUsesWith(CI, Res);
7401         }
7402           
7403         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7404         Value *In = ICI->getOperand(0);
7405         if (ShiftAmt) {
7406           // Perform a logical shr by shiftamt.
7407           // Insert the shift to put the result in the low bit.
7408           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7409                                   ConstantInt::get(In->getType(), ShiftAmt),
7410                                                    In->getName()+".lobit"), CI);
7411         }
7412           
7413         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7414           Constant *One = ConstantInt::get(In->getType(), 1);
7415           In = BinaryOperator::CreateXor(In, One, "tmp");
7416           InsertNewInstBefore(cast<Instruction>(In), CI);
7417         }
7418           
7419         if (CI.getType() == In->getType())
7420           return ReplaceInstUsesWith(CI, In);
7421         else
7422           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7423       }
7424     }
7425   }
7426
7427   return 0;
7428 }
7429
7430 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7431   // If one of the common conversion will work ..
7432   if (Instruction *Result = commonIntCastTransforms(CI))
7433     return Result;
7434
7435   Value *Src = CI.getOperand(0);
7436
7437   // If this is a cast of a cast
7438   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7439     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7440     // types and if the sizes are just right we can convert this into a logical
7441     // 'and' which will be much cheaper than the pair of casts.
7442     if (isa<TruncInst>(CSrc)) {
7443       // Get the sizes of the types involved
7444       Value *A = CSrc->getOperand(0);
7445       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7446       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7447       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7448       // If we're actually extending zero bits and the trunc is a no-op
7449       if (MidSize < DstSize && SrcSize == DstSize) {
7450         // Replace both of the casts with an And of the type mask.
7451         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7452         Constant *AndConst = ConstantInt::get(AndValue);
7453         Instruction *And = 
7454           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7455         // Unfortunately, if the type changed, we need to cast it back.
7456         if (And->getType() != CI.getType()) {
7457           And->setName(CSrc->getName()+".mask");
7458           InsertNewInstBefore(And, CI);
7459           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7460         }
7461         return And;
7462       }
7463     }
7464   }
7465
7466   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7467     return transformZExtICmp(ICI, CI);
7468
7469   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7470   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7471     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7472     // of the (zext icmp) will be transformed.
7473     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7474     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7475     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7476         (transformZExtICmp(LHS, CI, false) ||
7477          transformZExtICmp(RHS, CI, false))) {
7478       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7479       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7480       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7481     }
7482   }
7483
7484   return 0;
7485 }
7486
7487 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7488   if (Instruction *I = commonIntCastTransforms(CI))
7489     return I;
7490   
7491   Value *Src = CI.getOperand(0);
7492   
7493   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7494   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7495   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7496     // If we are just checking for a icmp eq of a single bit and zext'ing it
7497     // to an integer, then shift the bit to the appropriate place and then
7498     // cast to integer to avoid the comparison.
7499     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7500       const APInt &Op1CV = Op1C->getValue();
7501       
7502       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7503       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7504       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7505           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7506         Value *In = ICI->getOperand(0);
7507         Value *Sh = ConstantInt::get(In->getType(),
7508                                      In->getType()->getPrimitiveSizeInBits()-1);
7509         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7510                                                         In->getName()+".lobit"),
7511                                  CI);
7512         if (In->getType() != CI.getType())
7513           In = CastInst::CreateIntegerCast(In, CI.getType(),
7514                                            true/*SExt*/, "tmp", &CI);
7515         
7516         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7517           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7518                                      In->getName()+".not"), CI);
7519         
7520         return ReplaceInstUsesWith(CI, In);
7521       }
7522     }
7523   }
7524
7525   // See if the value being truncated is already sign extended.  If so, just
7526   // eliminate the trunc/sext pair.
7527   if (getOpcode(Src) == Instruction::Trunc) {
7528     Value *Op = cast<User>(Src)->getOperand(0);
7529     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7530     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7531     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7532     unsigned NumSignBits = ComputeNumSignBits(Op);
7533
7534     if (OpBits == DestBits) {
7535       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7536       // bits, it is already ready.
7537       if (NumSignBits > DestBits-MidBits)
7538         return ReplaceInstUsesWith(CI, Op);
7539     } else if (OpBits < DestBits) {
7540       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7541       // bits, just sext from i32.
7542       if (NumSignBits > OpBits-MidBits)
7543         return new SExtInst(Op, CI.getType(), "tmp");
7544     } else {
7545       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7546       // bits, just truncate to i32.
7547       if (NumSignBits > OpBits-MidBits)
7548         return new TruncInst(Op, CI.getType(), "tmp");
7549     }
7550   }
7551       
7552   return 0;
7553 }
7554
7555 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7556 /// in the specified FP type without changing its value.
7557 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7558   APFloat F = CFP->getValueAPF();
7559   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7560     return ConstantFP::get(F);
7561   return 0;
7562 }
7563
7564 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7565 /// through it until we get the source value.
7566 static Value *LookThroughFPExtensions(Value *V) {
7567   if (Instruction *I = dyn_cast<Instruction>(V))
7568     if (I->getOpcode() == Instruction::FPExt)
7569       return LookThroughFPExtensions(I->getOperand(0));
7570   
7571   // If this value is a constant, return the constant in the smallest FP type
7572   // that can accurately represent it.  This allows us to turn
7573   // (float)((double)X+2.0) into x+2.0f.
7574   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7575     if (CFP->getType() == Type::PPC_FP128Ty)
7576       return V;  // No constant folding of this.
7577     // See if the value can be truncated to float and then reextended.
7578     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7579       return V;
7580     if (CFP->getType() == Type::DoubleTy)
7581       return V;  // Won't shrink.
7582     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7583       return V;
7584     // Don't try to shrink to various long double types.
7585   }
7586   
7587   return V;
7588 }
7589
7590 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7591   if (Instruction *I = commonCastTransforms(CI))
7592     return I;
7593   
7594   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7595   // smaller than the destination type, we can eliminate the truncate by doing
7596   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7597   // many builtins (sqrt, etc).
7598   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7599   if (OpI && OpI->hasOneUse()) {
7600     switch (OpI->getOpcode()) {
7601     default: break;
7602     case Instruction::Add:
7603     case Instruction::Sub:
7604     case Instruction::Mul:
7605     case Instruction::FDiv:
7606     case Instruction::FRem:
7607       const Type *SrcTy = OpI->getType();
7608       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7609       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7610       if (LHSTrunc->getType() != SrcTy && 
7611           RHSTrunc->getType() != SrcTy) {
7612         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7613         // If the source types were both smaller than the destination type of
7614         // the cast, do this xform.
7615         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7616             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7617           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7618                                       CI.getType(), CI);
7619           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7620                                       CI.getType(), CI);
7621           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7622         }
7623       }
7624       break;  
7625     }
7626   }
7627   return 0;
7628 }
7629
7630 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7631   return commonCastTransforms(CI);
7632 }
7633
7634 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7635   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7636   // mantissa to accurately represent all values of X.  For example, do not
7637   // do this with i64->float->i64.
7638   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7639     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7640         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7641                     SrcI->getType()->getFPMantissaWidth())
7642       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7643
7644   return commonCastTransforms(FI);
7645 }
7646
7647 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7648   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7649   // mantissa to accurately represent all values of X.  For example, do not
7650   // do this with i64->float->i64.
7651   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7652     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7653         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7654                     SrcI->getType()->getFPMantissaWidth())
7655       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7656   
7657   return commonCastTransforms(FI);
7658 }
7659
7660 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7661   return commonCastTransforms(CI);
7662 }
7663
7664 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7665   return commonCastTransforms(CI);
7666 }
7667
7668 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7669   return commonPointerCastTransforms(CI);
7670 }
7671
7672 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7673   if (Instruction *I = commonCastTransforms(CI))
7674     return I;
7675   
7676   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7677   if (!DestPointee->isSized()) return 0;
7678
7679   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7680   ConstantInt *Cst;
7681   Value *X;
7682   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7683                                     m_ConstantInt(Cst)))) {
7684     // If the source and destination operands have the same type, see if this
7685     // is a single-index GEP.
7686     if (X->getType() == CI.getType()) {
7687       // Get the size of the pointee type.
7688       uint64_t Size = TD->getABITypeSize(DestPointee);
7689
7690       // Convert the constant to intptr type.
7691       APInt Offset = Cst->getValue();
7692       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7693
7694       // If Offset is evenly divisible by Size, we can do this xform.
7695       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7696         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7697         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7698       }
7699     }
7700     // TODO: Could handle other cases, e.g. where add is indexing into field of
7701     // struct etc.
7702   } else if (CI.getOperand(0)->hasOneUse() &&
7703              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7704     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7705     // "inttoptr+GEP" instead of "add+intptr".
7706     
7707     // Get the size of the pointee type.
7708     uint64_t Size = TD->getABITypeSize(DestPointee);
7709     
7710     // Convert the constant to intptr type.
7711     APInt Offset = Cst->getValue();
7712     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7713     
7714     // If Offset is evenly divisible by Size, we can do this xform.
7715     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7716       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7717       
7718       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7719                                                             "tmp"), CI);
7720       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7721     }
7722   }
7723   return 0;
7724 }
7725
7726 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7727   // If the operands are integer typed then apply the integer transforms,
7728   // otherwise just apply the common ones.
7729   Value *Src = CI.getOperand(0);
7730   const Type *SrcTy = Src->getType();
7731   const Type *DestTy = CI.getType();
7732
7733   if (SrcTy->isInteger() && DestTy->isInteger()) {
7734     if (Instruction *Result = commonIntCastTransforms(CI))
7735       return Result;
7736   } else if (isa<PointerType>(SrcTy)) {
7737     if (Instruction *I = commonPointerCastTransforms(CI))
7738       return I;
7739   } else {
7740     if (Instruction *Result = commonCastTransforms(CI))
7741       return Result;
7742   }
7743
7744
7745   // Get rid of casts from one type to the same type. These are useless and can
7746   // be replaced by the operand.
7747   if (DestTy == Src->getType())
7748     return ReplaceInstUsesWith(CI, Src);
7749
7750   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7751     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7752     const Type *DstElTy = DstPTy->getElementType();
7753     const Type *SrcElTy = SrcPTy->getElementType();
7754     
7755     // If the address spaces don't match, don't eliminate the bitcast, which is
7756     // required for changing types.
7757     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7758       return 0;
7759     
7760     // If we are casting a malloc or alloca to a pointer to a type of the same
7761     // size, rewrite the allocation instruction to allocate the "right" type.
7762     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7763       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7764         return V;
7765     
7766     // If the source and destination are pointers, and this cast is equivalent
7767     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7768     // This can enhance SROA and other transforms that want type-safe pointers.
7769     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7770     unsigned NumZeros = 0;
7771     while (SrcElTy != DstElTy && 
7772            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7773            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7774       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7775       ++NumZeros;
7776     }
7777
7778     // If we found a path from the src to dest, create the getelementptr now.
7779     if (SrcElTy == DstElTy) {
7780       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7781       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7782                                        ((Instruction*) NULL));
7783     }
7784   }
7785
7786   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7787     if (SVI->hasOneUse()) {
7788       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7789       // a bitconvert to a vector with the same # elts.
7790       if (isa<VectorType>(DestTy) && 
7791           cast<VectorType>(DestTy)->getNumElements() == 
7792                 SVI->getType()->getNumElements()) {
7793         CastInst *Tmp;
7794         // If either of the operands is a cast from CI.getType(), then
7795         // evaluating the shuffle in the casted destination's type will allow
7796         // us to eliminate at least one cast.
7797         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7798              Tmp->getOperand(0)->getType() == DestTy) ||
7799             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7800              Tmp->getOperand(0)->getType() == DestTy)) {
7801           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7802                                                SVI->getOperand(0), DestTy, &CI);
7803           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7804                                                SVI->getOperand(1), DestTy, &CI);
7805           // Return a new shuffle vector.  Use the same element ID's, as we
7806           // know the vector types match #elts.
7807           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7808         }
7809       }
7810     }
7811   }
7812   return 0;
7813 }
7814
7815 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7816 ///   %C = or %A, %B
7817 ///   %D = select %cond, %C, %A
7818 /// into:
7819 ///   %C = select %cond, %B, 0
7820 ///   %D = or %A, %C
7821 ///
7822 /// Assuming that the specified instruction is an operand to the select, return
7823 /// a bitmask indicating which operands of this instruction are foldable if they
7824 /// equal the other incoming value of the select.
7825 ///
7826 static unsigned GetSelectFoldableOperands(Instruction *I) {
7827   switch (I->getOpcode()) {
7828   case Instruction::Add:
7829   case Instruction::Mul:
7830   case Instruction::And:
7831   case Instruction::Or:
7832   case Instruction::Xor:
7833     return 3;              // Can fold through either operand.
7834   case Instruction::Sub:   // Can only fold on the amount subtracted.
7835   case Instruction::Shl:   // Can only fold on the shift amount.
7836   case Instruction::LShr:
7837   case Instruction::AShr:
7838     return 1;
7839   default:
7840     return 0;              // Cannot fold
7841   }
7842 }
7843
7844 /// GetSelectFoldableConstant - For the same transformation as the previous
7845 /// function, return the identity constant that goes into the select.
7846 static Constant *GetSelectFoldableConstant(Instruction *I) {
7847   switch (I->getOpcode()) {
7848   default: assert(0 && "This cannot happen!"); abort();
7849   case Instruction::Add:
7850   case Instruction::Sub:
7851   case Instruction::Or:
7852   case Instruction::Xor:
7853   case Instruction::Shl:
7854   case Instruction::LShr:
7855   case Instruction::AShr:
7856     return Constant::getNullValue(I->getType());
7857   case Instruction::And:
7858     return Constant::getAllOnesValue(I->getType());
7859   case Instruction::Mul:
7860     return ConstantInt::get(I->getType(), 1);
7861   }
7862 }
7863
7864 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7865 /// have the same opcode and only one use each.  Try to simplify this.
7866 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7867                                           Instruction *FI) {
7868   if (TI->getNumOperands() == 1) {
7869     // If this is a non-volatile load or a cast from the same type,
7870     // merge.
7871     if (TI->isCast()) {
7872       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7873         return 0;
7874     } else {
7875       return 0;  // unknown unary op.
7876     }
7877
7878     // Fold this by inserting a select from the input values.
7879     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7880                                            FI->getOperand(0), SI.getName()+".v");
7881     InsertNewInstBefore(NewSI, SI);
7882     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7883                             TI->getType());
7884   }
7885
7886   // Only handle binary operators here.
7887   if (!isa<BinaryOperator>(TI))
7888     return 0;
7889
7890   // Figure out if the operations have any operands in common.
7891   Value *MatchOp, *OtherOpT, *OtherOpF;
7892   bool MatchIsOpZero;
7893   if (TI->getOperand(0) == FI->getOperand(0)) {
7894     MatchOp  = TI->getOperand(0);
7895     OtherOpT = TI->getOperand(1);
7896     OtherOpF = FI->getOperand(1);
7897     MatchIsOpZero = true;
7898   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7899     MatchOp  = TI->getOperand(1);
7900     OtherOpT = TI->getOperand(0);
7901     OtherOpF = FI->getOperand(0);
7902     MatchIsOpZero = false;
7903   } else if (!TI->isCommutative()) {
7904     return 0;
7905   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7906     MatchOp  = TI->getOperand(0);
7907     OtherOpT = TI->getOperand(1);
7908     OtherOpF = FI->getOperand(0);
7909     MatchIsOpZero = true;
7910   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7911     MatchOp  = TI->getOperand(1);
7912     OtherOpT = TI->getOperand(0);
7913     OtherOpF = FI->getOperand(1);
7914     MatchIsOpZero = true;
7915   } else {
7916     return 0;
7917   }
7918
7919   // If we reach here, they do have operations in common.
7920   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7921                                          OtherOpF, SI.getName()+".v");
7922   InsertNewInstBefore(NewSI, SI);
7923
7924   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7925     if (MatchIsOpZero)
7926       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
7927     else
7928       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
7929   }
7930   assert(0 && "Shouldn't get here");
7931   return 0;
7932 }
7933
7934 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7935   Value *CondVal = SI.getCondition();
7936   Value *TrueVal = SI.getTrueValue();
7937   Value *FalseVal = SI.getFalseValue();
7938
7939   // select true, X, Y  -> X
7940   // select false, X, Y -> Y
7941   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7942     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7943
7944   // select C, X, X -> X
7945   if (TrueVal == FalseVal)
7946     return ReplaceInstUsesWith(SI, TrueVal);
7947
7948   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7949     return ReplaceInstUsesWith(SI, FalseVal);
7950   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7951     return ReplaceInstUsesWith(SI, TrueVal);
7952   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7953     if (isa<Constant>(TrueVal))
7954       return ReplaceInstUsesWith(SI, TrueVal);
7955     else
7956       return ReplaceInstUsesWith(SI, FalseVal);
7957   }
7958
7959   if (SI.getType() == Type::Int1Ty) {
7960     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7961       if (C->getZExtValue()) {
7962         // Change: A = select B, true, C --> A = or B, C
7963         return BinaryOperator::CreateOr(CondVal, FalseVal);
7964       } else {
7965         // Change: A = select B, false, C --> A = and !B, C
7966         Value *NotCond =
7967           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
7968                                              "not."+CondVal->getName()), SI);
7969         return BinaryOperator::CreateAnd(NotCond, FalseVal);
7970       }
7971     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7972       if (C->getZExtValue() == false) {
7973         // Change: A = select B, C, false --> A = and B, C
7974         return BinaryOperator::CreateAnd(CondVal, TrueVal);
7975       } else {
7976         // Change: A = select B, C, true --> A = or !B, C
7977         Value *NotCond =
7978           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
7979                                              "not."+CondVal->getName()), SI);
7980         return BinaryOperator::CreateOr(NotCond, TrueVal);
7981       }
7982     }
7983     
7984     // select a, b, a  -> a&b
7985     // select a, a, b  -> a|b
7986     if (CondVal == TrueVal)
7987       return BinaryOperator::CreateOr(CondVal, FalseVal);
7988     else if (CondVal == FalseVal)
7989       return BinaryOperator::CreateAnd(CondVal, TrueVal);
7990   }
7991
7992   // Selecting between two integer constants?
7993   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7994     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7995       // select C, 1, 0 -> zext C to int
7996       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7997         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
7998       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7999         // select C, 0, 1 -> zext !C to int
8000         Value *NotCond =
8001           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8002                                                "not."+CondVal->getName()), SI);
8003         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8004       }
8005       
8006       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8007
8008       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8009
8010         // (x <s 0) ? -1 : 0 -> ashr x, 31
8011         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8012           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8013             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8014               // The comparison constant and the result are not neccessarily the
8015               // same width. Make an all-ones value by inserting a AShr.
8016               Value *X = IC->getOperand(0);
8017               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8018               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8019               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8020                                                         ShAmt, "ones");
8021               InsertNewInstBefore(SRA, SI);
8022               
8023               // Finally, convert to the type of the select RHS.  We figure out
8024               // if this requires a SExt, Trunc or BitCast based on the sizes.
8025               Instruction::CastOps opc = Instruction::BitCast;
8026               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8027               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8028               if (SRASize < SISize)
8029                 opc = Instruction::SExt;
8030               else if (SRASize > SISize)
8031                 opc = Instruction::Trunc;
8032               return CastInst::Create(opc, SRA, SI.getType());
8033             }
8034           }
8035
8036
8037         // If one of the constants is zero (we know they can't both be) and we
8038         // have an icmp instruction with zero, and we have an 'and' with the
8039         // non-constant value, eliminate this whole mess.  This corresponds to
8040         // cases like this: ((X & 27) ? 27 : 0)
8041         if (TrueValC->isZero() || FalseValC->isZero())
8042           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8043               cast<Constant>(IC->getOperand(1))->isNullValue())
8044             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8045               if (ICA->getOpcode() == Instruction::And &&
8046                   isa<ConstantInt>(ICA->getOperand(1)) &&
8047                   (ICA->getOperand(1) == TrueValC ||
8048                    ICA->getOperand(1) == FalseValC) &&
8049                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8050                 // Okay, now we know that everything is set up, we just don't
8051                 // know whether we have a icmp_ne or icmp_eq and whether the 
8052                 // true or false val is the zero.
8053                 bool ShouldNotVal = !TrueValC->isZero();
8054                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8055                 Value *V = ICA;
8056                 if (ShouldNotVal)
8057                   V = InsertNewInstBefore(BinaryOperator::Create(
8058                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8059                 return ReplaceInstUsesWith(SI, V);
8060               }
8061       }
8062     }
8063
8064   // See if we are selecting two values based on a comparison of the two values.
8065   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8066     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8067       // Transform (X == Y) ? X : Y  -> Y
8068       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8069         // This is not safe in general for floating point:  
8070         // consider X== -0, Y== +0.
8071         // It becomes safe if either operand is a nonzero constant.
8072         ConstantFP *CFPt, *CFPf;
8073         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8074               !CFPt->getValueAPF().isZero()) ||
8075             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8076              !CFPf->getValueAPF().isZero()))
8077         return ReplaceInstUsesWith(SI, FalseVal);
8078       }
8079       // Transform (X != Y) ? X : Y  -> X
8080       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8081         return ReplaceInstUsesWith(SI, TrueVal);
8082       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8083
8084     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8085       // Transform (X == Y) ? Y : X  -> X
8086       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8087         // This is not safe in general for floating point:  
8088         // consider X== -0, Y== +0.
8089         // It becomes safe if either operand is a nonzero constant.
8090         ConstantFP *CFPt, *CFPf;
8091         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8092               !CFPt->getValueAPF().isZero()) ||
8093             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8094              !CFPf->getValueAPF().isZero()))
8095           return ReplaceInstUsesWith(SI, FalseVal);
8096       }
8097       // Transform (X != Y) ? Y : X  -> Y
8098       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8099         return ReplaceInstUsesWith(SI, TrueVal);
8100       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8101     }
8102   }
8103
8104   // See if we are selecting two values based on a comparison of the two values.
8105   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8106     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8107       // Transform (X == Y) ? X : Y  -> Y
8108       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8109         return ReplaceInstUsesWith(SI, FalseVal);
8110       // Transform (X != Y) ? X : Y  -> X
8111       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8112         return ReplaceInstUsesWith(SI, TrueVal);
8113       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8114
8115     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8116       // Transform (X == Y) ? Y : X  -> X
8117       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8118         return ReplaceInstUsesWith(SI, FalseVal);
8119       // Transform (X != Y) ? Y : X  -> Y
8120       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8121         return ReplaceInstUsesWith(SI, TrueVal);
8122       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8123     }
8124   }
8125
8126   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8127     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8128       if (TI->hasOneUse() && FI->hasOneUse()) {
8129         Instruction *AddOp = 0, *SubOp = 0;
8130
8131         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8132         if (TI->getOpcode() == FI->getOpcode())
8133           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8134             return IV;
8135
8136         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8137         // even legal for FP.
8138         if (TI->getOpcode() == Instruction::Sub &&
8139             FI->getOpcode() == Instruction::Add) {
8140           AddOp = FI; SubOp = TI;
8141         } else if (FI->getOpcode() == Instruction::Sub &&
8142                    TI->getOpcode() == Instruction::Add) {
8143           AddOp = TI; SubOp = FI;
8144         }
8145
8146         if (AddOp) {
8147           Value *OtherAddOp = 0;
8148           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8149             OtherAddOp = AddOp->getOperand(1);
8150           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8151             OtherAddOp = AddOp->getOperand(0);
8152           }
8153
8154           if (OtherAddOp) {
8155             // So at this point we know we have (Y -> OtherAddOp):
8156             //        select C, (add X, Y), (sub X, Z)
8157             Value *NegVal;  // Compute -Z
8158             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8159               NegVal = ConstantExpr::getNeg(C);
8160             } else {
8161               NegVal = InsertNewInstBefore(
8162                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8163             }
8164
8165             Value *NewTrueOp = OtherAddOp;
8166             Value *NewFalseOp = NegVal;
8167             if (AddOp != TI)
8168               std::swap(NewTrueOp, NewFalseOp);
8169             Instruction *NewSel =
8170               SelectInst::Create(CondVal, NewTrueOp,
8171                                  NewFalseOp, SI.getName() + ".p");
8172
8173             NewSel = InsertNewInstBefore(NewSel, SI);
8174             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8175           }
8176         }
8177       }
8178
8179   // See if we can fold the select into one of our operands.
8180   if (SI.getType()->isInteger()) {
8181     // See the comment above GetSelectFoldableOperands for a description of the
8182     // transformation we are doing here.
8183     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8184       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8185           !isa<Constant>(FalseVal))
8186         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8187           unsigned OpToFold = 0;
8188           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8189             OpToFold = 1;
8190           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8191             OpToFold = 2;
8192           }
8193
8194           if (OpToFold) {
8195             Constant *C = GetSelectFoldableConstant(TVI);
8196             Instruction *NewSel =
8197               SelectInst::Create(SI.getCondition(),
8198                                  TVI->getOperand(2-OpToFold), C);
8199             InsertNewInstBefore(NewSel, SI);
8200             NewSel->takeName(TVI);
8201             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8202               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8203             else {
8204               assert(0 && "Unknown instruction!!");
8205             }
8206           }
8207         }
8208
8209     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8210       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8211           !isa<Constant>(TrueVal))
8212         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8213           unsigned OpToFold = 0;
8214           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8215             OpToFold = 1;
8216           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8217             OpToFold = 2;
8218           }
8219
8220           if (OpToFold) {
8221             Constant *C = GetSelectFoldableConstant(FVI);
8222             Instruction *NewSel =
8223               SelectInst::Create(SI.getCondition(), C,
8224                                  FVI->getOperand(2-OpToFold));
8225             InsertNewInstBefore(NewSel, SI);
8226             NewSel->takeName(FVI);
8227             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8228               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8229             else
8230               assert(0 && "Unknown instruction!!");
8231           }
8232         }
8233   }
8234
8235   if (BinaryOperator::isNot(CondVal)) {
8236     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8237     SI.setOperand(1, FalseVal);
8238     SI.setOperand(2, TrueVal);
8239     return &SI;
8240   }
8241
8242   return 0;
8243 }
8244
8245 /// EnforceKnownAlignment - If the specified pointer points to an object that
8246 /// we control, modify the object's alignment to PrefAlign. This isn't
8247 /// often possible though. If alignment is important, a more reliable approach
8248 /// is to simply align all global variables and allocation instructions to
8249 /// their preferred alignment from the beginning.
8250 ///
8251 static unsigned EnforceKnownAlignment(Value *V,
8252                                       unsigned Align, unsigned PrefAlign) {
8253
8254   User *U = dyn_cast<User>(V);
8255   if (!U) return Align;
8256
8257   switch (getOpcode(U)) {
8258   default: break;
8259   case Instruction::BitCast:
8260     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8261   case Instruction::GetElementPtr: {
8262     // If all indexes are zero, it is just the alignment of the base pointer.
8263     bool AllZeroOperands = true;
8264     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8265       if (!isa<Constant>(U->getOperand(i)) ||
8266           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8267         AllZeroOperands = false;
8268         break;
8269       }
8270
8271     if (AllZeroOperands) {
8272       // Treat this like a bitcast.
8273       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8274     }
8275     break;
8276   }
8277   }
8278
8279   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8280     // If there is a large requested alignment and we can, bump up the alignment
8281     // of the global.
8282     if (!GV->isDeclaration()) {
8283       GV->setAlignment(PrefAlign);
8284       Align = PrefAlign;
8285     }
8286   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8287     // If there is a requested alignment and if this is an alloca, round up.  We
8288     // don't do this for malloc, because some systems can't respect the request.
8289     if (isa<AllocaInst>(AI)) {
8290       AI->setAlignment(PrefAlign);
8291       Align = PrefAlign;
8292     }
8293   }
8294
8295   return Align;
8296 }
8297
8298 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8299 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8300 /// and it is more than the alignment of the ultimate object, see if we can
8301 /// increase the alignment of the ultimate object, making this check succeed.
8302 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8303                                                   unsigned PrefAlign) {
8304   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8305                       sizeof(PrefAlign) * CHAR_BIT;
8306   APInt Mask = APInt::getAllOnesValue(BitWidth);
8307   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8308   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8309   unsigned TrailZ = KnownZero.countTrailingOnes();
8310   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8311
8312   if (PrefAlign > Align)
8313     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8314   
8315     // We don't need to make any adjustment.
8316   return Align;
8317 }
8318
8319 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8320   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8321   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8322   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8323   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8324
8325   if (CopyAlign < MinAlign) {
8326     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8327     return MI;
8328   }
8329   
8330   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8331   // load/store.
8332   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8333   if (MemOpLength == 0) return 0;
8334   
8335   // Source and destination pointer types are always "i8*" for intrinsic.  See
8336   // if the size is something we can handle with a single primitive load/store.
8337   // A single load+store correctly handles overlapping memory in the memmove
8338   // case.
8339   unsigned Size = MemOpLength->getZExtValue();
8340   if (Size == 0) return MI;  // Delete this mem transfer.
8341   
8342   if (Size > 8 || (Size&(Size-1)))
8343     return 0;  // If not 1/2/4/8 bytes, exit.
8344   
8345   // Use an integer load+store unless we can find something better.
8346   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8347   
8348   // Memcpy forces the use of i8* for the source and destination.  That means
8349   // that if you're using memcpy to move one double around, you'll get a cast
8350   // from double* to i8*.  We'd much rather use a double load+store rather than
8351   // an i64 load+store, here because this improves the odds that the source or
8352   // dest address will be promotable.  See if we can find a better type than the
8353   // integer datatype.
8354   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8355     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8356     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8357       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8358       // down through these levels if so.
8359       while (!SrcETy->isSingleValueType()) {
8360         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8361           if (STy->getNumElements() == 1)
8362             SrcETy = STy->getElementType(0);
8363           else
8364             break;
8365         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8366           if (ATy->getNumElements() == 1)
8367             SrcETy = ATy->getElementType();
8368           else
8369             break;
8370         } else
8371           break;
8372       }
8373       
8374       if (SrcETy->isSingleValueType())
8375         NewPtrTy = PointerType::getUnqual(SrcETy);
8376     }
8377   }
8378   
8379   
8380   // If the memcpy/memmove provides better alignment info than we can
8381   // infer, use it.
8382   SrcAlign = std::max(SrcAlign, CopyAlign);
8383   DstAlign = std::max(DstAlign, CopyAlign);
8384   
8385   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8386   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8387   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8388   InsertNewInstBefore(L, *MI);
8389   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8390
8391   // Set the size of the copy to 0, it will be deleted on the next iteration.
8392   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8393   return MI;
8394 }
8395
8396 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8397   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8398   if (MI->getAlignment()->getZExtValue() < Alignment) {
8399     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8400     return MI;
8401   }
8402   
8403   // Extract the length and alignment and fill if they are constant.
8404   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8405   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8406   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8407     return 0;
8408   uint64_t Len = LenC->getZExtValue();
8409   Alignment = MI->getAlignment()->getZExtValue();
8410   
8411   // If the length is zero, this is a no-op
8412   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8413   
8414   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8415   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8416     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8417     
8418     Value *Dest = MI->getDest();
8419     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8420
8421     // Alignment 0 is identity for alignment 1 for memset, but not store.
8422     if (Alignment == 0) Alignment = 1;
8423     
8424     // Extract the fill value and store.
8425     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8426     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8427                                       Alignment), *MI);
8428     
8429     // Set the size of the copy to 0, it will be deleted on the next iteration.
8430     MI->setLength(Constant::getNullValue(LenC->getType()));
8431     return MI;
8432   }
8433
8434   return 0;
8435 }
8436
8437
8438 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8439 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8440 /// the heavy lifting.
8441 ///
8442 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8443   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8444   if (!II) return visitCallSite(&CI);
8445   
8446   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8447   // visitCallSite.
8448   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8449     bool Changed = false;
8450
8451     // memmove/cpy/set of zero bytes is a noop.
8452     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8453       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8454
8455       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8456         if (CI->getZExtValue() == 1) {
8457           // Replace the instruction with just byte operations.  We would
8458           // transform other cases to loads/stores, but we don't know if
8459           // alignment is sufficient.
8460         }
8461     }
8462
8463     // If we have a memmove and the source operation is a constant global,
8464     // then the source and dest pointers can't alias, so we can change this
8465     // into a call to memcpy.
8466     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8467       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8468         if (GVSrc->isConstant()) {
8469           Module *M = CI.getParent()->getParent()->getParent();
8470           Intrinsic::ID MemCpyID;
8471           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8472             MemCpyID = Intrinsic::memcpy_i32;
8473           else
8474             MemCpyID = Intrinsic::memcpy_i64;
8475           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8476           Changed = true;
8477         }
8478
8479       // memmove(x,x,size) -> noop.
8480       if (MMI->getSource() == MMI->getDest())
8481         return EraseInstFromFunction(CI);
8482     }
8483
8484     // If we can determine a pointer alignment that is bigger than currently
8485     // set, update the alignment.
8486     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8487       if (Instruction *I = SimplifyMemTransfer(MI))
8488         return I;
8489     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8490       if (Instruction *I = SimplifyMemSet(MSI))
8491         return I;
8492     }
8493           
8494     if (Changed) return II;
8495   } else {
8496     switch (II->getIntrinsicID()) {
8497     default: break;
8498     case Intrinsic::ppc_altivec_lvx:
8499     case Intrinsic::ppc_altivec_lvxl:
8500     case Intrinsic::x86_sse_loadu_ps:
8501     case Intrinsic::x86_sse2_loadu_pd:
8502     case Intrinsic::x86_sse2_loadu_dq:
8503       // Turn PPC lvx     -> load if the pointer is known aligned.
8504       // Turn X86 loadups -> load if the pointer is known aligned.
8505       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8506         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8507                                          PointerType::getUnqual(II->getType()),
8508                                          CI);
8509         return new LoadInst(Ptr);
8510       }
8511       break;
8512     case Intrinsic::ppc_altivec_stvx:
8513     case Intrinsic::ppc_altivec_stvxl:
8514       // Turn stvx -> store if the pointer is known aligned.
8515       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8516         const Type *OpPtrTy = 
8517           PointerType::getUnqual(II->getOperand(1)->getType());
8518         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8519         return new StoreInst(II->getOperand(1), Ptr);
8520       }
8521       break;
8522     case Intrinsic::x86_sse_storeu_ps:
8523     case Intrinsic::x86_sse2_storeu_pd:
8524     case Intrinsic::x86_sse2_storeu_dq:
8525     case Intrinsic::x86_sse2_storel_dq:
8526       // Turn X86 storeu -> store if the pointer is known aligned.
8527       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8528         const Type *OpPtrTy = 
8529           PointerType::getUnqual(II->getOperand(2)->getType());
8530         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8531         return new StoreInst(II->getOperand(2), Ptr);
8532       }
8533       break;
8534       
8535     case Intrinsic::x86_sse_cvttss2si: {
8536       // These intrinsics only demands the 0th element of its input vector.  If
8537       // we can simplify the input based on that, do so now.
8538       uint64_t UndefElts;
8539       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8540                                                 UndefElts)) {
8541         II->setOperand(1, V);
8542         return II;
8543       }
8544       break;
8545     }
8546       
8547     case Intrinsic::ppc_altivec_vperm:
8548       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8549       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8550         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8551         
8552         // Check that all of the elements are integer constants or undefs.
8553         bool AllEltsOk = true;
8554         for (unsigned i = 0; i != 16; ++i) {
8555           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8556               !isa<UndefValue>(Mask->getOperand(i))) {
8557             AllEltsOk = false;
8558             break;
8559           }
8560         }
8561         
8562         if (AllEltsOk) {
8563           // Cast the input vectors to byte vectors.
8564           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8565           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8566           Value *Result = UndefValue::get(Op0->getType());
8567           
8568           // Only extract each element once.
8569           Value *ExtractedElts[32];
8570           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8571           
8572           for (unsigned i = 0; i != 16; ++i) {
8573             if (isa<UndefValue>(Mask->getOperand(i)))
8574               continue;
8575             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8576             Idx &= 31;  // Match the hardware behavior.
8577             
8578             if (ExtractedElts[Idx] == 0) {
8579               Instruction *Elt = 
8580                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8581               InsertNewInstBefore(Elt, CI);
8582               ExtractedElts[Idx] = Elt;
8583             }
8584           
8585             // Insert this value into the result vector.
8586             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8587                                                i, "tmp");
8588             InsertNewInstBefore(cast<Instruction>(Result), CI);
8589           }
8590           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8591         }
8592       }
8593       break;
8594
8595     case Intrinsic::stackrestore: {
8596       // If the save is right next to the restore, remove the restore.  This can
8597       // happen when variable allocas are DCE'd.
8598       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8599         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8600           BasicBlock::iterator BI = SS;
8601           if (&*++BI == II)
8602             return EraseInstFromFunction(CI);
8603         }
8604       }
8605       
8606       // Scan down this block to see if there is another stack restore in the
8607       // same block without an intervening call/alloca.
8608       BasicBlock::iterator BI = II;
8609       TerminatorInst *TI = II->getParent()->getTerminator();
8610       bool CannotRemove = false;
8611       for (++BI; &*BI != TI; ++BI) {
8612         if (isa<AllocaInst>(BI)) {
8613           CannotRemove = true;
8614           break;
8615         }
8616         if (isa<CallInst>(BI)) {
8617           if (!isa<IntrinsicInst>(BI)) {
8618             CannotRemove = true;
8619             break;
8620           }
8621           // If there is a stackrestore below this one, remove this one.
8622           return EraseInstFromFunction(CI);
8623         }
8624       }
8625       
8626       // If the stack restore is in a return/unwind block and if there are no
8627       // allocas or calls between the restore and the return, nuke the restore.
8628       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8629         return EraseInstFromFunction(CI);
8630       break;
8631     }
8632     }
8633   }
8634
8635   return visitCallSite(II);
8636 }
8637
8638 // InvokeInst simplification
8639 //
8640 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8641   return visitCallSite(&II);
8642 }
8643
8644 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8645 /// passed through the varargs area, we can eliminate the use of the cast.
8646 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8647                                          const CastInst * const CI,
8648                                          const TargetData * const TD,
8649                                          const int ix) {
8650   if (!CI->isLosslessCast())
8651     return false;
8652
8653   // The size of ByVal arguments is derived from the type, so we
8654   // can't change to a type with a different size.  If the size were
8655   // passed explicitly we could avoid this check.
8656   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8657     return true;
8658
8659   const Type* SrcTy = 
8660             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8661   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8662   if (!SrcTy->isSized() || !DstTy->isSized())
8663     return false;
8664   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8665     return false;
8666   return true;
8667 }
8668
8669 // visitCallSite - Improvements for call and invoke instructions.
8670 //
8671 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8672   bool Changed = false;
8673
8674   // If the callee is a constexpr cast of a function, attempt to move the cast
8675   // to the arguments of the call/invoke.
8676   if (transformConstExprCastCall(CS)) return 0;
8677
8678   Value *Callee = CS.getCalledValue();
8679
8680   if (Function *CalleeF = dyn_cast<Function>(Callee))
8681     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8682       Instruction *OldCall = CS.getInstruction();
8683       // If the call and callee calling conventions don't match, this call must
8684       // be unreachable, as the call is undefined.
8685       new StoreInst(ConstantInt::getTrue(),
8686                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8687                                     OldCall);
8688       if (!OldCall->use_empty())
8689         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8690       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8691         return EraseInstFromFunction(*OldCall);
8692       return 0;
8693     }
8694
8695   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8696     // This instruction is not reachable, just remove it.  We insert a store to
8697     // undef so that we know that this code is not reachable, despite the fact
8698     // that we can't modify the CFG here.
8699     new StoreInst(ConstantInt::getTrue(),
8700                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8701                   CS.getInstruction());
8702
8703     if (!CS.getInstruction()->use_empty())
8704       CS.getInstruction()->
8705         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8706
8707     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8708       // Don't break the CFG, insert a dummy cond branch.
8709       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8710                          ConstantInt::getTrue(), II);
8711     }
8712     return EraseInstFromFunction(*CS.getInstruction());
8713   }
8714
8715   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8716     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8717       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8718         return transformCallThroughTrampoline(CS);
8719
8720   const PointerType *PTy = cast<PointerType>(Callee->getType());
8721   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8722   if (FTy->isVarArg()) {
8723     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8724     // See if we can optimize any arguments passed through the varargs area of
8725     // the call.
8726     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8727            E = CS.arg_end(); I != E; ++I, ++ix) {
8728       CastInst *CI = dyn_cast<CastInst>(*I);
8729       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8730         *I = CI->getOperand(0);
8731         Changed = true;
8732       }
8733     }
8734   }
8735
8736   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8737     // Inline asm calls cannot throw - mark them 'nounwind'.
8738     CS.setDoesNotThrow();
8739     Changed = true;
8740   }
8741
8742   return Changed ? CS.getInstruction() : 0;
8743 }
8744
8745 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8746 // attempt to move the cast to the arguments of the call/invoke.
8747 //
8748 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8749   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8750   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8751   if (CE->getOpcode() != Instruction::BitCast || 
8752       !isa<Function>(CE->getOperand(0)))
8753     return false;
8754   Function *Callee = cast<Function>(CE->getOperand(0));
8755   Instruction *Caller = CS.getInstruction();
8756   const PAListPtr &CallerPAL = CS.getParamAttrs();
8757
8758   // Okay, this is a cast from a function to a different type.  Unless doing so
8759   // would cause a type conversion of one of our arguments, change this call to
8760   // be a direct call with arguments casted to the appropriate types.
8761   //
8762   const FunctionType *FT = Callee->getFunctionType();
8763   const Type *OldRetTy = Caller->getType();
8764   const Type *NewRetTy = FT->getReturnType();
8765
8766   if (isa<StructType>(NewRetTy))
8767     return false; // TODO: Handle multiple return values.
8768
8769   // Check to see if we are changing the return type...
8770   if (OldRetTy != NewRetTy) {
8771     if (Callee->isDeclaration() &&
8772         // Conversion is ok if changing from one pointer type to another or from
8773         // a pointer to an integer of the same size.
8774         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8775           isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
8776       return false;   // Cannot transform this return value.
8777
8778     if (!Caller->use_empty() &&
8779         // void -> non-void is handled specially
8780         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8781       return false;   // Cannot transform this return value.
8782
8783     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8784       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8785       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8786         return false;   // Attribute not compatible with transformed value.
8787     }
8788
8789     // If the callsite is an invoke instruction, and the return value is used by
8790     // a PHI node in a successor, we cannot change the return type of the call
8791     // because there is no place to put the cast instruction (without breaking
8792     // the critical edge).  Bail out in this case.
8793     if (!Caller->use_empty())
8794       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8795         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8796              UI != E; ++UI)
8797           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8798             if (PN->getParent() == II->getNormalDest() ||
8799                 PN->getParent() == II->getUnwindDest())
8800               return false;
8801   }
8802
8803   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8804   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8805
8806   CallSite::arg_iterator AI = CS.arg_begin();
8807   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8808     const Type *ParamTy = FT->getParamType(i);
8809     const Type *ActTy = (*AI)->getType();
8810
8811     if (!CastInst::isCastable(ActTy, ParamTy))
8812       return false;   // Cannot transform this parameter value.
8813
8814     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8815       return false;   // Attribute not compatible with transformed value.
8816
8817     // Converting from one pointer type to another or between a pointer and an
8818     // integer of the same size is safe even if we do not have a body.
8819     bool isConvertible = ActTy == ParamTy ||
8820       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8821        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8822     if (Callee->isDeclaration() && !isConvertible) return false;
8823   }
8824
8825   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8826       Callee->isDeclaration())
8827     return false;   // Do not delete arguments unless we have a function body.
8828
8829   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8830       !CallerPAL.isEmpty())
8831     // In this case we have more arguments than the new function type, but we
8832     // won't be dropping them.  Check that these extra arguments have attributes
8833     // that are compatible with being a vararg call argument.
8834     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8835       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8836         break;
8837       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8838       if (PAttrs & ParamAttr::VarArgsIncompatible)
8839         return false;
8840     }
8841
8842   // Okay, we decided that this is a safe thing to do: go ahead and start
8843   // inserting cast instructions as necessary...
8844   std::vector<Value*> Args;
8845   Args.reserve(NumActualArgs);
8846   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8847   attrVec.reserve(NumCommonArgs);
8848
8849   // Get any return attributes.
8850   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8851
8852   // If the return value is not being used, the type may not be compatible
8853   // with the existing attributes.  Wipe out any problematic attributes.
8854   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8855
8856   // Add the new return attributes.
8857   if (RAttrs)
8858     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8859
8860   AI = CS.arg_begin();
8861   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8862     const Type *ParamTy = FT->getParamType(i);
8863     if ((*AI)->getType() == ParamTy) {
8864       Args.push_back(*AI);
8865     } else {
8866       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8867           false, ParamTy, false);
8868       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8869       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8870     }
8871
8872     // Add any parameter attributes.
8873     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8874       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8875   }
8876
8877   // If the function takes more arguments than the call was taking, add them
8878   // now...
8879   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8880     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8881
8882   // If we are removing arguments to the function, emit an obnoxious warning...
8883   if (FT->getNumParams() < NumActualArgs) {
8884     if (!FT->isVarArg()) {
8885       cerr << "WARNING: While resolving call to function '"
8886            << Callee->getName() << "' arguments were dropped!\n";
8887     } else {
8888       // Add all of the arguments in their promoted form to the arg list...
8889       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8890         const Type *PTy = getPromotedType((*AI)->getType());
8891         if (PTy != (*AI)->getType()) {
8892           // Must promote to pass through va_arg area!
8893           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8894                                                                 PTy, false);
8895           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
8896           InsertNewInstBefore(Cast, *Caller);
8897           Args.push_back(Cast);
8898         } else {
8899           Args.push_back(*AI);
8900         }
8901
8902         // Add any parameter attributes.
8903         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8904           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8905       }
8906     }
8907   }
8908
8909   if (NewRetTy == Type::VoidTy)
8910     Caller->setName("");   // Void type should not have a name.
8911
8912   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8913
8914   Instruction *NC;
8915   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8916     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8917                             Args.begin(), Args.end(),
8918                             Caller->getName(), Caller);
8919     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8920     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8921   } else {
8922     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8923                           Caller->getName(), Caller);
8924     CallInst *CI = cast<CallInst>(Caller);
8925     if (CI->isTailCall())
8926       cast<CallInst>(NC)->setTailCall();
8927     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8928     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8929   }
8930
8931   // Insert a cast of the return type as necessary.
8932   Value *NV = NC;
8933   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8934     if (NV->getType() != Type::VoidTy) {
8935       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8936                                                             OldRetTy, false);
8937       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
8938
8939       // If this is an invoke instruction, we should insert it after the first
8940       // non-phi, instruction in the normal successor block.
8941       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8942         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
8943         InsertNewInstBefore(NC, *I);
8944       } else {
8945         // Otherwise, it's a call, just insert cast right after the call instr
8946         InsertNewInstBefore(NC, *Caller);
8947       }
8948       AddUsersToWorkList(*Caller);
8949     } else {
8950       NV = UndefValue::get(Caller->getType());
8951     }
8952   }
8953
8954   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8955     Caller->replaceAllUsesWith(NV);
8956   Caller->eraseFromParent();
8957   RemoveFromWorkList(Caller);
8958   return true;
8959 }
8960
8961 // transformCallThroughTrampoline - Turn a call to a function created by the
8962 // init_trampoline intrinsic into a direct call to the underlying function.
8963 //
8964 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8965   Value *Callee = CS.getCalledValue();
8966   const PointerType *PTy = cast<PointerType>(Callee->getType());
8967   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8968   const PAListPtr &Attrs = CS.getParamAttrs();
8969
8970   // If the call already has the 'nest' attribute somewhere then give up -
8971   // otherwise 'nest' would occur twice after splicing in the chain.
8972   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
8973     return 0;
8974
8975   IntrinsicInst *Tramp =
8976     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8977
8978   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
8979   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8980   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8981
8982   const PAListPtr &NestAttrs = NestF->getParamAttrs();
8983   if (!NestAttrs.isEmpty()) {
8984     unsigned NestIdx = 1;
8985     const Type *NestTy = 0;
8986     ParameterAttributes NestAttr = ParamAttr::None;
8987
8988     // Look for a parameter marked with the 'nest' attribute.
8989     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8990          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8991       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
8992         // Record the parameter type and any other attributes.
8993         NestTy = *I;
8994         NestAttr = NestAttrs.getParamAttrs(NestIdx);
8995         break;
8996       }
8997
8998     if (NestTy) {
8999       Instruction *Caller = CS.getInstruction();
9000       std::vector<Value*> NewArgs;
9001       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9002
9003       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9004       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9005
9006       // Insert the nest argument into the call argument list, which may
9007       // mean appending it.  Likewise for attributes.
9008
9009       // Add any function result attributes.
9010       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9011         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9012
9013       {
9014         unsigned Idx = 1;
9015         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9016         do {
9017           if (Idx == NestIdx) {
9018             // Add the chain argument and attributes.
9019             Value *NestVal = Tramp->getOperand(3);
9020             if (NestVal->getType() != NestTy)
9021               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9022             NewArgs.push_back(NestVal);
9023             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9024           }
9025
9026           if (I == E)
9027             break;
9028
9029           // Add the original argument and attributes.
9030           NewArgs.push_back(*I);
9031           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9032             NewAttrs.push_back
9033               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9034
9035           ++Idx, ++I;
9036         } while (1);
9037       }
9038
9039       // The trampoline may have been bitcast to a bogus type (FTy).
9040       // Handle this by synthesizing a new function type, equal to FTy
9041       // with the chain parameter inserted.
9042
9043       std::vector<const Type*> NewTypes;
9044       NewTypes.reserve(FTy->getNumParams()+1);
9045
9046       // Insert the chain's type into the list of parameter types, which may
9047       // mean appending it.
9048       {
9049         unsigned Idx = 1;
9050         FunctionType::param_iterator I = FTy->param_begin(),
9051           E = FTy->param_end();
9052
9053         do {
9054           if (Idx == NestIdx)
9055             // Add the chain's type.
9056             NewTypes.push_back(NestTy);
9057
9058           if (I == E)
9059             break;
9060
9061           // Add the original type.
9062           NewTypes.push_back(*I);
9063
9064           ++Idx, ++I;
9065         } while (1);
9066       }
9067
9068       // Replace the trampoline call with a direct call.  Let the generic
9069       // code sort out any function type mismatches.
9070       FunctionType *NewFTy =
9071         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9072       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9073         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9074       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9075
9076       Instruction *NewCaller;
9077       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9078         NewCaller = InvokeInst::Create(NewCallee,
9079                                        II->getNormalDest(), II->getUnwindDest(),
9080                                        NewArgs.begin(), NewArgs.end(),
9081                                        Caller->getName(), Caller);
9082         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9083         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9084       } else {
9085         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9086                                      Caller->getName(), Caller);
9087         if (cast<CallInst>(Caller)->isTailCall())
9088           cast<CallInst>(NewCaller)->setTailCall();
9089         cast<CallInst>(NewCaller)->
9090           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9091         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9092       }
9093       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9094         Caller->replaceAllUsesWith(NewCaller);
9095       Caller->eraseFromParent();
9096       RemoveFromWorkList(Caller);
9097       return 0;
9098     }
9099   }
9100
9101   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9102   // parameter, there is no need to adjust the argument list.  Let the generic
9103   // code sort out any function type mismatches.
9104   Constant *NewCallee =
9105     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9106   CS.setCalledFunction(NewCallee);
9107   return CS.getInstruction();
9108 }
9109
9110 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9111 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9112 /// and a single binop.
9113 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9114   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9115   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9116          isa<CmpInst>(FirstInst));
9117   unsigned Opc = FirstInst->getOpcode();
9118   Value *LHSVal = FirstInst->getOperand(0);
9119   Value *RHSVal = FirstInst->getOperand(1);
9120     
9121   const Type *LHSType = LHSVal->getType();
9122   const Type *RHSType = RHSVal->getType();
9123   
9124   // Scan to see if all operands are the same opcode, all have one use, and all
9125   // kill their operands (i.e. the operands have one use).
9126   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9127     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9128     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9129         // Verify type of the LHS matches so we don't fold cmp's of different
9130         // types or GEP's with different index types.
9131         I->getOperand(0)->getType() != LHSType ||
9132         I->getOperand(1)->getType() != RHSType)
9133       return 0;
9134
9135     // If they are CmpInst instructions, check their predicates
9136     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9137       if (cast<CmpInst>(I)->getPredicate() !=
9138           cast<CmpInst>(FirstInst)->getPredicate())
9139         return 0;
9140     
9141     // Keep track of which operand needs a phi node.
9142     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9143     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9144   }
9145   
9146   // Otherwise, this is safe to transform, determine if it is profitable.
9147
9148   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9149   // Indexes are often folded into load/store instructions, so we don't want to
9150   // hide them behind a phi.
9151   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9152     return 0;
9153   
9154   Value *InLHS = FirstInst->getOperand(0);
9155   Value *InRHS = FirstInst->getOperand(1);
9156   PHINode *NewLHS = 0, *NewRHS = 0;
9157   if (LHSVal == 0) {
9158     NewLHS = PHINode::Create(LHSType,
9159                              FirstInst->getOperand(0)->getName() + ".pn");
9160     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9161     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9162     InsertNewInstBefore(NewLHS, PN);
9163     LHSVal = NewLHS;
9164   }
9165   
9166   if (RHSVal == 0) {
9167     NewRHS = PHINode::Create(RHSType,
9168                              FirstInst->getOperand(1)->getName() + ".pn");
9169     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9170     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9171     InsertNewInstBefore(NewRHS, PN);
9172     RHSVal = NewRHS;
9173   }
9174   
9175   // Add all operands to the new PHIs.
9176   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9177     if (NewLHS) {
9178       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9179       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9180     }
9181     if (NewRHS) {
9182       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9183       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9184     }
9185   }
9186     
9187   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9188     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9189   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9190     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9191                            RHSVal);
9192   else {
9193     assert(isa<GetElementPtrInst>(FirstInst));
9194     return GetElementPtrInst::Create(LHSVal, RHSVal);
9195   }
9196 }
9197
9198 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9199 /// of the block that defines it.  This means that it must be obvious the value
9200 /// of the load is not changed from the point of the load to the end of the
9201 /// block it is in.
9202 ///
9203 /// Finally, it is safe, but not profitable, to sink a load targetting a
9204 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9205 /// to a register.
9206 static bool isSafeToSinkLoad(LoadInst *L) {
9207   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9208   
9209   for (++BBI; BBI != E; ++BBI)
9210     if (BBI->mayWriteToMemory())
9211       return false;
9212   
9213   // Check for non-address taken alloca.  If not address-taken already, it isn't
9214   // profitable to do this xform.
9215   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9216     bool isAddressTaken = false;
9217     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9218          UI != E; ++UI) {
9219       if (isa<LoadInst>(UI)) continue;
9220       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9221         // If storing TO the alloca, then the address isn't taken.
9222         if (SI->getOperand(1) == AI) continue;
9223       }
9224       isAddressTaken = true;
9225       break;
9226     }
9227     
9228     if (!isAddressTaken)
9229       return false;
9230   }
9231   
9232   return true;
9233 }
9234
9235
9236 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9237 // operator and they all are only used by the PHI, PHI together their
9238 // inputs, and do the operation once, to the result of the PHI.
9239 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9240   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9241
9242   // Scan the instruction, looking for input operations that can be folded away.
9243   // If all input operands to the phi are the same instruction (e.g. a cast from
9244   // the same type or "+42") we can pull the operation through the PHI, reducing
9245   // code size and simplifying code.
9246   Constant *ConstantOp = 0;
9247   const Type *CastSrcTy = 0;
9248   bool isVolatile = false;
9249   if (isa<CastInst>(FirstInst)) {
9250     CastSrcTy = FirstInst->getOperand(0)->getType();
9251   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9252     // Can fold binop, compare or shift here if the RHS is a constant, 
9253     // otherwise call FoldPHIArgBinOpIntoPHI.
9254     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9255     if (ConstantOp == 0)
9256       return FoldPHIArgBinOpIntoPHI(PN);
9257   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9258     isVolatile = LI->isVolatile();
9259     // We can't sink the load if the loaded value could be modified between the
9260     // load and the PHI.
9261     if (LI->getParent() != PN.getIncomingBlock(0) ||
9262         !isSafeToSinkLoad(LI))
9263       return 0;
9264   } else if (isa<GetElementPtrInst>(FirstInst)) {
9265     if (FirstInst->getNumOperands() == 2)
9266       return FoldPHIArgBinOpIntoPHI(PN);
9267     // Can't handle general GEPs yet.
9268     return 0;
9269   } else {
9270     return 0;  // Cannot fold this operation.
9271   }
9272
9273   // Check to see if all arguments are the same operation.
9274   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9275     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9276     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9277     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9278       return 0;
9279     if (CastSrcTy) {
9280       if (I->getOperand(0)->getType() != CastSrcTy)
9281         return 0;  // Cast operation must match.
9282     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9283       // We can't sink the load if the loaded value could be modified between 
9284       // the load and the PHI.
9285       if (LI->isVolatile() != isVolatile ||
9286           LI->getParent() != PN.getIncomingBlock(i) ||
9287           !isSafeToSinkLoad(LI))
9288         return 0;
9289       
9290       // If the PHI is volatile and its block has multiple successors, sinking
9291       // it would remove a load of the volatile value from the path through the
9292       // other successor.
9293       if (isVolatile &&
9294           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9295         return 0;
9296
9297       
9298     } else if (I->getOperand(1) != ConstantOp) {
9299       return 0;
9300     }
9301   }
9302
9303   // Okay, they are all the same operation.  Create a new PHI node of the
9304   // correct type, and PHI together all of the LHS's of the instructions.
9305   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9306                                    PN.getName()+".in");
9307   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9308
9309   Value *InVal = FirstInst->getOperand(0);
9310   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9311
9312   // Add all operands to the new PHI.
9313   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9314     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9315     if (NewInVal != InVal)
9316       InVal = 0;
9317     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9318   }
9319
9320   Value *PhiVal;
9321   if (InVal) {
9322     // The new PHI unions all of the same values together.  This is really
9323     // common, so we handle it intelligently here for compile-time speed.
9324     PhiVal = InVal;
9325     delete NewPN;
9326   } else {
9327     InsertNewInstBefore(NewPN, PN);
9328     PhiVal = NewPN;
9329   }
9330
9331   // Insert and return the new operation.
9332   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9333     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9334   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9335     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9336   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9337     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9338                            PhiVal, ConstantOp);
9339   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9340   
9341   // If this was a volatile load that we are merging, make sure to loop through
9342   // and mark all the input loads as non-volatile.  If we don't do this, we will
9343   // insert a new volatile load and the old ones will not be deletable.
9344   if (isVolatile)
9345     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9346       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9347   
9348   return new LoadInst(PhiVal, "", isVolatile);
9349 }
9350
9351 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9352 /// that is dead.
9353 static bool DeadPHICycle(PHINode *PN,
9354                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9355   if (PN->use_empty()) return true;
9356   if (!PN->hasOneUse()) return false;
9357
9358   // Remember this node, and if we find the cycle, return.
9359   if (!PotentiallyDeadPHIs.insert(PN))
9360     return true;
9361   
9362   // Don't scan crazily complex things.
9363   if (PotentiallyDeadPHIs.size() == 16)
9364     return false;
9365
9366   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9367     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9368
9369   return false;
9370 }
9371
9372 /// PHIsEqualValue - Return true if this phi node is always equal to
9373 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9374 ///   z = some value; x = phi (y, z); y = phi (x, z)
9375 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9376                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9377   // See if we already saw this PHI node.
9378   if (!ValueEqualPHIs.insert(PN))
9379     return true;
9380   
9381   // Don't scan crazily complex things.
9382   if (ValueEqualPHIs.size() == 16)
9383     return false;
9384  
9385   // Scan the operands to see if they are either phi nodes or are equal to
9386   // the value.
9387   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9388     Value *Op = PN->getIncomingValue(i);
9389     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9390       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9391         return false;
9392     } else if (Op != NonPhiInVal)
9393       return false;
9394   }
9395   
9396   return true;
9397 }
9398
9399
9400 // PHINode simplification
9401 //
9402 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9403   // If LCSSA is around, don't mess with Phi nodes
9404   if (MustPreserveLCSSA) return 0;
9405   
9406   if (Value *V = PN.hasConstantValue())
9407     return ReplaceInstUsesWith(PN, V);
9408
9409   // If all PHI operands are the same operation, pull them through the PHI,
9410   // reducing code size.
9411   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9412       PN.getIncomingValue(0)->hasOneUse())
9413     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9414       return Result;
9415
9416   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9417   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9418   // PHI)... break the cycle.
9419   if (PN.hasOneUse()) {
9420     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9421     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9422       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9423       PotentiallyDeadPHIs.insert(&PN);
9424       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9425         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9426     }
9427    
9428     // If this phi has a single use, and if that use just computes a value for
9429     // the next iteration of a loop, delete the phi.  This occurs with unused
9430     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9431     // common case here is good because the only other things that catch this
9432     // are induction variable analysis (sometimes) and ADCE, which is only run
9433     // late.
9434     if (PHIUser->hasOneUse() &&
9435         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9436         PHIUser->use_back() == &PN) {
9437       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9438     }
9439   }
9440
9441   // We sometimes end up with phi cycles that non-obviously end up being the
9442   // same value, for example:
9443   //   z = some value; x = phi (y, z); y = phi (x, z)
9444   // where the phi nodes don't necessarily need to be in the same block.  Do a
9445   // quick check to see if the PHI node only contains a single non-phi value, if
9446   // so, scan to see if the phi cycle is actually equal to that value.
9447   {
9448     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9449     // Scan for the first non-phi operand.
9450     while (InValNo != NumOperandVals && 
9451            isa<PHINode>(PN.getIncomingValue(InValNo)))
9452       ++InValNo;
9453
9454     if (InValNo != NumOperandVals) {
9455       Value *NonPhiInVal = PN.getOperand(InValNo);
9456       
9457       // Scan the rest of the operands to see if there are any conflicts, if so
9458       // there is no need to recursively scan other phis.
9459       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9460         Value *OpVal = PN.getIncomingValue(InValNo);
9461         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9462           break;
9463       }
9464       
9465       // If we scanned over all operands, then we have one unique value plus
9466       // phi values.  Scan PHI nodes to see if they all merge in each other or
9467       // the value.
9468       if (InValNo == NumOperandVals) {
9469         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9470         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9471           return ReplaceInstUsesWith(PN, NonPhiInVal);
9472       }
9473     }
9474   }
9475   return 0;
9476 }
9477
9478 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9479                                    Instruction *InsertPoint,
9480                                    InstCombiner *IC) {
9481   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9482   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9483   // We must cast correctly to the pointer type. Ensure that we
9484   // sign extend the integer value if it is smaller as this is
9485   // used for address computation.
9486   Instruction::CastOps opcode = 
9487      (VTySize < PtrSize ? Instruction::SExt :
9488       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9489   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9490 }
9491
9492
9493 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9494   Value *PtrOp = GEP.getOperand(0);
9495   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9496   // If so, eliminate the noop.
9497   if (GEP.getNumOperands() == 1)
9498     return ReplaceInstUsesWith(GEP, PtrOp);
9499
9500   if (isa<UndefValue>(GEP.getOperand(0)))
9501     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9502
9503   bool HasZeroPointerIndex = false;
9504   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9505     HasZeroPointerIndex = C->isNullValue();
9506
9507   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9508     return ReplaceInstUsesWith(GEP, PtrOp);
9509
9510   // Eliminate unneeded casts for indices.
9511   bool MadeChange = false;
9512   
9513   gep_type_iterator GTI = gep_type_begin(GEP);
9514   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9515     if (isa<SequentialType>(*GTI)) {
9516       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9517         if (CI->getOpcode() == Instruction::ZExt ||
9518             CI->getOpcode() == Instruction::SExt) {
9519           const Type *SrcTy = CI->getOperand(0)->getType();
9520           // We can eliminate a cast from i32 to i64 iff the target 
9521           // is a 32-bit pointer target.
9522           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9523             MadeChange = true;
9524             GEP.setOperand(i, CI->getOperand(0));
9525           }
9526         }
9527       }
9528       // If we are using a wider index than needed for this platform, shrink it
9529       // to what we need.  If the incoming value needs a cast instruction,
9530       // insert it.  This explicit cast can make subsequent optimizations more
9531       // obvious.
9532       Value *Op = GEP.getOperand(i);
9533       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9534         if (Constant *C = dyn_cast<Constant>(Op)) {
9535           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9536           MadeChange = true;
9537         } else {
9538           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9539                                 GEP);
9540           GEP.setOperand(i, Op);
9541           MadeChange = true;
9542         }
9543       }
9544     }
9545   }
9546   if (MadeChange) return &GEP;
9547
9548   // If this GEP instruction doesn't move the pointer, and if the input operand
9549   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9550   // real input to the dest type.
9551   if (GEP.hasAllZeroIndices()) {
9552     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9553       // If the bitcast is of an allocation, and the allocation will be
9554       // converted to match the type of the cast, don't touch this.
9555       if (isa<AllocationInst>(BCI->getOperand(0))) {
9556         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9557         if (Instruction *I = visitBitCast(*BCI)) {
9558           if (I != BCI) {
9559             I->takeName(BCI);
9560             BCI->getParent()->getInstList().insert(BCI, I);
9561             ReplaceInstUsesWith(*BCI, I);
9562           }
9563           return &GEP;
9564         }
9565       }
9566       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9567     }
9568   }
9569   
9570   // Combine Indices - If the source pointer to this getelementptr instruction
9571   // is a getelementptr instruction, combine the indices of the two
9572   // getelementptr instructions into a single instruction.
9573   //
9574   SmallVector<Value*, 8> SrcGEPOperands;
9575   if (User *Src = dyn_castGetElementPtr(PtrOp))
9576     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9577
9578   if (!SrcGEPOperands.empty()) {
9579     // Note that if our source is a gep chain itself that we wait for that
9580     // chain to be resolved before we perform this transformation.  This
9581     // avoids us creating a TON of code in some cases.
9582     //
9583     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9584         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9585       return 0;   // Wait until our source is folded to completion.
9586
9587     SmallVector<Value*, 8> Indices;
9588
9589     // Find out whether the last index in the source GEP is a sequential idx.
9590     bool EndsWithSequential = false;
9591     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9592            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9593       EndsWithSequential = !isa<StructType>(*I);
9594
9595     // Can we combine the two pointer arithmetics offsets?
9596     if (EndsWithSequential) {
9597       // Replace: gep (gep %P, long B), long A, ...
9598       // With:    T = long A+B; gep %P, T, ...
9599       //
9600       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9601       if (SO1 == Constant::getNullValue(SO1->getType())) {
9602         Sum = GO1;
9603       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9604         Sum = SO1;
9605       } else {
9606         // If they aren't the same type, convert both to an integer of the
9607         // target's pointer size.
9608         if (SO1->getType() != GO1->getType()) {
9609           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9610             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9611           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9612             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9613           } else {
9614             unsigned PS = TD->getPointerSizeInBits();
9615             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9616               // Convert GO1 to SO1's type.
9617               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9618
9619             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9620               // Convert SO1 to GO1's type.
9621               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9622             } else {
9623               const Type *PT = TD->getIntPtrType();
9624               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9625               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9626             }
9627           }
9628         }
9629         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9630           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9631         else {
9632           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9633           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9634         }
9635       }
9636
9637       // Recycle the GEP we already have if possible.
9638       if (SrcGEPOperands.size() == 2) {
9639         GEP.setOperand(0, SrcGEPOperands[0]);
9640         GEP.setOperand(1, Sum);
9641         return &GEP;
9642       } else {
9643         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9644                        SrcGEPOperands.end()-1);
9645         Indices.push_back(Sum);
9646         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9647       }
9648     } else if (isa<Constant>(*GEP.idx_begin()) &&
9649                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9650                SrcGEPOperands.size() != 1) {
9651       // Otherwise we can do the fold if the first index of the GEP is a zero
9652       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9653                      SrcGEPOperands.end());
9654       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9655     }
9656
9657     if (!Indices.empty())
9658       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9659                                        Indices.end(), GEP.getName());
9660
9661   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9662     // GEP of global variable.  If all of the indices for this GEP are
9663     // constants, we can promote this to a constexpr instead of an instruction.
9664
9665     // Scan for nonconstants...
9666     SmallVector<Constant*, 8> Indices;
9667     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9668     for (; I != E && isa<Constant>(*I); ++I)
9669       Indices.push_back(cast<Constant>(*I));
9670
9671     if (I == E) {  // If they are all constants...
9672       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9673                                                     &Indices[0],Indices.size());
9674
9675       // Replace all uses of the GEP with the new constexpr...
9676       return ReplaceInstUsesWith(GEP, CE);
9677     }
9678   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9679     if (!isa<PointerType>(X->getType())) {
9680       // Not interesting.  Source pointer must be a cast from pointer.
9681     } else if (HasZeroPointerIndex) {
9682       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9683       // into     : GEP [10 x i8]* X, i32 0, ...
9684       //
9685       // This occurs when the program declares an array extern like "int X[];"
9686       //
9687       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9688       const PointerType *XTy = cast<PointerType>(X->getType());
9689       if (const ArrayType *XATy =
9690           dyn_cast<ArrayType>(XTy->getElementType()))
9691         if (const ArrayType *CATy =
9692             dyn_cast<ArrayType>(CPTy->getElementType()))
9693           if (CATy->getElementType() == XATy->getElementType()) {
9694             // At this point, we know that the cast source type is a pointer
9695             // to an array of the same type as the destination pointer
9696             // array.  Because the array type is never stepped over (there
9697             // is a leading zero) we can fold the cast into this GEP.
9698             GEP.setOperand(0, X);
9699             return &GEP;
9700           }
9701     } else if (GEP.getNumOperands() == 2) {
9702       // Transform things like:
9703       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9704       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9705       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9706       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9707       if (isa<ArrayType>(SrcElTy) &&
9708           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9709           TD->getABITypeSize(ResElTy)) {
9710         Value *Idx[2];
9711         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9712         Idx[1] = GEP.getOperand(1);
9713         Value *V = InsertNewInstBefore(
9714                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9715         // V and GEP are both pointer types --> BitCast
9716         return new BitCastInst(V, GEP.getType());
9717       }
9718       
9719       // Transform things like:
9720       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9721       //   (where tmp = 8*tmp2) into:
9722       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9723       
9724       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9725         uint64_t ArrayEltSize =
9726             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9727         
9728         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9729         // allow either a mul, shift, or constant here.
9730         Value *NewIdx = 0;
9731         ConstantInt *Scale = 0;
9732         if (ArrayEltSize == 1) {
9733           NewIdx = GEP.getOperand(1);
9734           Scale = ConstantInt::get(NewIdx->getType(), 1);
9735         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9736           NewIdx = ConstantInt::get(CI->getType(), 1);
9737           Scale = CI;
9738         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9739           if (Inst->getOpcode() == Instruction::Shl &&
9740               isa<ConstantInt>(Inst->getOperand(1))) {
9741             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9742             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9743             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9744             NewIdx = Inst->getOperand(0);
9745           } else if (Inst->getOpcode() == Instruction::Mul &&
9746                      isa<ConstantInt>(Inst->getOperand(1))) {
9747             Scale = cast<ConstantInt>(Inst->getOperand(1));
9748             NewIdx = Inst->getOperand(0);
9749           }
9750         }
9751         
9752         // If the index will be to exactly the right offset with the scale taken
9753         // out, perform the transformation. Note, we don't know whether Scale is
9754         // signed or not. We'll use unsigned version of division/modulo
9755         // operation after making sure Scale doesn't have the sign bit set.
9756         if (Scale && Scale->getSExtValue() >= 0LL &&
9757             Scale->getZExtValue() % ArrayEltSize == 0) {
9758           Scale = ConstantInt::get(Scale->getType(),
9759                                    Scale->getZExtValue() / ArrayEltSize);
9760           if (Scale->getZExtValue() != 1) {
9761             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9762                                                        false /*ZExt*/);
9763             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9764             NewIdx = InsertNewInstBefore(Sc, GEP);
9765           }
9766
9767           // Insert the new GEP instruction.
9768           Value *Idx[2];
9769           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9770           Idx[1] = NewIdx;
9771           Instruction *NewGEP =
9772             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9773           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9774           // The NewGEP must be pointer typed, so must the old one -> BitCast
9775           return new BitCastInst(NewGEP, GEP.getType());
9776         }
9777       }
9778     }
9779   }
9780
9781   return 0;
9782 }
9783
9784 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9785   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9786   if (AI.isArrayAllocation()) {  // Check C != 1
9787     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9788       const Type *NewTy = 
9789         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9790       AllocationInst *New = 0;
9791
9792       // Create and insert the replacement instruction...
9793       if (isa<MallocInst>(AI))
9794         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9795       else {
9796         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9797         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9798       }
9799
9800       InsertNewInstBefore(New, AI);
9801
9802       // Scan to the end of the allocation instructions, to skip over a block of
9803       // allocas if possible...
9804       //
9805       BasicBlock::iterator It = New;
9806       while (isa<AllocationInst>(*It)) ++It;
9807
9808       // Now that I is pointing to the first non-allocation-inst in the block,
9809       // insert our getelementptr instruction...
9810       //
9811       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9812       Value *Idx[2];
9813       Idx[0] = NullIdx;
9814       Idx[1] = NullIdx;
9815       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9816                                            New->getName()+".sub", It);
9817
9818       // Now make everything use the getelementptr instead of the original
9819       // allocation.
9820       return ReplaceInstUsesWith(AI, V);
9821     } else if (isa<UndefValue>(AI.getArraySize())) {
9822       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9823     }
9824   }
9825
9826   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9827   // Note that we only do this for alloca's, because malloc should allocate and
9828   // return a unique pointer, even for a zero byte allocation.
9829   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9830       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9831     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9832
9833   return 0;
9834 }
9835
9836 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9837   Value *Op = FI.getOperand(0);
9838
9839   // free undef -> unreachable.
9840   if (isa<UndefValue>(Op)) {
9841     // Insert a new store to null because we cannot modify the CFG here.
9842     new StoreInst(ConstantInt::getTrue(),
9843                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9844     return EraseInstFromFunction(FI);
9845   }
9846   
9847   // If we have 'free null' delete the instruction.  This can happen in stl code
9848   // when lots of inlining happens.
9849   if (isa<ConstantPointerNull>(Op))
9850     return EraseInstFromFunction(FI);
9851   
9852   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9853   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9854     FI.setOperand(0, CI->getOperand(0));
9855     return &FI;
9856   }
9857   
9858   // Change free (gep X, 0,0,0,0) into free(X)
9859   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9860     if (GEPI->hasAllZeroIndices()) {
9861       AddToWorkList(GEPI);
9862       FI.setOperand(0, GEPI->getOperand(0));
9863       return &FI;
9864     }
9865   }
9866   
9867   // Change free(malloc) into nothing, if the malloc has a single use.
9868   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9869     if (MI->hasOneUse()) {
9870       EraseInstFromFunction(FI);
9871       return EraseInstFromFunction(*MI);
9872     }
9873
9874   return 0;
9875 }
9876
9877
9878 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9879 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9880                                         const TargetData *TD) {
9881   User *CI = cast<User>(LI.getOperand(0));
9882   Value *CastOp = CI->getOperand(0);
9883
9884   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9885     // Instead of loading constant c string, use corresponding integer value
9886     // directly if string length is small enough.
9887     const std::string &Str = CE->getOperand(0)->getStringValue();
9888     if (!Str.empty()) {
9889       unsigned len = Str.length();
9890       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9891       unsigned numBits = Ty->getPrimitiveSizeInBits();
9892       // Replace LI with immediate integer store.
9893       if ((numBits >> 3) == len + 1) {
9894         APInt StrVal(numBits, 0);
9895         APInt SingleChar(numBits, 0);
9896         if (TD->isLittleEndian()) {
9897           for (signed i = len-1; i >= 0; i--) {
9898             SingleChar = (uint64_t) Str[i];
9899             StrVal = (StrVal << 8) | SingleChar;
9900           }
9901         } else {
9902           for (unsigned i = 0; i < len; i++) {
9903             SingleChar = (uint64_t) Str[i];
9904             StrVal = (StrVal << 8) | SingleChar;
9905           }
9906           // Append NULL at the end.
9907           SingleChar = 0;
9908           StrVal = (StrVal << 8) | SingleChar;
9909         }
9910         Value *NL = ConstantInt::get(StrVal);
9911         return IC.ReplaceInstUsesWith(LI, NL);
9912       }
9913     }
9914   }
9915
9916   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9917   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9918     const Type *SrcPTy = SrcTy->getElementType();
9919
9920     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9921          isa<VectorType>(DestPTy)) {
9922       // If the source is an array, the code below will not succeed.  Check to
9923       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9924       // constants.
9925       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9926         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9927           if (ASrcTy->getNumElements() != 0) {
9928             Value *Idxs[2];
9929             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9930             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9931             SrcTy = cast<PointerType>(CastOp->getType());
9932             SrcPTy = SrcTy->getElementType();
9933           }
9934
9935       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9936             isa<VectorType>(SrcPTy)) &&
9937           // Do not allow turning this into a load of an integer, which is then
9938           // casted to a pointer, this pessimizes pointer analysis a lot.
9939           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9940           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9941                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9942
9943         // Okay, we are casting from one integer or pointer type to another of
9944         // the same size.  Instead of casting the pointer before the load, cast
9945         // the result of the loaded value.
9946         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9947                                                              CI->getName(),
9948                                                          LI.isVolatile()),LI);
9949         // Now cast the result of the load.
9950         return new BitCastInst(NewLoad, LI.getType());
9951       }
9952     }
9953   }
9954   return 0;
9955 }
9956
9957 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9958 /// from this value cannot trap.  If it is not obviously safe to load from the
9959 /// specified pointer, we do a quick local scan of the basic block containing
9960 /// ScanFrom, to determine if the address is already accessed.
9961 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9962   // If it is an alloca it is always safe to load from.
9963   if (isa<AllocaInst>(V)) return true;
9964
9965   // If it is a global variable it is mostly safe to load from.
9966   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9967     // Don't try to evaluate aliases.  External weak GV can be null.
9968     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9969
9970   // Otherwise, be a little bit agressive by scanning the local block where we
9971   // want to check to see if the pointer is already being loaded or stored
9972   // from/to.  If so, the previous load or store would have already trapped,
9973   // so there is no harm doing an extra load (also, CSE will later eliminate
9974   // the load entirely).
9975   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9976
9977   while (BBI != E) {
9978     --BBI;
9979
9980     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9981       if (LI->getOperand(0) == V) return true;
9982     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9983       if (SI->getOperand(1) == V) return true;
9984
9985   }
9986   return false;
9987 }
9988
9989 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9990 /// until we find the underlying object a pointer is referring to or something
9991 /// we don't understand.  Note that the returned pointer may be offset from the
9992 /// input, because we ignore GEP indices.
9993 static Value *GetUnderlyingObject(Value *Ptr) {
9994   while (1) {
9995     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9996       if (CE->getOpcode() == Instruction::BitCast ||
9997           CE->getOpcode() == Instruction::GetElementPtr)
9998         Ptr = CE->getOperand(0);
9999       else
10000         return Ptr;
10001     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10002       Ptr = BCI->getOperand(0);
10003     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10004       Ptr = GEP->getOperand(0);
10005     } else {
10006       return Ptr;
10007     }
10008   }
10009 }
10010
10011 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10012   Value *Op = LI.getOperand(0);
10013
10014   // Attempt to improve the alignment.
10015   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10016   if (KnownAlign >
10017       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10018                                 LI.getAlignment()))
10019     LI.setAlignment(KnownAlign);
10020
10021   // load (cast X) --> cast (load X) iff safe
10022   if (isa<CastInst>(Op))
10023     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10024       return Res;
10025
10026   // None of the following transforms are legal for volatile loads.
10027   if (LI.isVolatile()) return 0;
10028   
10029   if (&LI.getParent()->front() != &LI) {
10030     BasicBlock::iterator BBI = &LI; --BBI;
10031     // If the instruction immediately before this is a store to the same
10032     // address, do a simple form of store->load forwarding.
10033     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10034       if (SI->getOperand(1) == LI.getOperand(0))
10035         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10036     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10037       if (LIB->getOperand(0) == LI.getOperand(0))
10038         return ReplaceInstUsesWith(LI, LIB);
10039   }
10040
10041   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10042     const Value *GEPI0 = GEPI->getOperand(0);
10043     // TODO: Consider a target hook for valid address spaces for this xform.
10044     if (isa<ConstantPointerNull>(GEPI0) &&
10045         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10046       // Insert a new store to null instruction before the load to indicate
10047       // that this code is not reachable.  We do this instead of inserting
10048       // an unreachable instruction directly because we cannot modify the
10049       // CFG.
10050       new StoreInst(UndefValue::get(LI.getType()),
10051                     Constant::getNullValue(Op->getType()), &LI);
10052       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10053     }
10054   } 
10055
10056   if (Constant *C = dyn_cast<Constant>(Op)) {
10057     // load null/undef -> undef
10058     // TODO: Consider a target hook for valid address spaces for this xform.
10059     if (isa<UndefValue>(C) || (C->isNullValue() && 
10060         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10061       // Insert a new store to null instruction before the load to indicate that
10062       // this code is not reachable.  We do this instead of inserting an
10063       // unreachable instruction directly because we cannot modify the CFG.
10064       new StoreInst(UndefValue::get(LI.getType()),
10065                     Constant::getNullValue(Op->getType()), &LI);
10066       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10067     }
10068
10069     // Instcombine load (constant global) into the value loaded.
10070     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10071       if (GV->isConstant() && !GV->isDeclaration())
10072         return ReplaceInstUsesWith(LI, GV->getInitializer());
10073
10074     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10075     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10076       if (CE->getOpcode() == Instruction::GetElementPtr) {
10077         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10078           if (GV->isConstant() && !GV->isDeclaration())
10079             if (Constant *V = 
10080                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10081               return ReplaceInstUsesWith(LI, V);
10082         if (CE->getOperand(0)->isNullValue()) {
10083           // Insert a new store to null instruction before the load to indicate
10084           // that this code is not reachable.  We do this instead of inserting
10085           // an unreachable instruction directly because we cannot modify the
10086           // CFG.
10087           new StoreInst(UndefValue::get(LI.getType()),
10088                         Constant::getNullValue(Op->getType()), &LI);
10089           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10090         }
10091
10092       } else if (CE->isCast()) {
10093         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10094           return Res;
10095       }
10096     }
10097   }
10098     
10099   // If this load comes from anywhere in a constant global, and if the global
10100   // is all undef or zero, we know what it loads.
10101   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10102     if (GV->isConstant() && GV->hasInitializer()) {
10103       if (GV->getInitializer()->isNullValue())
10104         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10105       else if (isa<UndefValue>(GV->getInitializer()))
10106         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10107     }
10108   }
10109
10110   if (Op->hasOneUse()) {
10111     // Change select and PHI nodes to select values instead of addresses: this
10112     // helps alias analysis out a lot, allows many others simplifications, and
10113     // exposes redundancy in the code.
10114     //
10115     // Note that we cannot do the transformation unless we know that the
10116     // introduced loads cannot trap!  Something like this is valid as long as
10117     // the condition is always false: load (select bool %C, int* null, int* %G),
10118     // but it would not be valid if we transformed it to load from null
10119     // unconditionally.
10120     //
10121     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10122       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10123       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10124           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10125         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10126                                      SI->getOperand(1)->getName()+".val"), LI);
10127         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10128                                      SI->getOperand(2)->getName()+".val"), LI);
10129         return SelectInst::Create(SI->getCondition(), V1, V2);
10130       }
10131
10132       // load (select (cond, null, P)) -> load P
10133       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10134         if (C->isNullValue()) {
10135           LI.setOperand(0, SI->getOperand(2));
10136           return &LI;
10137         }
10138
10139       // load (select (cond, P, null)) -> load P
10140       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10141         if (C->isNullValue()) {
10142           LI.setOperand(0, SI->getOperand(1));
10143           return &LI;
10144         }
10145     }
10146   }
10147   return 0;
10148 }
10149
10150 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10151 /// when possible.
10152 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10153   User *CI = cast<User>(SI.getOperand(1));
10154   Value *CastOp = CI->getOperand(0);
10155
10156   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10157   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10158     const Type *SrcPTy = SrcTy->getElementType();
10159
10160     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10161       // If the source is an array, the code below will not succeed.  Check to
10162       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10163       // constants.
10164       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10165         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10166           if (ASrcTy->getNumElements() != 0) {
10167             Value* Idxs[2];
10168             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10169             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10170             SrcTy = cast<PointerType>(CastOp->getType());
10171             SrcPTy = SrcTy->getElementType();
10172           }
10173
10174       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10175           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10176                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10177
10178         // Okay, we are casting from one integer or pointer type to another of
10179         // the same size.  Instead of casting the pointer before 
10180         // the store, cast the value to be stored.
10181         Value *NewCast;
10182         Value *SIOp0 = SI.getOperand(0);
10183         Instruction::CastOps opcode = Instruction::BitCast;
10184         const Type* CastSrcTy = SIOp0->getType();
10185         const Type* CastDstTy = SrcPTy;
10186         if (isa<PointerType>(CastDstTy)) {
10187           if (CastSrcTy->isInteger())
10188             opcode = Instruction::IntToPtr;
10189         } else if (isa<IntegerType>(CastDstTy)) {
10190           if (isa<PointerType>(SIOp0->getType()))
10191             opcode = Instruction::PtrToInt;
10192         }
10193         if (Constant *C = dyn_cast<Constant>(SIOp0))
10194           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10195         else
10196           NewCast = IC.InsertNewInstBefore(
10197             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10198             SI);
10199         return new StoreInst(NewCast, CastOp);
10200       }
10201     }
10202   }
10203   return 0;
10204 }
10205
10206 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10207   Value *Val = SI.getOperand(0);
10208   Value *Ptr = SI.getOperand(1);
10209
10210   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10211     EraseInstFromFunction(SI);
10212     ++NumCombined;
10213     return 0;
10214   }
10215   
10216   // If the RHS is an alloca with a single use, zapify the store, making the
10217   // alloca dead.
10218   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10219     if (isa<AllocaInst>(Ptr)) {
10220       EraseInstFromFunction(SI);
10221       ++NumCombined;
10222       return 0;
10223     }
10224     
10225     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10226       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10227           GEP->getOperand(0)->hasOneUse()) {
10228         EraseInstFromFunction(SI);
10229         ++NumCombined;
10230         return 0;
10231       }
10232   }
10233
10234   // Attempt to improve the alignment.
10235   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10236   if (KnownAlign >
10237       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10238                                 SI.getAlignment()))
10239     SI.setAlignment(KnownAlign);
10240
10241   // Do really simple DSE, to catch cases where there are several consequtive
10242   // stores to the same location, separated by a few arithmetic operations. This
10243   // situation often occurs with bitfield accesses.
10244   BasicBlock::iterator BBI = &SI;
10245   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10246        --ScanInsts) {
10247     --BBI;
10248     
10249     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10250       // Prev store isn't volatile, and stores to the same location?
10251       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10252         ++NumDeadStore;
10253         ++BBI;
10254         EraseInstFromFunction(*PrevSI);
10255         continue;
10256       }
10257       break;
10258     }
10259     
10260     // If this is a load, we have to stop.  However, if the loaded value is from
10261     // the pointer we're loading and is producing the pointer we're storing,
10262     // then *this* store is dead (X = load P; store X -> P).
10263     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10264       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10265         EraseInstFromFunction(SI);
10266         ++NumCombined;
10267         return 0;
10268       }
10269       // Otherwise, this is a load from some other location.  Stores before it
10270       // may not be dead.
10271       break;
10272     }
10273     
10274     // Don't skip over loads or things that can modify memory.
10275     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10276       break;
10277   }
10278   
10279   
10280   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10281
10282   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10283   if (isa<ConstantPointerNull>(Ptr)) {
10284     if (!isa<UndefValue>(Val)) {
10285       SI.setOperand(0, UndefValue::get(Val->getType()));
10286       if (Instruction *U = dyn_cast<Instruction>(Val))
10287         AddToWorkList(U);  // Dropped a use.
10288       ++NumCombined;
10289     }
10290     return 0;  // Do not modify these!
10291   }
10292
10293   // store undef, Ptr -> noop
10294   if (isa<UndefValue>(Val)) {
10295     EraseInstFromFunction(SI);
10296     ++NumCombined;
10297     return 0;
10298   }
10299
10300   // If the pointer destination is a cast, see if we can fold the cast into the
10301   // source instead.
10302   if (isa<CastInst>(Ptr))
10303     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10304       return Res;
10305   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10306     if (CE->isCast())
10307       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10308         return Res;
10309
10310   
10311   // If this store is the last instruction in the basic block, and if the block
10312   // ends with an unconditional branch, try to move it to the successor block.
10313   BBI = &SI; ++BBI;
10314   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10315     if (BI->isUnconditional())
10316       if (SimplifyStoreAtEndOfBlock(SI))
10317         return 0;  // xform done!
10318   
10319   return 0;
10320 }
10321
10322 /// SimplifyStoreAtEndOfBlock - Turn things like:
10323 ///   if () { *P = v1; } else { *P = v2 }
10324 /// into a phi node with a store in the successor.
10325 ///
10326 /// Simplify things like:
10327 ///   *P = v1; if () { *P = v2; }
10328 /// into a phi node with a store in the successor.
10329 ///
10330 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10331   BasicBlock *StoreBB = SI.getParent();
10332   
10333   // Check to see if the successor block has exactly two incoming edges.  If
10334   // so, see if the other predecessor contains a store to the same location.
10335   // if so, insert a PHI node (if needed) and move the stores down.
10336   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10337   
10338   // Determine whether Dest has exactly two predecessors and, if so, compute
10339   // the other predecessor.
10340   pred_iterator PI = pred_begin(DestBB);
10341   BasicBlock *OtherBB = 0;
10342   if (*PI != StoreBB)
10343     OtherBB = *PI;
10344   ++PI;
10345   if (PI == pred_end(DestBB))
10346     return false;
10347   
10348   if (*PI != StoreBB) {
10349     if (OtherBB)
10350       return false;
10351     OtherBB = *PI;
10352   }
10353   if (++PI != pred_end(DestBB))
10354     return false;
10355   
10356   
10357   // Verify that the other block ends in a branch and is not otherwise empty.
10358   BasicBlock::iterator BBI = OtherBB->getTerminator();
10359   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10360   if (!OtherBr || BBI == OtherBB->begin())
10361     return false;
10362   
10363   // If the other block ends in an unconditional branch, check for the 'if then
10364   // else' case.  there is an instruction before the branch.
10365   StoreInst *OtherStore = 0;
10366   if (OtherBr->isUnconditional()) {
10367     // If this isn't a store, or isn't a store to the same location, bail out.
10368     --BBI;
10369     OtherStore = dyn_cast<StoreInst>(BBI);
10370     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10371       return false;
10372   } else {
10373     // Otherwise, the other block ended with a conditional branch. If one of the
10374     // destinations is StoreBB, then we have the if/then case.
10375     if (OtherBr->getSuccessor(0) != StoreBB && 
10376         OtherBr->getSuccessor(1) != StoreBB)
10377       return false;
10378     
10379     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10380     // if/then triangle.  See if there is a store to the same ptr as SI that
10381     // lives in OtherBB.
10382     for (;; --BBI) {
10383       // Check to see if we find the matching store.
10384       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10385         if (OtherStore->getOperand(1) != SI.getOperand(1))
10386           return false;
10387         break;
10388       }
10389       // If we find something that may be using the stored value, or if we run
10390       // out of instructions, we can't do the xform.
10391       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10392           BBI == OtherBB->begin())
10393         return false;
10394     }
10395     
10396     // In order to eliminate the store in OtherBr, we have to
10397     // make sure nothing reads the stored value in StoreBB.
10398     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10399       // FIXME: This should really be AA driven.
10400       if (isa<LoadInst>(I) || I->mayWriteToMemory())
10401         return false;
10402     }
10403   }
10404   
10405   // Insert a PHI node now if we need it.
10406   Value *MergedVal = OtherStore->getOperand(0);
10407   if (MergedVal != SI.getOperand(0)) {
10408     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10409     PN->reserveOperandSpace(2);
10410     PN->addIncoming(SI.getOperand(0), SI.getParent());
10411     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10412     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10413   }
10414   
10415   // Advance to a place where it is safe to insert the new store and
10416   // insert it.
10417   BBI = DestBB->getFirstNonPHI();
10418   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10419                                     OtherStore->isVolatile()), *BBI);
10420   
10421   // Nuke the old stores.
10422   EraseInstFromFunction(SI);
10423   EraseInstFromFunction(*OtherStore);
10424   ++NumCombined;
10425   return true;
10426 }
10427
10428
10429 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10430   // Change br (not X), label True, label False to: br X, label False, True
10431   Value *X = 0;
10432   BasicBlock *TrueDest;
10433   BasicBlock *FalseDest;
10434   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10435       !isa<Constant>(X)) {
10436     // Swap Destinations and condition...
10437     BI.setCondition(X);
10438     BI.setSuccessor(0, FalseDest);
10439     BI.setSuccessor(1, TrueDest);
10440     return &BI;
10441   }
10442
10443   // Cannonicalize fcmp_one -> fcmp_oeq
10444   FCmpInst::Predicate FPred; Value *Y;
10445   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10446                              TrueDest, FalseDest)))
10447     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10448          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10449       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10450       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10451       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10452       NewSCC->takeName(I);
10453       // Swap Destinations and condition...
10454       BI.setCondition(NewSCC);
10455       BI.setSuccessor(0, FalseDest);
10456       BI.setSuccessor(1, TrueDest);
10457       RemoveFromWorkList(I);
10458       I->eraseFromParent();
10459       AddToWorkList(NewSCC);
10460       return &BI;
10461     }
10462
10463   // Cannonicalize icmp_ne -> icmp_eq
10464   ICmpInst::Predicate IPred;
10465   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10466                       TrueDest, FalseDest)))
10467     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10468          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10469          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10470       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10471       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10472       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10473       NewSCC->takeName(I);
10474       // Swap Destinations and condition...
10475       BI.setCondition(NewSCC);
10476       BI.setSuccessor(0, FalseDest);
10477       BI.setSuccessor(1, TrueDest);
10478       RemoveFromWorkList(I);
10479       I->eraseFromParent();;
10480       AddToWorkList(NewSCC);
10481       return &BI;
10482     }
10483
10484   return 0;
10485 }
10486
10487 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10488   Value *Cond = SI.getCondition();
10489   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10490     if (I->getOpcode() == Instruction::Add)
10491       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10492         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10493         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10494           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10495                                                 AddRHS));
10496         SI.setOperand(0, I->getOperand(0));
10497         AddToWorkList(I);
10498         return &SI;
10499       }
10500   }
10501   return 0;
10502 }
10503
10504 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10505 /// is to leave as a vector operation.
10506 static bool CheapToScalarize(Value *V, bool isConstant) {
10507   if (isa<ConstantAggregateZero>(V)) 
10508     return true;
10509   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10510     if (isConstant) return true;
10511     // If all elts are the same, we can extract.
10512     Constant *Op0 = C->getOperand(0);
10513     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10514       if (C->getOperand(i) != Op0)
10515         return false;
10516     return true;
10517   }
10518   Instruction *I = dyn_cast<Instruction>(V);
10519   if (!I) return false;
10520   
10521   // Insert element gets simplified to the inserted element or is deleted if
10522   // this is constant idx extract element and its a constant idx insertelt.
10523   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10524       isa<ConstantInt>(I->getOperand(2)))
10525     return true;
10526   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10527     return true;
10528   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10529     if (BO->hasOneUse() &&
10530         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10531          CheapToScalarize(BO->getOperand(1), isConstant)))
10532       return true;
10533   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10534     if (CI->hasOneUse() &&
10535         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10536          CheapToScalarize(CI->getOperand(1), isConstant)))
10537       return true;
10538   
10539   return false;
10540 }
10541
10542 /// Read and decode a shufflevector mask.
10543 ///
10544 /// It turns undef elements into values that are larger than the number of
10545 /// elements in the input.
10546 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10547   unsigned NElts = SVI->getType()->getNumElements();
10548   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10549     return std::vector<unsigned>(NElts, 0);
10550   if (isa<UndefValue>(SVI->getOperand(2)))
10551     return std::vector<unsigned>(NElts, 2*NElts);
10552
10553   std::vector<unsigned> Result;
10554   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10555   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10556     if (isa<UndefValue>(CP->getOperand(i)))
10557       Result.push_back(NElts*2);  // undef -> 8
10558     else
10559       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10560   return Result;
10561 }
10562
10563 /// FindScalarElement - Given a vector and an element number, see if the scalar
10564 /// value is already around as a register, for example if it were inserted then
10565 /// extracted from the vector.
10566 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10567   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10568   const VectorType *PTy = cast<VectorType>(V->getType());
10569   unsigned Width = PTy->getNumElements();
10570   if (EltNo >= Width)  // Out of range access.
10571     return UndefValue::get(PTy->getElementType());
10572   
10573   if (isa<UndefValue>(V))
10574     return UndefValue::get(PTy->getElementType());
10575   else if (isa<ConstantAggregateZero>(V))
10576     return Constant::getNullValue(PTy->getElementType());
10577   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10578     return CP->getOperand(EltNo);
10579   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10580     // If this is an insert to a variable element, we don't know what it is.
10581     if (!isa<ConstantInt>(III->getOperand(2))) 
10582       return 0;
10583     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10584     
10585     // If this is an insert to the element we are looking for, return the
10586     // inserted value.
10587     if (EltNo == IIElt) 
10588       return III->getOperand(1);
10589     
10590     // Otherwise, the insertelement doesn't modify the value, recurse on its
10591     // vector input.
10592     return FindScalarElement(III->getOperand(0), EltNo);
10593   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10594     unsigned InEl = getShuffleMask(SVI)[EltNo];
10595     if (InEl < Width)
10596       return FindScalarElement(SVI->getOperand(0), InEl);
10597     else if (InEl < Width*2)
10598       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10599     else
10600       return UndefValue::get(PTy->getElementType());
10601   }
10602   
10603   // Otherwise, we don't know.
10604   return 0;
10605 }
10606
10607 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10608
10609   // If vector val is undef, replace extract with scalar undef.
10610   if (isa<UndefValue>(EI.getOperand(0)))
10611     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10612
10613   // If vector val is constant 0, replace extract with scalar 0.
10614   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10615     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10616   
10617   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10618     // If vector val is constant with uniform operands, replace EI
10619     // with that operand
10620     Constant *op0 = C->getOperand(0);
10621     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10622       if (C->getOperand(i) != op0) {
10623         op0 = 0; 
10624         break;
10625       }
10626     if (op0)
10627       return ReplaceInstUsesWith(EI, op0);
10628   }
10629   
10630   // If extracting a specified index from the vector, see if we can recursively
10631   // find a previously computed scalar that was inserted into the vector.
10632   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10633     unsigned IndexVal = IdxC->getZExtValue();
10634     unsigned VectorWidth = 
10635       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10636       
10637     // If this is extracting an invalid index, turn this into undef, to avoid
10638     // crashing the code below.
10639     if (IndexVal >= VectorWidth)
10640       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10641     
10642     // This instruction only demands the single element from the input vector.
10643     // If the input vector has a single use, simplify it based on this use
10644     // property.
10645     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10646       uint64_t UndefElts;
10647       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10648                                                 1 << IndexVal,
10649                                                 UndefElts)) {
10650         EI.setOperand(0, V);
10651         return &EI;
10652       }
10653     }
10654     
10655     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10656       return ReplaceInstUsesWith(EI, Elt);
10657     
10658     // If the this extractelement is directly using a bitcast from a vector of
10659     // the same number of elements, see if we can find the source element from
10660     // it.  In this case, we will end up needing to bitcast the scalars.
10661     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10662       if (const VectorType *VT = 
10663               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10664         if (VT->getNumElements() == VectorWidth)
10665           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10666             return new BitCastInst(Elt, EI.getType());
10667     }
10668   }
10669   
10670   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10671     if (I->hasOneUse()) {
10672       // Push extractelement into predecessor operation if legal and
10673       // profitable to do so
10674       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10675         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10676         if (CheapToScalarize(BO, isConstantElt)) {
10677           ExtractElementInst *newEI0 = 
10678             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10679                                    EI.getName()+".lhs");
10680           ExtractElementInst *newEI1 =
10681             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10682                                    EI.getName()+".rhs");
10683           InsertNewInstBefore(newEI0, EI);
10684           InsertNewInstBefore(newEI1, EI);
10685           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10686         }
10687       } else if (isa<LoadInst>(I)) {
10688         unsigned AS = 
10689           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10690         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10691                                          PointerType::get(EI.getType(), AS),EI);
10692         GetElementPtrInst *GEP =
10693           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10694         InsertNewInstBefore(GEP, EI);
10695         return new LoadInst(GEP);
10696       }
10697     }
10698     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10699       // Extracting the inserted element?
10700       if (IE->getOperand(2) == EI.getOperand(1))
10701         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10702       // If the inserted and extracted elements are constants, they must not
10703       // be the same value, extract from the pre-inserted value instead.
10704       if (isa<Constant>(IE->getOperand(2)) &&
10705           isa<Constant>(EI.getOperand(1))) {
10706         AddUsesToWorkList(EI);
10707         EI.setOperand(0, IE->getOperand(0));
10708         return &EI;
10709       }
10710     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10711       // If this is extracting an element from a shufflevector, figure out where
10712       // it came from and extract from the appropriate input element instead.
10713       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10714         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10715         Value *Src;
10716         if (SrcIdx < SVI->getType()->getNumElements())
10717           Src = SVI->getOperand(0);
10718         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10719           SrcIdx -= SVI->getType()->getNumElements();
10720           Src = SVI->getOperand(1);
10721         } else {
10722           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10723         }
10724         return new ExtractElementInst(Src, SrcIdx);
10725       }
10726     }
10727   }
10728   return 0;
10729 }
10730
10731 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10732 /// elements from either LHS or RHS, return the shuffle mask and true. 
10733 /// Otherwise, return false.
10734 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10735                                          std::vector<Constant*> &Mask) {
10736   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10737          "Invalid CollectSingleShuffleElements");
10738   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10739
10740   if (isa<UndefValue>(V)) {
10741     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10742     return true;
10743   } else if (V == LHS) {
10744     for (unsigned i = 0; i != NumElts; ++i)
10745       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10746     return true;
10747   } else if (V == RHS) {
10748     for (unsigned i = 0; i != NumElts; ++i)
10749       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10750     return true;
10751   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10752     // If this is an insert of an extract from some other vector, include it.
10753     Value *VecOp    = IEI->getOperand(0);
10754     Value *ScalarOp = IEI->getOperand(1);
10755     Value *IdxOp    = IEI->getOperand(2);
10756     
10757     if (!isa<ConstantInt>(IdxOp))
10758       return false;
10759     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10760     
10761     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10762       // Okay, we can handle this if the vector we are insertinting into is
10763       // transitively ok.
10764       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10765         // If so, update the mask to reflect the inserted undef.
10766         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10767         return true;
10768       }      
10769     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10770       if (isa<ConstantInt>(EI->getOperand(1)) &&
10771           EI->getOperand(0)->getType() == V->getType()) {
10772         unsigned ExtractedIdx =
10773           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10774         
10775         // This must be extracting from either LHS or RHS.
10776         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10777           // Okay, we can handle this if the vector we are insertinting into is
10778           // transitively ok.
10779           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10780             // If so, update the mask to reflect the inserted value.
10781             if (EI->getOperand(0) == LHS) {
10782               Mask[InsertedIdx & (NumElts-1)] = 
10783                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10784             } else {
10785               assert(EI->getOperand(0) == RHS);
10786               Mask[InsertedIdx & (NumElts-1)] = 
10787                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10788               
10789             }
10790             return true;
10791           }
10792         }
10793       }
10794     }
10795   }
10796   // TODO: Handle shufflevector here!
10797   
10798   return false;
10799 }
10800
10801 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10802 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10803 /// that computes V and the LHS value of the shuffle.
10804 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10805                                      Value *&RHS) {
10806   assert(isa<VectorType>(V->getType()) && 
10807          (RHS == 0 || V->getType() == RHS->getType()) &&
10808          "Invalid shuffle!");
10809   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10810
10811   if (isa<UndefValue>(V)) {
10812     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10813     return V;
10814   } else if (isa<ConstantAggregateZero>(V)) {
10815     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10816     return V;
10817   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10818     // If this is an insert of an extract from some other vector, include it.
10819     Value *VecOp    = IEI->getOperand(0);
10820     Value *ScalarOp = IEI->getOperand(1);
10821     Value *IdxOp    = IEI->getOperand(2);
10822     
10823     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10824       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10825           EI->getOperand(0)->getType() == V->getType()) {
10826         unsigned ExtractedIdx =
10827           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10828         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10829         
10830         // Either the extracted from or inserted into vector must be RHSVec,
10831         // otherwise we'd end up with a shuffle of three inputs.
10832         if (EI->getOperand(0) == RHS || RHS == 0) {
10833           RHS = EI->getOperand(0);
10834           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10835           Mask[InsertedIdx & (NumElts-1)] = 
10836             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10837           return V;
10838         }
10839         
10840         if (VecOp == RHS) {
10841           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10842           // Everything but the extracted element is replaced with the RHS.
10843           for (unsigned i = 0; i != NumElts; ++i) {
10844             if (i != InsertedIdx)
10845               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10846           }
10847           return V;
10848         }
10849         
10850         // If this insertelement is a chain that comes from exactly these two
10851         // vectors, return the vector and the effective shuffle.
10852         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10853           return EI->getOperand(0);
10854         
10855       }
10856     }
10857   }
10858   // TODO: Handle shufflevector here!
10859   
10860   // Otherwise, can't do anything fancy.  Return an identity vector.
10861   for (unsigned i = 0; i != NumElts; ++i)
10862     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10863   return V;
10864 }
10865
10866 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10867   Value *VecOp    = IE.getOperand(0);
10868   Value *ScalarOp = IE.getOperand(1);
10869   Value *IdxOp    = IE.getOperand(2);
10870   
10871   // Inserting an undef or into an undefined place, remove this.
10872   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10873     ReplaceInstUsesWith(IE, VecOp);
10874   
10875   // If the inserted element was extracted from some other vector, and if the 
10876   // indexes are constant, try to turn this into a shufflevector operation.
10877   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10878     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10879         EI->getOperand(0)->getType() == IE.getType()) {
10880       unsigned NumVectorElts = IE.getType()->getNumElements();
10881       unsigned ExtractedIdx =
10882         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10883       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10884       
10885       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10886         return ReplaceInstUsesWith(IE, VecOp);
10887       
10888       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10889         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10890       
10891       // If we are extracting a value from a vector, then inserting it right
10892       // back into the same place, just use the input vector.
10893       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10894         return ReplaceInstUsesWith(IE, VecOp);      
10895       
10896       // We could theoretically do this for ANY input.  However, doing so could
10897       // turn chains of insertelement instructions into a chain of shufflevector
10898       // instructions, and right now we do not merge shufflevectors.  As such,
10899       // only do this in a situation where it is clear that there is benefit.
10900       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10901         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10902         // the values of VecOp, except then one read from EIOp0.
10903         // Build a new shuffle mask.
10904         std::vector<Constant*> Mask;
10905         if (isa<UndefValue>(VecOp))
10906           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10907         else {
10908           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10909           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10910                                                        NumVectorElts));
10911         } 
10912         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10913         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10914                                      ConstantVector::get(Mask));
10915       }
10916       
10917       // If this insertelement isn't used by some other insertelement, turn it
10918       // (and any insertelements it points to), into one big shuffle.
10919       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10920         std::vector<Constant*> Mask;
10921         Value *RHS = 0;
10922         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10923         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10924         // We now have a shuffle of LHS, RHS, Mask.
10925         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10926       }
10927     }
10928   }
10929
10930   return 0;
10931 }
10932
10933
10934 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10935   Value *LHS = SVI.getOperand(0);
10936   Value *RHS = SVI.getOperand(1);
10937   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10938
10939   bool MadeChange = false;
10940   
10941   // Undefined shuffle mask -> undefined value.
10942   if (isa<UndefValue>(SVI.getOperand(2)))
10943     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10944   
10945   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10946   // the undef, change them to undefs.
10947   if (isa<UndefValue>(SVI.getOperand(1))) {
10948     // Scan to see if there are any references to the RHS.  If so, replace them
10949     // with undef element refs and set MadeChange to true.
10950     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10951       if (Mask[i] >= e && Mask[i] != 2*e) {
10952         Mask[i] = 2*e;
10953         MadeChange = true;
10954       }
10955     }
10956     
10957     if (MadeChange) {
10958       // Remap any references to RHS to use LHS.
10959       std::vector<Constant*> Elts;
10960       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10961         if (Mask[i] == 2*e)
10962           Elts.push_back(UndefValue::get(Type::Int32Ty));
10963         else
10964           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10965       }
10966       SVI.setOperand(2, ConstantVector::get(Elts));
10967     }
10968   }
10969   
10970   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10971   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10972   if (LHS == RHS || isa<UndefValue>(LHS)) {
10973     if (isa<UndefValue>(LHS) && LHS == RHS) {
10974       // shuffle(undef,undef,mask) -> undef.
10975       return ReplaceInstUsesWith(SVI, LHS);
10976     }
10977     
10978     // Remap any references to RHS to use LHS.
10979     std::vector<Constant*> Elts;
10980     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10981       if (Mask[i] >= 2*e)
10982         Elts.push_back(UndefValue::get(Type::Int32Ty));
10983       else {
10984         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10985             (Mask[i] <  e && isa<UndefValue>(LHS)))
10986           Mask[i] = 2*e;     // Turn into undef.
10987         else
10988           Mask[i] &= (e-1);  // Force to LHS.
10989         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10990       }
10991     }
10992     SVI.setOperand(0, SVI.getOperand(1));
10993     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10994     SVI.setOperand(2, ConstantVector::get(Elts));
10995     LHS = SVI.getOperand(0);
10996     RHS = SVI.getOperand(1);
10997     MadeChange = true;
10998   }
10999   
11000   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11001   bool isLHSID = true, isRHSID = true;
11002     
11003   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11004     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11005     // Is this an identity shuffle of the LHS value?
11006     isLHSID &= (Mask[i] == i);
11007       
11008     // Is this an identity shuffle of the RHS value?
11009     isRHSID &= (Mask[i]-e == i);
11010   }
11011
11012   // Eliminate identity shuffles.
11013   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11014   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11015   
11016   // If the LHS is a shufflevector itself, see if we can combine it with this
11017   // one without producing an unusual shuffle.  Here we are really conservative:
11018   // we are absolutely afraid of producing a shuffle mask not in the input
11019   // program, because the code gen may not be smart enough to turn a merged
11020   // shuffle into two specific shuffles: it may produce worse code.  As such,
11021   // we only merge two shuffles if the result is one of the two input shuffle
11022   // masks.  In this case, merging the shuffles just removes one instruction,
11023   // which we know is safe.  This is good for things like turning:
11024   // (splat(splat)) -> splat.
11025   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11026     if (isa<UndefValue>(RHS)) {
11027       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11028
11029       std::vector<unsigned> NewMask;
11030       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11031         if (Mask[i] >= 2*e)
11032           NewMask.push_back(2*e);
11033         else
11034           NewMask.push_back(LHSMask[Mask[i]]);
11035       
11036       // If the result mask is equal to the src shuffle or this shuffle mask, do
11037       // the replacement.
11038       if (NewMask == LHSMask || NewMask == Mask) {
11039         std::vector<Constant*> Elts;
11040         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11041           if (NewMask[i] >= e*2) {
11042             Elts.push_back(UndefValue::get(Type::Int32Ty));
11043           } else {
11044             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11045           }
11046         }
11047         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11048                                      LHSSVI->getOperand(1),
11049                                      ConstantVector::get(Elts));
11050       }
11051     }
11052   }
11053
11054   return MadeChange ? &SVI : 0;
11055 }
11056
11057
11058
11059
11060 /// TryToSinkInstruction - Try to move the specified instruction from its
11061 /// current block into the beginning of DestBlock, which can only happen if it's
11062 /// safe to move the instruction past all of the instructions between it and the
11063 /// end of its block.
11064 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11065   assert(I->hasOneUse() && "Invariants didn't hold!");
11066
11067   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11068   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11069     return false;
11070
11071   // Do not sink alloca instructions out of the entry block.
11072   if (isa<AllocaInst>(I) && I->getParent() ==
11073         &DestBlock->getParent()->getEntryBlock())
11074     return false;
11075
11076   // We can only sink load instructions if there is nothing between the load and
11077   // the end of block that could change the value.
11078   if (I->mayReadFromMemory()) {
11079     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11080          Scan != E; ++Scan)
11081       if (Scan->mayWriteToMemory())
11082         return false;
11083   }
11084
11085   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11086
11087   I->moveBefore(InsertPos);
11088   ++NumSunkInst;
11089   return true;
11090 }
11091
11092
11093 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11094 /// all reachable code to the worklist.
11095 ///
11096 /// This has a couple of tricks to make the code faster and more powerful.  In
11097 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11098 /// them to the worklist (this significantly speeds up instcombine on code where
11099 /// many instructions are dead or constant).  Additionally, if we find a branch
11100 /// whose condition is a known constant, we only visit the reachable successors.
11101 ///
11102 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11103                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11104                                        InstCombiner &IC,
11105                                        const TargetData *TD) {
11106   std::vector<BasicBlock*> Worklist;
11107   Worklist.push_back(BB);
11108
11109   while (!Worklist.empty()) {
11110     BB = Worklist.back();
11111     Worklist.pop_back();
11112     
11113     // We have now visited this block!  If we've already been here, ignore it.
11114     if (!Visited.insert(BB)) continue;
11115     
11116     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11117       Instruction *Inst = BBI++;
11118       
11119       // DCE instruction if trivially dead.
11120       if (isInstructionTriviallyDead(Inst)) {
11121         ++NumDeadInst;
11122         DOUT << "IC: DCE: " << *Inst;
11123         Inst->eraseFromParent();
11124         continue;
11125       }
11126       
11127       // ConstantProp instruction if trivially constant.
11128       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11129         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11130         Inst->replaceAllUsesWith(C);
11131         ++NumConstProp;
11132         Inst->eraseFromParent();
11133         continue;
11134       }
11135      
11136       IC.AddToWorkList(Inst);
11137     }
11138
11139     // Recursively visit successors.  If this is a branch or switch on a
11140     // constant, only visit the reachable successor.
11141     TerminatorInst *TI = BB->getTerminator();
11142     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11143       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11144         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11145         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11146         Worklist.push_back(ReachableBB);
11147         continue;
11148       }
11149     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11150       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11151         // See if this is an explicit destination.
11152         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11153           if (SI->getCaseValue(i) == Cond) {
11154             BasicBlock *ReachableBB = SI->getSuccessor(i);
11155             Worklist.push_back(ReachableBB);
11156             continue;
11157           }
11158         
11159         // Otherwise it is the default destination.
11160         Worklist.push_back(SI->getSuccessor(0));
11161         continue;
11162       }
11163     }
11164     
11165     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11166       Worklist.push_back(TI->getSuccessor(i));
11167   }
11168 }
11169
11170 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11171   bool Changed = false;
11172   TD = &getAnalysis<TargetData>();
11173   
11174   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11175              << F.getNameStr() << "\n");
11176
11177   {
11178     // Do a depth-first traversal of the function, populate the worklist with
11179     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11180     // track of which blocks we visit.
11181     SmallPtrSet<BasicBlock*, 64> Visited;
11182     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11183
11184     // Do a quick scan over the function.  If we find any blocks that are
11185     // unreachable, remove any instructions inside of them.  This prevents
11186     // the instcombine code from having to deal with some bad special cases.
11187     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11188       if (!Visited.count(BB)) {
11189         Instruction *Term = BB->getTerminator();
11190         while (Term != BB->begin()) {   // Remove instrs bottom-up
11191           BasicBlock::iterator I = Term; --I;
11192
11193           DOUT << "IC: DCE: " << *I;
11194           ++NumDeadInst;
11195
11196           if (!I->use_empty())
11197             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11198           I->eraseFromParent();
11199         }
11200       }
11201   }
11202
11203   while (!Worklist.empty()) {
11204     Instruction *I = RemoveOneFromWorkList();
11205     if (I == 0) continue;  // skip null values.
11206
11207     // Check to see if we can DCE the instruction.
11208     if (isInstructionTriviallyDead(I)) {
11209       // Add operands to the worklist.
11210       if (I->getNumOperands() < 4)
11211         AddUsesToWorkList(*I);
11212       ++NumDeadInst;
11213
11214       DOUT << "IC: DCE: " << *I;
11215
11216       I->eraseFromParent();
11217       RemoveFromWorkList(I);
11218       continue;
11219     }
11220
11221     // Instruction isn't dead, see if we can constant propagate it.
11222     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11223       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11224
11225       // Add operands to the worklist.
11226       AddUsesToWorkList(*I);
11227       ReplaceInstUsesWith(*I, C);
11228
11229       ++NumConstProp;
11230       I->eraseFromParent();
11231       RemoveFromWorkList(I);
11232       continue;
11233     }
11234
11235     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11236       // See if we can constant fold its operands.
11237       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11238         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11239           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11240             i->set(NewC);
11241         }
11242       }
11243     }
11244
11245     // See if we can trivially sink this instruction to a successor basic block.
11246     // FIXME: Remove GetResultInst test when first class support for aggregates
11247     // is implemented.
11248     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11249       BasicBlock *BB = I->getParent();
11250       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11251       if (UserParent != BB) {
11252         bool UserIsSuccessor = false;
11253         // See if the user is one of our successors.
11254         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11255           if (*SI == UserParent) {
11256             UserIsSuccessor = true;
11257             break;
11258           }
11259
11260         // If the user is one of our immediate successors, and if that successor
11261         // only has us as a predecessors (we'd have to split the critical edge
11262         // otherwise), we can keep going.
11263         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11264             next(pred_begin(UserParent)) == pred_end(UserParent))
11265           // Okay, the CFG is simple enough, try to sink this instruction.
11266           Changed |= TryToSinkInstruction(I, UserParent);
11267       }
11268     }
11269
11270     // Now that we have an instruction, try combining it to simplify it...
11271 #ifndef NDEBUG
11272     std::string OrigI;
11273 #endif
11274     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11275     if (Instruction *Result = visit(*I)) {
11276       ++NumCombined;
11277       // Should we replace the old instruction with a new one?
11278       if (Result != I) {
11279         DOUT << "IC: Old = " << *I
11280              << "    New = " << *Result;
11281
11282         // Everything uses the new instruction now.
11283         I->replaceAllUsesWith(Result);
11284
11285         // Push the new instruction and any users onto the worklist.
11286         AddToWorkList(Result);
11287         AddUsersToWorkList(*Result);
11288
11289         // Move the name to the new instruction first.
11290         Result->takeName(I);
11291
11292         // Insert the new instruction into the basic block...
11293         BasicBlock *InstParent = I->getParent();
11294         BasicBlock::iterator InsertPos = I;
11295
11296         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11297           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11298             ++InsertPos;
11299
11300         InstParent->getInstList().insert(InsertPos, Result);
11301
11302         // Make sure that we reprocess all operands now that we reduced their
11303         // use counts.
11304         AddUsesToWorkList(*I);
11305
11306         // Instructions can end up on the worklist more than once.  Make sure
11307         // we do not process an instruction that has been deleted.
11308         RemoveFromWorkList(I);
11309
11310         // Erase the old instruction.
11311         InstParent->getInstList().erase(I);
11312       } else {
11313 #ifndef NDEBUG
11314         DOUT << "IC: Mod = " << OrigI
11315              << "    New = " << *I;
11316 #endif
11317
11318         // If the instruction was modified, it's possible that it is now dead.
11319         // if so, remove it.
11320         if (isInstructionTriviallyDead(I)) {
11321           // Make sure we process all operands now that we are reducing their
11322           // use counts.
11323           AddUsesToWorkList(*I);
11324
11325           // Instructions may end up in the worklist more than once.  Erase all
11326           // occurrences of this instruction.
11327           RemoveFromWorkList(I);
11328           I->eraseFromParent();
11329         } else {
11330           AddToWorkList(I);
11331           AddUsersToWorkList(*I);
11332         }
11333       }
11334       Changed = true;
11335     }
11336   }
11337
11338   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11339     
11340   // Do an explicit clear, this shrinks the map if needed.
11341   WorklistMap.clear();
11342   return Changed;
11343 }
11344
11345
11346 bool InstCombiner::runOnFunction(Function &F) {
11347   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11348   
11349   bool EverMadeChange = false;
11350
11351   // Iterate while there is work to do.
11352   unsigned Iteration = 0;
11353   while (DoOneIteration(F, Iteration++))
11354     EverMadeChange = true;
11355   return EverMadeChange;
11356 }
11357
11358 FunctionPass *llvm::createInstructionCombiningPass() {
11359   return new InstCombiner();
11360 }
11361