514e91bdef32d6baea755388b86ba9983b571647
[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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include <algorithm>
65 #include <climits>
66 #include <sstream>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   class VISIBILITY_HIDDEN InstCombiner
78     : public FunctionPass,
79       public InstVisitor<InstCombiner, Instruction*> {
80     // Worklist of all of the instructions that need to be simplified.
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     TargetData *TD;
84     bool MustPreserveLCSSA;
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     InstCombiner() : FunctionPass(&ID) {}
88
89     LLVMContext *Context;
90     LLVMContext *getContext() const { return Context; }
91
92     /// AddToWorkList - Add the specified instruction to the worklist if it
93     /// isn't already in it.
94     void AddToWorkList(Instruction *I) {
95       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
96         Worklist.push_back(I);
97     }
98     
99     // RemoveFromWorkList - remove I from the worklist if it exists.
100     void RemoveFromWorkList(Instruction *I) {
101       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102       if (It == WorklistMap.end()) return; // Not in worklist.
103       
104       // Don't bother moving everything down, just null out the slot.
105       Worklist[It->second] = 0;
106       
107       WorklistMap.erase(It);
108     }
109     
110     Instruction *RemoveOneFromWorkList() {
111       Instruction *I = Worklist.back();
112       Worklist.pop_back();
113       WorklistMap.erase(I);
114       return I;
115     }
116
117     
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(Value &I) {
123       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124            UI != UE; ++UI)
125         AddToWorkList(cast<Instruction>(*UI));
126     }
127
128     /// AddUsesToWorkList - When an instruction is simplified, add operands to
129     /// the work lists because they might get more simplified now.
130     ///
131     void AddUsesToWorkList(Instruction &I) {
132       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133         if (Instruction *Op = dyn_cast<Instruction>(*i))
134           AddToWorkList(Op);
135     }
136     
137     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138     /// dead.  Add all of its operands to the worklist, turning them into
139     /// undef's to reduce the number of uses of those instructions.
140     ///
141     /// Return the specified operand before it is turned into an undef.
142     ///
143     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144       Value *R = I.getOperand(op);
145       
146       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
148           AddToWorkList(Op);
149           // Set the operand to undef to drop the use.
150           *i = UndefValue::get(Op->getType());
151         }
152       
153       return R;
154     }
155
156   public:
157     virtual bool runOnFunction(Function &F);
158     
159     bool DoOneIteration(Function &F, unsigned ItNum);
160
161     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162       AU.addPreservedID(LCSSAID);
163       AU.setPreservesCFG();
164     }
165
166     TargetData *getTargetData() const { return TD; }
167
168     // Visitation implementation - Implement instruction combining for different
169     // instruction types.  The semantics are as follows:
170     // Return Value:
171     //    null        - No change was made
172     //     I          - Change was made, I is still valid, I may be dead though
173     //   otherwise    - Change was made, replace I with returned instruction
174     //
175     Instruction *visitAdd(BinaryOperator &I);
176     Instruction *visitFAdd(BinaryOperator &I);
177     Instruction *visitSub(BinaryOperator &I);
178     Instruction *visitFSub(BinaryOperator &I);
179     Instruction *visitMul(BinaryOperator &I);
180     Instruction *visitFMul(BinaryOperator &I);
181     Instruction *visitURem(BinaryOperator &I);
182     Instruction *visitSRem(BinaryOperator &I);
183     Instruction *visitFRem(BinaryOperator &I);
184     bool SimplifyDivRemOfSelect(BinaryOperator &I);
185     Instruction *commonRemTransforms(BinaryOperator &I);
186     Instruction *commonIRemTransforms(BinaryOperator &I);
187     Instruction *commonDivTransforms(BinaryOperator &I);
188     Instruction *commonIDivTransforms(BinaryOperator &I);
189     Instruction *visitUDiv(BinaryOperator &I);
190     Instruction *visitSDiv(BinaryOperator &I);
191     Instruction *visitFDiv(BinaryOperator &I);
192     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
194     Instruction *visitAnd(BinaryOperator &I);
195     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
198                                      Value *A, Value *B, Value *C);
199     Instruction *visitOr (BinaryOperator &I);
200     Instruction *visitXor(BinaryOperator &I);
201     Instruction *visitShl(BinaryOperator &I);
202     Instruction *visitAShr(BinaryOperator &I);
203     Instruction *visitLShr(BinaryOperator &I);
204     Instruction *commonShiftTransforms(BinaryOperator &I);
205     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206                                       Constant *RHSC);
207     Instruction *visitFCmpInst(FCmpInst &I);
208     Instruction *visitICmpInst(ICmpInst &I);
209     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211                                                 Instruction *LHS,
212                                                 ConstantInt *RHS);
213     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214                                 ConstantInt *DivRHS);
215
216     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
217                              ICmpInst::Predicate Cond, Instruction &I);
218     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219                                      BinaryOperator &I);
220     Instruction *commonCastTransforms(CastInst &CI);
221     Instruction *commonIntCastTransforms(CastInst &CI);
222     Instruction *commonPointerCastTransforms(CastInst &CI);
223     Instruction *visitTrunc(TruncInst &CI);
224     Instruction *visitZExt(ZExtInst &CI);
225     Instruction *visitSExt(SExtInst &CI);
226     Instruction *visitFPTrunc(FPTruncInst &CI);
227     Instruction *visitFPExt(CastInst &CI);
228     Instruction *visitFPToUI(FPToUIInst &FI);
229     Instruction *visitFPToSI(FPToSIInst &FI);
230     Instruction *visitUIToFP(CastInst &CI);
231     Instruction *visitSIToFP(CastInst &CI);
232     Instruction *visitPtrToInt(PtrToIntInst &CI);
233     Instruction *visitIntToPtr(IntToPtrInst &CI);
234     Instruction *visitBitCast(BitCastInst &CI);
235     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236                                 Instruction *FI);
237     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
238     Instruction *visitSelectInst(SelectInst &SI);
239     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
240     Instruction *visitCallInst(CallInst &CI);
241     Instruction *visitInvokeInst(InvokeInst &II);
242     Instruction *visitPHINode(PHINode &PN);
243     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244     Instruction *visitAllocationInst(AllocationInst &AI);
245     Instruction *visitFreeInst(FreeInst &FI);
246     Instruction *visitLoadInst(LoadInst &LI);
247     Instruction *visitStoreInst(StoreInst &SI);
248     Instruction *visitBranchInst(BranchInst &BI);
249     Instruction *visitSwitchInst(SwitchInst &SI);
250     Instruction *visitInsertElementInst(InsertElementInst &IE);
251     Instruction *visitExtractElementInst(ExtractElementInst &EI);
252     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
253     Instruction *visitExtractValueInst(ExtractValueInst &EV);
254
255     // visitInstruction - Specify what to return for unhandled instructions...
256     Instruction *visitInstruction(Instruction &I) { return 0; }
257
258   private:
259     Instruction *visitCallSite(CallSite CS);
260     bool transformConstExprCastCall(CallSite CS);
261     Instruction *transformCallThroughTrampoline(CallSite CS);
262     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263                                    bool DoXform = true);
264     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
265     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
267
268   public:
269     // InsertNewInstBefore - insert an instruction New before instruction Old
270     // in the program.  Add the new instruction to the worklist.
271     //
272     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273       assert(New && New->getParent() == 0 &&
274              "New instruction already inserted into a basic block!");
275       BasicBlock *BB = Old.getParent();
276       BB->getInstList().insert(&Old, New);  // Insert inst
277       AddToWorkList(New);
278       return New;
279     }
280
281     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282     /// This also adds the cast to the worklist.  Finally, this returns the
283     /// cast.
284     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285                             Instruction &Pos) {
286       if (V->getType() == Ty) return V;
287
288       if (Constant *CV = dyn_cast<Constant>(V))
289         return ConstantExpr::getCast(opc, CV, Ty);
290       
291       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
292       AddToWorkList(C);
293       return C;
294     }
295         
296     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298     }
299
300
301     // ReplaceInstUsesWith - This method is to be used when an instruction is
302     // found to be dead, replacable with another preexisting expression.  Here
303     // we add all uses of I to the worklist, replace all uses of I with the new
304     // value, then return I, so that the inst combiner will know that I was
305     // modified.
306     //
307     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308       AddUsersToWorkList(I);         // Add all modified instrs to worklist
309       if (&I != V) {
310         I.replaceAllUsesWith(V);
311         return &I;
312       } else {
313         // If we are replacing the instruction with itself, this must be in a
314         // segment of unreachable code, so just clobber the instruction.
315         I.replaceAllUsesWith(UndefValue::get(I.getType()));
316         return &I;
317       }
318     }
319
320     // EraseInstFromFunction - When dealing with an instruction that has side
321     // effects or produces a void value, we can't rely on DCE to delete the
322     // instruction.  Instead, visit methods should return the value returned by
323     // this function.
324     Instruction *EraseInstFromFunction(Instruction &I) {
325       assert(I.use_empty() && "Cannot erase instruction that is used!");
326       AddUsesToWorkList(I);
327       RemoveFromWorkList(&I);
328       I.eraseFromParent();
329       return 0;  // Don't do anything with FI
330     }
331         
332     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333                            APInt &KnownOne, unsigned Depth = 0) const {
334       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335     }
336     
337     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
338                            unsigned Depth = 0) const {
339       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340     }
341     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342       return llvm::ComputeNumSignBits(Op, TD, Depth);
343     }
344
345   private:
346
347     /// SimplifyCommutative - This performs a few simplifications for 
348     /// commutative operators.
349     bool SimplifyCommutative(BinaryOperator &I);
350
351     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352     /// most-complex to least-complex order.
353     bool SimplifyCompare(CmpInst &I);
354
355     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356     /// based on the demanded bits.
357     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
358                                    APInt& KnownZero, APInt& KnownOne,
359                                    unsigned Depth);
360     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth=0);
363         
364     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365     /// SimplifyDemandedBits knows about.  See if the instruction has any
366     /// properties that allow us to simplify its operands.
367     bool SimplifyDemandedInstructionBits(Instruction &Inst);
368         
369     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370                                       APInt& UndefElts, unsigned Depth = 0);
371       
372     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373     // PHI node as operand #0, see if we can fold the instruction into the PHI
374     // (which is only possible if all operands to the PHI are constants).
375     Instruction *FoldOpIntoPhi(Instruction &I);
376
377     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378     // operator and they all are only used by the PHI, PHI together their
379     // inputs, and do the operation once, to the result of the PHI.
380     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
384     
385     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
387     
388     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389                               bool isSub, Instruction &I);
390     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391                                  bool isSigned, bool Inside, Instruction &IB);
392     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393     Instruction *MatchBSwap(BinaryOperator &I);
394     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
395     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
396     Instruction *SimplifyMemSet(MemSetInst *MI);
397
398
399     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
400
401     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
402                                     unsigned CastOpc, int &NumCastsRemoved);
403     unsigned GetOrEnforceKnownAlignment(Value *V,
404                                         unsigned PrefAlign = 0);
405
406   };
407 }
408
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
412
413 // getComplexity:  Assign a complexity or rank value to LLVM Values...
414 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(LLVMContext *Context, Value *V) {
416   if (isa<Instruction>(V)) {
417     if (BinaryOperator::isNeg(V) ||
418         BinaryOperator::isFNeg(V) ||
419         BinaryOperator::isNot(V))
420       return 3;
421     return 4;
422   }
423   if (isa<Argument>(V)) return 3;
424   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425 }
426
427 // isOnlyUse - Return true if this instruction will be deleted if we stop using
428 // it.
429 static bool isOnlyUse(Value *V) {
430   return V->hasOneUse() || isa<Constant>(V);
431 }
432
433 // getPromotedType - Return the specified type promoted as it would be to pass
434 // though a va_arg area...
435 static const Type *getPromotedType(const Type *Ty) {
436   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437     if (ITy->getBitWidth() < 32)
438       return Type::Int32Ty;
439   }
440   return Ty;
441 }
442
443 /// getBitCastOperand - If the specified operand is a CastInst, a constant
444 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445 /// operand value, otherwise return null.
446 static Value *getBitCastOperand(Value *V) {
447   if (Operator *O = dyn_cast<Operator>(V)) {
448     if (O->getOpcode() == Instruction::BitCast)
449       return O->getOperand(0);
450     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451       if (GEP->hasAllZeroIndices())
452         return GEP->getPointerOperand();
453   }
454   return 0;
455 }
456
457 /// This function is a wrapper around CastInst::isEliminableCastPair. It
458 /// simply extracts arguments and returns what that function returns.
459 static Instruction::CastOps 
460 isEliminableCastPair(
461   const CastInst *CI, ///< The first cast instruction
462   unsigned opcode,       ///< The opcode of the second cast instruction
463   const Type *DstTy,     ///< The target type for the second cast instruction
464   TargetData *TD         ///< The target data for pointer size
465 ) {
466
467   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
468   const Type *MidTy = CI->getType();                  // B from above
469
470   // Get the opcodes of the two Cast instructions
471   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
474   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
475                                                 DstTy,
476                                                 TD ? TD->getIntPtrType() : 0);
477   
478   // We don't want to form an inttoptr or ptrtoint that converts to an integer
479   // type that differs from the pointer size.
480   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482     Res = 0;
483   
484   return Instruction::CastOps(Res);
485 }
486
487 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488 /// in any code being generated.  It does not require codegen if V is simple
489 /// enough or if the cast can be folded into other casts.
490 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
491                               const Type *Ty, TargetData *TD) {
492   if (V->getType() == Ty || isa<Constant>(V)) return false;
493   
494   // If this is another cast that can be eliminated, it isn't codegen either.
495   if (const CastInst *CI = dyn_cast<CastInst>(V))
496     if (isEliminableCastPair(CI, opcode, Ty, TD))
497       return false;
498   return true;
499 }
500
501 // SimplifyCommutative - This performs a few simplifications for commutative
502 // operators:
503 //
504 //  1. Order operands such that they are listed from right (least complex) to
505 //     left (most complex).  This puts constants before unary operators before
506 //     binary operators.
507 //
508 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510 //
511 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512   bool Changed = false;
513   if (getComplexity(Context, I.getOperand(0)) < 
514       getComplexity(Context, I.getOperand(1)))
515     Changed = !I.swapOperands();
516
517   if (!I.isAssociative()) return Changed;
518   Instruction::BinaryOps Opcode = I.getOpcode();
519   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521       if (isa<Constant>(I.getOperand(1))) {
522         Constant *Folded = ConstantExpr::get(I.getOpcode(),
523                                              cast<Constant>(I.getOperand(1)),
524                                              cast<Constant>(Op->getOperand(1)));
525         I.setOperand(0, Op->getOperand(0));
526         I.setOperand(1, Folded);
527         return true;
528       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530             isOnlyUse(Op) && isOnlyUse(Op1)) {
531           Constant *C1 = cast<Constant>(Op->getOperand(1));
532           Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
535           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
536           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
537                                                     Op1->getOperand(0),
538                                                     Op1->getName(), &I);
539           AddToWorkList(New);
540           I.setOperand(0, New);
541           I.setOperand(1, Folded);
542           return true;
543         }
544     }
545   return Changed;
546 }
547
548 /// SimplifyCompare - For a CmpInst this function just orders the operands
549 /// so that theyare listed from right (least complex) to left (most complex).
550 /// This puts constants before unary operators before binary operators.
551 bool InstCombiner::SimplifyCompare(CmpInst &I) {
552   if (getComplexity(Context, I.getOperand(0)) >=
553       getComplexity(Context, I.getOperand(1)))
554     return false;
555   I.swapOperands();
556   // Compare instructions are not associative so there's nothing else we can do.
557   return true;
558 }
559
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
562 //
563 static inline Value *dyn_castNegVal(Value *V) {
564   if (BinaryOperator::isNeg(V))
565     return BinaryOperator::getNegArgument(V);
566
567   // Constants can be considered to be negated values if they can be folded.
568   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569     return ConstantExpr::getNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return ConstantExpr::getNeg(C);
574
575   return 0;
576 }
577
578 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579 // instruction if the LHS is a constant negative zero (which is the 'negate'
580 // form).
581 //
582 static inline Value *dyn_castFNegVal(Value *V) {
583   if (BinaryOperator::isFNeg(V))
584     return BinaryOperator::getFNegArgument(V);
585
586   // Constants can be considered to be negated values if they can be folded.
587   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
588     return ConstantExpr::getFNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isFloatingPoint())
592       return ConstantExpr::getFNeg(C);
593
594   return 0;
595 }
596
597 static inline Value *dyn_castNotVal(Value *V) {
598   if (BinaryOperator::isNot(V))
599     return BinaryOperator::getNotArgument(V);
600
601   // Constants can be considered to be not'ed values...
602   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
603     return ConstantInt::get(C->getType(), ~C->getValue());
604   return 0;
605 }
606
607 // dyn_castFoldableMul - If this value is a multiply that can be folded into
608 // other computations (because it has a constant operand), return the
609 // non-constant operand of the multiply, and set CST to point to the multiplier.
610 // Otherwise, return null.
611 //
612 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
613   if (V->hasOneUse() && V->getType()->isInteger())
614     if (Instruction *I = dyn_cast<Instruction>(V)) {
615       if (I->getOpcode() == Instruction::Mul)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617           return I->getOperand(0);
618       if (I->getOpcode() == Instruction::Shl)
619         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620           // The multiplier is really 1 << CST.
621           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
623           CST = ConstantInt::get(V->getType()->getContext(),
624                                  APInt(BitWidth, 1).shl(CSTVal));
625           return I->getOperand(0);
626         }
627     }
628   return 0;
629 }
630
631 /// AddOne - Add one to a ConstantInt
632 static Constant *AddOne(Constant *C) {
633   return ConstantExpr::getAdd(C, 
634     ConstantInt::get(C->getType(), 1));
635 }
636 /// SubOne - Subtract one from a ConstantInt
637 static Constant *SubOne(ConstantInt *C) {
638   return ConstantExpr::getSub(C, 
639     ConstantInt::get(C->getType(), 1));
640 }
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
642 /// this size.
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644   uint32_t W = C1->getBitWidth();
645   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646   if (sign) {
647     LHSExt.sext(W * 2);
648     RHSExt.sext(W * 2);
649   } else {
650     LHSExt.zext(W * 2);
651     RHSExt.zext(W * 2);
652   }
653
654   APInt MulExt = LHSExt * RHSExt;
655
656   if (sign) {
657     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659     return MulExt.slt(Min) || MulExt.sgt(Max);
660   } else 
661     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662 }
663
664
665 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
666 /// specified instruction is a constant integer.  If so, check to see if there
667 /// are any bits set in the constant that are not demanded.  If so, shrink the
668 /// constant and return true.
669 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
670                                    APInt Demanded) {
671   assert(I && "No instruction?");
672   assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674   // If the operand is not a constant integer, nothing to do.
675   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676   if (!OpC) return false;
677
678   // If there are no bits set that aren't demanded, nothing to do.
679   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680   if ((~Demanded & OpC->getValue()) == 0)
681     return false;
682
683   // This instruction is producing bits that are not demanded. Shrink the RHS.
684   Demanded &= OpC->getValue();
685   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
686   return true;
687 }
688
689 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
690 // set of known zero and one bits, compute the maximum and minimum values that
691 // could have the specified known zero and known one bits, returning them in
692 // min/max.
693 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
694                                                    const APInt& KnownOne,
695                                                    APInt& Min, APInt& Max) {
696   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697          KnownZero.getBitWidth() == Min.getBitWidth() &&
698          KnownZero.getBitWidth() == Max.getBitWidth() &&
699          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
700   APInt UnknownBits = ~(KnownZero|KnownOne);
701
702   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703   // bit if it is unknown.
704   Min = KnownOne;
705   Max = KnownOne|UnknownBits;
706   
707   if (UnknownBits.isNegative()) { // Sign bit is unknown
708     Min.set(Min.getBitWidth()-1);
709     Max.clear(Max.getBitWidth()-1);
710   }
711 }
712
713 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714 // a set of known zero and one bits, compute the maximum and minimum values that
715 // could have the specified known zero and known one bits, returning them in
716 // min/max.
717 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
718                                                      const APInt &KnownOne,
719                                                      APInt &Min, APInt &Max) {
720   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721          KnownZero.getBitWidth() == Min.getBitWidth() &&
722          KnownZero.getBitWidth() == Max.getBitWidth() &&
723          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724   APInt UnknownBits = ~(KnownZero|KnownOne);
725   
726   // The minimum value is when the unknown bits are all zeros.
727   Min = KnownOne;
728   // The maximum value is when the unknown bits are all ones.
729   Max = KnownOne|UnknownBits;
730 }
731
732 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733 /// SimplifyDemandedBits knows about.  See if the instruction has any
734 /// properties that allow us to simplify its operands.
735 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
736   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
737   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739   
740   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
741                                      KnownZero, KnownOne, 0);
742   if (V == 0) return false;
743   if (V == &Inst) return true;
744   ReplaceInstUsesWith(Inst, V);
745   return true;
746 }
747
748 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749 /// specified instruction operand if possible, updating it in place.  It returns
750 /// true if it made any change and false otherwise.
751 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
752                                         APInt &KnownZero, APInt &KnownOne,
753                                         unsigned Depth) {
754   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755                                           KnownZero, KnownOne, Depth);
756   if (NewVal == 0) return false;
757   U.set(NewVal);
758   return true;
759 }
760
761
762 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763 /// value based on the demanded bits.  When this function is called, it is known
764 /// that only the bits set in DemandedMask of the result of V are ever used
765 /// downstream. Consequently, depending on the mask and V, it may be possible
766 /// to replace V with a constant or one of its operands. In such cases, this
767 /// function does the replacement and returns true. In all other cases, it
768 /// returns false after analyzing the expression and setting KnownOne and known
769 /// to be one in the expression.  KnownZero contains all the bits that are known
770 /// to be zero in the expression. These are provided to potentially allow the
771 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772 /// the expression. KnownOne and KnownZero always follow the invariant that 
773 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
775 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776 /// and KnownOne must all be the same.
777 ///
778 /// This returns null if it did not change anything and it permits no
779 /// simplification.  This returns V itself if it did some simplification of V's
780 /// operands based on the information about what bits are demanded. This returns
781 /// some other non-null value if it found out that V is equal to another value
782 /// in the context where the specified bits are demanded, but not for all users.
783 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784                                              APInt &KnownZero, APInt &KnownOne,
785                                              unsigned Depth) {
786   assert(V != 0 && "Null pointer of Value???");
787   assert(Depth <= 6 && "Limit Search Depth");
788   uint32_t BitWidth = DemandedMask.getBitWidth();
789   const Type *VTy = V->getType();
790   assert((TD || !isa<PointerType>(VTy)) &&
791          "SimplifyDemandedBits needs to know bit widths!");
792   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793          (!VTy->isIntOrIntVector() ||
794           VTy->getScalarSizeInBits() == BitWidth) &&
795          KnownZero.getBitWidth() == BitWidth &&
796          KnownOne.getBitWidth() == BitWidth &&
797          "Value *V, DemandedMask, KnownZero and KnownOne "
798          "must have same BitWidth");
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getValue() & DemandedMask;
802     KnownZero = ~KnownOne & DemandedMask;
803     return 0;
804   }
805   if (isa<ConstantPointerNull>(V)) {
806     // We know all of the bits for a constant!
807     KnownOne.clear();
808     KnownZero = DemandedMask;
809     return 0;
810   }
811
812   KnownZero.clear();
813   KnownOne.clear();
814   if (DemandedMask == 0) {   // Not demanding any bits from V.
815     if (isa<UndefValue>(V))
816       return 0;
817     return UndefValue::get(VTy);
818   }
819   
820   if (Depth == 6)        // Limit search depth.
821     return 0;
822   
823   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
826   Instruction *I = dyn_cast<Instruction>(V);
827   if (!I) {
828     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829     return 0;        // Only analyze instructions.
830   }
831
832   // If there are multiple uses of this value and we aren't at the root, then
833   // we can't do any simplifications of the operands, because DemandedMask
834   // only reflects the bits demanded by *one* of the users.
835   if (Depth != 0 && !I->hasOneUse()) {
836     // Despite the fact that we can't simplify this instruction in all User's
837     // context, we can at least compute the knownzero/knownone bits, and we can
838     // do simplifications that apply to *just* the one user if we know that
839     // this instruction has a simpler value in that context.
840     if (I->getOpcode() == Instruction::And) {
841       // If either the LHS or the RHS are Zero, the result is zero.
842       ComputeMaskedBits(I->getOperand(1), DemandedMask,
843                         RHSKnownZero, RHSKnownOne, Depth+1);
844       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845                         LHSKnownZero, LHSKnownOne, Depth+1);
846       
847       // If all of the demanded bits are known 1 on one side, return the other.
848       // These bits cannot contribute to the result of the 'and' in this
849       // context.
850       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
851           (DemandedMask & ~LHSKnownZero))
852         return I->getOperand(0);
853       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
854           (DemandedMask & ~RHSKnownZero))
855         return I->getOperand(1);
856       
857       // If all of the demanded bits in the inputs are known zeros, return zero.
858       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
859         return Constant::getNullValue(VTy);
860       
861     } else if (I->getOpcode() == Instruction::Or) {
862       // We can simplify (X|Y) -> X or Y in the user's context if we know that
863       // only bits from X or Y are demanded.
864       
865       // If either the LHS or the RHS are One, the result is One.
866       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
867                         RHSKnownZero, RHSKnownOne, Depth+1);
868       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
869                         LHSKnownZero, LHSKnownOne, Depth+1);
870       
871       // If all of the demanded bits are known zero on one side, return the
872       // other.  These bits cannot contribute to the result of the 'or' in this
873       // context.
874       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
875           (DemandedMask & ~LHSKnownOne))
876         return I->getOperand(0);
877       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
878           (DemandedMask & ~RHSKnownOne))
879         return I->getOperand(1);
880       
881       // If all of the potentially set bits on one side are known to be set on
882       // the other side, just use the 'other' side.
883       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
884           (DemandedMask & (~RHSKnownZero)))
885         return I->getOperand(0);
886       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
887           (DemandedMask & (~LHSKnownZero)))
888         return I->getOperand(1);
889     }
890     
891     // Compute the KnownZero/KnownOne bits to simplify things downstream.
892     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893     return 0;
894   }
895   
896   // If this is the root being simplified, allow it to have multiple uses,
897   // just set the DemandedMask to all bits so that we can try to simplify the
898   // operands.  This allows visitTruncInst (for example) to simplify the
899   // operand of a trunc without duplicating all the logic below.
900   if (Depth == 0 && !V->hasOneUse())
901     DemandedMask = APInt::getAllOnesValue(BitWidth);
902   
903   switch (I->getOpcode()) {
904   default:
905     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
906     break;
907   case Instruction::And:
908     // If either the LHS or the RHS are Zero, the result is zero.
909     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910                              RHSKnownZero, RHSKnownOne, Depth+1) ||
911         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
912                              LHSKnownZero, LHSKnownOne, Depth+1))
913       return I;
914     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
915     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
916
917     // If all of the demanded bits are known 1 on one side, return the other.
918     // These bits cannot contribute to the result of the 'and'.
919     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
920         (DemandedMask & ~LHSKnownZero))
921       return I->getOperand(0);
922     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
923         (DemandedMask & ~RHSKnownZero))
924       return I->getOperand(1);
925     
926     // If all of the demanded bits in the inputs are known zeros, return zero.
927     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
928       return Constant::getNullValue(VTy);
929       
930     // If the RHS is a constant, see if we can simplify it.
931     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
932       return I;
933       
934     // Output known-1 bits are only known if set in both the LHS & RHS.
935     RHSKnownOne &= LHSKnownOne;
936     // Output known-0 are known to be clear if zero in either the LHS | RHS.
937     RHSKnownZero |= LHSKnownZero;
938     break;
939   case Instruction::Or:
940     // If either the LHS or the RHS are One, the result is One.
941     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
942                              RHSKnownZero, RHSKnownOne, Depth+1) ||
943         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
944                              LHSKnownZero, LHSKnownOne, Depth+1))
945       return I;
946     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
947     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
948     
949     // If all of the demanded bits are known zero on one side, return the other.
950     // These bits cannot contribute to the result of the 'or'.
951     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
952         (DemandedMask & ~LHSKnownOne))
953       return I->getOperand(0);
954     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
955         (DemandedMask & ~RHSKnownOne))
956       return I->getOperand(1);
957
958     // If all of the potentially set bits on one side are known to be set on
959     // the other side, just use the 'other' side.
960     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
961         (DemandedMask & (~RHSKnownZero)))
962       return I->getOperand(0);
963     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
964         (DemandedMask & (~LHSKnownZero)))
965       return I->getOperand(1);
966         
967     // If the RHS is a constant, see if we can simplify it.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask))
969       return I;
970           
971     // Output known-0 bits are only known if clear in both the LHS & RHS.
972     RHSKnownZero &= LHSKnownZero;
973     // Output known-1 are known to be set if set in either the LHS | RHS.
974     RHSKnownOne |= LHSKnownOne;
975     break;
976   case Instruction::Xor: {
977     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978                              RHSKnownZero, RHSKnownOne, Depth+1) ||
979         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return I;
982     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
983     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
984     
985     // If all of the demanded bits are known zero on one side, return the other.
986     // These bits cannot contribute to the result of the 'xor'.
987     if ((DemandedMask & RHSKnownZero) == DemandedMask)
988       return I->getOperand(0);
989     if ((DemandedMask & LHSKnownZero) == DemandedMask)
990       return I->getOperand(1);
991     
992     // Output known-0 bits are known if clear or set in both the LHS & RHS.
993     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
994                          (RHSKnownOne & LHSKnownOne);
995     // Output known-1 are known to be set if set in only one of the LHS, RHS.
996     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
997                         (RHSKnownOne & LHSKnownZero);
998     
999     // If all of the demanded bits are known to be zero on one side or the
1000     // other, turn this into an *inclusive* or.
1001     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003       Instruction *Or =
1004         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1005                                  I->getName());
1006       return InsertNewInstBefore(Or, *I);
1007     }
1008     
1009     // If all of the demanded bits on one side are known, and all of the set
1010     // bits on that side are also known to be set on the other side, turn this
1011     // into an AND, as we know the bits will be cleared.
1012     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1014       // all known
1015       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1016         Constant *AndC = Constant::getIntegerValue(VTy,
1017                                                    ~RHSKnownOne & DemandedMask);
1018         Instruction *And = 
1019           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1020         return InsertNewInstBefore(And, *I);
1021       }
1022     }
1023     
1024     // If the RHS is a constant, see if we can simplify it.
1025     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1026     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1027       return I;
1028     
1029     RHSKnownZero = KnownZeroOut;
1030     RHSKnownOne  = KnownOneOut;
1031     break;
1032   }
1033   case Instruction::Select:
1034     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1036         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1037                              LHSKnownZero, LHSKnownOne, Depth+1))
1038       return I;
1039     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1040     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1041     
1042     // If the operands are constants, see if we can simplify them.
1043     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044         ShrinkDemandedConstant(I, 2, DemandedMask))
1045       return I;
1046     
1047     // Only known if known in both the LHS and RHS.
1048     RHSKnownOne &= LHSKnownOne;
1049     RHSKnownZero &= LHSKnownZero;
1050     break;
1051   case Instruction::Trunc: {
1052     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1053     DemandedMask.zext(truncBf);
1054     RHSKnownZero.zext(truncBf);
1055     RHSKnownOne.zext(truncBf);
1056     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1057                              RHSKnownZero, RHSKnownOne, Depth+1))
1058       return I;
1059     DemandedMask.trunc(BitWidth);
1060     RHSKnownZero.trunc(BitWidth);
1061     RHSKnownOne.trunc(BitWidth);
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     break;
1064   }
1065   case Instruction::BitCast:
1066     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1067       return false;  // vector->int or fp->int?
1068
1069     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070       if (const VectorType *SrcVTy =
1071             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073           // Don't touch a bitcast between vectors of different element counts.
1074           return false;
1075       } else
1076         // Don't touch a scalar-to-vector bitcast.
1077         return false;
1078     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079       // Don't touch a vector-to-scalar bitcast.
1080       return false;
1081
1082     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1083                              RHSKnownZero, RHSKnownOne, Depth+1))
1084       return I;
1085     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1086     break;
1087   case Instruction::ZExt: {
1088     // Compute the bits in the result that are not present in the input.
1089     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1090     
1091     DemandedMask.trunc(SrcBitWidth);
1092     RHSKnownZero.trunc(SrcBitWidth);
1093     RHSKnownOne.trunc(SrcBitWidth);
1094     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1095                              RHSKnownZero, RHSKnownOne, Depth+1))
1096       return I;
1097     DemandedMask.zext(BitWidth);
1098     RHSKnownZero.zext(BitWidth);
1099     RHSKnownOne.zext(BitWidth);
1100     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1101     // The top bits are known to be zero.
1102     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1103     break;
1104   }
1105   case Instruction::SExt: {
1106     // Compute the bits in the result that are not present in the input.
1107     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1108     
1109     APInt InputDemandedBits = DemandedMask & 
1110                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1111
1112     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1113     // If any of the sign extended bits are demanded, we know that the sign
1114     // bit is demanded.
1115     if ((NewBits & DemandedMask) != 0)
1116       InputDemandedBits.set(SrcBitWidth-1);
1117       
1118     InputDemandedBits.trunc(SrcBitWidth);
1119     RHSKnownZero.trunc(SrcBitWidth);
1120     RHSKnownOne.trunc(SrcBitWidth);
1121     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1122                              RHSKnownZero, RHSKnownOne, Depth+1))
1123       return I;
1124     InputDemandedBits.zext(BitWidth);
1125     RHSKnownZero.zext(BitWidth);
1126     RHSKnownOne.zext(BitWidth);
1127     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1128       
1129     // If the sign bit of the input is known set or clear, then we know the
1130     // top bits of the result.
1131
1132     // If the input sign bit is known zero, or if the NewBits are not demanded
1133     // convert this into a zero extension.
1134     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1135       // Convert to ZExt cast
1136       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137       return InsertNewInstBefore(NewCast, *I);
1138     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1139       RHSKnownOne |= NewBits;
1140     }
1141     break;
1142   }
1143   case Instruction::Add: {
1144     // Figure out what the input bits are.  If the top bits of the and result
1145     // are not demanded, then the add doesn't demand them from its input
1146     // either.
1147     unsigned NLZ = DemandedMask.countLeadingZeros();
1148       
1149     // If there is a constant on the RHS, there are a variety of xformations
1150     // we can do.
1151     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152       // If null, this should be simplified elsewhere.  Some of the xforms here
1153       // won't work if the RHS is zero.
1154       if (RHS->isZero())
1155         break;
1156       
1157       // If the top bit of the output is demanded, demand everything from the
1158       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1159       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1160
1161       // Find information about known zero/one bits in the input.
1162       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1163                                LHSKnownZero, LHSKnownOne, Depth+1))
1164         return I;
1165
1166       // If the RHS of the add has bits set that can't affect the input, reduce
1167       // the constant.
1168       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1169         return I;
1170       
1171       // Avoid excess work.
1172       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173         break;
1174       
1175       // Turn it into OR if input bits are zero.
1176       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177         Instruction *Or =
1178           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1179                                    I->getName());
1180         return InsertNewInstBefore(Or, *I);
1181       }
1182       
1183       // We can say something about the output known-zero and known-one bits,
1184       // depending on potential carries from the input constant and the
1185       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1186       // bits set and the RHS constant is 0x01001, then we know we have a known
1187       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188       
1189       // To compute this, we first compute the potential carry bits.  These are
1190       // the bits which may be modified.  I'm not aware of a better way to do
1191       // this scan.
1192       const APInt &RHSVal = RHS->getValue();
1193       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1194       
1195       // Now that we know which bits have carries, compute the known-1/0 sets.
1196       
1197       // Bits are known one if they are known zero in one operand and one in the
1198       // other, and there is no input carry.
1199       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1200                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201       
1202       // Bits are known zero if they are known zero in both operands and there
1203       // is no input carry.
1204       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205     } else {
1206       // If the high-bits of this ADD are not demanded, then it does not demand
1207       // the high bits of its LHS or RHS.
1208       if (DemandedMask[BitWidth-1] == 0) {
1209         // Right fill the mask of bits for this ADD to demand the most
1210         // significant bit and all those below it.
1211         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1212         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1214             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1215                                  LHSKnownZero, LHSKnownOne, Depth+1))
1216           return I;
1217       }
1218     }
1219     break;
1220   }
1221   case Instruction::Sub:
1222     // If the high-bits of this SUB are not demanded, then it does not demand
1223     // the high bits of its LHS or RHS.
1224     if (DemandedMask[BitWidth-1] == 0) {
1225       // Right fill the mask of bits for this SUB to demand the most
1226       // significant bit and all those below it.
1227       uint32_t NLZ = DemandedMask.countLeadingZeros();
1228       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1229       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1231           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1232                                LHSKnownZero, LHSKnownOne, Depth+1))
1233         return I;
1234     }
1235     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236     // the known zeros and ones.
1237     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1238     break;
1239   case Instruction::Shl:
1240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1243       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1244                                RHSKnownZero, RHSKnownOne, Depth+1))
1245         return I;
1246       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1247       RHSKnownZero <<= ShiftAmt;
1248       RHSKnownOne  <<= ShiftAmt;
1249       // low bits known zero.
1250       if (ShiftAmt)
1251         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1252     }
1253     break;
1254   case Instruction::LShr:
1255     // For a logical shift right
1256     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1258       
1259       // Unsigned shift right.
1260       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1261       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1262                                RHSKnownZero, RHSKnownOne, Depth+1))
1263         return I;
1264       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1265       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1267       if (ShiftAmt) {
1268         // Compute the new bits that are at the top now.
1269         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1270         RHSKnownZero |= HighBits;  // high bits known zero.
1271       }
1272     }
1273     break;
1274   case Instruction::AShr:
1275     // If this is an arithmetic shift right and only the low-bit is set, we can
1276     // always convert this into a logical shr, even if the shift amount is
1277     // variable.  The low bit of the shift cannot be an input sign bit unless
1278     // the shift amount is >= the size of the datatype, which is undefined.
1279     if (DemandedMask == 1) {
1280       // Perform the logical shift right.
1281       Instruction *NewVal = BinaryOperator::CreateLShr(
1282                         I->getOperand(0), I->getOperand(1), I->getName());
1283       return InsertNewInstBefore(NewVal, *I);
1284     }    
1285
1286     // If the sign bit is the only bit demanded by this ashr, then there is no
1287     // need to do it, the shift doesn't change the high bit.
1288     if (DemandedMask.isSignBit())
1289       return I->getOperand(0);
1290     
1291     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1293       
1294       // Signed shift right.
1295       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1296       // If any of the "high bits" are demanded, we should set the sign bit as
1297       // demanded.
1298       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299         DemandedMaskIn.set(BitWidth-1);
1300       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1301                                RHSKnownZero, RHSKnownOne, Depth+1))
1302         return I;
1303       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1304       // Compute the new bits that are at the top now.
1305       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1306       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308         
1309       // Handle the sign bits.
1310       APInt SignBit(APInt::getSignBit(BitWidth));
1311       // Adjust to where it is now in the mask.
1312       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1313         
1314       // If the input sign bit is known to be zero, or if none of the top bits
1315       // are demanded, turn this into an unsigned shift right.
1316       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1317           (HighBits & ~DemandedMask) == HighBits) {
1318         // Perform the logical shift right.
1319         Instruction *NewVal = BinaryOperator::CreateLShr(
1320                           I->getOperand(0), SA, I->getName());
1321         return InsertNewInstBefore(NewVal, *I);
1322       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323         RHSKnownOne |= HighBits;
1324       }
1325     }
1326     break;
1327   case Instruction::SRem:
1328     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329       APInt RA = Rem->getValue().abs();
1330       if (RA.isPowerOf2()) {
1331         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1332           return I->getOperand(0);
1333
1334         APInt LowBits = RA - 1;
1335         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1336         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1337                                  LHSKnownZero, LHSKnownOne, Depth+1))
1338           return I;
1339
1340         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341           LHSKnownZero |= ~LowBits;
1342
1343         KnownZero |= LHSKnownZero & DemandedMask;
1344
1345         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1346       }
1347     }
1348     break;
1349   case Instruction::URem: {
1350     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1352     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353                              KnownZero2, KnownOne2, Depth+1) ||
1354         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1355                              KnownZero2, KnownOne2, Depth+1))
1356       return I;
1357
1358     unsigned Leaders = KnownZero2.countLeadingOnes();
1359     Leaders = std::max(Leaders,
1360                        KnownZero2.countLeadingOnes());
1361     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1362     break;
1363   }
1364   case Instruction::Call:
1365     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366       switch (II->getIntrinsicID()) {
1367       default: break;
1368       case Intrinsic::bswap: {
1369         // If the only bits demanded come from one byte of the bswap result,
1370         // just shift the input byte into position to eliminate the bswap.
1371         unsigned NLZ = DemandedMask.countLeadingZeros();
1372         unsigned NTZ = DemandedMask.countTrailingZeros();
1373           
1374         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1375         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1376         // have 14 leading zeros, round to 8.
1377         NLZ &= ~7;
1378         NTZ &= ~7;
1379         // If we need exactly one byte, we can do this transformation.
1380         if (BitWidth-NLZ-NTZ == 8) {
1381           unsigned ResultBit = NTZ;
1382           unsigned InputBit = BitWidth-NTZ-8;
1383           
1384           // Replace this with either a left or right shift to get the byte into
1385           // the right place.
1386           Instruction *NewVal;
1387           if (InputBit > ResultBit)
1388             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1389                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1390           else
1391             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1392                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1393           NewVal->takeName(I);
1394           return InsertNewInstBefore(NewVal, *I);
1395         }
1396           
1397         // TODO: Could compute known zero/one bits based on the input.
1398         break;
1399       }
1400       }
1401     }
1402     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1403     break;
1404   }
1405   
1406   // If the client is only demanding bits that we know, return the known
1407   // constant.
1408   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409     return Constant::getIntegerValue(VTy, RHSKnownOne);
1410   return false;
1411 }
1412
1413
1414 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1415 /// any number of elements. DemandedElts contains the set of elements that are
1416 /// actually used by the caller.  This method analyzes which elements of the
1417 /// operand are undef and returns that information in UndefElts.
1418 ///
1419 /// If the information about demanded elements can be used to simplify the
1420 /// operation, the operation is simplified, then the resultant value is
1421 /// returned.  This returns null if no change was made.
1422 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423                                                 APInt& UndefElts,
1424                                                 unsigned Depth) {
1425   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1426   APInt EltMask(APInt::getAllOnesValue(VWidth));
1427   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1428
1429   if (isa<UndefValue>(V)) {
1430     // If the entire vector is undefined, just return this info.
1431     UndefElts = EltMask;
1432     return 0;
1433   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434     UndefElts = EltMask;
1435     return UndefValue::get(V->getType());
1436   }
1437
1438   UndefElts = 0;
1439   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1441     Constant *Undef = UndefValue::get(EltTy);
1442
1443     std::vector<Constant*> Elts;
1444     for (unsigned i = 0; i != VWidth; ++i)
1445       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1446         Elts.push_back(Undef);
1447         UndefElts.set(i);
1448       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1449         Elts.push_back(Undef);
1450         UndefElts.set(i);
1451       } else {                               // Otherwise, defined.
1452         Elts.push_back(CP->getOperand(i));
1453       }
1454
1455     // If we changed the constant, return it.
1456     Constant *NewCP = ConstantVector::get(Elts);
1457     return NewCP != CP ? NewCP : 0;
1458   } else if (isa<ConstantAggregateZero>(V)) {
1459     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1460     // set to undef.
1461     
1462     // Check if this is identity. If so, return 0 since we are not simplifying
1463     // anything.
1464     if (DemandedElts == ((1ULL << VWidth) -1))
1465       return 0;
1466     
1467     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1468     Constant *Zero = Constant::getNullValue(EltTy);
1469     Constant *Undef = UndefValue::get(EltTy);
1470     std::vector<Constant*> Elts;
1471     for (unsigned i = 0; i != VWidth; ++i) {
1472       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473       Elts.push_back(Elt);
1474     }
1475     UndefElts = DemandedElts ^ EltMask;
1476     return ConstantVector::get(Elts);
1477   }
1478   
1479   // Limit search depth.
1480   if (Depth == 10)
1481     return 0;
1482
1483   // If multiple users are using the root value, procede with
1484   // simplification conservatively assuming that all elements
1485   // are needed.
1486   if (!V->hasOneUse()) {
1487     // Quit if we find multiple users of a non-root value though.
1488     // They'll be handled when it's their turn to be visited by
1489     // the main instcombine process.
1490     if (Depth != 0)
1491       // TODO: Just compute the UndefElts information recursively.
1492       return 0;
1493
1494     // Conservatively assume that all elements are needed.
1495     DemandedElts = EltMask;
1496   }
1497   
1498   Instruction *I = dyn_cast<Instruction>(V);
1499   if (!I) return 0;        // Only analyze instructions.
1500   
1501   bool MadeChange = false;
1502   APInt UndefElts2(VWidth, 0);
1503   Value *TmpV;
1504   switch (I->getOpcode()) {
1505   default: break;
1506     
1507   case Instruction::InsertElement: {
1508     // If this is a variable index, we don't know which element it overwrites.
1509     // demand exactly the same input as we produce.
1510     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1511     if (Idx == 0) {
1512       // Note that we can't propagate undef elt info, because we don't know
1513       // which elt is getting updated.
1514       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515                                         UndefElts2, Depth+1);
1516       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517       break;
1518     }
1519     
1520     // If this is inserting an element that isn't demanded, remove this
1521     // insertelement.
1522     unsigned IdxNo = Idx->getZExtValue();
1523     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1524       return AddSoonDeadInstToWorklist(*I, 0);
1525     
1526     // Otherwise, the element inserted overwrites whatever was there, so the
1527     // input demanded set is simpler than the output set.
1528     APInt DemandedElts2 = DemandedElts;
1529     DemandedElts2.clear(IdxNo);
1530     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1531                                       UndefElts, Depth+1);
1532     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534     // The inserted element is defined.
1535     UndefElts.clear(IdxNo);
1536     break;
1537   }
1538   case Instruction::ShuffleVector: {
1539     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1540     uint64_t LHSVWidth =
1541       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1542     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1543     for (unsigned i = 0; i < VWidth; i++) {
1544       if (DemandedElts[i]) {
1545         unsigned MaskVal = Shuffle->getMaskValue(i);
1546         if (MaskVal != -1u) {
1547           assert(MaskVal < LHSVWidth * 2 &&
1548                  "shufflevector mask index out of range!");
1549           if (MaskVal < LHSVWidth)
1550             LeftDemanded.set(MaskVal);
1551           else
1552             RightDemanded.set(MaskVal - LHSVWidth);
1553         }
1554       }
1555     }
1556
1557     APInt UndefElts4(LHSVWidth, 0);
1558     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1559                                       UndefElts4, Depth+1);
1560     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
1562     APInt UndefElts3(LHSVWidth, 0);
1563     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564                                       UndefElts3, Depth+1);
1565     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567     bool NewUndefElts = false;
1568     for (unsigned i = 0; i < VWidth; i++) {
1569       unsigned MaskVal = Shuffle->getMaskValue(i);
1570       if (MaskVal == -1u) {
1571         UndefElts.set(i);
1572       } else if (MaskVal < LHSVWidth) {
1573         if (UndefElts4[MaskVal]) {
1574           NewUndefElts = true;
1575           UndefElts.set(i);
1576         }
1577       } else {
1578         if (UndefElts3[MaskVal - LHSVWidth]) {
1579           NewUndefElts = true;
1580           UndefElts.set(i);
1581         }
1582       }
1583     }
1584
1585     if (NewUndefElts) {
1586       // Add additional discovered undefs.
1587       std::vector<Constant*> Elts;
1588       for (unsigned i = 0; i < VWidth; ++i) {
1589         if (UndefElts[i])
1590           Elts.push_back(UndefValue::get(Type::Int32Ty));
1591         else
1592           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1593                                           Shuffle->getMaskValue(i)));
1594       }
1595       I->setOperand(2, ConstantVector::get(Elts));
1596       MadeChange = true;
1597     }
1598     break;
1599   }
1600   case Instruction::BitCast: {
1601     // Vector->vector casts only.
1602     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603     if (!VTy) break;
1604     unsigned InVWidth = VTy->getNumElements();
1605     APInt InputDemandedElts(InVWidth, 0);
1606     unsigned Ratio;
1607
1608     if (VWidth == InVWidth) {
1609       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1610       // elements as are demanded of us.
1611       Ratio = 1;
1612       InputDemandedElts = DemandedElts;
1613     } else if (VWidth > InVWidth) {
1614       // Untested so far.
1615       break;
1616       
1617       // If there are more elements in the result than there are in the source,
1618       // then an input element is live if any of the corresponding output
1619       // elements are live.
1620       Ratio = VWidth/InVWidth;
1621       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1622         if (DemandedElts[OutIdx])
1623           InputDemandedElts.set(OutIdx/Ratio);
1624       }
1625     } else {
1626       // Untested so far.
1627       break;
1628       
1629       // If there are more elements in the source than there are in the result,
1630       // then an input element is live if the corresponding output element is
1631       // live.
1632       Ratio = InVWidth/VWidth;
1633       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1634         if (DemandedElts[InIdx/Ratio])
1635           InputDemandedElts.set(InIdx);
1636     }
1637     
1638     // div/rem demand all inputs, because they don't want divide by zero.
1639     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640                                       UndefElts2, Depth+1);
1641     if (TmpV) {
1642       I->setOperand(0, TmpV);
1643       MadeChange = true;
1644     }
1645     
1646     UndefElts = UndefElts2;
1647     if (VWidth > InVWidth) {
1648       llvm_unreachable("Unimp");
1649       // If there are more elements in the result than there are in the source,
1650       // then an output element is undef if the corresponding input element is
1651       // undef.
1652       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1653         if (UndefElts2[OutIdx/Ratio])
1654           UndefElts.set(OutIdx);
1655     } else if (VWidth < InVWidth) {
1656       llvm_unreachable("Unimp");
1657       // If there are more elements in the source than there are in the result,
1658       // then a result element is undef if all of the corresponding input
1659       // elements are undef.
1660       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1661       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1662         if (!UndefElts2[InIdx])            // Not undef?
1663           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1664     }
1665     break;
1666   }
1667   case Instruction::And:
1668   case Instruction::Or:
1669   case Instruction::Xor:
1670   case Instruction::Add:
1671   case Instruction::Sub:
1672   case Instruction::Mul:
1673     // div/rem demand all inputs, because they don't want divide by zero.
1674     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675                                       UndefElts, Depth+1);
1676     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678                                       UndefElts2, Depth+1);
1679     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680       
1681     // Output elements are undefined if both are undefined.  Consider things
1682     // like undef&0.  The result is known zero, not undef.
1683     UndefElts &= UndefElts2;
1684     break;
1685     
1686   case Instruction::Call: {
1687     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688     if (!II) break;
1689     switch (II->getIntrinsicID()) {
1690     default: break;
1691       
1692     // Binary vector operations that work column-wise.  A dest element is a
1693     // function of the corresponding input elements from the two inputs.
1694     case Intrinsic::x86_sse_sub_ss:
1695     case Intrinsic::x86_sse_mul_ss:
1696     case Intrinsic::x86_sse_min_ss:
1697     case Intrinsic::x86_sse_max_ss:
1698     case Intrinsic::x86_sse2_sub_sd:
1699     case Intrinsic::x86_sse2_mul_sd:
1700     case Intrinsic::x86_sse2_min_sd:
1701     case Intrinsic::x86_sse2_max_sd:
1702       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703                                         UndefElts, Depth+1);
1704       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706                                         UndefElts2, Depth+1);
1707       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709       // If only the low elt is demanded and this is a scalarizable intrinsic,
1710       // scalarize it now.
1711       if (DemandedElts == 1) {
1712         switch (II->getIntrinsicID()) {
1713         default: break;
1714         case Intrinsic::x86_sse_sub_ss:
1715         case Intrinsic::x86_sse_mul_ss:
1716         case Intrinsic::x86_sse2_sub_sd:
1717         case Intrinsic::x86_sse2_mul_sd:
1718           // TODO: Lower MIN/MAX/ABS/etc
1719           Value *LHS = II->getOperand(1);
1720           Value *RHS = II->getOperand(2);
1721           // Extract the element as scalars.
1722           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1723             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1724           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1725             ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
1726           
1727           switch (II->getIntrinsicID()) {
1728           default: llvm_unreachable("Case stmts out of sync!");
1729           case Intrinsic::x86_sse_sub_ss:
1730           case Intrinsic::x86_sse2_sub_sd:
1731             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1732                                                         II->getName()), *II);
1733             break;
1734           case Intrinsic::x86_sse_mul_ss:
1735           case Intrinsic::x86_sse2_mul_sd:
1736             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1737                                                          II->getName()), *II);
1738             break;
1739           }
1740           
1741           Instruction *New =
1742             InsertElementInst::Create(
1743               UndefValue::get(II->getType()), TmpV,
1744               ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
1745           InsertNewInstBefore(New, *II);
1746           AddSoonDeadInstToWorklist(*II, 0);
1747           return New;
1748         }            
1749       }
1750         
1751       // Output elements are undefined if both are undefined.  Consider things
1752       // like undef&0.  The result is known zero, not undef.
1753       UndefElts &= UndefElts2;
1754       break;
1755     }
1756     break;
1757   }
1758   }
1759   return MadeChange ? I : 0;
1760 }
1761
1762
1763 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1764 /// function is designed to check a chain of associative operators for a
1765 /// potential to apply a certain optimization.  Since the optimization may be
1766 /// applicable if the expression was reassociated, this checks the chain, then
1767 /// reassociates the expression as necessary to expose the optimization
1768 /// opportunity.  This makes use of a special Functor, which must define
1769 /// 'shouldApply' and 'apply' methods.
1770 ///
1771 template<typename Functor>
1772 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1773   unsigned Opcode = Root.getOpcode();
1774   Value *LHS = Root.getOperand(0);
1775
1776   // Quick check, see if the immediate LHS matches...
1777   if (F.shouldApply(LHS))
1778     return F.apply(Root);
1779
1780   // Otherwise, if the LHS is not of the same opcode as the root, return.
1781   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1782   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1783     // Should we apply this transform to the RHS?
1784     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786     // If not to the RHS, check to see if we should apply to the LHS...
1787     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1789       ShouldApply = true;
1790     }
1791
1792     // If the functor wants to apply the optimization to the RHS of LHSI,
1793     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794     if (ShouldApply) {
1795       // Now all of the instructions are in the current basic block, go ahead
1796       // and perform the reassociation.
1797       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799       // First move the selected RHS to the LHS of the root...
1800       Root.setOperand(0, LHSI->getOperand(1));
1801
1802       // Make what used to be the LHS of the root be the user of the root...
1803       Value *ExtraOperand = TmpLHSI->getOperand(1);
1804       if (&Root == TmpLHSI) {
1805         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1806         return 0;
1807       }
1808       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1809       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1810       BasicBlock::iterator ARI = &Root; ++ARI;
1811       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1812       ARI = Root;
1813
1814       // Now propagate the ExtraOperand down the chain of instructions until we
1815       // get to LHSI.
1816       while (TmpLHSI != LHSI) {
1817         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1818         // Move the instruction to immediately before the chain we are
1819         // constructing to avoid breaking dominance properties.
1820         NextLHSI->moveBefore(ARI);
1821         ARI = NextLHSI;
1822
1823         Value *NextOp = NextLHSI->getOperand(1);
1824         NextLHSI->setOperand(1, ExtraOperand);
1825         TmpLHSI = NextLHSI;
1826         ExtraOperand = NextOp;
1827       }
1828
1829       // Now that the instructions are reassociated, have the functor perform
1830       // the transformation...
1831       return F.apply(Root);
1832     }
1833
1834     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835   }
1836   return 0;
1837 }
1838
1839 namespace {
1840
1841 // AddRHS - Implements: X + X --> X << 1
1842 struct AddRHS {
1843   Value *RHS;
1844   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1845   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846   Instruction *apply(BinaryOperator &Add) const {
1847     return BinaryOperator::CreateShl(Add.getOperand(0),
1848                                      ConstantInt::get(Add.getType(), 1));
1849   }
1850 };
1851
1852 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853 //                 iff C1&C2 == 0
1854 struct AddMaskingAnd {
1855   Constant *C2;
1856   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1857   bool shouldApply(Value *LHS) const {
1858     ConstantInt *C1;
1859     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1860            ConstantExpr::getAnd(C1, C2)->isNullValue();
1861   }
1862   Instruction *apply(BinaryOperator &Add) const {
1863     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1864   }
1865 };
1866
1867 }
1868
1869 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1870                                              InstCombiner *IC) {
1871   LLVMContext *Context = IC->getContext();
1872   
1873   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1874     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1875   }
1876
1877   // Figure out if the constant is the left or the right argument.
1878   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1879   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1880
1881   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1882     if (ConstIsRHS)
1883       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1884     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1885   }
1886
1887   Value *Op0 = SO, *Op1 = ConstOperand;
1888   if (!ConstIsRHS)
1889     std::swap(Op0, Op1);
1890   Instruction *New;
1891   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1892     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1893   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1894     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1895                           Op0, Op1, SO->getName()+".cmp");
1896   else {
1897     llvm_unreachable("Unknown binary instruction type!");
1898   }
1899   return IC->InsertNewInstBefore(New, I);
1900 }
1901
1902 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1903 // constant as the other operand, try to fold the binary operator into the
1904 // select arguments.  This also works for Cast instructions, which obviously do
1905 // not have a second operand.
1906 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1907                                      InstCombiner *IC) {
1908   // Don't modify shared select instructions
1909   if (!SI->hasOneUse()) return 0;
1910   Value *TV = SI->getOperand(1);
1911   Value *FV = SI->getOperand(2);
1912
1913   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1914     // Bool selects with constant operands can be folded to logical ops.
1915     if (SI->getType() == Type::Int1Ty) return 0;
1916
1917     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1918     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1919
1920     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1921                               SelectFalseVal);
1922   }
1923   return 0;
1924 }
1925
1926
1927 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1928 /// node as operand #0, see if we can fold the instruction into the PHI (which
1929 /// is only possible if all operands to the PHI are constants).
1930 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1931   PHINode *PN = cast<PHINode>(I.getOperand(0));
1932   unsigned NumPHIValues = PN->getNumIncomingValues();
1933   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1934
1935   // Check to see if all of the operands of the PHI are constants.  If there is
1936   // one non-constant value, remember the BB it is.  If there is more than one
1937   // or if *it* is a PHI, bail out.
1938   BasicBlock *NonConstBB = 0;
1939   for (unsigned i = 0; i != NumPHIValues; ++i)
1940     if (!isa<Constant>(PN->getIncomingValue(i))) {
1941       if (NonConstBB) return 0;  // More than one non-const value.
1942       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1943       NonConstBB = PN->getIncomingBlock(i);
1944       
1945       // If the incoming non-constant value is in I's block, we have an infinite
1946       // loop.
1947       if (NonConstBB == I.getParent())
1948         return 0;
1949     }
1950   
1951   // If there is exactly one non-constant value, we can insert a copy of the
1952   // operation in that block.  However, if this is a critical edge, we would be
1953   // inserting the computation one some other paths (e.g. inside a loop).  Only
1954   // do this if the pred block is unconditionally branching into the phi block.
1955   if (NonConstBB) {
1956     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1957     if (!BI || !BI->isUnconditional()) return 0;
1958   }
1959
1960   // Okay, we can do the transformation: create the new PHI node.
1961   PHINode *NewPN = PHINode::Create(I.getType(), "");
1962   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1963   InsertNewInstBefore(NewPN, *PN);
1964   NewPN->takeName(PN);
1965
1966   // Next, add all of the operands to the PHI.
1967   if (I.getNumOperands() == 2) {
1968     Constant *C = cast<Constant>(I.getOperand(1));
1969     for (unsigned i = 0; i != NumPHIValues; ++i) {
1970       Value *InV = 0;
1971       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1972         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1973           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1974         else
1975           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1976       } else {
1977         assert(PN->getIncomingBlock(i) == NonConstBB);
1978         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1979           InV = BinaryOperator::Create(BO->getOpcode(),
1980                                        PN->getIncomingValue(i), C, "phitmp",
1981                                        NonConstBB->getTerminator());
1982         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1984                                 CI->getPredicate(),
1985                                 PN->getIncomingValue(i), C, "phitmp",
1986                                 NonConstBB->getTerminator());
1987         else
1988           llvm_unreachable("Unknown binop!");
1989         
1990         AddToWorkList(cast<Instruction>(InV));
1991       }
1992       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1993     }
1994   } else { 
1995     CastInst *CI = cast<CastInst>(&I);
1996     const Type *RetTy = CI->getType();
1997     for (unsigned i = 0; i != NumPHIValues; ++i) {
1998       Value *InV;
1999       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2000         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2001       } else {
2002         assert(PN->getIncomingBlock(i) == NonConstBB);
2003         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2004                                I.getType(), "phitmp", 
2005                                NonConstBB->getTerminator());
2006         AddToWorkList(cast<Instruction>(InV));
2007       }
2008       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2009     }
2010   }
2011   return ReplaceInstUsesWith(I, NewPN);
2012 }
2013
2014
2015 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2016 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2017 /// This basically requires proving that the add in the original type would not
2018 /// overflow to change the sign bit or have a carry out.
2019 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2020   // There are different heuristics we can use for this.  Here are some simple
2021   // ones.
2022   
2023   // Add has the property that adding any two 2's complement numbers can only 
2024   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2025   // have at least two sign bits, we know that the addition of the two values will
2026   // sign extend fine.
2027   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2028     return true;
2029   
2030   
2031   // If one of the operands only has one non-zero bit, and if the other operand
2032   // has a known-zero bit in a more significant place than it (not including the
2033   // sign bit) the ripple may go up to and fill the zero, but won't change the
2034   // sign.  For example, (X & ~4) + 1.
2035   
2036   // TODO: Implement.
2037   
2038   return false;
2039 }
2040
2041
2042 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2043   bool Changed = SimplifyCommutative(I);
2044   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2045
2046   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2047     // X + undef -> undef
2048     if (isa<UndefValue>(RHS))
2049       return ReplaceInstUsesWith(I, RHS);
2050
2051     // X + 0 --> X
2052     if (RHSC->isNullValue())
2053       return ReplaceInstUsesWith(I, LHS);
2054
2055     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2056       // X + (signbit) --> X ^ signbit
2057       const APInt& Val = CI->getValue();
2058       uint32_t BitWidth = Val.getBitWidth();
2059       if (Val == APInt::getSignBit(BitWidth))
2060         return BinaryOperator::CreateXor(LHS, RHS);
2061       
2062       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2063       // (X & 254)+1 -> (X&254)|1
2064       if (SimplifyDemandedInstructionBits(I))
2065         return &I;
2066
2067       // zext(bool) + C -> bool ? C + 1 : C
2068       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2069         if (ZI->getSrcTy() == Type::Int1Ty)
2070           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2071     }
2072
2073     if (isa<PHINode>(LHS))
2074       if (Instruction *NV = FoldOpIntoPhi(I))
2075         return NV;
2076     
2077     ConstantInt *XorRHS = 0;
2078     Value *XorLHS = 0;
2079     if (isa<ConstantInt>(RHSC) &&
2080         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2081       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2082       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2083       
2084       uint32_t Size = TySizeBits / 2;
2085       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2086       APInt CFF80Val(-C0080Val);
2087       do {
2088         if (TySizeBits > Size) {
2089           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2090           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2091           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2092               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2093             // This is a sign extend if the top bits are known zero.
2094             if (!MaskedValueIsZero(XorLHS, 
2095                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2096               Size = 0;  // Not a sign ext, but can't be any others either.
2097             break;
2098           }
2099         }
2100         Size >>= 1;
2101         C0080Val = APIntOps::lshr(C0080Val, Size);
2102         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2103       } while (Size >= 1);
2104       
2105       // FIXME: This shouldn't be necessary. When the backends can handle types
2106       // with funny bit widths then this switch statement should be removed. It
2107       // is just here to get the size of the "middle" type back up to something
2108       // that the back ends can handle.
2109       const Type *MiddleType = 0;
2110       switch (Size) {
2111         default: break;
2112         case 32: MiddleType = Type::Int32Ty; break;
2113         case 16: MiddleType = Type::Int16Ty; break;
2114         case  8: MiddleType = Type::Int8Ty; break;
2115       }
2116       if (MiddleType) {
2117         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2118         InsertNewInstBefore(NewTrunc, I);
2119         return new SExtInst(NewTrunc, I.getType(), I.getName());
2120       }
2121     }
2122   }
2123
2124   if (I.getType() == Type::Int1Ty)
2125     return BinaryOperator::CreateXor(LHS, RHS);
2126
2127   // X + X --> X << 1
2128   if (I.getType()->isInteger()) {
2129     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2130       return Result;
2131
2132     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2133       if (RHSI->getOpcode() == Instruction::Sub)
2134         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2135           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2136     }
2137     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2138       if (LHSI->getOpcode() == Instruction::Sub)
2139         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2140           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2141     }
2142   }
2143
2144   // -A + B  -->  B - A
2145   // -A + -B  -->  -(A + B)
2146   if (Value *LHSV = dyn_castNegVal(LHS)) {
2147     if (LHS->getType()->isIntOrIntVector()) {
2148       if (Value *RHSV = dyn_castNegVal(RHS)) {
2149         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2150         InsertNewInstBefore(NewAdd, I);
2151         return BinaryOperator::CreateNeg(NewAdd);
2152       }
2153     }
2154     
2155     return BinaryOperator::CreateSub(RHS, LHSV);
2156   }
2157
2158   // A + -B  -->  A - B
2159   if (!isa<Constant>(RHS))
2160     if (Value *V = dyn_castNegVal(RHS))
2161       return BinaryOperator::CreateSub(LHS, V);
2162
2163
2164   ConstantInt *C2;
2165   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2166     if (X == RHS)   // X*C + X --> X * (C+1)
2167       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2168
2169     // X*C1 + X*C2 --> X * (C1+C2)
2170     ConstantInt *C1;
2171     if (X == dyn_castFoldableMul(RHS, C1))
2172       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2173   }
2174
2175   // X + X*C --> X * (C+1)
2176   if (dyn_castFoldableMul(RHS, C2) == LHS)
2177     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2178
2179   // X + ~X --> -1   since   ~X = -X-1
2180   if (dyn_castNotVal(LHS) == RHS ||
2181       dyn_castNotVal(RHS) == LHS)
2182     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2183   
2184
2185   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2186   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2187     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2188       return R;
2189   
2190   // A+B --> A|B iff A and B have no bits set in common.
2191   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2192     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2193     APInt LHSKnownOne(IT->getBitWidth(), 0);
2194     APInt LHSKnownZero(IT->getBitWidth(), 0);
2195     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2196     if (LHSKnownZero != 0) {
2197       APInt RHSKnownOne(IT->getBitWidth(), 0);
2198       APInt RHSKnownZero(IT->getBitWidth(), 0);
2199       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2200       
2201       // No bits in common -> bitwise or.
2202       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2203         return BinaryOperator::CreateOr(LHS, RHS);
2204     }
2205   }
2206
2207   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2208   if (I.getType()->isIntOrIntVector()) {
2209     Value *W, *X, *Y, *Z;
2210     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2211         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2212       if (W != Y) {
2213         if (W == Z) {
2214           std::swap(Y, Z);
2215         } else if (Y == X) {
2216           std::swap(W, X);
2217         } else if (X == Z) {
2218           std::swap(Y, Z);
2219           std::swap(W, X);
2220         }
2221       }
2222
2223       if (W == Y) {
2224         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2225                                                             LHS->getName()), I);
2226         return BinaryOperator::CreateMul(W, NewAdd);
2227       }
2228     }
2229   }
2230
2231   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2232     Value *X = 0;
2233     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2234       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2235
2236     // (X & FF00) + xx00  -> (X+xx00) & FF00
2237     if (LHS->hasOneUse() &&
2238         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2239       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2240       if (Anded == CRHS) {
2241         // See if all bits from the first bit set in the Add RHS up are included
2242         // in the mask.  First, get the rightmost bit.
2243         const APInt& AddRHSV = CRHS->getValue();
2244
2245         // Form a mask of all bits from the lowest bit added through the top.
2246         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2247
2248         // See if the and mask includes all of these bits.
2249         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2250
2251         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2252           // Okay, the xform is safe.  Insert the new add pronto.
2253           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2254                                                             LHS->getName()), I);
2255           return BinaryOperator::CreateAnd(NewAdd, C2);
2256         }
2257       }
2258     }
2259
2260     // Try to fold constant add into select arguments.
2261     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2262       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2263         return R;
2264   }
2265
2266   // add (select X 0 (sub n A)) A  -->  select X A n
2267   {
2268     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2269     Value *A = RHS;
2270     if (!SI) {
2271       SI = dyn_cast<SelectInst>(RHS);
2272       A = LHS;
2273     }
2274     if (SI && SI->hasOneUse()) {
2275       Value *TV = SI->getTrueValue();
2276       Value *FV = SI->getFalseValue();
2277       Value *N;
2278
2279       // Can we fold the add into the argument of the select?
2280       // We check both true and false select arguments for a matching subtract.
2281       if (match(FV, m_Zero()) &&
2282           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2283         // Fold the add into the true select value.
2284         return SelectInst::Create(SI->getCondition(), N, A);
2285       if (match(TV, m_Zero()) &&
2286           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2287         // Fold the add into the false select value.
2288         return SelectInst::Create(SI->getCondition(), A, N);
2289     }
2290   }
2291
2292   // Check for (add (sext x), y), see if we can merge this into an
2293   // integer add followed by a sext.
2294   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2295     // (add (sext x), cst) --> (sext (add x, cst'))
2296     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2297       Constant *CI = 
2298         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2299       if (LHSConv->hasOneUse() &&
2300           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2301           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302         // Insert the new, smaller add.
2303         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2304                                                         CI, "addconv");
2305         InsertNewInstBefore(NewAdd, I);
2306         return new SExtInst(NewAdd, I.getType());
2307       }
2308     }
2309     
2310     // (add (sext x), (sext y)) --> (sext (add int x, y))
2311     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2312       // Only do this if x/y have the same type, if at last one of them has a
2313       // single use (so we don't increase the number of sexts), and if the
2314       // integer add will not overflow.
2315       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318                                    RHSConv->getOperand(0))) {
2319         // Insert the new integer add.
2320         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2321                                                         RHSConv->getOperand(0),
2322                                                         "addconv");
2323         InsertNewInstBefore(NewAdd, I);
2324         return new SExtInst(NewAdd, I.getType());
2325       }
2326     }
2327   }
2328
2329   return Changed ? &I : 0;
2330 }
2331
2332 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2333   bool Changed = SimplifyCommutative(I);
2334   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2335
2336   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2337     // X + 0 --> X
2338     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2339       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2340                               (I.getType())->getValueAPF()))
2341         return ReplaceInstUsesWith(I, LHS);
2342     }
2343
2344     if (isa<PHINode>(LHS))
2345       if (Instruction *NV = FoldOpIntoPhi(I))
2346         return NV;
2347   }
2348
2349   // -A + B  -->  B - A
2350   // -A + -B  -->  -(A + B)
2351   if (Value *LHSV = dyn_castFNegVal(LHS))
2352     return BinaryOperator::CreateFSub(RHS, LHSV);
2353
2354   // A + -B  -->  A - B
2355   if (!isa<Constant>(RHS))
2356     if (Value *V = dyn_castFNegVal(RHS))
2357       return BinaryOperator::CreateFSub(LHS, V);
2358
2359   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2360   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2361     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2362       return ReplaceInstUsesWith(I, LHS);
2363
2364   // Check for (add double (sitofp x), y), see if we can merge this into an
2365   // integer add followed by a promotion.
2366   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2367     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2368     // ... if the constant fits in the integer value.  This is useful for things
2369     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2370     // requires a constant pool load, and generally allows the add to be better
2371     // instcombined.
2372     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2373       Constant *CI = 
2374       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2375       if (LHSConv->hasOneUse() &&
2376           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2377           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2378         // Insert the new integer add.
2379         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2380                                                         CI, "addconv");
2381         InsertNewInstBefore(NewAdd, I);
2382         return new SIToFPInst(NewAdd, I.getType());
2383       }
2384     }
2385     
2386     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2387     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2388       // Only do this if x/y have the same type, if at last one of them has a
2389       // single use (so we don't increase the number of int->fp conversions),
2390       // and if the integer add will not overflow.
2391       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2392           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2393           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2394                                    RHSConv->getOperand(0))) {
2395         // Insert the new integer add.
2396         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2397                                                         RHSConv->getOperand(0),
2398                                                         "addconv");
2399         InsertNewInstBefore(NewAdd, I);
2400         return new SIToFPInst(NewAdd, I.getType());
2401       }
2402     }
2403   }
2404   
2405   return Changed ? &I : 0;
2406 }
2407
2408 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2409   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2410
2411   if (Op0 == Op1)                        // sub X, X  -> 0
2412     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2413
2414   // If this is a 'B = x-(-A)', change to B = x+A...
2415   if (Value *V = dyn_castNegVal(Op1))
2416     return BinaryOperator::CreateAdd(Op0, V);
2417
2418   if (isa<UndefValue>(Op0))
2419     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2420   if (isa<UndefValue>(Op1))
2421     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2422
2423   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424     // Replace (-1 - A) with (~A)...
2425     if (C->isAllOnesValue())
2426       return BinaryOperator::CreateNot(Op1);
2427
2428     // C - ~X == X + (1+C)
2429     Value *X = 0;
2430     if (match(Op1, m_Not(m_Value(X))))
2431       return BinaryOperator::CreateAdd(X, AddOne(C));
2432
2433     // -(X >>u 31) -> (X >>s 31)
2434     // -(X >>s 31) -> (X >>u 31)
2435     if (C->isZero()) {
2436       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2437         if (SI->getOpcode() == Instruction::LShr) {
2438           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439             // Check to see if we are shifting out everything but the sign bit.
2440             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441                 SI->getType()->getPrimitiveSizeInBits()-1) {
2442               // Ok, the transformation is safe.  Insert AShr.
2443               return BinaryOperator::Create(Instruction::AShr, 
2444                                           SI->getOperand(0), CU, SI->getName());
2445             }
2446           }
2447         }
2448         else if (SI->getOpcode() == Instruction::AShr) {
2449           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450             // Check to see if we are shifting out everything but the sign bit.
2451             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452                 SI->getType()->getPrimitiveSizeInBits()-1) {
2453               // Ok, the transformation is safe.  Insert LShr. 
2454               return BinaryOperator::CreateLShr(
2455                                           SI->getOperand(0), CU, SI->getName());
2456             }
2457           }
2458         }
2459       }
2460     }
2461
2462     // Try to fold constant sub into select arguments.
2463     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465         return R;
2466
2467     // C - zext(bool) -> bool ? C - 1 : C
2468     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469       if (ZI->getSrcTy() == Type::Int1Ty)
2470         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2471   }
2472
2473   if (I.getType() == Type::Int1Ty)
2474     return BinaryOperator::CreateXor(Op0, Op1);
2475
2476   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2477     if (Op1I->getOpcode() == Instruction::Add) {
2478       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2479         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2480                                          I.getName());
2481       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2482         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2483                                          I.getName());
2484       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486           // C1-(X+C2) --> (C1-C2)-X
2487           return BinaryOperator::CreateSub(
2488             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2489       }
2490     }
2491
2492     if (Op1I->hasOneUse()) {
2493       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494       // is not used by anyone else...
2495       //
2496       if (Op1I->getOpcode() == Instruction::Sub) {
2497         // Swap the two operands of the subexpr...
2498         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499         Op1I->setOperand(0, IIOp1);
2500         Op1I->setOperand(1, IIOp0);
2501
2502         // Create the new top level add instruction...
2503         return BinaryOperator::CreateAdd(Op0, Op1);
2504       }
2505
2506       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507       //
2508       if (Op1I->getOpcode() == Instruction::And &&
2509           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
2512         Value *NewNot =
2513           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2514         return BinaryOperator::CreateAnd(Op0, NewNot);
2515       }
2516
2517       // 0 - (X sdiv C)  -> (X sdiv -C)
2518       if (Op1I->getOpcode() == Instruction::SDiv)
2519         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2520           if (CSI->isZero())
2521             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2522               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2523                                           ConstantExpr::getNeg(DivRHS));
2524
2525       // X - X*C --> X * (1-C)
2526       ConstantInt *C2 = 0;
2527       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2528         Constant *CP1 = 
2529           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2530                                              C2);
2531         return BinaryOperator::CreateMul(Op0, CP1);
2532       }
2533     }
2534   }
2535
2536   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2537     if (Op0I->getOpcode() == Instruction::Add) {
2538       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2539         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2540       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2541         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2542     } else if (Op0I->getOpcode() == Instruction::Sub) {
2543       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2544         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2545                                          I.getName());
2546     }
2547   }
2548
2549   ConstantInt *C1;
2550   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2551     if (X == Op1)  // X*C - X --> X * (C-1)
2552       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2553
2554     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2555     if (X == dyn_castFoldableMul(Op1, C2))
2556       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2557   }
2558   return 0;
2559 }
2560
2561 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2562   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2563
2564   // If this is a 'B = x-(-A)', change to B = x+A...
2565   if (Value *V = dyn_castFNegVal(Op1))
2566     return BinaryOperator::CreateFAdd(Op0, V);
2567
2568   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2569     if (Op1I->getOpcode() == Instruction::FAdd) {
2570       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2571         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2572                                           I.getName());
2573       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2574         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2575                                           I.getName());
2576     }
2577   }
2578
2579   return 0;
2580 }
2581
2582 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2583 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2584 /// TrueIfSigned if the result of the comparison is true when the input value is
2585 /// signed.
2586 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2587                            bool &TrueIfSigned) {
2588   switch (pred) {
2589   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2590     TrueIfSigned = true;
2591     return RHS->isZero();
2592   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2593     TrueIfSigned = true;
2594     return RHS->isAllOnesValue();
2595   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2596     TrueIfSigned = false;
2597     return RHS->isAllOnesValue();
2598   case ICmpInst::ICMP_UGT:
2599     // True if LHS u> RHS and RHS == high-bit-mask - 1
2600     TrueIfSigned = true;
2601     return RHS->getValue() ==
2602       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2603   case ICmpInst::ICMP_UGE: 
2604     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2605     TrueIfSigned = true;
2606     return RHS->getValue().isSignBit();
2607   default:
2608     return false;
2609   }
2610 }
2611
2612 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2613   bool Changed = SimplifyCommutative(I);
2614   Value *Op0 = I.getOperand(0);
2615
2616   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2617     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2618
2619   // Simplify mul instructions with a constant RHS...
2620   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2621     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2622
2623       // ((X << C1)*C2) == (X * (C2 << C1))
2624       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2625         if (SI->getOpcode() == Instruction::Shl)
2626           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2627             return BinaryOperator::CreateMul(SI->getOperand(0),
2628                                         ConstantExpr::getShl(CI, ShOp));
2629
2630       if (CI->isZero())
2631         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2632       if (CI->equalsInt(1))                  // X * 1  == X
2633         return ReplaceInstUsesWith(I, Op0);
2634       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2635         return BinaryOperator::CreateNeg(Op0, I.getName());
2636
2637       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2638       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2639         return BinaryOperator::CreateShl(Op0,
2640                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2641       }
2642     } else if (isa<VectorType>(Op1->getType())) {
2643       if (Op1->isNullValue())
2644         return ReplaceInstUsesWith(I, Op1);
2645
2646       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2647         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2648           return BinaryOperator::CreateNeg(Op0, I.getName());
2649
2650         // As above, vector X*splat(1.0) -> X in all defined cases.
2651         if (Constant *Splat = Op1V->getSplatValue()) {
2652           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2653             if (CI->equalsInt(1))
2654               return ReplaceInstUsesWith(I, Op0);
2655         }
2656       }
2657     }
2658     
2659     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2660       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2661           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2662         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2663         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2664                                                      Op1, "tmp");
2665         InsertNewInstBefore(Add, I);
2666         Value *C1C2 = ConstantExpr::getMul(Op1, 
2667                                            cast<Constant>(Op0I->getOperand(1)));
2668         return BinaryOperator::CreateAdd(Add, C1C2);
2669         
2670       }
2671
2672     // Try to fold constant mul into select arguments.
2673     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2674       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2675         return R;
2676
2677     if (isa<PHINode>(Op0))
2678       if (Instruction *NV = FoldOpIntoPhi(I))
2679         return NV;
2680   }
2681
2682   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2683     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2684       return BinaryOperator::CreateMul(Op0v, Op1v);
2685
2686   // (X / Y) *  Y = X - (X % Y)
2687   // (X / Y) * -Y = (X % Y) - X
2688   {
2689     Value *Op1 = I.getOperand(1);
2690     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691     if (!BO ||
2692         (BO->getOpcode() != Instruction::UDiv && 
2693          BO->getOpcode() != Instruction::SDiv)) {
2694       Op1 = Op0;
2695       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696     }
2697     Value *Neg = dyn_castNegVal(Op1);
2698     if (BO && BO->hasOneUse() &&
2699         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700         (BO->getOpcode() == Instruction::UDiv ||
2701          BO->getOpcode() == Instruction::SDiv)) {
2702       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
2704       Instruction *Rem;
2705       if (BO->getOpcode() == Instruction::UDiv)
2706         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2707       else
2708         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2709
2710       InsertNewInstBefore(Rem, I);
2711       Rem->takeName(BO);
2712
2713       if (Op1BO == Op1)
2714         return BinaryOperator::CreateSub(Op0BO, Rem);
2715       else
2716         return BinaryOperator::CreateSub(Rem, Op0BO);
2717     }
2718   }
2719
2720   if (I.getType() == Type::Int1Ty)
2721     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2722
2723   // If one of the operands of the multiply is a cast from a boolean value, then
2724   // we know the bool is either zero or one, so this is a 'masking' multiply.
2725   // See if we can simplify things based on how the boolean was originally
2726   // formed.
2727   CastInst *BoolCast = 0;
2728   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2729     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2730       BoolCast = CI;
2731   if (!BoolCast)
2732     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2733       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2734         BoolCast = CI;
2735   if (BoolCast) {
2736     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2737       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2738       const Type *SCOpTy = SCIOp0->getType();
2739       bool TIS = false;
2740       
2741       // If the icmp is true iff the sign bit of X is set, then convert this
2742       // multiply into a shift/and combination.
2743       if (isa<ConstantInt>(SCIOp1) &&
2744           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2745           TIS) {
2746         // Shift the X value right to turn it into "all signbits".
2747         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2748                                           SCOpTy->getPrimitiveSizeInBits()-1);
2749         Value *V =
2750           InsertNewInstBefore(
2751             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2752                                             BoolCast->getOperand(0)->getName()+
2753                                             ".mask"), I);
2754
2755         // If the multiply type is not the same as the source type, sign extend
2756         // or truncate to the multiply type.
2757         if (I.getType() != V->getType()) {
2758           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2759           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2760           Instruction::CastOps opcode = 
2761             (SrcBits == DstBits ? Instruction::BitCast : 
2762              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2763           V = InsertCastBefore(opcode, V, I.getType(), I);
2764         }
2765
2766         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2767         return BinaryOperator::CreateAnd(V, OtherOp);
2768       }
2769     }
2770   }
2771
2772   return Changed ? &I : 0;
2773 }
2774
2775 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2776   bool Changed = SimplifyCommutative(I);
2777   Value *Op0 = I.getOperand(0);
2778
2779   // Simplify mul instructions with a constant RHS...
2780   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2781     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2782       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2783       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2784       if (Op1F->isExactlyValue(1.0))
2785         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2786     } else if (isa<VectorType>(Op1->getType())) {
2787       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2788         // As above, vector X*splat(1.0) -> X in all defined cases.
2789         if (Constant *Splat = Op1V->getSplatValue()) {
2790           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2791             if (F->isExactlyValue(1.0))
2792               return ReplaceInstUsesWith(I, Op0);
2793         }
2794       }
2795     }
2796
2797     // Try to fold constant mul into select arguments.
2798     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2799       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2800         return R;
2801
2802     if (isa<PHINode>(Op0))
2803       if (Instruction *NV = FoldOpIntoPhi(I))
2804         return NV;
2805   }
2806
2807   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2808     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2809       return BinaryOperator::CreateFMul(Op0v, Op1v);
2810
2811   return Changed ? &I : 0;
2812 }
2813
2814 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2815 /// instruction.
2816 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2817   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2818   
2819   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2820   int NonNullOperand = -1;
2821   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2822     if (ST->isNullValue())
2823       NonNullOperand = 2;
2824   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2825   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2826     if (ST->isNullValue())
2827       NonNullOperand = 1;
2828   
2829   if (NonNullOperand == -1)
2830     return false;
2831   
2832   Value *SelectCond = SI->getOperand(0);
2833   
2834   // Change the div/rem to use 'Y' instead of the select.
2835   I.setOperand(1, SI->getOperand(NonNullOperand));
2836   
2837   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2838   // problem.  However, the select, or the condition of the select may have
2839   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2840   // propagate the known value for the select into other uses of it, and
2841   // propagate a known value of the condition into its other users.
2842   
2843   // If the select and condition only have a single use, don't bother with this,
2844   // early exit.
2845   if (SI->use_empty() && SelectCond->hasOneUse())
2846     return true;
2847   
2848   // Scan the current block backward, looking for other uses of SI.
2849   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2850   
2851   while (BBI != BBFront) {
2852     --BBI;
2853     // If we found a call to a function, we can't assume it will return, so
2854     // information from below it cannot be propagated above it.
2855     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2856       break;
2857     
2858     // Replace uses of the select or its condition with the known values.
2859     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2860          I != E; ++I) {
2861       if (*I == SI) {
2862         *I = SI->getOperand(NonNullOperand);
2863         AddToWorkList(BBI);
2864       } else if (*I == SelectCond) {
2865         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2866                                    ConstantInt::getFalse(*Context);
2867         AddToWorkList(BBI);
2868       }
2869     }
2870     
2871     // If we past the instruction, quit looking for it.
2872     if (&*BBI == SI)
2873       SI = 0;
2874     if (&*BBI == SelectCond)
2875       SelectCond = 0;
2876     
2877     // If we ran out of things to eliminate, break out of the loop.
2878     if (SelectCond == 0 && SI == 0)
2879       break;
2880     
2881   }
2882   return true;
2883 }
2884
2885
2886 /// This function implements the transforms on div instructions that work
2887 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2888 /// used by the visitors to those instructions.
2889 /// @brief Transforms common to all three div instructions
2890 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2891   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2892
2893   // undef / X -> 0        for integer.
2894   // undef / X -> undef    for FP (the undef could be a snan).
2895   if (isa<UndefValue>(Op0)) {
2896     if (Op0->getType()->isFPOrFPVector())
2897       return ReplaceInstUsesWith(I, Op0);
2898     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2899   }
2900
2901   // X / undef -> undef
2902   if (isa<UndefValue>(Op1))
2903     return ReplaceInstUsesWith(I, Op1);
2904
2905   return 0;
2906 }
2907
2908 /// This function implements the transforms common to both integer division
2909 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2910 /// division instructions.
2911 /// @brief Common integer divide transforms
2912 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2913   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
2915   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2916   if (Op0 == Op1) {
2917     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2918       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2919       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2920       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2921     }
2922
2923     Constant *CI = ConstantInt::get(I.getType(), 1);
2924     return ReplaceInstUsesWith(I, CI);
2925   }
2926   
2927   if (Instruction *Common = commonDivTransforms(I))
2928     return Common;
2929   
2930   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2931   // This does not apply for fdiv.
2932   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2933     return &I;
2934
2935   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2936     // div X, 1 == X
2937     if (RHS->equalsInt(1))
2938       return ReplaceInstUsesWith(I, Op0);
2939
2940     // (X / C1) / C2  -> X / (C1*C2)
2941     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2942       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2943         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2944           if (MultiplyOverflows(RHS, LHSRHS,
2945                                 I.getOpcode()==Instruction::SDiv))
2946             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2947           else 
2948             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2949                                       ConstantExpr::getMul(RHS, LHSRHS));
2950         }
2951
2952     if (!RHS->isZero()) { // avoid X udiv 0
2953       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2954         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2955           return R;
2956       if (isa<PHINode>(Op0))
2957         if (Instruction *NV = FoldOpIntoPhi(I))
2958           return NV;
2959     }
2960   }
2961
2962   // 0 / X == 0, we don't need to preserve faults!
2963   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2964     if (LHS->equalsInt(0))
2965       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2966
2967   // It can't be division by zero, hence it must be division by one.
2968   if (I.getType() == Type::Int1Ty)
2969     return ReplaceInstUsesWith(I, Op0);
2970
2971   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2972     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2973       // div X, 1 == X
2974       if (X->isOne())
2975         return ReplaceInstUsesWith(I, Op0);
2976   }
2977
2978   return 0;
2979 }
2980
2981 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2982   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2983
2984   // Handle the integer div common cases
2985   if (Instruction *Common = commonIDivTransforms(I))
2986     return Common;
2987
2988   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2989     // X udiv C^2 -> X >> C
2990     // Check to see if this is an unsigned division with an exact power of 2,
2991     // if so, convert to a right shift.
2992     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2993       return BinaryOperator::CreateLShr(Op0, 
2994             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2995
2996     // X udiv C, where C >= signbit
2997     if (C->getValue().isNegative()) {
2998       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
2999                                                     ICmpInst::ICMP_ULT, Op0, C),
3000                                       I);
3001       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3002                                 ConstantInt::get(I.getType(), 1));
3003     }
3004   }
3005
3006   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3007   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3008     if (RHSI->getOpcode() == Instruction::Shl &&
3009         isa<ConstantInt>(RHSI->getOperand(0))) {
3010       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3011       if (C1.isPowerOf2()) {
3012         Value *N = RHSI->getOperand(1);
3013         const Type *NTy = N->getType();
3014         if (uint32_t C2 = C1.logBase2()) {
3015           Constant *C2V = ConstantInt::get(NTy, C2);
3016           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3017         }
3018         return BinaryOperator::CreateLShr(Op0, N);
3019       }
3020     }
3021   }
3022   
3023   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3024   // where C1&C2 are powers of two.
3025   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3026     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3027       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3028         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3029         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3030           // Compute the shift amounts
3031           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3032           // Construct the "on true" case of the select
3033           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3034           Instruction *TSI = BinaryOperator::CreateLShr(
3035                                                  Op0, TC, SI->getName()+".t");
3036           TSI = InsertNewInstBefore(TSI, I);
3037   
3038           // Construct the "on false" case of the select
3039           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3040           Instruction *FSI = BinaryOperator::CreateLShr(
3041                                                  Op0, FC, SI->getName()+".f");
3042           FSI = InsertNewInstBefore(FSI, I);
3043
3044           // construct the select instruction and return it.
3045           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3046         }
3047       }
3048   return 0;
3049 }
3050
3051 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3052   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054   // Handle the integer div common cases
3055   if (Instruction *Common = commonIDivTransforms(I))
3056     return Common;
3057
3058   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3059     // sdiv X, -1 == -X
3060     if (RHS->isAllOnesValue())
3061       return BinaryOperator::CreateNeg(Op0);
3062
3063     // sdiv X, C  --> ashr X, log2(C)
3064     if (cast<SDivOperator>(&I)->isExact() &&
3065         RHS->getValue().isNonNegative() &&
3066         RHS->getValue().isPowerOf2()) {
3067       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3068                                             RHS->getValue().exactLogBase2());
3069       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3070     }
3071   }
3072
3073   // If the sign bits of both operands are zero (i.e. we can prove they are
3074   // unsigned inputs), turn this into a udiv.
3075   if (I.getType()->isInteger()) {
3076     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3077     if (MaskedValueIsZero(Op0, Mask)) {
3078       if (MaskedValueIsZero(Op1, Mask)) {
3079         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3080         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3081       }
3082       ConstantInt *ShiftedInt;
3083       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3084           ShiftedInt->getValue().isPowerOf2()) {
3085         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3086         // Safe because the only negative value (1 << Y) can take on is
3087         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3088         // the sign bit set.
3089         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090       }
3091     }
3092   }
3093   
3094   return 0;
3095 }
3096
3097 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3098   return commonDivTransforms(I);
3099 }
3100
3101 /// This function implements the transforms on rem instructions that work
3102 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3103 /// is used by the visitors to those instructions.
3104 /// @brief Transforms common to all three rem instructions
3105 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3106   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107
3108   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3109     if (I.getType()->isFPOrFPVector())
3110       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3111     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3112   }
3113   if (isa<UndefValue>(Op1))
3114     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3115
3116   // Handle cases involving: rem X, (select Cond, Y, Z)
3117   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3118     return &I;
3119
3120   return 0;
3121 }
3122
3123 /// This function implements the transforms common to both integer remainder
3124 /// instructions (urem and srem). It is called by the visitors to those integer
3125 /// remainder instructions.
3126 /// @brief Common integer remainder transforms
3127 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3128   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3129
3130   if (Instruction *common = commonRemTransforms(I))
3131     return common;
3132
3133   // 0 % X == 0 for integer, we don't need to preserve faults!
3134   if (Constant *LHS = dyn_cast<Constant>(Op0))
3135     if (LHS->isNullValue())
3136       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3137
3138   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3139     // X % 0 == undef, we don't need to preserve faults!
3140     if (RHS->equalsInt(0))
3141       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3142     
3143     if (RHS->equalsInt(1))  // X % 1 == 0
3144       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3145
3146     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3147       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3148         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3149           return R;
3150       } else if (isa<PHINode>(Op0I)) {
3151         if (Instruction *NV = FoldOpIntoPhi(I))
3152           return NV;
3153       }
3154
3155       // See if we can fold away this rem instruction.
3156       if (SimplifyDemandedInstructionBits(I))
3157         return &I;
3158     }
3159   }
3160
3161   return 0;
3162 }
3163
3164 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3165   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167   if (Instruction *common = commonIRemTransforms(I))
3168     return common;
3169   
3170   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3171     // X urem C^2 -> X and C
3172     // Check to see if this is an unsigned remainder with an exact power of 2,
3173     // if so, convert to a bitwise and.
3174     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3175       if (C->getValue().isPowerOf2())
3176         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3177   }
3178
3179   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3180     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3181     if (RHSI->getOpcode() == Instruction::Shl &&
3182         isa<ConstantInt>(RHSI->getOperand(0))) {
3183       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3184         Constant *N1 = Constant::getAllOnesValue(I.getType());
3185         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3186                                                                    "tmp"), I);
3187         return BinaryOperator::CreateAnd(Op0, Add);
3188       }
3189     }
3190   }
3191
3192   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3193   // where C1&C2 are powers of two.
3194   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3195     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3196       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3197         // STO == 0 and SFO == 0 handled above.
3198         if ((STO->getValue().isPowerOf2()) && 
3199             (SFO->getValue().isPowerOf2())) {
3200           Value *TrueAnd = InsertNewInstBefore(
3201             BinaryOperator::CreateAnd(Op0, SubOne(STO),
3202                                       SI->getName()+".t"), I);
3203           Value *FalseAnd = InsertNewInstBefore(
3204             BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3205                                       SI->getName()+".f"), I);
3206           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3207         }
3208       }
3209   }
3210   
3211   return 0;
3212 }
3213
3214 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3215   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3216
3217   // Handle the integer rem common cases
3218   if (Instruction *common = commonIRemTransforms(I))
3219     return common;
3220   
3221   if (Value *RHSNeg = dyn_castNegVal(Op1))
3222     if (!isa<Constant>(RHSNeg) ||
3223         (isa<ConstantInt>(RHSNeg) &&
3224          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3225       // X % -Y -> X % Y
3226       AddUsesToWorkList(I);
3227       I.setOperand(1, RHSNeg);
3228       return &I;
3229     }
3230
3231   // If the sign bits of both operands are zero (i.e. we can prove they are
3232   // unsigned inputs), turn this into a urem.
3233   if (I.getType()->isInteger()) {
3234     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3235     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3236       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3237       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3238     }
3239   }
3240
3241   // If it's a constant vector, flip any negative values positive.
3242   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3243     unsigned VWidth = RHSV->getNumOperands();
3244
3245     bool hasNegative = false;
3246     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3247       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3248         if (RHS->getValue().isNegative())
3249           hasNegative = true;
3250
3251     if (hasNegative) {
3252       std::vector<Constant *> Elts(VWidth);
3253       for (unsigned i = 0; i != VWidth; ++i) {
3254         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3255           if (RHS->getValue().isNegative())
3256             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3257           else
3258             Elts[i] = RHS;
3259         }
3260       }
3261
3262       Constant *NewRHSV = ConstantVector::get(Elts);
3263       if (NewRHSV != RHSV) {
3264         AddUsesToWorkList(I);
3265         I.setOperand(1, NewRHSV);
3266         return &I;
3267       }
3268     }
3269   }
3270
3271   return 0;
3272 }
3273
3274 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3275   return commonRemTransforms(I);
3276 }
3277
3278 // isOneBitSet - Return true if there is exactly one bit set in the specified
3279 // constant.
3280 static bool isOneBitSet(const ConstantInt *CI) {
3281   return CI->getValue().isPowerOf2();
3282 }
3283
3284 // isHighOnes - Return true if the constant is of the form 1+0+.
3285 // This is the same as lowones(~X).
3286 static bool isHighOnes(const ConstantInt *CI) {
3287   return (~CI->getValue() + 1).isPowerOf2();
3288 }
3289
3290 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3291 /// are carefully arranged to allow folding of expressions such as:
3292 ///
3293 ///      (A < B) | (A > B) --> (A != B)
3294 ///
3295 /// Note that this is only valid if the first and second predicates have the
3296 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3297 ///
3298 /// Three bits are used to represent the condition, as follows:
3299 ///   0  A > B
3300 ///   1  A == B
3301 ///   2  A < B
3302 ///
3303 /// <=>  Value  Definition
3304 /// 000     0   Always false
3305 /// 001     1   A >  B
3306 /// 010     2   A == B
3307 /// 011     3   A >= B
3308 /// 100     4   A <  B
3309 /// 101     5   A != B
3310 /// 110     6   A <= B
3311 /// 111     7   Always true
3312 ///  
3313 static unsigned getICmpCode(const ICmpInst *ICI) {
3314   switch (ICI->getPredicate()) {
3315     // False -> 0
3316   case ICmpInst::ICMP_UGT: return 1;  // 001
3317   case ICmpInst::ICMP_SGT: return 1;  // 001
3318   case ICmpInst::ICMP_EQ:  return 2;  // 010
3319   case ICmpInst::ICMP_UGE: return 3;  // 011
3320   case ICmpInst::ICMP_SGE: return 3;  // 011
3321   case ICmpInst::ICMP_ULT: return 4;  // 100
3322   case ICmpInst::ICMP_SLT: return 4;  // 100
3323   case ICmpInst::ICMP_NE:  return 5;  // 101
3324   case ICmpInst::ICMP_ULE: return 6;  // 110
3325   case ICmpInst::ICMP_SLE: return 6;  // 110
3326     // True -> 7
3327   default:
3328     llvm_unreachable("Invalid ICmp predicate!");
3329     return 0;
3330   }
3331 }
3332
3333 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3334 /// predicate into a three bit mask. It also returns whether it is an ordered
3335 /// predicate by reference.
3336 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3337   isOrdered = false;
3338   switch (CC) {
3339   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3340   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3341   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3342   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3343   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3344   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3345   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3346   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3347   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3348   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3349   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3350   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3351   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3352   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3353     // True -> 7
3354   default:
3355     // Not expecting FCMP_FALSE and FCMP_TRUE;
3356     llvm_unreachable("Unexpected FCmp predicate!");
3357     return 0;
3358   }
3359 }
3360
3361 /// getICmpValue - This is the complement of getICmpCode, which turns an
3362 /// opcode and two operands into either a constant true or false, or a brand 
3363 /// new ICmp instruction. The sign is passed in to determine which kind
3364 /// of predicate to use in the new icmp instruction.
3365 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3366                            LLVMContext *Context) {
3367   switch (code) {
3368   default: llvm_unreachable("Illegal ICmp code!");
3369   case  0: return ConstantInt::getFalse(*Context);
3370   case  1: 
3371     if (sign)
3372       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3373     else
3374       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3375   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3376   case  3: 
3377     if (sign)
3378       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3379     else
3380       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3381   case  4: 
3382     if (sign)
3383       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3384     else
3385       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3386   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3387   case  6: 
3388     if (sign)
3389       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3390     else
3391       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3392   case  7: return ConstantInt::getTrue(*Context);
3393   }
3394 }
3395
3396 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3397 /// opcode and two operands into either a FCmp instruction. isordered is passed
3398 /// in to determine which kind of predicate to use in the new fcmp instruction.
3399 static Value *getFCmpValue(bool isordered, unsigned code,
3400                            Value *LHS, Value *RHS, LLVMContext *Context) {
3401   switch (code) {
3402   default: llvm_unreachable("Illegal FCmp code!");
3403   case  0:
3404     if (isordered)
3405       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3406     else
3407       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3408   case  1: 
3409     if (isordered)
3410       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3411     else
3412       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3413   case  2: 
3414     if (isordered)
3415       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3416     else
3417       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3418   case  3: 
3419     if (isordered)
3420       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3421     else
3422       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3423   case  4: 
3424     if (isordered)
3425       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3426     else
3427       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3428   case  5: 
3429     if (isordered)
3430       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3431     else
3432       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3433   case  6: 
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3438   case  7: return ConstantInt::getTrue(*Context);
3439   }
3440 }
3441
3442 /// PredicatesFoldable - Return true if both predicates match sign or if at
3443 /// least one of them is an equality comparison (which is signless).
3444 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3445   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3446          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3447          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3448 }
3449
3450 namespace { 
3451 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3452 struct FoldICmpLogical {
3453   InstCombiner &IC;
3454   Value *LHS, *RHS;
3455   ICmpInst::Predicate pred;
3456   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3457     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3458       pred(ICI->getPredicate()) {}
3459   bool shouldApply(Value *V) const {
3460     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3461       if (PredicatesFoldable(pred, ICI->getPredicate()))
3462         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3463                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3464     return false;
3465   }
3466   Instruction *apply(Instruction &Log) const {
3467     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3468     if (ICI->getOperand(0) != LHS) {
3469       assert(ICI->getOperand(1) == LHS);
3470       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3471     }
3472
3473     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3474     unsigned LHSCode = getICmpCode(ICI);
3475     unsigned RHSCode = getICmpCode(RHSICI);
3476     unsigned Code;
3477     switch (Log.getOpcode()) {
3478     case Instruction::And: Code = LHSCode & RHSCode; break;
3479     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3480     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3481     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3482     }
3483
3484     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3485                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3486       
3487     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3488     if (Instruction *I = dyn_cast<Instruction>(RV))
3489       return I;
3490     // Otherwise, it's a constant boolean value...
3491     return IC.ReplaceInstUsesWith(Log, RV);
3492   }
3493 };
3494 } // end anonymous namespace
3495
3496 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3497 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3498 // guaranteed to be a binary operator.
3499 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3500                                     ConstantInt *OpRHS,
3501                                     ConstantInt *AndRHS,
3502                                     BinaryOperator &TheAnd) {
3503   Value *X = Op->getOperand(0);
3504   Constant *Together = 0;
3505   if (!Op->isShift())
3506     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3507
3508   switch (Op->getOpcode()) {
3509   case Instruction::Xor:
3510     if (Op->hasOneUse()) {
3511       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3512       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3513       InsertNewInstBefore(And, TheAnd);
3514       And->takeName(Op);
3515       return BinaryOperator::CreateXor(And, Together);
3516     }
3517     break;
3518   case Instruction::Or:
3519     if (Together == AndRHS) // (X | C) & C --> C
3520       return ReplaceInstUsesWith(TheAnd, AndRHS);
3521
3522     if (Op->hasOneUse() && Together != OpRHS) {
3523       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3524       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3525       InsertNewInstBefore(Or, TheAnd);
3526       Or->takeName(Op);
3527       return BinaryOperator::CreateAnd(Or, AndRHS);
3528     }
3529     break;
3530   case Instruction::Add:
3531     if (Op->hasOneUse()) {
3532       // Adding a one to a single bit bit-field should be turned into an XOR
3533       // of the bit.  First thing to check is to see if this AND is with a
3534       // single bit constant.
3535       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3536
3537       // If there is only one bit set...
3538       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3539         // Ok, at this point, we know that we are masking the result of the
3540         // ADD down to exactly one bit.  If the constant we are adding has
3541         // no bits set below this bit, then we can eliminate the ADD.
3542         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3543
3544         // Check to see if any bits below the one bit set in AndRHSV are set.
3545         if ((AddRHS & (AndRHSV-1)) == 0) {
3546           // If not, the only thing that can effect the output of the AND is
3547           // the bit specified by AndRHSV.  If that bit is set, the effect of
3548           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3549           // no effect.
3550           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3551             TheAnd.setOperand(0, X);
3552             return &TheAnd;
3553           } else {
3554             // Pull the XOR out of the AND.
3555             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3556             InsertNewInstBefore(NewAnd, TheAnd);
3557             NewAnd->takeName(Op);
3558             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3559           }
3560         }
3561       }
3562     }
3563     break;
3564
3565   case Instruction::Shl: {
3566     // We know that the AND will not produce any of the bits shifted in, so if
3567     // the anded constant includes them, clear them now!
3568     //
3569     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3570     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3571     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3572     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3573
3574     if (CI->getValue() == ShlMask) { 
3575     // Masking out bits that the shift already masks
3576       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3577     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3578       TheAnd.setOperand(1, CI);
3579       return &TheAnd;
3580     }
3581     break;
3582   }
3583   case Instruction::LShr:
3584   {
3585     // We know that the AND will not produce any of the bits shifted in, so if
3586     // the anded constant includes them, clear them now!  This only applies to
3587     // unsigned shifts, because a signed shr may bring in set bits!
3588     //
3589     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3590     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3591     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3592     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3593
3594     if (CI->getValue() == ShrMask) {   
3595     // Masking out bits that the shift already masks.
3596       return ReplaceInstUsesWith(TheAnd, Op);
3597     } else if (CI != AndRHS) {
3598       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3599       return &TheAnd;
3600     }
3601     break;
3602   }
3603   case Instruction::AShr:
3604     // Signed shr.
3605     // See if this is shifting in some sign extension, then masking it out
3606     // with an and.
3607     if (Op->hasOneUse()) {
3608       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3611       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3612       if (C == AndRHS) {          // Masking out bits shifted in.
3613         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3614         // Make the argument unsigned.
3615         Value *ShVal = Op->getOperand(0);
3616         ShVal = InsertNewInstBefore(
3617             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3618                                    Op->getName()), TheAnd);
3619         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3620       }
3621     }
3622     break;
3623   }
3624   return 0;
3625 }
3626
3627
3628 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3629 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3630 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3631 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3632 /// insert new instructions.
3633 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3634                                            bool isSigned, bool Inside, 
3635                                            Instruction &IB) {
3636   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3637             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3638          "Lo is not <= Hi in range emission code!");
3639     
3640   if (Inside) {
3641     if (Lo == Hi)  // Trivially false.
3642       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3643
3644     // V >= Min && V < Hi --> V < Hi
3645     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3646       ICmpInst::Predicate pred = (isSigned ? 
3647         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3648       return new ICmpInst(*Context, pred, V, Hi);
3649     }
3650
3651     // Emit V-Lo <u Hi-Lo
3652     Constant *NegLo = ConstantExpr::getNeg(Lo);
3653     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3654     InsertNewInstBefore(Add, IB);
3655     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3656     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3657   }
3658
3659   if (Lo == Hi)  // Trivially true.
3660     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3661
3662   // V < Min || V >= Hi -> V > Hi-1
3663   Hi = SubOne(cast<ConstantInt>(Hi));
3664   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665     ICmpInst::Predicate pred = (isSigned ? 
3666         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3667     return new ICmpInst(*Context, pred, V, Hi);
3668   }
3669
3670   // Emit V-Lo >u Hi-1-Lo
3671   // Note that Hi has already had one subtracted from it, above.
3672   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3673   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3674   InsertNewInstBefore(Add, IB);
3675   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3676   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3677 }
3678
3679 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3681 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3682 // not, since all 1s are not contiguous.
3683 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3684   const APInt& V = Val->getValue();
3685   uint32_t BitWidth = Val->getType()->getBitWidth();
3686   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3687
3688   // look for the first zero bit after the run of ones
3689   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3690   // look for the first non-zero bit
3691   ME = V.getActiveBits(); 
3692   return true;
3693 }
3694
3695 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696 /// where isSub determines whether the operator is a sub.  If we can fold one of
3697 /// the following xforms:
3698 /// 
3699 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702 ///
3703 /// return (A +/- B).
3704 ///
3705 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3706                                         ConstantInt *Mask, bool isSub,
3707                                         Instruction &I) {
3708   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709   if (!LHSI || LHSI->getNumOperands() != 2 ||
3710       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714   switch (LHSI->getOpcode()) {
3715   default: return 0;
3716   case Instruction::And:
3717     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3718       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3719       if ((Mask->getValue().countLeadingZeros() + 
3720            Mask->getValue().countPopulation()) == 
3721           Mask->getValue().getBitWidth())
3722         break;
3723
3724       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725       // part, we don't need any explicit masks to take them out of A.  If that
3726       // is all N is, ignore it.
3727       uint32_t MB = 0, ME = 0;
3728       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3729         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3730         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3731         if (MaskedValueIsZero(RHS, Mask))
3732           break;
3733       }
3734     }
3735     return 0;
3736   case Instruction::Or:
3737   case Instruction::Xor:
3738     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3739     if ((Mask->getValue().countLeadingZeros() + 
3740          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3741         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3742       break;
3743     return 0;
3744   }
3745   
3746   Instruction *New;
3747   if (isSub)
3748     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3749   else
3750     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3751   return InsertNewInstBefore(New, I);
3752 }
3753
3754 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3755 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3756                                           ICmpInst *LHS, ICmpInst *RHS) {
3757   Value *Val, *Val2;
3758   ConstantInt *LHSCst, *RHSCst;
3759   ICmpInst::Predicate LHSCC, RHSCC;
3760   
3761   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3762   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3763                          m_ConstantInt(LHSCst))) ||
3764       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3765                          m_ConstantInt(RHSCst))))
3766     return 0;
3767   
3768   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3769   // where C is a power of 2
3770   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3771       LHSCst->getValue().isPowerOf2()) {
3772     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3773     InsertNewInstBefore(NewOr, I);
3774     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3775   }
3776   
3777   // From here on, we only handle:
3778   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3779   if (Val != Val2) return 0;
3780   
3781   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3782   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3783       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3784       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3785       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3786     return 0;
3787   
3788   // We can't fold (ugt x, C) & (sgt x, C2).
3789   if (!PredicatesFoldable(LHSCC, RHSCC))
3790     return 0;
3791     
3792   // Ensure that the larger constant is on the RHS.
3793   bool ShouldSwap;
3794   if (ICmpInst::isSignedPredicate(LHSCC) ||
3795       (ICmpInst::isEquality(LHSCC) && 
3796        ICmpInst::isSignedPredicate(RHSCC)))
3797     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3798   else
3799     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3800     
3801   if (ShouldSwap) {
3802     std::swap(LHS, RHS);
3803     std::swap(LHSCst, RHSCst);
3804     std::swap(LHSCC, RHSCC);
3805   }
3806
3807   // At this point, we know we have have two icmp instructions
3808   // comparing a value against two constants and and'ing the result
3809   // together.  Because of the above check, we know that we only have
3810   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3811   // (from the FoldICmpLogical check above), that the two constants 
3812   // are not equal and that the larger constant is on the RHS
3813   assert(LHSCst != RHSCst && "Compares not folded above?");
3814
3815   switch (LHSCC) {
3816   default: llvm_unreachable("Unknown integer condition code!");
3817   case ICmpInst::ICMP_EQ:
3818     switch (RHSCC) {
3819     default: llvm_unreachable("Unknown integer condition code!");
3820     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3821     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3822     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3823       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3824     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3825     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3826     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3827       return ReplaceInstUsesWith(I, LHS);
3828     }
3829   case ICmpInst::ICMP_NE:
3830     switch (RHSCC) {
3831     default: llvm_unreachable("Unknown integer condition code!");
3832     case ICmpInst::ICMP_ULT:
3833       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3834         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3835       break;                        // (X != 13 & X u< 15) -> no change
3836     case ICmpInst::ICMP_SLT:
3837       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3838         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3839       break;                        // (X != 13 & X s< 15) -> no change
3840     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3841     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3842     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3843       return ReplaceInstUsesWith(I, RHS);
3844     case ICmpInst::ICMP_NE:
3845       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3846         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3847         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3848                                                      Val->getName()+".off");
3849         InsertNewInstBefore(Add, I);
3850         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3851                             ConstantInt::get(Add->getType(), 1));
3852       }
3853       break;                        // (X != 13 & X != 15) -> no change
3854     }
3855     break;
3856   case ICmpInst::ICMP_ULT:
3857     switch (RHSCC) {
3858     default: llvm_unreachable("Unknown integer condition code!");
3859     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3860     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3861       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3862     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3863       break;
3864     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3865     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3866       return ReplaceInstUsesWith(I, LHS);
3867     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3868       break;
3869     }
3870     break;
3871   case ICmpInst::ICMP_SLT:
3872     switch (RHSCC) {
3873     default: llvm_unreachable("Unknown integer condition code!");
3874     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3875     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3876       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3877     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3878       break;
3879     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3880     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3881       return ReplaceInstUsesWith(I, LHS);
3882     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3883       break;
3884     }
3885     break;
3886   case ICmpInst::ICMP_UGT:
3887     switch (RHSCC) {
3888     default: llvm_unreachable("Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3890     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3891       return ReplaceInstUsesWith(I, RHS);
3892     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:
3895       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3896         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3897       break;                        // (X u> 13 & X != 15) -> no change
3898     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3899       return InsertRangeTest(Val, AddOne(LHSCst),
3900                              RHSCst, false, true, I);
3901     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3902       break;
3903     }
3904     break;
3905   case ICmpInst::ICMP_SGT:
3906     switch (RHSCC) {
3907     default: llvm_unreachable("Unknown integer condition code!");
3908     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3909     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3910       return ReplaceInstUsesWith(I, RHS);
3911     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3912       break;
3913     case ICmpInst::ICMP_NE:
3914       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3915         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3916       break;                        // (X s> 13 & X != 15) -> no change
3917     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3918       return InsertRangeTest(Val, AddOne(LHSCst),
3919                              RHSCst, true, true, I);
3920     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3921       break;
3922     }
3923     break;
3924   }
3925  
3926   return 0;
3927 }
3928
3929 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3930                                           FCmpInst *RHS) {
3931   
3932   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3933       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3934     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3935     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3936       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3937         // If either of the constants are nans, then the whole thing returns
3938         // false.
3939         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3940           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3941         return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3942                             LHS->getOperand(0), RHS->getOperand(0));
3943       }
3944     
3945     // Handle vector zeros.  This occurs because the canonical form of
3946     // "fcmp ord x,x" is "fcmp ord x, 0".
3947     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3948         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3949       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3950                           LHS->getOperand(0), RHS->getOperand(0));
3951     return 0;
3952   }
3953   
3954   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3957   
3958   
3959   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960     // Swap RHS operands to match LHS.
3961     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962     std::swap(Op1LHS, Op1RHS);
3963   }
3964   
3965   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3967     if (Op0CC == Op1CC)
3968       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3969     
3970     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3971       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3972     if (Op0CC == FCmpInst::FCMP_TRUE)
3973       return ReplaceInstUsesWith(I, RHS);
3974     if (Op1CC == FCmpInst::FCMP_TRUE)
3975       return ReplaceInstUsesWith(I, LHS);
3976     
3977     bool Op0Ordered;
3978     bool Op1Ordered;
3979     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3981     if (Op1Pred == 0) {
3982       std::swap(LHS, RHS);
3983       std::swap(Op0Pred, Op1Pred);
3984       std::swap(Op0Ordered, Op1Ordered);
3985     }
3986     if (Op0Pred == 0) {
3987       // uno && ueq -> uno && (uno || eq) -> ueq
3988       // ord && olt -> ord && (ord && lt) -> olt
3989       if (Op0Ordered == Op1Ordered)
3990         return ReplaceInstUsesWith(I, RHS);
3991       
3992       // uno && oeq -> uno && (ord && eq) -> false
3993       // uno && ord -> false
3994       if (!Op0Ordered)
3995         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3996       // ord && ueq -> ord && (uno || eq) -> oeq
3997       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998                                             Op0LHS, Op0RHS, Context));
3999     }
4000   }
4001
4002   return 0;
4003 }
4004
4005
4006 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4007   bool Changed = SimplifyCommutative(I);
4008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4009
4010   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4011     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4012
4013   // and X, X = X
4014   if (Op0 == Op1)
4015     return ReplaceInstUsesWith(I, Op1);
4016
4017   // See if we can simplify any instructions used by the instruction whose sole 
4018   // purpose is to compute bits we don't care about.
4019   if (SimplifyDemandedInstructionBits(I))
4020     return &I;
4021   if (isa<VectorType>(I.getType())) {
4022     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4023       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4024         return ReplaceInstUsesWith(I, I.getOperand(0));
4025     } else if (isa<ConstantAggregateZero>(Op1)) {
4026       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4027     }
4028   }
4029
4030   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4031     const APInt& AndRHSMask = AndRHS->getValue();
4032     APInt NotAndRHS(~AndRHSMask);
4033
4034     // Optimize a variety of ((val OP C1) & C2) combinations...
4035     if (isa<BinaryOperator>(Op0)) {
4036       Instruction *Op0I = cast<Instruction>(Op0);
4037       Value *Op0LHS = Op0I->getOperand(0);
4038       Value *Op0RHS = Op0I->getOperand(1);
4039       switch (Op0I->getOpcode()) {
4040       case Instruction::Xor:
4041       case Instruction::Or:
4042         // If the mask is only needed on one incoming arm, push it up.
4043         if (Op0I->hasOneUse()) {
4044           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045             // Not masking anything out for the LHS, move to RHS.
4046             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4047                                                    Op0RHS->getName()+".masked");
4048             InsertNewInstBefore(NewRHS, I);
4049             return BinaryOperator::Create(
4050                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4051           }
4052           if (!isa<Constant>(Op0RHS) &&
4053               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054             // Not masking anything out for the RHS, move to LHS.
4055             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4056                                                    Op0LHS->getName()+".masked");
4057             InsertNewInstBefore(NewLHS, I);
4058             return BinaryOperator::Create(
4059                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4060           }
4061         }
4062
4063         break;
4064       case Instruction::Add:
4065         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4069           return BinaryOperator::CreateAnd(V, AndRHS);
4070         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4071           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4072         break;
4073
4074       case Instruction::Sub:
4075         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4076         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4077         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4078         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4079           return BinaryOperator::CreateAnd(V, AndRHS);
4080
4081         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082         // has 1's for all bits that the subtraction with A might affect.
4083         if (Op0I->hasOneUse()) {
4084           uint32_t BitWidth = AndRHSMask.getBitWidth();
4085           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4087
4088           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4089           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4090               MaskedValueIsZero(Op0LHS, Mask)) {
4091             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4092             InsertNewInstBefore(NewNeg, I);
4093             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4094           }
4095         }
4096         break;
4097
4098       case Instruction::Shl:
4099       case Instruction::LShr:
4100         // (1 << x) & 1 --> zext(x == 0)
4101         // (1 >> x) & 1 --> zext(x == 0)
4102         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4103           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4104                                     Op0RHS, Constant::getNullValue(I.getType()));
4105           InsertNewInstBefore(NewICmp, I);
4106           return new ZExtInst(NewICmp, I.getType());
4107         }
4108         break;
4109       }
4110
4111       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4112         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4113           return Res;
4114     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4115       // If this is an integer truncation or change from signed-to-unsigned, and
4116       // if the source is an and/or with immediate, transform it.  This
4117       // frequently occurs for bitfield accesses.
4118       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4119         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4120             CastOp->getNumOperands() == 2)
4121           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4122             if (CastOp->getOpcode() == Instruction::And) {
4123               // Change: and (cast (and X, C1) to T), C2
4124               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4125               // This will fold the two constants together, which may allow 
4126               // other simplifications.
4127               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4128                 CastOp->getOperand(0), I.getType(), 
4129                 CastOp->getName()+".shrunk");
4130               NewCast = InsertNewInstBefore(NewCast, I);
4131               // trunc_or_bitcast(C1)&C2
4132               Constant *C3 =
4133                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4134               C3 = ConstantExpr::getAnd(C3, AndRHS);
4135               return BinaryOperator::CreateAnd(NewCast, C3);
4136             } else if (CastOp->getOpcode() == Instruction::Or) {
4137               // Change: and (cast (or X, C1) to T), C2
4138               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4139               Constant *C3 =
4140                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4141               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4142                 // trunc(C1)&C2
4143                 return ReplaceInstUsesWith(I, AndRHS);
4144             }
4145           }
4146       }
4147     }
4148
4149     // Try to fold constant and into select arguments.
4150     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4151       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4152         return R;
4153     if (isa<PHINode>(Op0))
4154       if (Instruction *NV = FoldOpIntoPhi(I))
4155         return NV;
4156   }
4157
4158   Value *Op0NotVal = dyn_castNotVal(Op0);
4159   Value *Op1NotVal = dyn_castNotVal(Op1);
4160
4161   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4162     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4163
4164   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4165   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4166     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4167                                                I.getName()+".demorgan");
4168     InsertNewInstBefore(Or, I);
4169     return BinaryOperator::CreateNot(Or);
4170   }
4171   
4172   {
4173     Value *A = 0, *B = 0, *C = 0, *D = 0;
4174     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4175       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4176         return ReplaceInstUsesWith(I, Op1);
4177     
4178       // (A|B) & ~(A&B) -> A^B
4179       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4180         if ((A == C && B == D) || (A == D && B == C))
4181           return BinaryOperator::CreateXor(A, B);
4182       }
4183     }
4184     
4185     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4186       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4187         return ReplaceInstUsesWith(I, Op0);
4188
4189       // ~(A&B) & (A|B) -> A^B
4190       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4191         if ((A == C && B == D) || (A == D && B == C))
4192           return BinaryOperator::CreateXor(A, B);
4193       }
4194     }
4195     
4196     if (Op0->hasOneUse() &&
4197         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4198       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4199         I.swapOperands();     // Simplify below
4200         std::swap(Op0, Op1);
4201       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4202         cast<BinaryOperator>(Op0)->swapOperands();
4203         I.swapOperands();     // Simplify below
4204         std::swap(Op0, Op1);
4205       }
4206     }
4207
4208     if (Op1->hasOneUse() &&
4209         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4210       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4211         cast<BinaryOperator>(Op1)->swapOperands();
4212         std::swap(A, B);
4213       }
4214       if (A == Op0) {                                // A&(A^B) -> A & ~B
4215         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4216         InsertNewInstBefore(NotB, I);
4217         return BinaryOperator::CreateAnd(A, NotB);
4218       }
4219     }
4220
4221     // (A&((~A)|B)) -> A&B
4222     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4223         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4224       return BinaryOperator::CreateAnd(A, Op1);
4225     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4226         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4227       return BinaryOperator::CreateAnd(A, Op0);
4228   }
4229   
4230   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4232     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4233       return R;
4234
4235     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4237         return Res;
4238   }
4239
4240   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4241   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244         const Type *SrcTy = Op0C->getOperand(0)->getType();
4245         if (SrcTy == Op1C->getOperand(0)->getType() &&
4246             SrcTy->isIntOrIntVector() &&
4247             // Only do this if the casts both really cause code to be generated.
4248             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4249                               I.getType(), TD) &&
4250             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4251                               I.getType(), TD)) {
4252           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4253                                                          Op1C->getOperand(0),
4254                                                          I.getName());
4255           InsertNewInstBefore(NewOp, I);
4256           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4257         }
4258       }
4259     
4260   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4261   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4262     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4263       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4264           SI0->getOperand(1) == SI1->getOperand(1) &&
4265           (SI0->hasOneUse() || SI1->hasOneUse())) {
4266         Instruction *NewOp =
4267           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4268                                                         SI1->getOperand(0),
4269                                                         SI0->getName()), I);
4270         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4271                                       SI1->getOperand(1));
4272       }
4273   }
4274
4275   // If and'ing two fcmp, try combine them into one.
4276   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4277     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4278       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4279         return Res;
4280   }
4281
4282   return Changed ? &I : 0;
4283 }
4284
4285 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4286 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4287 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4288 /// the expression came from the corresponding "byte swapped" byte in some other
4289 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4290 /// we know that the expression deposits the low byte of %X into the high byte
4291 /// of the bswap result and that all other bytes are zero.  This expression is
4292 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4293 /// match.
4294 ///
4295 /// This function returns true if the match was unsuccessful and false if so.
4296 /// On entry to the function the "OverallLeftShift" is a signed integer value
4297 /// indicating the number of bytes that the subexpression is later shifted.  For
4298 /// example, if the expression is later right shifted by 16 bits, the
4299 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4300 /// byte of ByteValues is actually being set.
4301 ///
4302 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4303 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4304 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4305 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4306 /// always in the local (OverallLeftShift) coordinate space.
4307 ///
4308 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4309                               SmallVector<Value*, 8> &ByteValues) {
4310   if (Instruction *I = dyn_cast<Instruction>(V)) {
4311     // If this is an or instruction, it may be an inner node of the bswap.
4312     if (I->getOpcode() == Instruction::Or) {
4313       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314                                ByteValues) ||
4315              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4316                                ByteValues);
4317     }
4318   
4319     // If this is a logical shift by a constant multiple of 8, recurse with
4320     // OverallLeftShift and ByteMask adjusted.
4321     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4322       unsigned ShAmt = 
4323         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4324       // Ensure the shift amount is defined and of a byte value.
4325       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4326         return true;
4327
4328       unsigned ByteShift = ShAmt >> 3;
4329       if (I->getOpcode() == Instruction::Shl) {
4330         // X << 2 -> collect(X, +2)
4331         OverallLeftShift += ByteShift;
4332         ByteMask >>= ByteShift;
4333       } else {
4334         // X >>u 2 -> collect(X, -2)
4335         OverallLeftShift -= ByteShift;
4336         ByteMask <<= ByteShift;
4337         ByteMask &= (~0U >> (32-ByteValues.size()));
4338       }
4339
4340       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4341       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4342
4343       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4344                                ByteValues);
4345     }
4346
4347     // If this is a logical 'and' with a mask that clears bytes, clear the
4348     // corresponding bytes in ByteMask.
4349     if (I->getOpcode() == Instruction::And &&
4350         isa<ConstantInt>(I->getOperand(1))) {
4351       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4352       unsigned NumBytes = ByteValues.size();
4353       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4354       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4355       
4356       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4357         // If this byte is masked out by a later operation, we don't care what
4358         // the and mask is.
4359         if ((ByteMask & (1 << i)) == 0)
4360           continue;
4361         
4362         // If the AndMask is all zeros for this byte, clear the bit.
4363         APInt MaskB = AndMask & Byte;
4364         if (MaskB == 0) {
4365           ByteMask &= ~(1U << i);
4366           continue;
4367         }
4368         
4369         // If the AndMask is not all ones for this byte, it's not a bytezap.
4370         if (MaskB != Byte)
4371           return true;
4372
4373         // Otherwise, this byte is kept.
4374       }
4375
4376       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4377                                ByteValues);
4378     }
4379   }
4380   
4381   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4382   // the input value to the bswap.  Some observations: 1) if more than one byte
4383   // is demanded from this input, then it could not be successfully assembled
4384   // into a byteswap.  At least one of the two bytes would not be aligned with
4385   // their ultimate destination.
4386   if (!isPowerOf2_32(ByteMask)) return true;
4387   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4388   
4389   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4390   // is demanded, it needs to go into byte 0 of the result.  This means that the
4391   // byte needs to be shifted until it lands in the right byte bucket.  The
4392   // shift amount depends on the position: if the byte is coming from the high
4393   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4394   // low part, it must be shifted left.
4395   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4396   if (InputByteNo < ByteValues.size()/2) {
4397     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4398       return true;
4399   } else {
4400     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4401       return true;
4402   }
4403   
4404   // If the destination byte value is already defined, the values are or'd
4405   // together, which isn't a bswap (unless it's an or of the same bits).
4406   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4407     return true;
4408   ByteValues[DestByteNo] = V;
4409   return false;
4410 }
4411
4412 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4413 /// If so, insert the new bswap intrinsic and return it.
4414 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4415   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4416   if (!ITy || ITy->getBitWidth() % 16 || 
4417       // ByteMask only allows up to 32-byte values.
4418       ITy->getBitWidth() > 32*8) 
4419     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4420   
4421   /// ByteValues - For each byte of the result, we keep track of which value
4422   /// defines each byte.
4423   SmallVector<Value*, 8> ByteValues;
4424   ByteValues.resize(ITy->getBitWidth()/8);
4425     
4426   // Try to find all the pieces corresponding to the bswap.
4427   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4428   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4429     return 0;
4430   
4431   // Check to see if all of the bytes come from the same value.
4432   Value *V = ByteValues[0];
4433   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4434   
4435   // Check to make sure that all of the bytes come from the same value.
4436   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4437     if (ByteValues[i] != V)
4438       return 0;
4439   const Type *Tys[] = { ITy };
4440   Module *M = I.getParent()->getParent()->getParent();
4441   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4442   return CallInst::Create(F, V);
4443 }
4444
4445 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4446 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4447 /// we can simplify this expression to "cond ? C : D or B".
4448 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4449                                          Value *C, Value *D,
4450                                          LLVMContext *Context) {
4451   // If A is not a select of -1/0, this cannot match.
4452   Value *Cond = 0;
4453   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4454     return 0;
4455
4456   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4457   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4458     return SelectInst::Create(Cond, C, B);
4459   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4460     return SelectInst::Create(Cond, C, B);
4461   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4462   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4463     return SelectInst::Create(Cond, C, D);
4464   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4465     return SelectInst::Create(Cond, C, D);
4466   return 0;
4467 }
4468
4469 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4470 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4471                                          ICmpInst *LHS, ICmpInst *RHS) {
4472   Value *Val, *Val2;
4473   ConstantInt *LHSCst, *RHSCst;
4474   ICmpInst::Predicate LHSCC, RHSCC;
4475   
4476   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4477   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4478              m_ConstantInt(LHSCst))) ||
4479       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4480              m_ConstantInt(RHSCst))))
4481     return 0;
4482   
4483   // From here on, we only handle:
4484   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4485   if (Val != Val2) return 0;
4486   
4487   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4488   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4489       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4490       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4491       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4492     return 0;
4493   
4494   // We can't fold (ugt x, C) | (sgt x, C2).
4495   if (!PredicatesFoldable(LHSCC, RHSCC))
4496     return 0;
4497   
4498   // Ensure that the larger constant is on the RHS.
4499   bool ShouldSwap;
4500   if (ICmpInst::isSignedPredicate(LHSCC) ||
4501       (ICmpInst::isEquality(LHSCC) && 
4502        ICmpInst::isSignedPredicate(RHSCC)))
4503     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504   else
4505     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4506   
4507   if (ShouldSwap) {
4508     std::swap(LHS, RHS);
4509     std::swap(LHSCst, RHSCst);
4510     std::swap(LHSCC, RHSCC);
4511   }
4512   
4513   // At this point, we know we have have two icmp instructions
4514   // comparing a value against two constants and or'ing the result
4515   // together.  Because of the above check, we know that we only have
4516   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4517   // FoldICmpLogical check above), that the two constants are not
4518   // equal.
4519   assert(LHSCst != RHSCst && "Compares not folded above?");
4520
4521   switch (LHSCC) {
4522   default: llvm_unreachable("Unknown integer condition code!");
4523   case ICmpInst::ICMP_EQ:
4524     switch (RHSCC) {
4525     default: llvm_unreachable("Unknown integer condition code!");
4526     case ICmpInst::ICMP_EQ:
4527       if (LHSCst == SubOne(RHSCst)) {
4528         // (X == 13 | X == 14) -> X-13 <u 2
4529         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4530         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4531                                                      Val->getName()+".off");
4532         InsertNewInstBefore(Add, I);
4533         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4534         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4535       }
4536       break;                         // (X == 13 | X == 15) -> no change
4537     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4538     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4539       break;
4540     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4541     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4542     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4543       return ReplaceInstUsesWith(I, RHS);
4544     }
4545     break;
4546   case ICmpInst::ICMP_NE:
4547     switch (RHSCC) {
4548     default: llvm_unreachable("Unknown integer condition code!");
4549     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4550     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4551     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4552       return ReplaceInstUsesWith(I, LHS);
4553     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4554     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4555     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4556       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4557     }
4558     break;
4559   case ICmpInst::ICMP_ULT:
4560     switch (RHSCC) {
4561     default: llvm_unreachable("Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4563       break;
4564     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4565       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4566       // this can cause overflow.
4567       if (RHSCst->isMaxValue(false))
4568         return ReplaceInstUsesWith(I, LHS);
4569       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4570                              false, false, I);
4571     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4572       break;
4573     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4574     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4575       return ReplaceInstUsesWith(I, RHS);
4576     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4577       break;
4578     }
4579     break;
4580   case ICmpInst::ICMP_SLT:
4581     switch (RHSCC) {
4582     default: llvm_unreachable("Unknown integer condition code!");
4583     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4584       break;
4585     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4586       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4587       // this can cause overflow.
4588       if (RHSCst->isMaxValue(true))
4589         return ReplaceInstUsesWith(I, LHS);
4590       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4591                              true, false, I);
4592     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4593       break;
4594     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4595     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4596       return ReplaceInstUsesWith(I, RHS);
4597     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4598       break;
4599     }
4600     break;
4601   case ICmpInst::ICMP_UGT:
4602     switch (RHSCC) {
4603     default: llvm_unreachable("Unknown integer condition code!");
4604     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4605     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4606       return ReplaceInstUsesWith(I, LHS);
4607     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4608       break;
4609     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4610     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4611       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4612     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4613       break;
4614     }
4615     break;
4616   case ICmpInst::ICMP_SGT:
4617     switch (RHSCC) {
4618     default: llvm_unreachable("Unknown integer condition code!");
4619     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4620     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4621       return ReplaceInstUsesWith(I, LHS);
4622     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4623       break;
4624     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4625     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4626       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4627     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4628       break;
4629     }
4630     break;
4631   }
4632   return 0;
4633 }
4634
4635 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4636                                          FCmpInst *RHS) {
4637   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4638       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4639       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4640     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4641       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4642         // If either of the constants are nans, then the whole thing returns
4643         // true.
4644         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4645           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4646         
4647         // Otherwise, no need to compare the two constants, compare the
4648         // rest.
4649         return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4650                             LHS->getOperand(0), RHS->getOperand(0));
4651       }
4652     
4653     // Handle vector zeros.  This occurs because the canonical form of
4654     // "fcmp uno x,x" is "fcmp uno x, 0".
4655     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4656         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4657       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4658                           LHS->getOperand(0), RHS->getOperand(0));
4659     
4660     return 0;
4661   }
4662   
4663   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4664   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4665   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4666   
4667   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4668     // Swap RHS operands to match LHS.
4669     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4670     std::swap(Op1LHS, Op1RHS);
4671   }
4672   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4673     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4674     if (Op0CC == Op1CC)
4675       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4676                           Op0LHS, Op0RHS);
4677     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4678       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4679     if (Op0CC == FCmpInst::FCMP_FALSE)
4680       return ReplaceInstUsesWith(I, RHS);
4681     if (Op1CC == FCmpInst::FCMP_FALSE)
4682       return ReplaceInstUsesWith(I, LHS);
4683     bool Op0Ordered;
4684     bool Op1Ordered;
4685     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4686     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4687     if (Op0Ordered == Op1Ordered) {
4688       // If both are ordered or unordered, return a new fcmp with
4689       // or'ed predicates.
4690       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4691                                Op0LHS, Op0RHS, Context);
4692       if (Instruction *I = dyn_cast<Instruction>(RV))
4693         return I;
4694       // Otherwise, it's a constant boolean value...
4695       return ReplaceInstUsesWith(I, RV);
4696     }
4697   }
4698   return 0;
4699 }
4700
4701 /// FoldOrWithConstants - This helper function folds:
4702 ///
4703 ///     ((A | B) & C1) | (B & C2)
4704 ///
4705 /// into:
4706 /// 
4707 ///     (A & C1) | B
4708 ///
4709 /// when the XOR of the two constants is "all ones" (-1).
4710 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4711                                                Value *A, Value *B, Value *C) {
4712   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4713   if (!CI1) return 0;
4714
4715   Value *V1 = 0;
4716   ConstantInt *CI2 = 0;
4717   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4718
4719   APInt Xor = CI1->getValue() ^ CI2->getValue();
4720   if (!Xor.isAllOnesValue()) return 0;
4721
4722   if (V1 == A || V1 == B) {
4723     Instruction *NewOp =
4724       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4725     return BinaryOperator::CreateOr(NewOp, V1);
4726   }
4727
4728   return 0;
4729 }
4730
4731 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4732   bool Changed = SimplifyCommutative(I);
4733   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4734
4735   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4736     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4737
4738   // or X, X = X
4739   if (Op0 == Op1)
4740     return ReplaceInstUsesWith(I, Op0);
4741
4742   // See if we can simplify any instructions used by the instruction whose sole 
4743   // purpose is to compute bits we don't care about.
4744   if (SimplifyDemandedInstructionBits(I))
4745     return &I;
4746   if (isa<VectorType>(I.getType())) {
4747     if (isa<ConstantAggregateZero>(Op1)) {
4748       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4749     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4750       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4751         return ReplaceInstUsesWith(I, I.getOperand(1));
4752     }
4753   }
4754
4755   // or X, -1 == -1
4756   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4757     ConstantInt *C1 = 0; Value *X = 0;
4758     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4759     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4760         isOnlyUse(Op0)) {
4761       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4762       InsertNewInstBefore(Or, I);
4763       Or->takeName(Op0);
4764       return BinaryOperator::CreateAnd(Or, 
4765                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4766     }
4767
4768     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4769     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4770         isOnlyUse(Op0)) {
4771       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4772       InsertNewInstBefore(Or, I);
4773       Or->takeName(Op0);
4774       return BinaryOperator::CreateXor(Or,
4775                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4776     }
4777
4778     // Try to fold constant and into select arguments.
4779     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4780       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4781         return R;
4782     if (isa<PHINode>(Op0))
4783       if (Instruction *NV = FoldOpIntoPhi(I))
4784         return NV;
4785   }
4786
4787   Value *A = 0, *B = 0;
4788   ConstantInt *C1 = 0, *C2 = 0;
4789
4790   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4791     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4792       return ReplaceInstUsesWith(I, Op1);
4793   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4794     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4795       return ReplaceInstUsesWith(I, Op0);
4796
4797   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4798   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4799   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4800       match(Op1, m_Or(m_Value(), m_Value())) ||
4801       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4802        match(Op1, m_Shift(m_Value(), m_Value())))) {
4803     if (Instruction *BSwap = MatchBSwap(I))
4804       return BSwap;
4805   }
4806   
4807   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4808   if (Op0->hasOneUse() &&
4809       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4810       MaskedValueIsZero(Op1, C1->getValue())) {
4811     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4812     InsertNewInstBefore(NOr, I);
4813     NOr->takeName(Op0);
4814     return BinaryOperator::CreateXor(NOr, C1);
4815   }
4816
4817   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4818   if (Op1->hasOneUse() &&
4819       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4820       MaskedValueIsZero(Op0, C1->getValue())) {
4821     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4822     InsertNewInstBefore(NOr, I);
4823     NOr->takeName(Op0);
4824     return BinaryOperator::CreateXor(NOr, C1);
4825   }
4826
4827   // (A & C)|(B & D)
4828   Value *C = 0, *D = 0;
4829   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4830       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4831     Value *V1 = 0, *V2 = 0, *V3 = 0;
4832     C1 = dyn_cast<ConstantInt>(C);
4833     C2 = dyn_cast<ConstantInt>(D);
4834     if (C1 && C2) {  // (A & C1)|(B & C2)
4835       // If we have: ((V + N) & C1) | (V & C2)
4836       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837       // replace with V+N.
4838       if (C1->getValue() == ~C2->getValue()) {
4839         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4840             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4841           // Add commutes, try both ways.
4842           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843             return ReplaceInstUsesWith(I, A);
4844           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845             return ReplaceInstUsesWith(I, A);
4846         }
4847         // Or commutes, try both ways.
4848         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4849             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4850           // Add commutes, try both ways.
4851           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852             return ReplaceInstUsesWith(I, B);
4853           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854             return ReplaceInstUsesWith(I, B);
4855         }
4856       }
4857       V1 = 0; V2 = 0; V3 = 0;
4858     }
4859     
4860     // Check to see if we have any common things being and'ed.  If so, find the
4861     // terms for V1 & (V2|V3).
4862     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4864         V1 = A, V2 = C, V3 = D;
4865       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866         V1 = A, V2 = B, V3 = C;
4867       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868         V1 = C, V2 = A, V3 = D;
4869       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870         V1 = C, V2 = A, V3 = B;
4871       
4872       if (V1) {
4873         Value *Or =
4874           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4875         return BinaryOperator::CreateAnd(V1, Or);
4876       }
4877     }
4878
4879     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4880     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4881       return Match;
4882     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4883       return Match;
4884     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4885       return Match;
4886     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4887       return Match;
4888
4889     // ((A&~B)|(~A&B)) -> A^B
4890     if ((match(C, m_Not(m_Specific(D))) &&
4891          match(B, m_Not(m_Specific(A)))))
4892       return BinaryOperator::CreateXor(A, D);
4893     // ((~B&A)|(~A&B)) -> A^B
4894     if ((match(A, m_Not(m_Specific(D))) &&
4895          match(B, m_Not(m_Specific(C)))))
4896       return BinaryOperator::CreateXor(C, D);
4897     // ((A&~B)|(B&~A)) -> A^B
4898     if ((match(C, m_Not(m_Specific(B))) &&
4899          match(D, m_Not(m_Specific(A)))))
4900       return BinaryOperator::CreateXor(A, B);
4901     // ((~B&A)|(B&~A)) -> A^B
4902     if ((match(A, m_Not(m_Specific(B))) &&
4903          match(D, m_Not(m_Specific(C)))))
4904       return BinaryOperator::CreateXor(C, B);
4905   }
4906   
4907   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4908   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4911           SI0->getOperand(1) == SI1->getOperand(1) &&
4912           (SI0->hasOneUse() || SI1->hasOneUse())) {
4913         Instruction *NewOp =
4914         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4915                                                      SI1->getOperand(0),
4916                                                      SI0->getName()), I);
4917         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4918                                       SI1->getOperand(1));
4919       }
4920   }
4921
4922   // ((A|B)&1)|(B&-2) -> (A&1) | B
4923   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4924       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4925     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4926     if (Ret) return Ret;
4927   }
4928   // (B&-2)|((A|B)&1) -> (A&1) | B
4929   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4930       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4931     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4932     if (Ret) return Ret;
4933   }
4934
4935   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4936     if (A == Op1)   // ~A | A == -1
4937       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4938   } else {
4939     A = 0;
4940   }
4941   // Note, A is still live here!
4942   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4943     if (Op0 == B)
4944       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4945
4946     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4947     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4948       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4949                                               I.getName()+".demorgan"), I);
4950       return BinaryOperator::CreateNot(And);
4951     }
4952   }
4953
4954   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4955   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4956     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4957       return R;
4958
4959     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4960       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4961         return Res;
4962   }
4963     
4964   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4965   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4966     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4967       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4968         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4969             !isa<ICmpInst>(Op1C->getOperand(0))) {
4970           const Type *SrcTy = Op0C->getOperand(0)->getType();
4971           if (SrcTy == Op1C->getOperand(0)->getType() &&
4972               SrcTy->isIntOrIntVector() &&
4973               // Only do this if the casts both really cause code to be
4974               // generated.
4975               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4976                                 I.getType(), TD) &&
4977               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4978                                 I.getType(), TD)) {
4979             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4980                                                           Op1C->getOperand(0),
4981                                                           I.getName());
4982             InsertNewInstBefore(NewOp, I);
4983             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4984           }
4985         }
4986       }
4987   }
4988   
4989     
4990   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4991   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4992     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4993       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4994         return Res;
4995   }
4996
4997   return Changed ? &I : 0;
4998 }
4999
5000 namespace {
5001
5002 // XorSelf - Implements: X ^ X --> 0
5003 struct XorSelf {
5004   Value *RHS;
5005   XorSelf(Value *rhs) : RHS(rhs) {}
5006   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5007   Instruction *apply(BinaryOperator &Xor) const {
5008     return &Xor;
5009   }
5010 };
5011
5012 }
5013
5014 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5015   bool Changed = SimplifyCommutative(I);
5016   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5017
5018   if (isa<UndefValue>(Op1)) {
5019     if (isa<UndefValue>(Op0))
5020       // Handle undef ^ undef -> 0 special case. This is a common
5021       // idiom (misuse).
5022       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5023     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5024   }
5025
5026   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5027   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5028     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5029     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5030   }
5031   
5032   // See if we can simplify any instructions used by the instruction whose sole 
5033   // purpose is to compute bits we don't care about.
5034   if (SimplifyDemandedInstructionBits(I))
5035     return &I;
5036   if (isa<VectorType>(I.getType()))
5037     if (isa<ConstantAggregateZero>(Op1))
5038       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5039
5040   // Is this a ~ operation?
5041   if (Value *NotOp = dyn_castNotVal(&I)) {
5042     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5043     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5044     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5045       if (Op0I->getOpcode() == Instruction::And || 
5046           Op0I->getOpcode() == Instruction::Or) {
5047         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5048         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5049           Instruction *NotY =
5050             BinaryOperator::CreateNot(Op0I->getOperand(1),
5051                                       Op0I->getOperand(1)->getName()+".not");
5052           InsertNewInstBefore(NotY, I);
5053           if (Op0I->getOpcode() == Instruction::And)
5054             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5055           else
5056             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5057         }
5058       }
5059     }
5060   }
5061   
5062   
5063   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5064     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5065       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5066       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5067         return new ICmpInst(*Context, ICI->getInversePredicate(),
5068                             ICI->getOperand(0), ICI->getOperand(1));
5069
5070       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5071         return new FCmpInst(*Context, FCI->getInversePredicate(),
5072                             FCI->getOperand(0), FCI->getOperand(1));
5073     }
5074
5075     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5076     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5078         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5079           Instruction::CastOps Opcode = Op0C->getOpcode();
5080           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5081             if (RHS == ConstantExpr::getCast(Opcode, 
5082                                              ConstantInt::getTrue(*Context),
5083                                              Op0C->getDestTy())) {
5084               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5085                                      *Context,
5086                                      CI->getOpcode(), CI->getInversePredicate(),
5087                                      CI->getOperand(0), CI->getOperand(1)), I);
5088               NewCI->takeName(CI);
5089               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5090             }
5091           }
5092         }
5093       }
5094     }
5095
5096     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5097       // ~(c-X) == X-c-1 == X+(-c-1)
5098       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5099         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5100           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5101           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5102                                       ConstantInt::get(I.getType(), 1));
5103           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5104         }
5105           
5106       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5107         if (Op0I->getOpcode() == Instruction::Add) {
5108           // ~(X-c) --> (-c-1)-X
5109           if (RHS->isAllOnesValue()) {
5110             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5111             return BinaryOperator::CreateSub(
5112                            ConstantExpr::getSub(NegOp0CI,
5113                                       ConstantInt::get(I.getType(), 1)),
5114                                       Op0I->getOperand(0));
5115           } else if (RHS->getValue().isSignBit()) {
5116             // (X + C) ^ signbit -> (X + C + signbit)
5117             Constant *C = ConstantInt::get(*Context,
5118                                            RHS->getValue() + Op0CI->getValue());
5119             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5120
5121           }
5122         } else if (Op0I->getOpcode() == Instruction::Or) {
5123           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5124           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5125             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5126             // Anything in both C1 and C2 is known to be zero, remove it from
5127             // NewRHS.
5128             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5129             NewRHS = ConstantExpr::getAnd(NewRHS, 
5130                                        ConstantExpr::getNot(CommonBits));
5131             AddToWorkList(Op0I);
5132             I.setOperand(0, Op0I->getOperand(0));
5133             I.setOperand(1, NewRHS);
5134             return &I;
5135           }
5136         }
5137       }
5138     }
5139
5140     // Try to fold constant and into select arguments.
5141     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5142       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5143         return R;
5144     if (isa<PHINode>(Op0))
5145       if (Instruction *NV = FoldOpIntoPhi(I))
5146         return NV;
5147   }
5148
5149   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5150     if (X == Op1)
5151       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5152
5153   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5154     if (X == Op0)
5155       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5156
5157   
5158   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5159   if (Op1I) {
5160     Value *A, *B;
5161     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5162       if (A == Op0) {              // B^(B|A) == (A|B)^B
5163         Op1I->swapOperands();
5164         I.swapOperands();
5165         std::swap(Op0, Op1);
5166       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5167         I.swapOperands();     // Simplified below.
5168         std::swap(Op0, Op1);
5169       }
5170     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5171       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5172     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5173       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5174     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5175                Op1I->hasOneUse()){
5176       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5177         Op1I->swapOperands();
5178         std::swap(A, B);
5179       }
5180       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5181         I.swapOperands();     // Simplified below.
5182         std::swap(Op0, Op1);
5183       }
5184     }
5185   }
5186   
5187   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5188   if (Op0I) {
5189     Value *A, *B;
5190     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5191         Op0I->hasOneUse()) {
5192       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5193         std::swap(A, B);
5194       if (B == Op1) {                                // (A|B)^B == A & ~B
5195         Instruction *NotB =
5196           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5197         return BinaryOperator::CreateAnd(A, NotB);
5198       }
5199     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5200       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5201     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5202       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5203     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5204                Op0I->hasOneUse()){
5205       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5206         std::swap(A, B);
5207       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5208           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5209         Instruction *N =
5210           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5211         return BinaryOperator::CreateAnd(N, Op1);
5212       }
5213     }
5214   }
5215   
5216   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5217   if (Op0I && Op1I && Op0I->isShift() && 
5218       Op0I->getOpcode() == Op1I->getOpcode() && 
5219       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5220       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5221     Instruction *NewOp =
5222       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5223                                                     Op1I->getOperand(0),
5224                                                     Op0I->getName()), I);
5225     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5226                                   Op1I->getOperand(1));
5227   }
5228     
5229   if (Op0I && Op1I) {
5230     Value *A, *B, *C, *D;
5231     // (A & B)^(A | B) -> A ^ B
5232     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5233         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5234       if ((A == C && B == D) || (A == D && B == C)) 
5235         return BinaryOperator::CreateXor(A, B);
5236     }
5237     // (A | B)^(A & B) -> A ^ B
5238     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5239         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5240       if ((A == C && B == D) || (A == D && B == C)) 
5241         return BinaryOperator::CreateXor(A, B);
5242     }
5243     
5244     // (A & B)^(C & D)
5245     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5246         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5247         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5248       // (X & Y)^(X & Y) -> (Y^Z) & X
5249       Value *X = 0, *Y = 0, *Z = 0;
5250       if (A == C)
5251         X = A, Y = B, Z = D;
5252       else if (A == D)
5253         X = A, Y = B, Z = C;
5254       else if (B == C)
5255         X = B, Y = A, Z = D;
5256       else if (B == D)
5257         X = B, Y = A, Z = C;
5258       
5259       if (X) {
5260         Instruction *NewOp =
5261         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5262         return BinaryOperator::CreateAnd(NewOp, X);
5263       }
5264     }
5265   }
5266     
5267   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5268   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5269     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5270       return R;
5271
5272   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5273   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5274     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5275       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5276         const Type *SrcTy = Op0C->getOperand(0)->getType();
5277         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5278             // Only do this if the casts both really cause code to be generated.
5279             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5280                               I.getType(), TD) &&
5281             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5282                               I.getType(), TD)) {
5283           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5284                                                          Op1C->getOperand(0),
5285                                                          I.getName());
5286           InsertNewInstBefore(NewOp, I);
5287           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5288         }
5289       }
5290   }
5291
5292   return Changed ? &I : 0;
5293 }
5294
5295 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5296                                    LLVMContext *Context) {
5297   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5298 }
5299
5300 static bool HasAddOverflow(ConstantInt *Result,
5301                            ConstantInt *In1, ConstantInt *In2,
5302                            bool IsSigned) {
5303   if (IsSigned)
5304     if (In2->getValue().isNegative())
5305       return Result->getValue().sgt(In1->getValue());
5306     else
5307       return Result->getValue().slt(In1->getValue());
5308   else
5309     return Result->getValue().ult(In1->getValue());
5310 }
5311
5312 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5313 /// overflowed for this type.
5314 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5315                             Constant *In2, LLVMContext *Context,
5316                             bool IsSigned = false) {
5317   Result = ConstantExpr::getAdd(In1, In2);
5318
5319   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5320     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5321       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5322       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5323                          ExtractElement(In1, Idx, Context),
5324                          ExtractElement(In2, Idx, Context),
5325                          IsSigned))
5326         return true;
5327     }
5328     return false;
5329   }
5330
5331   return HasAddOverflow(cast<ConstantInt>(Result),
5332                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5333                         IsSigned);
5334 }
5335
5336 static bool HasSubOverflow(ConstantInt *Result,
5337                            ConstantInt *In1, ConstantInt *In2,
5338                            bool IsSigned) {
5339   if (IsSigned)
5340     if (In2->getValue().isNegative())
5341       return Result->getValue().slt(In1->getValue());
5342     else
5343       return Result->getValue().sgt(In1->getValue());
5344   else
5345     return Result->getValue().ugt(In1->getValue());
5346 }
5347
5348 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5349 /// overflowed for this type.
5350 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5351                             Constant *In2, LLVMContext *Context,
5352                             bool IsSigned = false) {
5353   Result = ConstantExpr::getSub(In1, In2);
5354
5355   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5356     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5357       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5358       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5359                          ExtractElement(In1, Idx, Context),
5360                          ExtractElement(In2, Idx, Context),
5361                          IsSigned))
5362         return true;
5363     }
5364     return false;
5365   }
5366
5367   return HasSubOverflow(cast<ConstantInt>(Result),
5368                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5369                         IsSigned);
5370 }
5371
5372 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5373 /// code necessary to compute the offset from the base pointer (without adding
5374 /// in the base pointer).  Return the result as a signed integer of intptr size.
5375 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5376   TargetData &TD = *IC.getTargetData();
5377   gep_type_iterator GTI = gep_type_begin(GEP);
5378   const Type *IntPtrTy = TD.getIntPtrType();
5379   LLVMContext *Context = IC.getContext();
5380   Value *Result = Constant::getNullValue(IntPtrTy);
5381
5382   // Build a mask for high order bits.
5383   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5384   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5385
5386   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5387        ++i, ++GTI) {
5388     Value *Op = *i;
5389     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5390     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5391       if (OpC->isZero()) continue;
5392       
5393       // Handle a struct index, which adds its field offset to the pointer.
5394       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5395         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5396         
5397         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5398           Result = 
5399              ConstantInt::get(*Context, 
5400                               RC->getValue() + APInt(IntPtrWidth, Size));
5401         else
5402           Result = IC.InsertNewInstBefore(
5403                    BinaryOperator::CreateAdd(Result,
5404                                         ConstantInt::get(IntPtrTy, Size),
5405                                              GEP->getName()+".offs"), I);
5406         continue;
5407       }
5408       
5409       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5410       Constant *OC =
5411               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412       Scale = ConstantExpr::getMul(OC, Scale);
5413       if (Constant *RC = dyn_cast<Constant>(Result))
5414         Result = ConstantExpr::getAdd(RC, Scale);
5415       else {
5416         // Emit an add instruction.
5417         Result = IC.InsertNewInstBefore(
5418            BinaryOperator::CreateAdd(Result, Scale,
5419                                      GEP->getName()+".offs"), I);
5420       }
5421       continue;
5422     }
5423     // Convert to correct type.
5424     if (Op->getType() != IntPtrTy) {
5425       if (Constant *OpC = dyn_cast<Constant>(Op))
5426         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5427       else
5428         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429                                                                 true,
5430                                                       Op->getName()+".c"), I);
5431     }
5432     if (Size != 1) {
5433       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5434       if (Constant *OpC = dyn_cast<Constant>(Op))
5435         Op = ConstantExpr::getMul(OpC, Scale);
5436       else    // We'll let instcombine(mul) convert this to a shl if possible.
5437         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5438                                                   GEP->getName()+".idx"), I);
5439     }
5440
5441     // Emit an add instruction.
5442     if (isa<Constant>(Op) && isa<Constant>(Result))
5443       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5444                                     cast<Constant>(Result));
5445     else
5446       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5447                                                   GEP->getName()+".offs"), I);
5448   }
5449   return Result;
5450 }
5451
5452
5453 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5454 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5455 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5456 /// be complex, and scales are involved.  The above expression would also be
5457 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5458 /// This later form is less amenable to optimization though, and we are allowed
5459 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5460 ///
5461 /// If we can't emit an optimized form for this expression, this returns null.
5462 /// 
5463 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464                                           InstCombiner &IC) {
5465   TargetData &TD = *IC.getTargetData();
5466   gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468   // Check to see if this gep only has a single variable index.  If so, and if
5469   // any constant indices are a multiple of its scale, then we can compute this
5470   // in terms of the scale of the variable index.  For example, if the GEP
5471   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472   // because the expression will cross zero at the same point.
5473   unsigned i, e = GEP->getNumOperands();
5474   int64_t Offset = 0;
5475   for (i = 1; i != e; ++i, ++GTI) {
5476     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477       // Compute the aggregate offset of constant indices.
5478       if (CI->isZero()) continue;
5479
5480       // Handle a struct index, which adds its field offset to the pointer.
5481       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483       } else {
5484         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5485         Offset += Size*CI->getSExtValue();
5486       }
5487     } else {
5488       // Found our variable index.
5489       break;
5490     }
5491   }
5492   
5493   // If there are no variable indices, we must have a constant offset, just
5494   // evaluate it the general way.
5495   if (i == e) return 0;
5496   
5497   Value *VariableIdx = GEP->getOperand(i);
5498   // Determine the scale factor of the variable element.  For example, this is
5499   // 4 if the variable index is into an array of i32.
5500   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5501   
5502   // Verify that there are no other variable indices.  If so, emit the hard way.
5503   for (++i, ++GTI; i != e; ++i, ++GTI) {
5504     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505     if (!CI) return 0;
5506    
5507     // Compute the aggregate offset of constant indices.
5508     if (CI->isZero()) continue;
5509     
5510     // Handle a struct index, which adds its field offset to the pointer.
5511     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513     } else {
5514       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5515       Offset += Size*CI->getSExtValue();
5516     }
5517   }
5518   
5519   // Okay, we know we have a single variable index, which must be a
5520   // pointer/array/vector index.  If there is no offset, life is simple, return
5521   // the index.
5522   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523   if (Offset == 0) {
5524     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5525     // we don't need to bother extending: the extension won't affect where the
5526     // computation crosses zero.
5527     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5529                                   VariableIdx->getName(), &I);
5530     return VariableIdx;
5531   }
5532   
5533   // Otherwise, there is an index.  The computation we will do will be modulo
5534   // the pointer size, so get it.
5535   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536   
5537   Offset &= PtrSizeMask;
5538   VariableScale &= PtrSizeMask;
5539
5540   // To do this transformation, any constant index must be a multiple of the
5541   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5542   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5543   // multiple of the variable scale.
5544   int64_t NewOffs = Offset / (int64_t)VariableScale;
5545   if (Offset != NewOffs*(int64_t)VariableScale)
5546     return 0;
5547
5548   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5549   const Type *IntPtrTy = TD.getIntPtrType();
5550   if (VariableIdx->getType() != IntPtrTy)
5551     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5552                                               true /*SExt*/, 
5553                                               VariableIdx->getName(), &I);
5554   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5555   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5556 }
5557
5558
5559 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5560 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5561 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5562                                        ICmpInst::Predicate Cond,
5563                                        Instruction &I) {
5564   // Look through bitcasts.
5565   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5566     RHS = BCI->getOperand(0);
5567
5568   Value *PtrBase = GEPLHS->getOperand(0);
5569   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5570     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5571     // This transformation (ignoring the base and scales) is valid because we
5572     // know pointers can't overflow since the gep is inbounds.  See if we can
5573     // output an optimized form.
5574     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5575     
5576     // If not, synthesize the offset the hard way.
5577     if (Offset == 0)
5578       Offset = EmitGEPOffset(GEPLHS, I, *this);
5579     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5580                         Constant::getNullValue(Offset->getType()));
5581   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5582     // If the base pointers are different, but the indices are the same, just
5583     // compare the base pointer.
5584     if (PtrBase != GEPRHS->getOperand(0)) {
5585       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5586       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5587                         GEPRHS->getOperand(0)->getType();
5588       if (IndicesTheSame)
5589         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5590           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5591             IndicesTheSame = false;
5592             break;
5593           }
5594
5595       // If all indices are the same, just compare the base pointers.
5596       if (IndicesTheSame)
5597         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5598                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5599
5600       // Otherwise, the base pointers are different and the indices are
5601       // different, bail out.
5602       return 0;
5603     }
5604
5605     // If one of the GEPs has all zero indices, recurse.
5606     bool AllZeros = true;
5607     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5608       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5609           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5610         AllZeros = false;
5611         break;
5612       }
5613     if (AllZeros)
5614       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5615                           ICmpInst::getSwappedPredicate(Cond), I);
5616
5617     // If the other GEP has all zero indices, recurse.
5618     AllZeros = true;
5619     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5620       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5621           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5622         AllZeros = false;
5623         break;
5624       }
5625     if (AllZeros)
5626       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5627
5628     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5629       // If the GEPs only differ by one index, compare it.
5630       unsigned NumDifferences = 0;  // Keep track of # differences.
5631       unsigned DiffOperand = 0;     // The operand that differs.
5632       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5633         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5634           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5635                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5636             // Irreconcilable differences.
5637             NumDifferences = 2;
5638             break;
5639           } else {
5640             if (NumDifferences++) break;
5641             DiffOperand = i;
5642           }
5643         }
5644
5645       if (NumDifferences == 0)   // SAME GEP?
5646         return ReplaceInstUsesWith(I, // No comparison is needed here.
5647                                    ConstantInt::get(Type::Int1Ty,
5648                                              ICmpInst::isTrueWhenEqual(Cond)));
5649
5650       else if (NumDifferences == 1) {
5651         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5652         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5653         // Make sure we do a signed comparison here.
5654         return new ICmpInst(*Context,
5655                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5656       }
5657     }
5658
5659     // Only lower this if the icmp is the only user of the GEP or if we expect
5660     // the result to fold to a constant!
5661     if (TD &&
5662         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5663         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5665       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5667       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5668     }
5669   }
5670   return 0;
5671 }
5672
5673 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674 ///
5675 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676                                                 Instruction *LHSI,
5677                                                 Constant *RHSC) {
5678   if (!isa<ConstantFP>(RHSC)) return 0;
5679   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680   
5681   // Get the width of the mantissa.  We don't want to hack on conversions that
5682   // might lose information from the integer, e.g. "i64 -> float"
5683   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5684   if (MantissaWidth == -1) return 0;  // Unknown.
5685   
5686   // Check to see that the input is converted from an integer type that is small
5687   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5688   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5689   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5690   
5691   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5692   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693   if (LHSUnsigned)
5694     ++InputSize;
5695   
5696   // If the conversion would lose info, don't hack on this.
5697   if ((int)InputSize > MantissaWidth)
5698     return 0;
5699   
5700   // Otherwise, we can potentially simplify the comparison.  We know that it
5701   // will always come through as an integer value and we know the constant is
5702   // not a NAN (it would have been previously simplified).
5703   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704   
5705   ICmpInst::Predicate Pred;
5706   switch (I.getPredicate()) {
5707   default: llvm_unreachable("Unexpected predicate!");
5708   case FCmpInst::FCMP_UEQ:
5709   case FCmpInst::FCMP_OEQ:
5710     Pred = ICmpInst::ICMP_EQ;
5711     break;
5712   case FCmpInst::FCMP_UGT:
5713   case FCmpInst::FCMP_OGT:
5714     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715     break;
5716   case FCmpInst::FCMP_UGE:
5717   case FCmpInst::FCMP_OGE:
5718     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719     break;
5720   case FCmpInst::FCMP_ULT:
5721   case FCmpInst::FCMP_OLT:
5722     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723     break;
5724   case FCmpInst::FCMP_ULE:
5725   case FCmpInst::FCMP_OLE:
5726     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727     break;
5728   case FCmpInst::FCMP_UNE:
5729   case FCmpInst::FCMP_ONE:
5730     Pred = ICmpInst::ICMP_NE;
5731     break;
5732   case FCmpInst::FCMP_ORD:
5733     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5734   case FCmpInst::FCMP_UNO:
5735     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5736   }
5737   
5738   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739   
5740   // Now we know that the APFloat is a normal number, zero or inf.
5741   
5742   // See if the FP constant is too large for the integer.  For example,
5743   // comparing an i8 to 300.0.
5744   unsigned IntWidth = IntTy->getScalarSizeInBits();
5745   
5746   if (!LHSUnsigned) {
5747     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5748     // and large values.
5749     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751                           APFloat::rmNearestTiesToEven);
5752     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5753       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5754           Pred == ICmpInst::ICMP_SLE)
5755         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5757     }
5758   } else {
5759     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760     // +INF and large values.
5761     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763                           APFloat::rmNearestTiesToEven);
5764     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5765       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5766           Pred == ICmpInst::ICMP_ULE)
5767         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5768       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5769     }
5770   }
5771   
5772   if (!LHSUnsigned) {
5773     // See if the RHS value is < SignedMin.
5774     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776                           APFloat::rmNearestTiesToEven);
5777     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779           Pred == ICmpInst::ICMP_SGE)
5780         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5782     }
5783   }
5784
5785   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5787   // casting the FP value to the integer value and back, checking for equality.
5788   // Don't do this for zero, because -0.0 is not fractional.
5789   Constant *RHSInt = LHSUnsigned
5790     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5791     : ConstantExpr::getFPToSI(RHSC, IntTy);
5792   if (!RHS.isZero()) {
5793     bool Equal = LHSUnsigned
5794       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5795       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5796     if (!Equal) {
5797       // If we had a comparison against a fractional value, we have to adjust
5798       // the compare predicate and sometimes the value.  RHSC is rounded towards
5799       // zero at this point.
5800       switch (Pred) {
5801       default: llvm_unreachable("Unexpected integer comparison!");
5802       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5803         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5804       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5805         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5806       case ICmpInst::ICMP_ULE:
5807         // (float)int <= 4.4   --> int <= 4
5808         // (float)int <= -4.4  --> false
5809         if (RHS.isNegative())
5810           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5811         break;
5812       case ICmpInst::ICMP_SLE:
5813         // (float)int <= 4.4   --> int <= 4
5814         // (float)int <= -4.4  --> int < -4
5815         if (RHS.isNegative())
5816           Pred = ICmpInst::ICMP_SLT;
5817         break;
5818       case ICmpInst::ICMP_ULT:
5819         // (float)int < -4.4   --> false
5820         // (float)int < 4.4    --> int <= 4
5821         if (RHS.isNegative())
5822           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5823         Pred = ICmpInst::ICMP_ULE;
5824         break;
5825       case ICmpInst::ICMP_SLT:
5826         // (float)int < -4.4   --> int < -4
5827         // (float)int < 4.4    --> int <= 4
5828         if (!RHS.isNegative())
5829           Pred = ICmpInst::ICMP_SLE;
5830         break;
5831       case ICmpInst::ICMP_UGT:
5832         // (float)int > 4.4    --> int > 4
5833         // (float)int > -4.4   --> true
5834         if (RHS.isNegative())
5835           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5836         break;
5837       case ICmpInst::ICMP_SGT:
5838         // (float)int > 4.4    --> int > 4
5839         // (float)int > -4.4   --> int >= -4
5840         if (RHS.isNegative())
5841           Pred = ICmpInst::ICMP_SGE;
5842         break;
5843       case ICmpInst::ICMP_UGE:
5844         // (float)int >= -4.4   --> true
5845         // (float)int >= 4.4    --> int > 4
5846         if (!RHS.isNegative())
5847           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5848         Pred = ICmpInst::ICMP_UGT;
5849         break;
5850       case ICmpInst::ICMP_SGE:
5851         // (float)int >= -4.4   --> int >= -4
5852         // (float)int >= 4.4    --> int > 4
5853         if (!RHS.isNegative())
5854           Pred = ICmpInst::ICMP_SGT;
5855         break;
5856       }
5857     }
5858   }
5859
5860   // Lower this FP comparison into an appropriate integer version of the
5861   // comparison.
5862   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5863 }
5864
5865 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866   bool Changed = SimplifyCompare(I);
5867   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5868
5869   // Fold trivial predicates.
5870   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5871     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5872   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5873     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5874   
5875   // Simplify 'fcmp pred X, X'
5876   if (Op0 == Op1) {
5877     switch (I.getPredicate()) {
5878     default: llvm_unreachable("Unknown predicate!");
5879     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5880     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5881     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5882       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5883     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5884     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5885     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5886       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5887       
5888     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5889     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5890     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5891     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5892       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893       I.setPredicate(FCmpInst::FCMP_UNO);
5894       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5895       return &I;
5896       
5897     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5898     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5899     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5900     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5901       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902       I.setPredicate(FCmpInst::FCMP_ORD);
5903       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5904       return &I;
5905     }
5906   }
5907     
5908   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5909     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5910
5911   // Handle fcmp with constant RHS
5912   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5913     // If the constant is a nan, see if we can fold the comparison based on it.
5914     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915       if (CFP->getValueAPF().isNaN()) {
5916         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5917           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5918         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919                "Comparison must be either ordered or unordered!");
5920         // True if unordered.
5921         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5922       }
5923     }
5924     
5925     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926       switch (LHSI->getOpcode()) {
5927       case Instruction::PHI:
5928         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929         // block.  If in the same block, we're encouraging jump threading.  If
5930         // not, we are just pessimizing the code by making an i1 phi.
5931         if (LHSI->getParent() == I.getParent())
5932           if (Instruction *NV = FoldOpIntoPhi(I))
5933             return NV;
5934         break;
5935       case Instruction::SIToFP:
5936       case Instruction::UIToFP:
5937         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938           return NV;
5939         break;
5940       case Instruction::Select:
5941         // If either operand of the select is a constant, we can fold the
5942         // comparison into the select arms, which will cause one to be
5943         // constant folded and the select turned into a bitwise or.
5944         Value *Op1 = 0, *Op2 = 0;
5945         if (LHSI->hasOneUse()) {
5946           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947             // Fold the known value into the constant operand.
5948             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5949             // Insert a new FCmp of the other select operand.
5950             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5951                                                       LHSI->getOperand(2), RHSC,
5952                                                       I.getName()), I);
5953           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954             // Fold the known value into the constant operand.
5955             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5956             // Insert a new FCmp of the other select operand.
5957             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5958                                                       LHSI->getOperand(1), RHSC,
5959                                                       I.getName()), I);
5960           }
5961         }
5962
5963         if (Op1)
5964           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5965         break;
5966       }
5967   }
5968
5969   return Changed ? &I : 0;
5970 }
5971
5972 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973   bool Changed = SimplifyCompare(I);
5974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975   const Type *Ty = Op0->getType();
5976
5977   // icmp X, X
5978   if (Op0 == Op1)
5979     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5980                                                    I.isTrueWhenEqual()));
5981
5982   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5983     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5984   
5985   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5986   // addresses never equal each other!  We already know that Op0 != Op1.
5987   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988        isa<ConstantPointerNull>(Op0)) &&
5989       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5990        isa<ConstantPointerNull>(Op1)))
5991     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5992                                                    !I.isTrueWhenEqual()));
5993
5994   // icmp's with boolean values can always be turned into bitwise operations
5995   if (Ty == Type::Int1Ty) {
5996     switch (I.getPredicate()) {
5997     default: llvm_unreachable("Invalid icmp instruction!");
5998     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5999       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6000       InsertNewInstBefore(Xor, I);
6001       return BinaryOperator::CreateNot(Xor);
6002     }
6003     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6004       return BinaryOperator::CreateXor(Op0, Op1);
6005
6006     case ICmpInst::ICMP_UGT:
6007       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6010       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6011       InsertNewInstBefore(Not, I);
6012       return BinaryOperator::CreateAnd(Not, Op1);
6013     }
6014     case ICmpInst::ICMP_SGT:
6015       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6016       // FALL THROUGH
6017     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6018       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6019       InsertNewInstBefore(Not, I);
6020       return BinaryOperator::CreateAnd(Not, Op0);
6021     }
6022     case ICmpInst::ICMP_UGE:
6023       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6024       // FALL THROUGH
6025     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6026       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6027       InsertNewInstBefore(Not, I);
6028       return BinaryOperator::CreateOr(Not, Op1);
6029     }
6030     case ICmpInst::ICMP_SGE:
6031       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6032       // FALL THROUGH
6033     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6034       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6035       InsertNewInstBefore(Not, I);
6036       return BinaryOperator::CreateOr(Not, Op0);
6037     }
6038     }
6039   }
6040
6041   unsigned BitWidth = 0;
6042   if (TD)
6043     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044   else if (Ty->isIntOrIntVector())
6045     BitWidth = Ty->getScalarSizeInBits();
6046
6047   bool isSignBit = false;
6048
6049   // See if we are doing a comparison with a constant.
6050   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6051     Value *A = 0, *B = 0;
6052     
6053     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054     if (I.isEquality() && CI->isNullValue() &&
6055         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6056       // (icmp cond A B) if cond is equality
6057       return new ICmpInst(*Context, I.getPredicate(), A, B);
6058     }
6059     
6060     // If we have an icmp le or icmp ge instruction, turn it into the
6061     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6062     // them being folded in the code below.
6063     switch (I.getPredicate()) {
6064     default: break;
6065     case ICmpInst::ICMP_ULE:
6066       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6067         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6068       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6069                           AddOne(CI));
6070     case ICmpInst::ICMP_SLE:
6071       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6072         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6073       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6074                           AddOne(CI));
6075     case ICmpInst::ICMP_UGE:
6076       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6077         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6078       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6079                           SubOne(CI));
6080     case ICmpInst::ICMP_SGE:
6081       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6082         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6083       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6084                           SubOne(CI));
6085     }
6086     
6087     // If this comparison is a normal comparison, it demands all
6088     // bits, if it is a sign bit comparison, it only demands the sign bit.
6089     bool UnusedBit;
6090     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091   }
6092
6093   // See if we can fold the comparison based on range information we can get
6094   // by checking whether bits are known to be zero or one in the input.
6095   if (BitWidth != 0) {
6096     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099     if (SimplifyDemandedBits(I.getOperandUse(0),
6100                              isSignBit ? APInt::getSignBit(BitWidth)
6101                                        : APInt::getAllOnesValue(BitWidth),
6102                              Op0KnownZero, Op0KnownOne, 0))
6103       return &I;
6104     if (SimplifyDemandedBits(I.getOperandUse(1),
6105                              APInt::getAllOnesValue(BitWidth),
6106                              Op1KnownZero, Op1KnownOne, 0))
6107       return &I;
6108
6109     // Given the known and unknown bits, compute a range that the LHS could be
6110     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6111     // EQ and NE we use unsigned values.
6112     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116                                              Op0Min, Op0Max);
6117       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118                                              Op1Min, Op1Max);
6119     } else {
6120       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121                                                Op0Min, Op0Max);
6122       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123                                                Op1Min, Op1Max);
6124     }
6125
6126     // If Min and Max are known to be the same, then SimplifyDemandedBits
6127     // figured out that the LHS is a constant.  Just constant fold this now so
6128     // that code below can assume that Min != Max.
6129     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6130       return new ICmpInst(*Context, I.getPredicate(),
6131                           ConstantInt::get(*Context, Op0Min), Op1);
6132     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6133       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6134                           ConstantInt::get(*Context, Op1Min));
6135
6136     // Based on the range information we know about the LHS, see if we can
6137     // simplify this comparison.  For example, (x&4) < 8  is always true.
6138     switch (I.getPredicate()) {
6139     default: llvm_unreachable("Unknown icmp opcode!");
6140     case ICmpInst::ICMP_EQ:
6141       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6142         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6143       break;
6144     case ICmpInst::ICMP_NE:
6145       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6146         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6147       break;
6148     case ICmpInst::ICMP_ULT:
6149       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6150         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6151       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6152         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6153       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6154         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6155       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6157           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158                               SubOne(CI));
6159
6160         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6161         if (CI->isMinValue(true))
6162           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6163                            Constant::getAllOnesValue(Op0->getType()));
6164       }
6165       break;
6166     case ICmpInst::ICMP_UGT:
6167       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6168         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6169       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6170         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6171
6172       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6173         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6174       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6176           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177                               AddOne(CI));
6178
6179         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6180         if (CI->isMaxValue(true))
6181           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6182                               Constant::getNullValue(Op0->getType()));
6183       }
6184       break;
6185     case ICmpInst::ICMP_SLT:
6186       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6187         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6188       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6189         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6190       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6191         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6192       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6194           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6195                               SubOne(CI));
6196       }
6197       break;
6198     case ICmpInst::ICMP_SGT:
6199       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6200         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6201       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6202         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6203
6204       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6205         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6208           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209                               AddOne(CI));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGE:
6213       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6215         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6216       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6217         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6218       break;
6219     case ICmpInst::ICMP_SLE:
6220       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6222         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6223       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6224         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6225       break;
6226     case ICmpInst::ICMP_UGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6230       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6232       break;
6233     case ICmpInst::ICMP_ULE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6237       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6239       break;
6240     }
6241
6242     // Turn a signed comparison into an unsigned one if both operands
6243     // are known to have the same sign.
6244     if (I.isSignedPredicate() &&
6245         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6247       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6248   }
6249
6250   // Test if the ICmpInst instruction is used exclusively by a select as
6251   // part of a minimum or maximum operation. If so, refrain from doing
6252   // any other folding. This helps out other analyses which understand
6253   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254   // and CodeGen. And in this case, at least one of the comparison
6255   // operands has at least one user besides the compare (the select),
6256   // which would often largely negate the benefit of folding anyway.
6257   if (I.hasOneUse())
6258     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261         return 0;
6262
6263   // See if we are doing a comparison between a constant and an instruction that
6264   // can be folded into the comparison.
6265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6266     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6267     // instruction, see if that instruction also has constants so that the 
6268     // instruction can be folded into the icmp 
6269     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6270       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271         return Res;
6272   }
6273
6274   // Handle icmp with constant (but not simple integer constant) RHS
6275   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277       switch (LHSI->getOpcode()) {
6278       case Instruction::GetElementPtr:
6279         if (RHSC->isNullValue()) {
6280           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6281           bool isAllZeros = true;
6282           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283             if (!isa<Constant>(LHSI->getOperand(i)) ||
6284                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285               isAllZeros = false;
6286               break;
6287             }
6288           if (isAllZeros)
6289             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6290                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6291         }
6292         break;
6293
6294       case Instruction::PHI:
6295         // Only fold icmp into the PHI if the phi and fcmp are in the same
6296         // block.  If in the same block, we're encouraging jump threading.  If
6297         // not, we are just pessimizing the code by making an i1 phi.
6298         if (LHSI->getParent() == I.getParent())
6299           if (Instruction *NV = FoldOpIntoPhi(I))
6300             return NV;
6301         break;
6302       case Instruction::Select: {
6303         // If either operand of the select is a constant, we can fold the
6304         // comparison into the select arms, which will cause one to be
6305         // constant folded and the select turned into a bitwise or.
6306         Value *Op1 = 0, *Op2 = 0;
6307         if (LHSI->hasOneUse()) {
6308           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309             // Fold the known value into the constant operand.
6310             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6311             // Insert a new ICmp of the other select operand.
6312             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6313                                                    LHSI->getOperand(2), RHSC,
6314                                                    I.getName()), I);
6315           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316             // Fold the known value into the constant operand.
6317             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6318             // Insert a new ICmp of the other select operand.
6319             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6320                                                    LHSI->getOperand(1), RHSC,
6321                                                    I.getName()), I);
6322           }
6323         }
6324
6325         if (Op1)
6326           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6327         break;
6328       }
6329       case Instruction::Malloc:
6330         // If we have (malloc != null), and if the malloc has a single use, we
6331         // can assume it is successful and remove the malloc.
6332         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333           AddToWorkList(LHSI);
6334           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6335                                                          !I.isTrueWhenEqual()));
6336         }
6337         break;
6338       }
6339   }
6340
6341   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6342   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6343     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6344       return NI;
6345   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6346     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6348       return NI;
6349
6350   // Test to see if the operands of the icmp are casted versions of other
6351   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6352   // now.
6353   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354     if (isa<PointerType>(Op0->getType()) && 
6355         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6356       // We keep moving the cast from the left operand over to the right
6357       // operand, where it can often be eliminated completely.
6358       Op0 = CI->getOperand(0);
6359
6360       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361       // so eliminate it as well.
6362       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363         Op1 = CI2->getOperand(0);
6364
6365       // If Op1 is a constant, we can fold the cast into the constant.
6366       if (Op0->getType() != Op1->getType()) {
6367         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6368           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6369         } else {
6370           // Otherwise, cast the RHS right before the icmp
6371           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6372         }
6373       }
6374       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6375     }
6376   }
6377   
6378   if (isa<CastInst>(Op0)) {
6379     // Handle the special case of: icmp (cast bool to X), <cst>
6380     // This comes up when you have code like
6381     //   int X = A < B;
6382     //   if (X) ...
6383     // For generality, we handle any zero-extension of any operand comparison
6384     // with a constant or another cast from the same type.
6385     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6386       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6387         return R;
6388   }
6389   
6390   // See if it's the same type of instruction on the left and right.
6391   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6393       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6394           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6395         switch (Op0I->getOpcode()) {
6396         default: break;
6397         case Instruction::Add:
6398         case Instruction::Sub:
6399         case Instruction::Xor:
6400           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6401             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6402                                 Op1I->getOperand(0));
6403           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405             if (CI->getValue().isSignBit()) {
6406               ICmpInst::Predicate Pred = I.isSignedPredicate()
6407                                              ? I.getUnsignedPredicate()
6408                                              : I.getSignedPredicate();
6409               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6410                                   Op1I->getOperand(0));
6411             }
6412             
6413             if (CI->getValue().isMaxSignedValue()) {
6414               ICmpInst::Predicate Pred = I.isSignedPredicate()
6415                                              ? I.getUnsignedPredicate()
6416                                              : I.getSignedPredicate();
6417               Pred = I.getSwappedPredicate(Pred);
6418               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6419                                   Op1I->getOperand(0));
6420             }
6421           }
6422           break;
6423         case Instruction::Mul:
6424           if (!I.isEquality())
6425             break;
6426
6427           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429             // Mask = -1 >> count-trailing-zeros(Cst).
6430             if (!CI->isZero() && !CI->isOne()) {
6431               const APInt &AP = CI->getValue();
6432               ConstantInt *Mask = ConstantInt::get(*Context, 
6433                                       APInt::getLowBitsSet(AP.getBitWidth(),
6434                                                            AP.getBitWidth() -
6435                                                       AP.countTrailingZeros()));
6436               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437                                                             Mask);
6438               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439                                                             Mask);
6440               InsertNewInstBefore(And1, I);
6441               InsertNewInstBefore(And2, I);
6442               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6443             }
6444           }
6445           break;
6446         }
6447       }
6448     }
6449   }
6450   
6451   // ~x < ~y --> y < x
6452   { Value *A, *B;
6453     if (match(Op0, m_Not(m_Value(A))) &&
6454         match(Op1, m_Not(m_Value(B))))
6455       return new ICmpInst(*Context, I.getPredicate(), B, A);
6456   }
6457   
6458   if (I.isEquality()) {
6459     Value *A, *B, *C, *D;
6460     
6461     // -x == -y --> x == y
6462     if (match(Op0, m_Neg(m_Value(A))) &&
6463         match(Op1, m_Neg(m_Value(B))))
6464       return new ICmpInst(*Context, I.getPredicate(), A, B);
6465     
6466     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6467       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6468         Value *OtherVal = A == Op1 ? B : A;
6469         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6470                             Constant::getNullValue(A->getType()));
6471       }
6472
6473       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6474         // A^c1 == C^c2 --> A == C^(c1^c2)
6475         ConstantInt *C1, *C2;
6476         if (match(B, m_ConstantInt(C1)) &&
6477             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6478           Constant *NC = 
6479                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6480           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6481           return new ICmpInst(*Context, I.getPredicate(), A,
6482                               InsertNewInstBefore(Xor, I));
6483         }
6484         
6485         // A^B == A^D -> B == D
6486         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6490       }
6491     }
6492     
6493     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6494         (A == Op0 || B == Op0)) {
6495       // A == (A^B)  ->  B == 0
6496       Value *OtherVal = A == Op0 ? B : A;
6497       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6498                           Constant::getNullValue(A->getType()));
6499     }
6500
6501     // (A-B) == A  ->  B == 0
6502     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6503       return new ICmpInst(*Context, I.getPredicate(), B, 
6504                           Constant::getNullValue(B->getType()));
6505
6506     // A == (A-B)  ->  B == 0
6507     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6508       return new ICmpInst(*Context, I.getPredicate(), B,
6509                           Constant::getNullValue(B->getType()));
6510     
6511     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6513         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6514         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6515       Value *X = 0, *Y = 0, *Z = 0;
6516       
6517       if (A == C) {
6518         X = B; Y = D; Z = A;
6519       } else if (A == D) {
6520         X = B; Y = C; Z = A;
6521       } else if (B == C) {
6522         X = A; Y = D; Z = B;
6523       } else if (B == D) {
6524         X = A; Y = C; Z = B;
6525       }
6526       
6527       if (X) {   // Build (X^Y) & Z
6528         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6530         I.setOperand(0, Op1);
6531         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6532         return &I;
6533       }
6534     }
6535   }
6536   return Changed ? &I : 0;
6537 }
6538
6539
6540 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541 /// and CmpRHS are both known to be integer constants.
6542 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543                                           ConstantInt *DivRHS) {
6544   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545   const APInt &CmpRHSV = CmpRHS->getValue();
6546   
6547   // FIXME: If the operand types don't match the type of the divide 
6548   // then don't attempt this transform. The code below doesn't have the
6549   // logic to deal with a signed divide and an unsigned compare (and
6550   // vice versa). This is because (x /s C1) <s C2  produces different 
6551   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6553   // work. :(  The if statement below tests that condition and bails 
6554   // if it finds it. 
6555   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557     return 0;
6558   if (DivRHS->isZero())
6559     return 0; // The ProdOV computation fails on divide by zero.
6560   if (DivIsSigned && DivRHS->isAllOnesValue())
6561     return 0; // The overflow computation also screws up here
6562   if (DivRHS->isOne())
6563     return 0; // Not worth bothering, and eliminates some funny cases
6564               // with INT_MIN.
6565
6566   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6568   // C2 (CI). By solving for X we can turn this into a range check 
6569   // instead of computing a divide. 
6570   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6571
6572   // Determine if the product overflows by seeing if the product is
6573   // not equal to the divide. Make sure we do the same kind of divide
6574   // as in the LHS instruction that we're folding. 
6575   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6576                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6577
6578   // Get the ICmp opcode
6579   ICmpInst::Predicate Pred = ICI.getPredicate();
6580
6581   // Figure out the interval that is being checked.  For example, a comparison
6582   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6583   // Compute this interval based on the constants involved and the signedness of
6584   // the compare/divide.  This computes a half-open interval, keeping track of
6585   // whether either value in the interval overflows.  After analysis each
6586   // overflow variable is set to 0 if it's corresponding bound variable is valid
6587   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588   int LoOverflow = 0, HiOverflow = 0;
6589   Constant *LoBound = 0, *HiBound = 0;
6590   
6591   if (!DivIsSigned) {  // udiv
6592     // e.g. X/5 op 3  --> [15, 20)
6593     LoBound = Prod;
6594     HiOverflow = LoOverflow = ProdOV;
6595     if (!HiOverflow)
6596       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6597   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6598     if (CmpRHSV == 0) {       // (X / pos) op 0
6599       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6600       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6601       HiBound = DivRHS;
6602     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6603       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6604       HiOverflow = LoOverflow = ProdOV;
6605       if (!HiOverflow)
6606         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6607     } else {                       // (X / pos) op neg
6608       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6609       HiBound = AddOne(Prod);
6610       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6611       if (!LoOverflow) {
6612         ConstantInt* DivNeg =
6613                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6614         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6615                                      true) ? -1 : 0;
6616        }
6617     }
6618   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6619     if (CmpRHSV == 0) {       // (X / neg) op 0
6620       // e.g. X/-5 op 0  --> [-4, 5)
6621       LoBound = AddOne(DivRHS);
6622       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6623       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6624         HiOverflow = 1;            // [INTMIN+1, overflow)
6625         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6626       }
6627     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6628       // e.g. X/-5 op 3  --> [-19, -14)
6629       HiBound = AddOne(Prod);
6630       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6631       if (!LoOverflow)
6632         LoOverflow = AddWithOverflow(LoBound, HiBound,
6633                                      DivRHS, Context, true) ? -1 : 0;
6634     } else {                       // (X / neg) op neg
6635       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6636       LoOverflow = HiOverflow = ProdOV;
6637       if (!HiOverflow)
6638         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6639     }
6640     
6641     // Dividing by a negative swaps the condition.  LT <-> GT
6642     Pred = ICmpInst::getSwappedPredicate(Pred);
6643   }
6644
6645   Value *X = DivI->getOperand(0);
6646   switch (Pred) {
6647   default: llvm_unreachable("Unhandled icmp opcode!");
6648   case ICmpInst::ICMP_EQ:
6649     if (LoOverflow && HiOverflow)
6650       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6651     else if (HiOverflow)
6652       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6653                           ICmpInst::ICMP_UGE, X, LoBound);
6654     else if (LoOverflow)
6655       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6656                           ICmpInst::ICMP_ULT, X, HiBound);
6657     else
6658       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6659   case ICmpInst::ICMP_NE:
6660     if (LoOverflow && HiOverflow)
6661       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6662     else if (HiOverflow)
6663       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6664                           ICmpInst::ICMP_ULT, X, LoBound);
6665     else if (LoOverflow)
6666       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6667                           ICmpInst::ICMP_UGE, X, HiBound);
6668     else
6669       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6670   case ICmpInst::ICMP_ULT:
6671   case ICmpInst::ICMP_SLT:
6672     if (LoOverflow == +1)   // Low bound is greater than input range.
6673       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6674     if (LoOverflow == -1)   // Low bound is less than input range.
6675       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6676     return new ICmpInst(*Context, Pred, X, LoBound);
6677   case ICmpInst::ICMP_UGT:
6678   case ICmpInst::ICMP_SGT:
6679     if (HiOverflow == +1)       // High bound greater than input range.
6680       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6681     else if (HiOverflow == -1)  // High bound less than input range.
6682       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6683     if (Pred == ICmpInst::ICMP_UGT)
6684       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6685     else
6686       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6687   }
6688 }
6689
6690
6691 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6692 ///
6693 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6694                                                           Instruction *LHSI,
6695                                                           ConstantInt *RHS) {
6696   const APInt &RHSV = RHS->getValue();
6697   
6698   switch (LHSI->getOpcode()) {
6699   case Instruction::Trunc:
6700     if (ICI.isEquality() && LHSI->hasOneUse()) {
6701       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6702       // of the high bits truncated out of x are known.
6703       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6704              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6705       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6706       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6707       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6708       
6709       // If all the high bits are known, we can do this xform.
6710       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6711         // Pull in the high bits from known-ones set.
6712         APInt NewRHS(RHS->getValue());
6713         NewRHS.zext(SrcBits);
6714         NewRHS |= KnownOne;
6715         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6716                             ConstantInt::get(*Context, NewRHS));
6717       }
6718     }
6719     break;
6720       
6721   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6722     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6723       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6724       // fold the xor.
6725       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6726           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6727         Value *CompareVal = LHSI->getOperand(0);
6728         
6729         // If the sign bit of the XorCST is not set, there is no change to
6730         // the operation, just stop using the Xor.
6731         if (!XorCST->getValue().isNegative()) {
6732           ICI.setOperand(0, CompareVal);
6733           AddToWorkList(LHSI);
6734           return &ICI;
6735         }
6736         
6737         // Was the old condition true if the operand is positive?
6738         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6739         
6740         // If so, the new one isn't.
6741         isTrueIfPositive ^= true;
6742         
6743         if (isTrueIfPositive)
6744           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6745                               SubOne(RHS));
6746         else
6747           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6748                               AddOne(RHS));
6749       }
6750
6751       if (LHSI->hasOneUse()) {
6752         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6753         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6754           const APInt &SignBit = XorCST->getValue();
6755           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6756                                          ? ICI.getUnsignedPredicate()
6757                                          : ICI.getSignedPredicate();
6758           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6759                               ConstantInt::get(*Context, RHSV ^ SignBit));
6760         }
6761
6762         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6763         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6764           const APInt &NotSignBit = XorCST->getValue();
6765           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6766                                          ? ICI.getUnsignedPredicate()
6767                                          : ICI.getSignedPredicate();
6768           Pred = ICI.getSwappedPredicate(Pred);
6769           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6770                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6771         }
6772       }
6773     }
6774     break;
6775   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6776     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6777         LHSI->getOperand(0)->hasOneUse()) {
6778       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6779       
6780       // If the LHS is an AND of a truncating cast, we can widen the
6781       // and/compare to be the input width without changing the value
6782       // produced, eliminating a cast.
6783       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6784         // We can do this transformation if either the AND constant does not
6785         // have its sign bit set or if it is an equality comparison. 
6786         // Extending a relational comparison when we're checking the sign
6787         // bit would not work.
6788         if (Cast->hasOneUse() &&
6789             (ICI.isEquality() ||
6790              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6791           uint32_t BitWidth = 
6792             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6793           APInt NewCST = AndCST->getValue();
6794           NewCST.zext(BitWidth);
6795           APInt NewCI = RHSV;
6796           NewCI.zext(BitWidth);
6797           Instruction *NewAnd = 
6798             BinaryOperator::CreateAnd(Cast->getOperand(0),
6799                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6800           InsertNewInstBefore(NewAnd, ICI);
6801           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6802                               ConstantInt::get(*Context, NewCI));
6803         }
6804       }
6805       
6806       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6807       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6808       // happens a LOT in code produced by the C front-end, for bitfield
6809       // access.
6810       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6811       if (Shift && !Shift->isShift())
6812         Shift = 0;
6813       
6814       ConstantInt *ShAmt;
6815       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6816       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6817       const Type *AndTy = AndCST->getType();          // Type of the and.
6818       
6819       // We can fold this as long as we can't shift unknown bits
6820       // into the mask.  This can only happen with signed shift
6821       // rights, as they sign-extend.
6822       if (ShAmt) {
6823         bool CanFold = Shift->isLogicalShift();
6824         if (!CanFold) {
6825           // To test for the bad case of the signed shr, see if any
6826           // of the bits shifted in could be tested after the mask.
6827           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6828           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6829           
6830           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6831           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6832                AndCST->getValue()) == 0)
6833             CanFold = true;
6834         }
6835         
6836         if (CanFold) {
6837           Constant *NewCst;
6838           if (Shift->getOpcode() == Instruction::Shl)
6839             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6840           else
6841             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6842           
6843           // Check to see if we are shifting out any of the bits being
6844           // compared.
6845           if (ConstantExpr::get(Shift->getOpcode(),
6846                                        NewCst, ShAmt) != RHS) {
6847             // If we shifted bits out, the fold is not going to work out.
6848             // As a special case, check to see if this means that the
6849             // result is always true or false now.
6850             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6851               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6852             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6853               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6854           } else {
6855             ICI.setOperand(1, NewCst);
6856             Constant *NewAndCST;
6857             if (Shift->getOpcode() == Instruction::Shl)
6858               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6859             else
6860               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6861             LHSI->setOperand(1, NewAndCST);
6862             LHSI->setOperand(0, Shift->getOperand(0));
6863             AddToWorkList(Shift); // Shift is dead.
6864             AddUsesToWorkList(ICI);
6865             return &ICI;
6866           }
6867         }
6868       }
6869       
6870       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6871       // preferable because it allows the C<<Y expression to be hoisted out
6872       // of a loop if Y is invariant and X is not.
6873       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6874           ICI.isEquality() && !Shift->isArithmeticShift() &&
6875           !isa<Constant>(Shift->getOperand(0))) {
6876         // Compute C << Y.
6877         Value *NS;
6878         if (Shift->getOpcode() == Instruction::LShr) {
6879           NS = BinaryOperator::CreateShl(AndCST, 
6880                                          Shift->getOperand(1), "tmp");
6881         } else {
6882           // Insert a logical shift.
6883           NS = BinaryOperator::CreateLShr(AndCST,
6884                                           Shift->getOperand(1), "tmp");
6885         }
6886         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6887         
6888         // Compute X & (C << Y).
6889         Instruction *NewAnd = 
6890           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6891         InsertNewInstBefore(NewAnd, ICI);
6892         
6893         ICI.setOperand(0, NewAnd);
6894         return &ICI;
6895       }
6896     }
6897     break;
6898     
6899   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6900     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6901     if (!ShAmt) break;
6902     
6903     uint32_t TypeBits = RHSV.getBitWidth();
6904     
6905     // Check that the shift amount is in range.  If not, don't perform
6906     // undefined shifts.  When the shift is visited it will be
6907     // simplified.
6908     if (ShAmt->uge(TypeBits))
6909       break;
6910     
6911     if (ICI.isEquality()) {
6912       // If we are comparing against bits always shifted out, the
6913       // comparison cannot succeed.
6914       Constant *Comp =
6915         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6916                                                                  ShAmt);
6917       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6918         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6919         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6920         return ReplaceInstUsesWith(ICI, Cst);
6921       }
6922       
6923       if (LHSI->hasOneUse()) {
6924         // Otherwise strength reduce the shift into an and.
6925         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6926         Constant *Mask =
6927           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6928                                                        TypeBits-ShAmtVal));
6929         
6930         Instruction *AndI =
6931           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6932                                     Mask, LHSI->getName()+".mask");
6933         Value *And = InsertNewInstBefore(AndI, ICI);
6934         return new ICmpInst(*Context, ICI.getPredicate(), And,
6935                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6936       }
6937     }
6938     
6939     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6940     bool TrueIfSigned = false;
6941     if (LHSI->hasOneUse() &&
6942         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6943       // (X << 31) <s 0  --> (X&1) != 0
6944       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6945                                            (TypeBits-ShAmt->getZExtValue()-1));
6946       Instruction *AndI =
6947         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6948                                   Mask, LHSI->getName()+".mask");
6949       Value *And = InsertNewInstBefore(AndI, ICI);
6950       
6951       return new ICmpInst(*Context,
6952                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6953                           And, Constant::getNullValue(And->getType()));
6954     }
6955     break;
6956   }
6957     
6958   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6959   case Instruction::AShr: {
6960     // Only handle equality comparisons of shift-by-constant.
6961     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6962     if (!ShAmt || !ICI.isEquality()) break;
6963
6964     // Check that the shift amount is in range.  If not, don't perform
6965     // undefined shifts.  When the shift is visited it will be
6966     // simplified.
6967     uint32_t TypeBits = RHSV.getBitWidth();
6968     if (ShAmt->uge(TypeBits))
6969       break;
6970     
6971     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6972       
6973     // If we are comparing against bits always shifted out, the
6974     // comparison cannot succeed.
6975     APInt Comp = RHSV << ShAmtVal;
6976     if (LHSI->getOpcode() == Instruction::LShr)
6977       Comp = Comp.lshr(ShAmtVal);
6978     else
6979       Comp = Comp.ashr(ShAmtVal);
6980     
6981     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6982       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6983       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6984       return ReplaceInstUsesWith(ICI, Cst);
6985     }
6986     
6987     // Otherwise, check to see if the bits shifted out are known to be zero.
6988     // If so, we can compare against the unshifted value:
6989     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6990     if (LHSI->hasOneUse() &&
6991         MaskedValueIsZero(LHSI->getOperand(0), 
6992                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6993       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6994                           ConstantExpr::getShl(RHS, ShAmt));
6995     }
6996       
6997     if (LHSI->hasOneUse()) {
6998       // Otherwise strength reduce the shift into an and.
6999       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7000       Constant *Mask = ConstantInt::get(*Context, Val);
7001       
7002       Instruction *AndI =
7003         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7004                                   Mask, LHSI->getName()+".mask");
7005       Value *And = InsertNewInstBefore(AndI, ICI);
7006       return new ICmpInst(*Context, ICI.getPredicate(), And,
7007                           ConstantExpr::getShl(RHS, ShAmt));
7008     }
7009     break;
7010   }
7011     
7012   case Instruction::SDiv:
7013   case Instruction::UDiv:
7014     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7015     // Fold this div into the comparison, producing a range check. 
7016     // Determine, based on the divide type, what the range is being 
7017     // checked.  If there is an overflow on the low or high side, remember 
7018     // it, otherwise compute the range [low, hi) bounding the new value.
7019     // See: InsertRangeTest above for the kinds of replacements possible.
7020     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7021       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7022                                           DivRHS))
7023         return R;
7024     break;
7025
7026   case Instruction::Add:
7027     // Fold: icmp pred (add, X, C1), C2
7028
7029     if (!ICI.isEquality()) {
7030       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7031       if (!LHSC) break;
7032       const APInt &LHSV = LHSC->getValue();
7033
7034       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7035                             .subtract(LHSV);
7036
7037       if (ICI.isSignedPredicate()) {
7038         if (CR.getLower().isSignBit()) {
7039           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7040                               ConstantInt::get(*Context, CR.getUpper()));
7041         } else if (CR.getUpper().isSignBit()) {
7042           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7043                               ConstantInt::get(*Context, CR.getLower()));
7044         }
7045       } else {
7046         if (CR.getLower().isMinValue()) {
7047           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7048                               ConstantInt::get(*Context, CR.getUpper()));
7049         } else if (CR.getUpper().isMinValue()) {
7050           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7051                               ConstantInt::get(*Context, CR.getLower()));
7052         }
7053       }
7054     }
7055     break;
7056   }
7057   
7058   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7059   if (ICI.isEquality()) {
7060     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7061     
7062     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7063     // the second operand is a constant, simplify a bit.
7064     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7065       switch (BO->getOpcode()) {
7066       case Instruction::SRem:
7067         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7068         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7069           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7070           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7071             Instruction *NewRem =
7072               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7073                                          BO->getName());
7074             InsertNewInstBefore(NewRem, ICI);
7075             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7076                                 Constant::getNullValue(BO->getType()));
7077           }
7078         }
7079         break;
7080       case Instruction::Add:
7081         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7082         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7083           if (BO->hasOneUse())
7084             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7085                                 ConstantExpr::getSub(RHS, BOp1C));
7086         } else if (RHSV == 0) {
7087           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7088           // efficiently invertible, or if the add has just this one use.
7089           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7090           
7091           if (Value *NegVal = dyn_castNegVal(BOp1))
7092             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7093           else if (Value *NegVal = dyn_castNegVal(BOp0))
7094             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7095           else if (BO->hasOneUse()) {
7096             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7097             InsertNewInstBefore(Neg, ICI);
7098             Neg->takeName(BO);
7099             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7100           }
7101         }
7102         break;
7103       case Instruction::Xor:
7104         // For the xor case, we can xor two constants together, eliminating
7105         // the explicit xor.
7106         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7107           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7108                               ConstantExpr::getXor(RHS, BOC));
7109         
7110         // FALLTHROUGH
7111       case Instruction::Sub:
7112         // Replace (([sub|xor] A, B) != 0) with (A != B)
7113         if (RHSV == 0)
7114           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7115                               BO->getOperand(1));
7116         break;
7117         
7118       case Instruction::Or:
7119         // If bits are being or'd in that are not present in the constant we
7120         // are comparing against, then the comparison could never succeed!
7121         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7122           Constant *NotCI = ConstantExpr::getNot(RHS);
7123           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7124             return ReplaceInstUsesWith(ICI,
7125                                        ConstantInt::get(Type::Int1Ty, 
7126                                        isICMP_NE));
7127         }
7128         break;
7129         
7130       case Instruction::And:
7131         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7132           // If bits are being compared against that are and'd out, then the
7133           // comparison can never succeed!
7134           if ((RHSV & ~BOC->getValue()) != 0)
7135             return ReplaceInstUsesWith(ICI,
7136                                        ConstantInt::get(Type::Int1Ty,
7137                                        isICMP_NE));
7138           
7139           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7140           if (RHS == BOC && RHSV.isPowerOf2())
7141             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7142                                 ICmpInst::ICMP_NE, LHSI,
7143                                 Constant::getNullValue(RHS->getType()));
7144           
7145           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7146           if (BOC->getValue().isSignBit()) {
7147             Value *X = BO->getOperand(0);
7148             Constant *Zero = Constant::getNullValue(X->getType());
7149             ICmpInst::Predicate pred = isICMP_NE ? 
7150               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7151             return new ICmpInst(*Context, pred, X, Zero);
7152           }
7153           
7154           // ((X & ~7) == 0) --> X < 8
7155           if (RHSV == 0 && isHighOnes(BOC)) {
7156             Value *X = BO->getOperand(0);
7157             Constant *NegX = ConstantExpr::getNeg(BOC);
7158             ICmpInst::Predicate pred = isICMP_NE ? 
7159               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7160             return new ICmpInst(*Context, pred, X, NegX);
7161           }
7162         }
7163       default: break;
7164       }
7165     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7166       // Handle icmp {eq|ne} <intrinsic>, intcst.
7167       if (II->getIntrinsicID() == Intrinsic::bswap) {
7168         AddToWorkList(II);
7169         ICI.setOperand(0, II->getOperand(1));
7170         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7171         return &ICI;
7172       }
7173     }
7174   }
7175   return 0;
7176 }
7177
7178 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7179 /// We only handle extending casts so far.
7180 ///
7181 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7182   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7183   Value *LHSCIOp        = LHSCI->getOperand(0);
7184   const Type *SrcTy     = LHSCIOp->getType();
7185   const Type *DestTy    = LHSCI->getType();
7186   Value *RHSCIOp;
7187
7188   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7189   // integer type is the same size as the pointer type.
7190   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7191       TD->getPointerSizeInBits() ==
7192          cast<IntegerType>(DestTy)->getBitWidth()) {
7193     Value *RHSOp = 0;
7194     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7195       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7196     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7197       RHSOp = RHSC->getOperand(0);
7198       // If the pointer types don't match, insert a bitcast.
7199       if (LHSCIOp->getType() != RHSOp->getType())
7200         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7201     }
7202
7203     if (RHSOp)
7204       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7205   }
7206   
7207   // The code below only handles extension cast instructions, so far.
7208   // Enforce this.
7209   if (LHSCI->getOpcode() != Instruction::ZExt &&
7210       LHSCI->getOpcode() != Instruction::SExt)
7211     return 0;
7212
7213   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7214   bool isSignedCmp = ICI.isSignedPredicate();
7215
7216   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7217     // Not an extension from the same type?
7218     RHSCIOp = CI->getOperand(0);
7219     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7220       return 0;
7221     
7222     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7223     // and the other is a zext), then we can't handle this.
7224     if (CI->getOpcode() != LHSCI->getOpcode())
7225       return 0;
7226
7227     // Deal with equality cases early.
7228     if (ICI.isEquality())
7229       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7230
7231     // A signed comparison of sign extended values simplifies into a
7232     // signed comparison.
7233     if (isSignedCmp && isSignedExt)
7234       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7235
7236     // The other three cases all fold into an unsigned comparison.
7237     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7238   }
7239
7240   // If we aren't dealing with a constant on the RHS, exit early
7241   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7242   if (!CI)
7243     return 0;
7244
7245   // Compute the constant that would happen if we truncated to SrcTy then
7246   // reextended to DestTy.
7247   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7248   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7249                                                 Res1, DestTy);
7250
7251   // If the re-extended constant didn't change...
7252   if (Res2 == CI) {
7253     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7254     // For example, we might have:
7255     //    %A = sext i16 %X to i32
7256     //    %B = icmp ugt i32 %A, 1330
7257     // It is incorrect to transform this into 
7258     //    %B = icmp ugt i16 %X, 1330
7259     // because %A may have negative value. 
7260     //
7261     // However, we allow this when the compare is EQ/NE, because they are
7262     // signless.
7263     if (isSignedExt == isSignedCmp || ICI.isEquality())
7264       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7265     return 0;
7266   }
7267
7268   // The re-extended constant changed so the constant cannot be represented 
7269   // in the shorter type. Consequently, we cannot emit a simple comparison.
7270
7271   // First, handle some easy cases. We know the result cannot be equal at this
7272   // point so handle the ICI.isEquality() cases
7273   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7274     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7275   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7276     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7277
7278   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7279   // should have been folded away previously and not enter in here.
7280   Value *Result;
7281   if (isSignedCmp) {
7282     // We're performing a signed comparison.
7283     if (cast<ConstantInt>(CI)->getValue().isNegative())
7284       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7285     else
7286       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7287   } else {
7288     // We're performing an unsigned comparison.
7289     if (isSignedExt) {
7290       // We're performing an unsigned comp with a sign extended value.
7291       // This is true if the input is >= 0. [aka >s -1]
7292       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7293       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7294                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7295     } else {
7296       // Unsigned extend & unsigned compare -> always true.
7297       Result = ConstantInt::getTrue(*Context);
7298     }
7299   }
7300
7301   // Finally, return the value computed.
7302   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7303       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7304     return ReplaceInstUsesWith(ICI, Result);
7305
7306   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7307           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7308          "ICmp should be folded!");
7309   if (Constant *CI = dyn_cast<Constant>(Result))
7310     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7311   return BinaryOperator::CreateNot(Result);
7312 }
7313
7314 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7315   return commonShiftTransforms(I);
7316 }
7317
7318 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7319   return commonShiftTransforms(I);
7320 }
7321
7322 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7323   if (Instruction *R = commonShiftTransforms(I))
7324     return R;
7325   
7326   Value *Op0 = I.getOperand(0);
7327   
7328   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7329   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7330     if (CSI->isAllOnesValue())
7331       return ReplaceInstUsesWith(I, CSI);
7332
7333   // See if we can turn a signed shr into an unsigned shr.
7334   if (MaskedValueIsZero(Op0,
7335                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7336     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7337
7338   // Arithmetic shifting an all-sign-bit value is a no-op.
7339   unsigned NumSignBits = ComputeNumSignBits(Op0);
7340   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7341     return ReplaceInstUsesWith(I, Op0);
7342
7343   return 0;
7344 }
7345
7346 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7347   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7348   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7349
7350   // shl X, 0 == X and shr X, 0 == X
7351   // shl 0, X == 0 and shr 0, X == 0
7352   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7353       Op0 == Constant::getNullValue(Op0->getType()))
7354     return ReplaceInstUsesWith(I, Op0);
7355   
7356   if (isa<UndefValue>(Op0)) {            
7357     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7358       return ReplaceInstUsesWith(I, Op0);
7359     else                                    // undef << X -> 0, undef >>u X -> 0
7360       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7361   }
7362   if (isa<UndefValue>(Op1)) {
7363     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7364       return ReplaceInstUsesWith(I, Op0);          
7365     else                                     // X << undef, X >>u undef -> 0
7366       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7367   }
7368
7369   // See if we can fold away this shift.
7370   if (SimplifyDemandedInstructionBits(I))
7371     return &I;
7372
7373   // Try to fold constant and into select arguments.
7374   if (isa<Constant>(Op0))
7375     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7376       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7377         return R;
7378
7379   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7380     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7381       return Res;
7382   return 0;
7383 }
7384
7385 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7386                                                BinaryOperator &I) {
7387   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7388
7389   // See if we can simplify any instructions used by the instruction whose sole 
7390   // purpose is to compute bits we don't care about.
7391   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7392   
7393   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7394   // a signed shift.
7395   //
7396   if (Op1->uge(TypeBits)) {
7397     if (I.getOpcode() != Instruction::AShr)
7398       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7399     else {
7400       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7401       return &I;
7402     }
7403   }
7404   
7405   // ((X*C1) << C2) == (X * (C1 << C2))
7406   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7407     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7408       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7409         return BinaryOperator::CreateMul(BO->getOperand(0),
7410                                         ConstantExpr::getShl(BOOp, Op1));
7411   
7412   // Try to fold constant and into select arguments.
7413   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7414     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7415       return R;
7416   if (isa<PHINode>(Op0))
7417     if (Instruction *NV = FoldOpIntoPhi(I))
7418       return NV;
7419   
7420   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7421   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7422     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7423     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7424     // place.  Don't try to do this transformation in this case.  Also, we
7425     // require that the input operand is a shift-by-constant so that we have
7426     // confidence that the shifts will get folded together.  We could do this
7427     // xform in more cases, but it is unlikely to be profitable.
7428     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7429         isa<ConstantInt>(TrOp->getOperand(1))) {
7430       // Okay, we'll do this xform.  Make the shift of shift.
7431       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7432       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7433                                                 I.getName());
7434       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7435
7436       // For logical shifts, the truncation has the effect of making the high
7437       // part of the register be zeros.  Emulate this by inserting an AND to
7438       // clear the top bits as needed.  This 'and' will usually be zapped by
7439       // other xforms later if dead.
7440       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7441       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7442       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7443       
7444       // The mask we constructed says what the trunc would do if occurring
7445       // between the shifts.  We want to know the effect *after* the second
7446       // shift.  We know that it is a logical shift by a constant, so adjust the
7447       // mask as appropriate.
7448       if (I.getOpcode() == Instruction::Shl)
7449         MaskV <<= Op1->getZExtValue();
7450       else {
7451         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7452         MaskV = MaskV.lshr(Op1->getZExtValue());
7453       }
7454
7455       Instruction *And =
7456         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7457                                   TI->getName());
7458       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7459
7460       // Return the value truncated to the interesting size.
7461       return new TruncInst(And, I.getType());
7462     }
7463   }
7464   
7465   if (Op0->hasOneUse()) {
7466     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7467       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7468       Value *V1, *V2;
7469       ConstantInt *CC;
7470       switch (Op0BO->getOpcode()) {
7471         default: break;
7472         case Instruction::Add:
7473         case Instruction::And:
7474         case Instruction::Or:
7475         case Instruction::Xor: {
7476           // These operators commute.
7477           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7478           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7479               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7480                     m_Specific(Op1)))){
7481             Instruction *YS = BinaryOperator::CreateShl(
7482                                             Op0BO->getOperand(0), Op1,
7483                                             Op0BO->getName());
7484             InsertNewInstBefore(YS, I); // (Y << C)
7485             Instruction *X = 
7486               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7487                                      Op0BO->getOperand(1)->getName());
7488             InsertNewInstBefore(X, I);  // (X + (Y << C))
7489             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7490             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7491                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7492           }
7493           
7494           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7495           Value *Op0BOOp1 = Op0BO->getOperand(1);
7496           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7497               match(Op0BOOp1, 
7498                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7499                           m_ConstantInt(CC))) &&
7500               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7501             Instruction *YS = BinaryOperator::CreateShl(
7502                                                      Op0BO->getOperand(0), Op1,
7503                                                      Op0BO->getName());
7504             InsertNewInstBefore(YS, I); // (Y << C)
7505             Instruction *XM =
7506               BinaryOperator::CreateAnd(V1,
7507                                         ConstantExpr::getShl(CC, Op1),
7508                                         V1->getName()+".mask");
7509             InsertNewInstBefore(XM, I); // X & (CC << C)
7510             
7511             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7512           }
7513         }
7514           
7515         // FALL THROUGH.
7516         case Instruction::Sub: {
7517           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7518           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7519               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7520                     m_Specific(Op1)))) {
7521             Instruction *YS = BinaryOperator::CreateShl(
7522                                                      Op0BO->getOperand(1), Op1,
7523                                                      Op0BO->getName());
7524             InsertNewInstBefore(YS, I); // (Y << C)
7525             Instruction *X =
7526               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7527                                      Op0BO->getOperand(0)->getName());
7528             InsertNewInstBefore(X, I);  // (X + (Y << C))
7529             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7530             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7531                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7532           }
7533           
7534           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7535           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7536               match(Op0BO->getOperand(0),
7537                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7538                           m_ConstantInt(CC))) && V2 == Op1 &&
7539               cast<BinaryOperator>(Op0BO->getOperand(0))
7540                   ->getOperand(0)->hasOneUse()) {
7541             Instruction *YS = BinaryOperator::CreateShl(
7542                                                      Op0BO->getOperand(1), Op1,
7543                                                      Op0BO->getName());
7544             InsertNewInstBefore(YS, I); // (Y << C)
7545             Instruction *XM =
7546               BinaryOperator::CreateAnd(V1, 
7547                                         ConstantExpr::getShl(CC, Op1),
7548                                         V1->getName()+".mask");
7549             InsertNewInstBefore(XM, I); // X & (CC << C)
7550             
7551             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7552           }
7553           
7554           break;
7555         }
7556       }
7557       
7558       
7559       // If the operand is an bitwise operator with a constant RHS, and the
7560       // shift is the only use, we can pull it out of the shift.
7561       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7562         bool isValid = true;     // Valid only for And, Or, Xor
7563         bool highBitSet = false; // Transform if high bit of constant set?
7564         
7565         switch (Op0BO->getOpcode()) {
7566           default: isValid = false; break;   // Do not perform transform!
7567           case Instruction::Add:
7568             isValid = isLeftShift;
7569             break;
7570           case Instruction::Or:
7571           case Instruction::Xor:
7572             highBitSet = false;
7573             break;
7574           case Instruction::And:
7575             highBitSet = true;
7576             break;
7577         }
7578         
7579         // If this is a signed shift right, and the high bit is modified
7580         // by the logical operation, do not perform the transformation.
7581         // The highBitSet boolean indicates the value of the high bit of
7582         // the constant which would cause it to be modified for this
7583         // operation.
7584         //
7585         if (isValid && I.getOpcode() == Instruction::AShr)
7586           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7587         
7588         if (isValid) {
7589           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7590           
7591           Instruction *NewShift =
7592             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7593           InsertNewInstBefore(NewShift, I);
7594           NewShift->takeName(Op0BO);
7595           
7596           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7597                                         NewRHS);
7598         }
7599       }
7600     }
7601   }
7602   
7603   // Find out if this is a shift of a shift by a constant.
7604   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7605   if (ShiftOp && !ShiftOp->isShift())
7606     ShiftOp = 0;
7607   
7608   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7609     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7610     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7611     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7612     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7613     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7614     Value *X = ShiftOp->getOperand(0);
7615     
7616     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7617     
7618     const IntegerType *Ty = cast<IntegerType>(I.getType());
7619     
7620     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7621     if (I.getOpcode() == ShiftOp->getOpcode()) {
7622       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7623       // saturates.
7624       if (AmtSum >= TypeBits) {
7625         if (I.getOpcode() != Instruction::AShr)
7626           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7627         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7628       }
7629       
7630       return BinaryOperator::Create(I.getOpcode(), X,
7631                                     ConstantInt::get(Ty, AmtSum));
7632     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7633                I.getOpcode() == Instruction::AShr) {
7634       if (AmtSum >= TypeBits)
7635         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7636       
7637       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7638       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7639     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7640                I.getOpcode() == Instruction::LShr) {
7641       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7642       if (AmtSum >= TypeBits)
7643         AmtSum = TypeBits-1;
7644       
7645       Instruction *Shift =
7646         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7647       InsertNewInstBefore(Shift, I);
7648
7649       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7650       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7651     }
7652     
7653     // Okay, if we get here, one shift must be left, and the other shift must be
7654     // right.  See if the amounts are equal.
7655     if (ShiftAmt1 == ShiftAmt2) {
7656       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7657       if (I.getOpcode() == Instruction::Shl) {
7658         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7659         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7660       }
7661       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7662       if (I.getOpcode() == Instruction::LShr) {
7663         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7664         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7665       }
7666       // We can simplify ((X << C) >>s C) into a trunc + sext.
7667       // NOTE: we could do this for any C, but that would make 'unusual' integer
7668       // types.  For now, just stick to ones well-supported by the code
7669       // generators.
7670       const Type *SExtType = 0;
7671       switch (Ty->getBitWidth() - ShiftAmt1) {
7672       case 1  :
7673       case 8  :
7674       case 16 :
7675       case 32 :
7676       case 64 :
7677       case 128:
7678         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7679         break;
7680       default: break;
7681       }
7682       if (SExtType) {
7683         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7684         InsertNewInstBefore(NewTrunc, I);
7685         return new SExtInst(NewTrunc, Ty);
7686       }
7687       // Otherwise, we can't handle it yet.
7688     } else if (ShiftAmt1 < ShiftAmt2) {
7689       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7690       
7691       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7692       if (I.getOpcode() == Instruction::Shl) {
7693         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7694                ShiftOp->getOpcode() == Instruction::AShr);
7695         Instruction *Shift =
7696           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7697         InsertNewInstBefore(Shift, I);
7698         
7699         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7700         return BinaryOperator::CreateAnd(Shift,
7701                                          ConstantInt::get(*Context, Mask));
7702       }
7703       
7704       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7705       if (I.getOpcode() == Instruction::LShr) {
7706         assert(ShiftOp->getOpcode() == Instruction::Shl);
7707         Instruction *Shift =
7708           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7709         InsertNewInstBefore(Shift, I);
7710         
7711         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712         return BinaryOperator::CreateAnd(Shift,
7713                                          ConstantInt::get(*Context, Mask));
7714       }
7715       
7716       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7717     } else {
7718       assert(ShiftAmt2 < ShiftAmt1);
7719       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7720
7721       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7722       if (I.getOpcode() == Instruction::Shl) {
7723         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724                ShiftOp->getOpcode() == Instruction::AShr);
7725         Instruction *Shift =
7726           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7727                                  ConstantInt::get(Ty, ShiftDiff));
7728         InsertNewInstBefore(Shift, I);
7729         
7730         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7731         return BinaryOperator::CreateAnd(Shift,
7732                                          ConstantInt::get(*Context, Mask));
7733       }
7734       
7735       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7736       if (I.getOpcode() == Instruction::LShr) {
7737         assert(ShiftOp->getOpcode() == Instruction::Shl);
7738         Instruction *Shift =
7739           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7740         InsertNewInstBefore(Shift, I);
7741         
7742         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7743         return BinaryOperator::CreateAnd(Shift,
7744                                          ConstantInt::get(*Context, Mask));
7745       }
7746       
7747       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7748     }
7749   }
7750   return 0;
7751 }
7752
7753
7754 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7755 /// expression.  If so, decompose it, returning some value X, such that Val is
7756 /// X*Scale+Offset.
7757 ///
7758 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7759                                         int &Offset, LLVMContext *Context) {
7760   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7761   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7762     Offset = CI->getZExtValue();
7763     Scale  = 0;
7764     return ConstantInt::get(Type::Int32Ty, 0);
7765   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7766     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7767       if (I->getOpcode() == Instruction::Shl) {
7768         // This is a value scaled by '1 << the shift amt'.
7769         Scale = 1U << RHS->getZExtValue();
7770         Offset = 0;
7771         return I->getOperand(0);
7772       } else if (I->getOpcode() == Instruction::Mul) {
7773         // This value is scaled by 'RHS'.
7774         Scale = RHS->getZExtValue();
7775         Offset = 0;
7776         return I->getOperand(0);
7777       } else if (I->getOpcode() == Instruction::Add) {
7778         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7779         // where C1 is divisible by C2.
7780         unsigned SubScale;
7781         Value *SubVal = 
7782           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7783                                     Offset, Context);
7784         Offset += RHS->getZExtValue();
7785         Scale = SubScale;
7786         return SubVal;
7787       }
7788     }
7789   }
7790
7791   // Otherwise, we can't look past this.
7792   Scale = 1;
7793   Offset = 0;
7794   return Val;
7795 }
7796
7797
7798 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7799 /// try to eliminate the cast by moving the type information into the alloc.
7800 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7801                                                    AllocationInst &AI) {
7802   const PointerType *PTy = cast<PointerType>(CI.getType());
7803   
7804   // Remove any uses of AI that are dead.
7805   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7806   
7807   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7808     Instruction *User = cast<Instruction>(*UI++);
7809     if (isInstructionTriviallyDead(User)) {
7810       while (UI != E && *UI == User)
7811         ++UI; // If this instruction uses AI more than once, don't break UI.
7812       
7813       ++NumDeadInst;
7814       DOUT << "IC: DCE: " << *User << '\n';
7815       EraseInstFromFunction(*User);
7816     }
7817   }
7818
7819   // This requires TargetData to get the alloca alignment and size information.
7820   if (!TD) return 0;
7821
7822   // Get the type really allocated and the type casted to.
7823   const Type *AllocElTy = AI.getAllocatedType();
7824   const Type *CastElTy = PTy->getElementType();
7825   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7826
7827   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7828   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7829   if (CastElTyAlign < AllocElTyAlign) return 0;
7830
7831   // If the allocation has multiple uses, only promote it if we are strictly
7832   // increasing the alignment of the resultant allocation.  If we keep it the
7833   // same, we open the door to infinite loops of various kinds.  (A reference
7834   // from a dbg.declare doesn't count as a use for this purpose.)
7835   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7836       CastElTyAlign == AllocElTyAlign) return 0;
7837
7838   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7839   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7840   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7841
7842   // See if we can satisfy the modulus by pulling a scale out of the array
7843   // size argument.
7844   unsigned ArraySizeScale;
7845   int ArrayOffset;
7846   Value *NumElements = // See if the array size is a decomposable linear expr.
7847     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7848                               ArrayOffset, Context);
7849  
7850   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7851   // do the xform.
7852   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7853       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7854
7855   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7856   Value *Amt = 0;
7857   if (Scale == 1) {
7858     Amt = NumElements;
7859   } else {
7860     // If the allocation size is constant, form a constant mul expression
7861     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7862     if (isa<ConstantInt>(NumElements))
7863       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7864                                  cast<ConstantInt>(Amt));
7865     // otherwise multiply the amount and the number of elements
7866     else {
7867       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7868       Amt = InsertNewInstBefore(Tmp, AI);
7869     }
7870   }
7871   
7872   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7873     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7874     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7875     Amt = InsertNewInstBefore(Tmp, AI);
7876   }
7877   
7878   AllocationInst *New;
7879   if (isa<MallocInst>(AI))
7880     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7881   else
7882     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7883   InsertNewInstBefore(New, AI);
7884   New->takeName(&AI);
7885   
7886   // If the allocation has one real use plus a dbg.declare, just remove the
7887   // declare.
7888   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7889     EraseInstFromFunction(*DI);
7890   }
7891   // If the allocation has multiple real uses, insert a cast and change all
7892   // things that used it to use the new cast.  This will also hack on CI, but it
7893   // will die soon.
7894   else if (!AI.hasOneUse()) {
7895     AddUsesToWorkList(AI);
7896     // New is the allocation instruction, pointer typed. AI is the original
7897     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7898     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7899     InsertNewInstBefore(NewCast, AI);
7900     AI.replaceAllUsesWith(NewCast);
7901   }
7902   return ReplaceInstUsesWith(CI, New);
7903 }
7904
7905 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7906 /// and return it as type Ty without inserting any new casts and without
7907 /// changing the computed value.  This is used by code that tries to decide
7908 /// whether promoting or shrinking integer operations to wider or smaller types
7909 /// will allow us to eliminate a truncate or extend.
7910 ///
7911 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7912 /// extension operation if Ty is larger.
7913 ///
7914 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7915 /// should return true if trunc(V) can be computed by computing V in the smaller
7916 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7917 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7918 /// efficiently truncated.
7919 ///
7920 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7921 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7922 /// the final result.
7923 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7924                                               unsigned CastOpc,
7925                                               int &NumCastsRemoved){
7926   // We can always evaluate constants in another type.
7927   if (isa<Constant>(V))
7928     return true;
7929   
7930   Instruction *I = dyn_cast<Instruction>(V);
7931   if (!I) return false;
7932   
7933   const Type *OrigTy = V->getType();
7934   
7935   // If this is an extension or truncate, we can often eliminate it.
7936   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7937     // If this is a cast from the destination type, we can trivially eliminate
7938     // it, and this will remove a cast overall.
7939     if (I->getOperand(0)->getType() == Ty) {
7940       // If the first operand is itself a cast, and is eliminable, do not count
7941       // this as an eliminable cast.  We would prefer to eliminate those two
7942       // casts first.
7943       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7944         ++NumCastsRemoved;
7945       return true;
7946     }
7947   }
7948
7949   // We can't extend or shrink something that has multiple uses: doing so would
7950   // require duplicating the instruction in general, which isn't profitable.
7951   if (!I->hasOneUse()) return false;
7952
7953   unsigned Opc = I->getOpcode();
7954   switch (Opc) {
7955   case Instruction::Add:
7956   case Instruction::Sub:
7957   case Instruction::Mul:
7958   case Instruction::And:
7959   case Instruction::Or:
7960   case Instruction::Xor:
7961     // These operators can all arbitrarily be extended or truncated.
7962     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7963                                       NumCastsRemoved) &&
7964            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7965                                       NumCastsRemoved);
7966
7967   case Instruction::UDiv:
7968   case Instruction::URem: {
7969     // UDiv and URem can be truncated if all the truncated bits are zero.
7970     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7971     uint32_t BitWidth = Ty->getScalarSizeInBits();
7972     if (BitWidth < OrigBitWidth) {
7973       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7974       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7975           MaskedValueIsZero(I->getOperand(1), Mask)) {
7976         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7977                                           NumCastsRemoved) &&
7978                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7979                                           NumCastsRemoved);
7980       }
7981     }
7982     break;
7983   }
7984   case Instruction::Shl:
7985     // If we are truncating the result of this SHL, and if it's a shift of a
7986     // constant amount, we can always perform a SHL in a smaller type.
7987     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7988       uint32_t BitWidth = Ty->getScalarSizeInBits();
7989       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7990           CI->getLimitedValue(BitWidth) < BitWidth)
7991         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7992                                           NumCastsRemoved);
7993     }
7994     break;
7995   case Instruction::LShr:
7996     // If this is a truncate of a logical shr, we can truncate it to a smaller
7997     // lshr iff we know that the bits we would otherwise be shifting in are
7998     // already zeros.
7999     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8000       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8001       uint32_t BitWidth = Ty->getScalarSizeInBits();
8002       if (BitWidth < OrigBitWidth &&
8003           MaskedValueIsZero(I->getOperand(0),
8004             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8005           CI->getLimitedValue(BitWidth) < BitWidth) {
8006         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8007                                           NumCastsRemoved);
8008       }
8009     }
8010     break;
8011   case Instruction::ZExt:
8012   case Instruction::SExt:
8013   case Instruction::Trunc:
8014     // If this is the same kind of case as our original (e.g. zext+zext), we
8015     // can safely replace it.  Note that replacing it does not reduce the number
8016     // of casts in the input.
8017     if (Opc == CastOpc)
8018       return true;
8019
8020     // sext (zext ty1), ty2 -> zext ty2
8021     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8022       return true;
8023     break;
8024   case Instruction::Select: {
8025     SelectInst *SI = cast<SelectInst>(I);
8026     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8027                                       NumCastsRemoved) &&
8028            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8029                                       NumCastsRemoved);
8030   }
8031   case Instruction::PHI: {
8032     // We can change a phi if we can change all operands.
8033     PHINode *PN = cast<PHINode>(I);
8034     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8035       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8036                                       NumCastsRemoved))
8037         return false;
8038     return true;
8039   }
8040   default:
8041     // TODO: Can handle more cases here.
8042     break;
8043   }
8044   
8045   return false;
8046 }
8047
8048 /// EvaluateInDifferentType - Given an expression that 
8049 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8050 /// evaluate the expression.
8051 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8052                                              bool isSigned) {
8053   if (Constant *C = dyn_cast<Constant>(V))
8054     return ConstantExpr::getIntegerCast(C, Ty,
8055                                                isSigned /*Sext or ZExt*/);
8056
8057   // Otherwise, it must be an instruction.
8058   Instruction *I = cast<Instruction>(V);
8059   Instruction *Res = 0;
8060   unsigned Opc = I->getOpcode();
8061   switch (Opc) {
8062   case Instruction::Add:
8063   case Instruction::Sub:
8064   case Instruction::Mul:
8065   case Instruction::And:
8066   case Instruction::Or:
8067   case Instruction::Xor:
8068   case Instruction::AShr:
8069   case Instruction::LShr:
8070   case Instruction::Shl:
8071   case Instruction::UDiv:
8072   case Instruction::URem: {
8073     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8074     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8075     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8076     break;
8077   }    
8078   case Instruction::Trunc:
8079   case Instruction::ZExt:
8080   case Instruction::SExt:
8081     // If the source type of the cast is the type we're trying for then we can
8082     // just return the source.  There's no need to insert it because it is not
8083     // new.
8084     if (I->getOperand(0)->getType() == Ty)
8085       return I->getOperand(0);
8086     
8087     // Otherwise, must be the same type of cast, so just reinsert a new one.
8088     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8089                            Ty);
8090     break;
8091   case Instruction::Select: {
8092     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8093     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8094     Res = SelectInst::Create(I->getOperand(0), True, False);
8095     break;
8096   }
8097   case Instruction::PHI: {
8098     PHINode *OPN = cast<PHINode>(I);
8099     PHINode *NPN = PHINode::Create(Ty);
8100     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8101       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8102       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8103     }
8104     Res = NPN;
8105     break;
8106   }
8107   default: 
8108     // TODO: Can handle more cases here.
8109     llvm_unreachable("Unreachable!");
8110     break;
8111   }
8112   
8113   Res->takeName(I);
8114   return InsertNewInstBefore(Res, *I);
8115 }
8116
8117 /// @brief Implement the transforms common to all CastInst visitors.
8118 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8119   Value *Src = CI.getOperand(0);
8120
8121   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8122   // eliminate it now.
8123   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8124     if (Instruction::CastOps opc = 
8125         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8126       // The first cast (CSrc) is eliminable so we need to fix up or replace
8127       // the second cast (CI). CSrc will then have a good chance of being dead.
8128       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8129     }
8130   }
8131
8132   // If we are casting a select then fold the cast into the select
8133   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8134     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8135       return NV;
8136
8137   // If we are casting a PHI then fold the cast into the PHI
8138   if (isa<PHINode>(Src))
8139     if (Instruction *NV = FoldOpIntoPhi(CI))
8140       return NV;
8141   
8142   return 0;
8143 }
8144
8145 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8146 /// or not there is a sequence of GEP indices into the type that will land us at
8147 /// the specified offset.  If so, fill them into NewIndices and return the
8148 /// resultant element type, otherwise return null.
8149 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8150                                        SmallVectorImpl<Value*> &NewIndices,
8151                                        const TargetData *TD,
8152                                        LLVMContext *Context) {
8153   if (!TD) return 0;
8154   if (!Ty->isSized()) return 0;
8155   
8156   // Start with the index over the outer type.  Note that the type size
8157   // might be zero (even if the offset isn't zero) if the indexed type
8158   // is something like [0 x {int, int}]
8159   const Type *IntPtrTy = TD->getIntPtrType();
8160   int64_t FirstIdx = 0;
8161   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8162     FirstIdx = Offset/TySize;
8163     Offset -= FirstIdx*TySize;
8164     
8165     // Handle hosts where % returns negative instead of values [0..TySize).
8166     if (Offset < 0) {
8167       --FirstIdx;
8168       Offset += TySize;
8169       assert(Offset >= 0);
8170     }
8171     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8172   }
8173   
8174   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8175     
8176   // Index into the types.  If we fail, set OrigBase to null.
8177   while (Offset) {
8178     // Indexing into tail padding between struct/array elements.
8179     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8180       return 0;
8181     
8182     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8183       const StructLayout *SL = TD->getStructLayout(STy);
8184       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8185              "Offset must stay within the indexed type");
8186       
8187       unsigned Elt = SL->getElementContainingOffset(Offset);
8188       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8189       
8190       Offset -= SL->getElementOffset(Elt);
8191       Ty = STy->getElementType(Elt);
8192     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8193       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8194       assert(EltSize && "Cannot index into a zero-sized array");
8195       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8196       Offset %= EltSize;
8197       Ty = AT->getElementType();
8198     } else {
8199       // Otherwise, we can't index into the middle of this atomic type, bail.
8200       return 0;
8201     }
8202   }
8203   
8204   return Ty;
8205 }
8206
8207 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8208 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8209   Value *Src = CI.getOperand(0);
8210   
8211   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8212     // If casting the result of a getelementptr instruction with no offset, turn
8213     // this into a cast of the original pointer!
8214     if (GEP->hasAllZeroIndices()) {
8215       // Changing the cast operand is usually not a good idea but it is safe
8216       // here because the pointer operand is being replaced with another 
8217       // pointer operand so the opcode doesn't need to change.
8218       AddToWorkList(GEP);
8219       CI.setOperand(0, GEP->getOperand(0));
8220       return &CI;
8221     }
8222     
8223     // If the GEP has a single use, and the base pointer is a bitcast, and the
8224     // GEP computes a constant offset, see if we can convert these three
8225     // instructions into fewer.  This typically happens with unions and other
8226     // non-type-safe code.
8227     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8228       if (GEP->hasAllConstantIndices()) {
8229         // We are guaranteed to get a constant from EmitGEPOffset.
8230         ConstantInt *OffsetV =
8231                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8232         int64_t Offset = OffsetV->getSExtValue();
8233         
8234         // Get the base pointer input of the bitcast, and the type it points to.
8235         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8236         const Type *GEPIdxTy =
8237           cast<PointerType>(OrigBase->getType())->getElementType();
8238         SmallVector<Value*, 8> NewIndices;
8239         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8240           // If we were able to index down into an element, create the GEP
8241           // and bitcast the result.  This eliminates one bitcast, potentially
8242           // two.
8243           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8244                                                         NewIndices.begin(),
8245                                                         NewIndices.end(), "");
8246           InsertNewInstBefore(NGEP, CI);
8247           NGEP->takeName(GEP);
8248           if (cast<GEPOperator>(GEP)->isInBounds())
8249             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8250           
8251           if (isa<BitCastInst>(CI))
8252             return new BitCastInst(NGEP, CI.getType());
8253           assert(isa<PtrToIntInst>(CI));
8254           return new PtrToIntInst(NGEP, CI.getType());
8255         }
8256       }      
8257     }
8258   }
8259     
8260   return commonCastTransforms(CI);
8261 }
8262
8263 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8264 /// type like i42.  We don't want to introduce operations on random non-legal
8265 /// integer types where they don't already exist in the code.  In the future,
8266 /// we should consider making this based off target-data, so that 32-bit targets
8267 /// won't get i64 operations etc.
8268 static bool isSafeIntegerType(const Type *Ty) {
8269   switch (Ty->getPrimitiveSizeInBits()) {
8270   case 8:
8271   case 16:
8272   case 32:
8273   case 64:
8274     return true;
8275   default: 
8276     return false;
8277   }
8278 }
8279
8280 /// commonIntCastTransforms - This function implements the common transforms
8281 /// for trunc, zext, and sext.
8282 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8283   if (Instruction *Result = commonCastTransforms(CI))
8284     return Result;
8285
8286   Value *Src = CI.getOperand(0);
8287   const Type *SrcTy = Src->getType();
8288   const Type *DestTy = CI.getType();
8289   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8290   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8291
8292   // See if we can simplify any instructions used by the LHS whose sole 
8293   // purpose is to compute bits we don't care about.
8294   if (SimplifyDemandedInstructionBits(CI))
8295     return &CI;
8296
8297   // If the source isn't an instruction or has more than one use then we
8298   // can't do anything more. 
8299   Instruction *SrcI = dyn_cast<Instruction>(Src);
8300   if (!SrcI || !Src->hasOneUse())
8301     return 0;
8302
8303   // Attempt to propagate the cast into the instruction for int->int casts.
8304   int NumCastsRemoved = 0;
8305   // Only do this if the dest type is a simple type, don't convert the
8306   // expression tree to something weird like i93 unless the source is also
8307   // strange.
8308   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8309        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8310       CanEvaluateInDifferentType(SrcI, DestTy,
8311                                  CI.getOpcode(), NumCastsRemoved)) {
8312     // If this cast is a truncate, evaluting in a different type always
8313     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8314     // we need to do an AND to maintain the clear top-part of the computation,
8315     // so we require that the input have eliminated at least one cast.  If this
8316     // is a sign extension, we insert two new casts (to do the extension) so we
8317     // require that two casts have been eliminated.
8318     bool DoXForm = false;
8319     bool JustReplace = false;
8320     switch (CI.getOpcode()) {
8321     default:
8322       // All the others use floating point so we shouldn't actually 
8323       // get here because of the check above.
8324       llvm_unreachable("Unknown cast type");
8325     case Instruction::Trunc:
8326       DoXForm = true;
8327       break;
8328     case Instruction::ZExt: {
8329       DoXForm = NumCastsRemoved >= 1;
8330       if (!DoXForm && 0) {
8331         // If it's unnecessary to issue an AND to clear the high bits, it's
8332         // always profitable to do this xform.
8333         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8334         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8335         if (MaskedValueIsZero(TryRes, Mask))
8336           return ReplaceInstUsesWith(CI, TryRes);
8337         
8338         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8339           if (TryI->use_empty())
8340             EraseInstFromFunction(*TryI);
8341       }
8342       break;
8343     }
8344     case Instruction::SExt: {
8345       DoXForm = NumCastsRemoved >= 2;
8346       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8347         // If we do not have to emit the truncate + sext pair, then it's always
8348         // profitable to do this xform.
8349         //
8350         // It's not safe to eliminate the trunc + sext pair if one of the
8351         // eliminated cast is a truncate. e.g.
8352         // t2 = trunc i32 t1 to i16
8353         // t3 = sext i16 t2 to i32
8354         // !=
8355         // i32 t1
8356         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8357         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8358         if (NumSignBits > (DestBitSize - SrcBitSize))
8359           return ReplaceInstUsesWith(CI, TryRes);
8360         
8361         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8362           if (TryI->use_empty())
8363             EraseInstFromFunction(*TryI);
8364       }
8365       break;
8366     }
8367     }
8368     
8369     if (DoXForm) {
8370       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8371            << " cast: " << CI;
8372       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8373                                            CI.getOpcode() == Instruction::SExt);
8374       if (JustReplace)
8375         // Just replace this cast with the result.
8376         return ReplaceInstUsesWith(CI, Res);
8377
8378       assert(Res->getType() == DestTy);
8379       switch (CI.getOpcode()) {
8380       default: llvm_unreachable("Unknown cast type!");
8381       case Instruction::Trunc:
8382         // Just replace this cast with the result.
8383         return ReplaceInstUsesWith(CI, Res);
8384       case Instruction::ZExt: {
8385         assert(SrcBitSize < DestBitSize && "Not a zext?");
8386
8387         // If the high bits are already zero, just replace this cast with the
8388         // result.
8389         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8390         if (MaskedValueIsZero(Res, Mask))
8391           return ReplaceInstUsesWith(CI, Res);
8392
8393         // We need to emit an AND to clear the high bits.
8394         Constant *C = ConstantInt::get(*Context, 
8395                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8396         return BinaryOperator::CreateAnd(Res, C);
8397       }
8398       case Instruction::SExt: {
8399         // If the high bits are already filled with sign bit, just replace this
8400         // cast with the result.
8401         unsigned NumSignBits = ComputeNumSignBits(Res);
8402         if (NumSignBits > (DestBitSize - SrcBitSize))
8403           return ReplaceInstUsesWith(CI, Res);
8404
8405         // We need to emit a cast to truncate, then a cast to sext.
8406         return CastInst::Create(Instruction::SExt,
8407             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8408                              CI), DestTy);
8409       }
8410       }
8411     }
8412   }
8413   
8414   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8415   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8416
8417   switch (SrcI->getOpcode()) {
8418   case Instruction::Add:
8419   case Instruction::Mul:
8420   case Instruction::And:
8421   case Instruction::Or:
8422   case Instruction::Xor:
8423     // If we are discarding information, rewrite.
8424     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8425       // Don't insert two casts unless at least one can be eliminated.
8426       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8427           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8428         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8430         return BinaryOperator::Create(
8431             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8432       }
8433     }
8434
8435     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8436     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8437         SrcI->getOpcode() == Instruction::Xor &&
8438         Op1 == ConstantInt::getTrue(*Context) &&
8439         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8440       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8441       return BinaryOperator::CreateXor(New,
8442                                       ConstantInt::get(CI.getType(), 1));
8443     }
8444     break;
8445
8446   case Instruction::Shl: {
8447     // Canonicalize trunc inside shl, if we can.
8448     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8449     if (CI && DestBitSize < SrcBitSize &&
8450         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8451       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8452       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8453       return BinaryOperator::CreateShl(Op0c, Op1c);
8454     }
8455     break;
8456   }
8457   }
8458   return 0;
8459 }
8460
8461 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8462   if (Instruction *Result = commonIntCastTransforms(CI))
8463     return Result;
8464   
8465   Value *Src = CI.getOperand(0);
8466   const Type *Ty = CI.getType();
8467   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8468   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8469
8470   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8471   if (DestBitWidth == 1) {
8472     Constant *One = ConstantInt::get(Src->getType(), 1);
8473     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8474     Value *Zero = Constant::getNullValue(Src->getType());
8475     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8476   }
8477
8478   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8479   ConstantInt *ShAmtV = 0;
8480   Value *ShiftOp = 0;
8481   if (Src->hasOneUse() &&
8482       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8483     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8484     
8485     // Get a mask for the bits shifting in.
8486     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8487     if (MaskedValueIsZero(ShiftOp, Mask)) {
8488       if (ShAmt >= DestBitWidth)        // All zeros.
8489         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8490       
8491       // Okay, we can shrink this.  Truncate the input, then return a new
8492       // shift.
8493       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8494       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8495       return BinaryOperator::CreateLShr(V1, V2);
8496     }
8497   }
8498   
8499   return 0;
8500 }
8501
8502 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8503 /// in order to eliminate the icmp.
8504 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8505                                              bool DoXform) {
8506   // If we are just checking for a icmp eq of a single bit and zext'ing it
8507   // to an integer, then shift the bit to the appropriate place and then
8508   // cast to integer to avoid the comparison.
8509   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8510     const APInt &Op1CV = Op1C->getValue();
8511       
8512     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8513     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8514     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8515         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8516       if (!DoXform) return ICI;
8517
8518       Value *In = ICI->getOperand(0);
8519       Value *Sh = ConstantInt::get(In->getType(),
8520                                    In->getType()->getScalarSizeInBits()-1);
8521       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8522                                                         In->getName()+".lobit"),
8523                                CI);
8524       if (In->getType() != CI.getType())
8525         In = CastInst::CreateIntegerCast(In, CI.getType(),
8526                                          false/*ZExt*/, "tmp", &CI);
8527
8528       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8529         Constant *One = ConstantInt::get(In->getType(), 1);
8530         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8531                                                          In->getName()+".not"),
8532                                  CI);
8533       }
8534
8535       return ReplaceInstUsesWith(CI, In);
8536     }
8537       
8538       
8539       
8540     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8541     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8542     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8543     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8544     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8545     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8546     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8547     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8548     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8549         // This only works for EQ and NE
8550         ICI->isEquality()) {
8551       // If Op1C some other power of two, convert:
8552       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8553       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8554       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8555       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8556         
8557       APInt KnownZeroMask(~KnownZero);
8558       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8559         if (!DoXform) return ICI;
8560
8561         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8562         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8563           // (X&4) == 2 --> false
8564           // (X&4) != 2 --> true
8565           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8566           Res = ConstantExpr::getZExt(Res, CI.getType());
8567           return ReplaceInstUsesWith(CI, Res);
8568         }
8569           
8570         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8571         Value *In = ICI->getOperand(0);
8572         if (ShiftAmt) {
8573           // Perform a logical shr by shiftamt.
8574           // Insert the shift to put the result in the low bit.
8575           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8576                               ConstantInt::get(In->getType(), ShiftAmt),
8577                                                    In->getName()+".lobit"), CI);
8578         }
8579           
8580         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8581           Constant *One = ConstantInt::get(In->getType(), 1);
8582           In = BinaryOperator::CreateXor(In, One, "tmp");
8583           InsertNewInstBefore(cast<Instruction>(In), CI);
8584         }
8585           
8586         if (CI.getType() == In->getType())
8587           return ReplaceInstUsesWith(CI, In);
8588         else
8589           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8590       }
8591     }
8592   }
8593
8594   return 0;
8595 }
8596
8597 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8598   // If one of the common conversion will work ..
8599   if (Instruction *Result = commonIntCastTransforms(CI))
8600     return Result;
8601
8602   Value *Src = CI.getOperand(0);
8603
8604   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8605   // types and if the sizes are just right we can convert this into a logical
8606   // 'and' which will be much cheaper than the pair of casts.
8607   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8608     // Get the sizes of the types involved.  We know that the intermediate type
8609     // will be smaller than A or C, but don't know the relation between A and C.
8610     Value *A = CSrc->getOperand(0);
8611     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8612     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8613     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8614     // If we're actually extending zero bits, then if
8615     // SrcSize <  DstSize: zext(a & mask)
8616     // SrcSize == DstSize: a & mask
8617     // SrcSize  > DstSize: trunc(a) & mask
8618     if (SrcSize < DstSize) {
8619       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8620       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8621       Instruction *And =
8622         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8623       InsertNewInstBefore(And, CI);
8624       return new ZExtInst(And, CI.getType());
8625     } else if (SrcSize == DstSize) {
8626       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8627       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8628                                                            AndValue));
8629     } else if (SrcSize > DstSize) {
8630       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8631       InsertNewInstBefore(Trunc, CI);
8632       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8633       return BinaryOperator::CreateAnd(Trunc, 
8634                                        ConstantInt::get(Trunc->getType(),
8635                                                                AndValue));
8636     }
8637   }
8638
8639   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8640     return transformZExtICmp(ICI, CI);
8641
8642   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8643   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8644     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8645     // of the (zext icmp) will be transformed.
8646     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8647     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8648     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8649         (transformZExtICmp(LHS, CI, false) ||
8650          transformZExtICmp(RHS, CI, false))) {
8651       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8652       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8653       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8654     }
8655   }
8656
8657   // zext(trunc(t) & C) -> (t & zext(C)).
8658   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8659     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8660       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8661         Value *TI0 = TI->getOperand(0);
8662         if (TI0->getType() == CI.getType())
8663           return
8664             BinaryOperator::CreateAnd(TI0,
8665                                 ConstantExpr::getZExt(C, CI.getType()));
8666       }
8667
8668   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8669   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8670     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8671       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8672         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8673             And->getOperand(1) == C)
8674           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8675             Value *TI0 = TI->getOperand(0);
8676             if (TI0->getType() == CI.getType()) {
8677               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8678               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8679               InsertNewInstBefore(NewAnd, *And);
8680               return BinaryOperator::CreateXor(NewAnd, ZC);
8681             }
8682           }
8683
8684   return 0;
8685 }
8686
8687 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8688   if (Instruction *I = commonIntCastTransforms(CI))
8689     return I;
8690   
8691   Value *Src = CI.getOperand(0);
8692   
8693   // Canonicalize sign-extend from i1 to a select.
8694   if (Src->getType() == Type::Int1Ty)
8695     return SelectInst::Create(Src,
8696                               Constant::getAllOnesValue(CI.getType()),
8697                               Constant::getNullValue(CI.getType()));
8698
8699   // See if the value being truncated is already sign extended.  If so, just
8700   // eliminate the trunc/sext pair.
8701   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8702     Value *Op = cast<User>(Src)->getOperand(0);
8703     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8704     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8705     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8706     unsigned NumSignBits = ComputeNumSignBits(Op);
8707
8708     if (OpBits == DestBits) {
8709       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8710       // bits, it is already ready.
8711       if (NumSignBits > DestBits-MidBits)
8712         return ReplaceInstUsesWith(CI, Op);
8713     } else if (OpBits < DestBits) {
8714       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8715       // bits, just sext from i32.
8716       if (NumSignBits > OpBits-MidBits)
8717         return new SExtInst(Op, CI.getType(), "tmp");
8718     } else {
8719       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8720       // bits, just truncate to i32.
8721       if (NumSignBits > OpBits-MidBits)
8722         return new TruncInst(Op, CI.getType(), "tmp");
8723     }
8724   }
8725
8726   // If the input is a shl/ashr pair of a same constant, then this is a sign
8727   // extension from a smaller value.  If we could trust arbitrary bitwidth
8728   // integers, we could turn this into a truncate to the smaller bit and then
8729   // use a sext for the whole extension.  Since we don't, look deeper and check
8730   // for a truncate.  If the source and dest are the same type, eliminate the
8731   // trunc and extend and just do shifts.  For example, turn:
8732   //   %a = trunc i32 %i to i8
8733   //   %b = shl i8 %a, 6
8734   //   %c = ashr i8 %b, 6
8735   //   %d = sext i8 %c to i32
8736   // into:
8737   //   %a = shl i32 %i, 30
8738   //   %d = ashr i32 %a, 30
8739   Value *A = 0;
8740   ConstantInt *BA = 0, *CA = 0;
8741   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8742                         m_ConstantInt(CA))) &&
8743       BA == CA && isa<TruncInst>(A)) {
8744     Value *I = cast<TruncInst>(A)->getOperand(0);
8745     if (I->getType() == CI.getType()) {
8746       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8747       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8748       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8749       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8750       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8751                                                         CI.getName()), CI);
8752       return BinaryOperator::CreateAShr(I, ShAmtV);
8753     }
8754   }
8755   
8756   return 0;
8757 }
8758
8759 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8760 /// in the specified FP type without changing its value.
8761 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8762                               LLVMContext *Context) {
8763   bool losesInfo;
8764   APFloat F = CFP->getValueAPF();
8765   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8766   if (!losesInfo)
8767     return ConstantFP::get(*Context, F);
8768   return 0;
8769 }
8770
8771 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8772 /// through it until we get the source value.
8773 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8774   if (Instruction *I = dyn_cast<Instruction>(V))
8775     if (I->getOpcode() == Instruction::FPExt)
8776       return LookThroughFPExtensions(I->getOperand(0), Context);
8777   
8778   // If this value is a constant, return the constant in the smallest FP type
8779   // that can accurately represent it.  This allows us to turn
8780   // (float)((double)X+2.0) into x+2.0f.
8781   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8782     if (CFP->getType() == Type::PPC_FP128Ty)
8783       return V;  // No constant folding of this.
8784     // See if the value can be truncated to float and then reextended.
8785     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8786       return V;
8787     if (CFP->getType() == Type::DoubleTy)
8788       return V;  // Won't shrink.
8789     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8790       return V;
8791     // Don't try to shrink to various long double types.
8792   }
8793   
8794   return V;
8795 }
8796
8797 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8798   if (Instruction *I = commonCastTransforms(CI))
8799     return I;
8800   
8801   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8802   // smaller than the destination type, we can eliminate the truncate by doing
8803   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8804   // many builtins (sqrt, etc).
8805   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8806   if (OpI && OpI->hasOneUse()) {
8807     switch (OpI->getOpcode()) {
8808     default: break;
8809     case Instruction::FAdd:
8810     case Instruction::FSub:
8811     case Instruction::FMul:
8812     case Instruction::FDiv:
8813     case Instruction::FRem:
8814       const Type *SrcTy = OpI->getType();
8815       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8816       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8817       if (LHSTrunc->getType() != SrcTy && 
8818           RHSTrunc->getType() != SrcTy) {
8819         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8820         // If the source types were both smaller than the destination type of
8821         // the cast, do this xform.
8822         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8823             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8824           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8825                                       CI.getType(), CI);
8826           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8827                                       CI.getType(), CI);
8828           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8829         }
8830       }
8831       break;  
8832     }
8833   }
8834   return 0;
8835 }
8836
8837 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8838   return commonCastTransforms(CI);
8839 }
8840
8841 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8842   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8843   if (OpI == 0)
8844     return commonCastTransforms(FI);
8845
8846   // fptoui(uitofp(X)) --> X
8847   // fptoui(sitofp(X)) --> X
8848   // This is safe if the intermediate type has enough bits in its mantissa to
8849   // accurately represent all values of X.  For example, do not do this with
8850   // i64->float->i64.  This is also safe for sitofp case, because any negative
8851   // 'X' value would cause an undefined result for the fptoui. 
8852   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8853       OpI->getOperand(0)->getType() == FI.getType() &&
8854       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8855                     OpI->getType()->getFPMantissaWidth())
8856     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8857
8858   return commonCastTransforms(FI);
8859 }
8860
8861 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8862   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8863   if (OpI == 0)
8864     return commonCastTransforms(FI);
8865   
8866   // fptosi(sitofp(X)) --> X
8867   // fptosi(uitofp(X)) --> X
8868   // This is safe if the intermediate type has enough bits in its mantissa to
8869   // accurately represent all values of X.  For example, do not do this with
8870   // i64->float->i64.  This is also safe for sitofp case, because any negative
8871   // 'X' value would cause an undefined result for the fptoui. 
8872   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8873       OpI->getOperand(0)->getType() == FI.getType() &&
8874       (int)FI.getType()->getScalarSizeInBits() <=
8875                     OpI->getType()->getFPMantissaWidth())
8876     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8877   
8878   return commonCastTransforms(FI);
8879 }
8880
8881 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8882   return commonCastTransforms(CI);
8883 }
8884
8885 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8886   return commonCastTransforms(CI);
8887 }
8888
8889 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8890   // If the destination integer type is smaller than the intptr_t type for
8891   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8892   // trunc to be exposed to other transforms.  Don't do this for extending
8893   // ptrtoint's, because we don't know if the target sign or zero extends its
8894   // pointers.
8895   if (TD &&
8896       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8897     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8898                                                     TD->getIntPtrType(),
8899                                                     "tmp"), CI);
8900     return new TruncInst(P, CI.getType());
8901   }
8902   
8903   return commonPointerCastTransforms(CI);
8904 }
8905
8906 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8907   // If the source integer type is larger than the intptr_t type for
8908   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8909   // allows the trunc to be exposed to other transforms.  Don't do this for
8910   // extending inttoptr's, because we don't know if the target sign or zero
8911   // extends to pointers.
8912   if (TD &&
8913       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8914       TD->getPointerSizeInBits()) {
8915     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8916                                                  TD->getIntPtrType(),
8917                                                  "tmp"), CI);
8918     return new IntToPtrInst(P, CI.getType());
8919   }
8920   
8921   if (Instruction *I = commonCastTransforms(CI))
8922     return I;
8923
8924   return 0;
8925 }
8926
8927 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8928   // If the operands are integer typed then apply the integer transforms,
8929   // otherwise just apply the common ones.
8930   Value *Src = CI.getOperand(0);
8931   const Type *SrcTy = Src->getType();
8932   const Type *DestTy = CI.getType();
8933
8934   if (isa<PointerType>(SrcTy)) {
8935     if (Instruction *I = commonPointerCastTransforms(CI))
8936       return I;
8937   } else {
8938     if (Instruction *Result = commonCastTransforms(CI))
8939       return Result;
8940   }
8941
8942
8943   // Get rid of casts from one type to the same type. These are useless and can
8944   // be replaced by the operand.
8945   if (DestTy == Src->getType())
8946     return ReplaceInstUsesWith(CI, Src);
8947
8948   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8949     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8950     const Type *DstElTy = DstPTy->getElementType();
8951     const Type *SrcElTy = SrcPTy->getElementType();
8952     
8953     // If the address spaces don't match, don't eliminate the bitcast, which is
8954     // required for changing types.
8955     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8956       return 0;
8957     
8958     // If we are casting a malloc or alloca to a pointer to a type of the same
8959     // size, rewrite the allocation instruction to allocate the "right" type.
8960     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8961       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8962         return V;
8963     
8964     // If the source and destination are pointers, and this cast is equivalent
8965     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8966     // This can enhance SROA and other transforms that want type-safe pointers.
8967     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8968     unsigned NumZeros = 0;
8969     while (SrcElTy != DstElTy && 
8970            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8971            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8972       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8973       ++NumZeros;
8974     }
8975
8976     // If we found a path from the src to dest, create the getelementptr now.
8977     if (SrcElTy == DstElTy) {
8978       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8979       Instruction *GEP = GetElementPtrInst::Create(Src,
8980                                                    Idxs.begin(), Idxs.end(), "",
8981                                                    ((Instruction*) NULL));
8982       cast<GEPOperator>(GEP)->setIsInBounds(true);
8983       return GEP;
8984     }
8985   }
8986
8987   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8988     if (DestVTy->getNumElements() == 1) {
8989       if (!isa<VectorType>(SrcTy)) {
8990         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8991                                        DestVTy->getElementType(), CI);
8992         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8993                                          Constant::getNullValue(Type::Int32Ty));
8994       }
8995       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8996     }
8997   }
8998
8999   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9000     if (SrcVTy->getNumElements() == 1) {
9001       if (!isa<VectorType>(DestTy)) {
9002         Instruction *Elem =
9003           ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
9004         InsertNewInstBefore(Elem, CI);
9005         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9006       }
9007     }
9008   }
9009
9010   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9011     if (SVI->hasOneUse()) {
9012       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9013       // a bitconvert to a vector with the same # elts.
9014       if (isa<VectorType>(DestTy) && 
9015           cast<VectorType>(DestTy)->getNumElements() ==
9016                 SVI->getType()->getNumElements() &&
9017           SVI->getType()->getNumElements() ==
9018             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9019         CastInst *Tmp;
9020         // If either of the operands is a cast from CI.getType(), then
9021         // evaluating the shuffle in the casted destination's type will allow
9022         // us to eliminate at least one cast.
9023         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9024              Tmp->getOperand(0)->getType() == DestTy) ||
9025             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9026              Tmp->getOperand(0)->getType() == DestTy)) {
9027           Value *LHS = InsertCastBefore(Instruction::BitCast,
9028                                         SVI->getOperand(0), DestTy, CI);
9029           Value *RHS = InsertCastBefore(Instruction::BitCast,
9030                                         SVI->getOperand(1), DestTy, CI);
9031           // Return a new shuffle vector.  Use the same element ID's, as we
9032           // know the vector types match #elts.
9033           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9034         }
9035       }
9036     }
9037   }
9038   return 0;
9039 }
9040
9041 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9042 ///   %C = or %A, %B
9043 ///   %D = select %cond, %C, %A
9044 /// into:
9045 ///   %C = select %cond, %B, 0
9046 ///   %D = or %A, %C
9047 ///
9048 /// Assuming that the specified instruction is an operand to the select, return
9049 /// a bitmask indicating which operands of this instruction are foldable if they
9050 /// equal the other incoming value of the select.
9051 ///
9052 static unsigned GetSelectFoldableOperands(Instruction *I) {
9053   switch (I->getOpcode()) {
9054   case Instruction::Add:
9055   case Instruction::Mul:
9056   case Instruction::And:
9057   case Instruction::Or:
9058   case Instruction::Xor:
9059     return 3;              // Can fold through either operand.
9060   case Instruction::Sub:   // Can only fold on the amount subtracted.
9061   case Instruction::Shl:   // Can only fold on the shift amount.
9062   case Instruction::LShr:
9063   case Instruction::AShr:
9064     return 1;
9065   default:
9066     return 0;              // Cannot fold
9067   }
9068 }
9069
9070 /// GetSelectFoldableConstant - For the same transformation as the previous
9071 /// function, return the identity constant that goes into the select.
9072 static Constant *GetSelectFoldableConstant(Instruction *I,
9073                                            LLVMContext *Context) {
9074   switch (I->getOpcode()) {
9075   default: llvm_unreachable("This cannot happen!");
9076   case Instruction::Add:
9077   case Instruction::Sub:
9078   case Instruction::Or:
9079   case Instruction::Xor:
9080   case Instruction::Shl:
9081   case Instruction::LShr:
9082   case Instruction::AShr:
9083     return Constant::getNullValue(I->getType());
9084   case Instruction::And:
9085     return Constant::getAllOnesValue(I->getType());
9086   case Instruction::Mul:
9087     return ConstantInt::get(I->getType(), 1);
9088   }
9089 }
9090
9091 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9092 /// have the same opcode and only one use each.  Try to simplify this.
9093 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9094                                           Instruction *FI) {
9095   if (TI->getNumOperands() == 1) {
9096     // If this is a non-volatile load or a cast from the same type,
9097     // merge.
9098     if (TI->isCast()) {
9099       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9100         return 0;
9101     } else {
9102       return 0;  // unknown unary op.
9103     }
9104
9105     // Fold this by inserting a select from the input values.
9106     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9107                                           FI->getOperand(0), SI.getName()+".v");
9108     InsertNewInstBefore(NewSI, SI);
9109     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9110                             TI->getType());
9111   }
9112
9113   // Only handle binary operators here.
9114   if (!isa<BinaryOperator>(TI))
9115     return 0;
9116
9117   // Figure out if the operations have any operands in common.
9118   Value *MatchOp, *OtherOpT, *OtherOpF;
9119   bool MatchIsOpZero;
9120   if (TI->getOperand(0) == FI->getOperand(0)) {
9121     MatchOp  = TI->getOperand(0);
9122     OtherOpT = TI->getOperand(1);
9123     OtherOpF = FI->getOperand(1);
9124     MatchIsOpZero = true;
9125   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9126     MatchOp  = TI->getOperand(1);
9127     OtherOpT = TI->getOperand(0);
9128     OtherOpF = FI->getOperand(0);
9129     MatchIsOpZero = false;
9130   } else if (!TI->isCommutative()) {
9131     return 0;
9132   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9133     MatchOp  = TI->getOperand(0);
9134     OtherOpT = TI->getOperand(1);
9135     OtherOpF = FI->getOperand(0);
9136     MatchIsOpZero = true;
9137   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9138     MatchOp  = TI->getOperand(1);
9139     OtherOpT = TI->getOperand(0);
9140     OtherOpF = FI->getOperand(1);
9141     MatchIsOpZero = true;
9142   } else {
9143     return 0;
9144   }
9145
9146   // If we reach here, they do have operations in common.
9147   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9148                                          OtherOpF, SI.getName()+".v");
9149   InsertNewInstBefore(NewSI, SI);
9150
9151   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9152     if (MatchIsOpZero)
9153       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9154     else
9155       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9156   }
9157   llvm_unreachable("Shouldn't get here");
9158   return 0;
9159 }
9160
9161 static bool isSelect01(Constant *C1, Constant *C2) {
9162   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9163   if (!C1I)
9164     return false;
9165   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9166   if (!C2I)
9167     return false;
9168   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9169 }
9170
9171 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9172 /// facilitate further optimization.
9173 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9174                                             Value *FalseVal) {
9175   // See the comment above GetSelectFoldableOperands for a description of the
9176   // transformation we are doing here.
9177   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9178     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9179         !isa<Constant>(FalseVal)) {
9180       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9181         unsigned OpToFold = 0;
9182         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9183           OpToFold = 1;
9184         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9185           OpToFold = 2;
9186         }
9187
9188         if (OpToFold) {
9189           Constant *C = GetSelectFoldableConstant(TVI, Context);
9190           Value *OOp = TVI->getOperand(2-OpToFold);
9191           // Avoid creating select between 2 constants unless it's selecting
9192           // between 0 and 1.
9193           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9194             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9195             InsertNewInstBefore(NewSel, SI);
9196             NewSel->takeName(TVI);
9197             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9198               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9199             llvm_unreachable("Unknown instruction!!");
9200           }
9201         }
9202       }
9203     }
9204   }
9205
9206   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9207     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9208         !isa<Constant>(TrueVal)) {
9209       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9210         unsigned OpToFold = 0;
9211         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9212           OpToFold = 1;
9213         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9214           OpToFold = 2;
9215         }
9216
9217         if (OpToFold) {
9218           Constant *C = GetSelectFoldableConstant(FVI, Context);
9219           Value *OOp = FVI->getOperand(2-OpToFold);
9220           // Avoid creating select between 2 constants unless it's selecting
9221           // between 0 and 1.
9222           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9223             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9224             InsertNewInstBefore(NewSel, SI);
9225             NewSel->takeName(FVI);
9226             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9227               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9228             llvm_unreachable("Unknown instruction!!");
9229           }
9230         }
9231       }
9232     }
9233   }
9234
9235   return 0;
9236 }
9237
9238 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9239 /// ICmpInst as its first operand.
9240 ///
9241 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9242                                                    ICmpInst *ICI) {
9243   bool Changed = false;
9244   ICmpInst::Predicate Pred = ICI->getPredicate();
9245   Value *CmpLHS = ICI->getOperand(0);
9246   Value *CmpRHS = ICI->getOperand(1);
9247   Value *TrueVal = SI.getTrueValue();
9248   Value *FalseVal = SI.getFalseValue();
9249
9250   // Check cases where the comparison is with a constant that
9251   // can be adjusted to fit the min/max idiom. We may edit ICI in
9252   // place here, so make sure the select is the only user.
9253   if (ICI->hasOneUse())
9254     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9255       switch (Pred) {
9256       default: break;
9257       case ICmpInst::ICMP_ULT:
9258       case ICmpInst::ICMP_SLT: {
9259         // X < MIN ? T : F  -->  F
9260         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9261           return ReplaceInstUsesWith(SI, FalseVal);
9262         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9263         Constant *AdjustedRHS = SubOne(CI);
9264         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9265             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9266           Pred = ICmpInst::getSwappedPredicate(Pred);
9267           CmpRHS = AdjustedRHS;
9268           std::swap(FalseVal, TrueVal);
9269           ICI->setPredicate(Pred);
9270           ICI->setOperand(1, CmpRHS);
9271           SI.setOperand(1, TrueVal);
9272           SI.setOperand(2, FalseVal);
9273           Changed = true;
9274         }
9275         break;
9276       }
9277       case ICmpInst::ICMP_UGT:
9278       case ICmpInst::ICMP_SGT: {
9279         // X > MAX ? T : F  -->  F
9280         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9281           return ReplaceInstUsesWith(SI, FalseVal);
9282         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9283         Constant *AdjustedRHS = AddOne(CI);
9284         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286           Pred = ICmpInst::getSwappedPredicate(Pred);
9287           CmpRHS = AdjustedRHS;
9288           std::swap(FalseVal, TrueVal);
9289           ICI->setPredicate(Pred);
9290           ICI->setOperand(1, CmpRHS);
9291           SI.setOperand(1, TrueVal);
9292           SI.setOperand(2, FalseVal);
9293           Changed = true;
9294         }
9295         break;
9296       }
9297       }
9298
9299       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9300       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9301       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9302       if (match(TrueVal, m_ConstantInt<-1>()) &&
9303           match(FalseVal, m_ConstantInt<0>()))
9304         Pred = ICI->getPredicate();
9305       else if (match(TrueVal, m_ConstantInt<0>()) &&
9306                match(FalseVal, m_ConstantInt<-1>()))
9307         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9308       
9309       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9310         // If we are just checking for a icmp eq of a single bit and zext'ing it
9311         // to an integer, then shift the bit to the appropriate place and then
9312         // cast to integer to avoid the comparison.
9313         const APInt &Op1CV = CI->getValue();
9314     
9315         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9316         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9317         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9318             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9319           Value *In = ICI->getOperand(0);
9320           Value *Sh = ConstantInt::get(In->getType(),
9321                                        In->getType()->getScalarSizeInBits()-1);
9322           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9323                                                         In->getName()+".lobit"),
9324                                    *ICI);
9325           if (In->getType() != SI.getType())
9326             In = CastInst::CreateIntegerCast(In, SI.getType(),
9327                                              true/*SExt*/, "tmp", ICI);
9328     
9329           if (Pred == ICmpInst::ICMP_SGT)
9330             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9331                                        In->getName()+".not"), *ICI);
9332     
9333           return ReplaceInstUsesWith(SI, In);
9334         }
9335       }
9336     }
9337
9338   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9339     // Transform (X == Y) ? X : Y  -> Y
9340     if (Pred == ICmpInst::ICMP_EQ)
9341       return ReplaceInstUsesWith(SI, FalseVal);
9342     // Transform (X != Y) ? X : Y  -> X
9343     if (Pred == ICmpInst::ICMP_NE)
9344       return ReplaceInstUsesWith(SI, TrueVal);
9345     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9346
9347   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9348     // Transform (X == Y) ? Y : X  -> X
9349     if (Pred == ICmpInst::ICMP_EQ)
9350       return ReplaceInstUsesWith(SI, FalseVal);
9351     // Transform (X != Y) ? Y : X  -> Y
9352     if (Pred == ICmpInst::ICMP_NE)
9353       return ReplaceInstUsesWith(SI, TrueVal);
9354     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9355   }
9356
9357   /// NOTE: if we wanted to, this is where to detect integer ABS
9358
9359   return Changed ? &SI : 0;
9360 }
9361
9362 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9363   Value *CondVal = SI.getCondition();
9364   Value *TrueVal = SI.getTrueValue();
9365   Value *FalseVal = SI.getFalseValue();
9366
9367   // select true, X, Y  -> X
9368   // select false, X, Y -> Y
9369   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9370     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9371
9372   // select C, X, X -> X
9373   if (TrueVal == FalseVal)
9374     return ReplaceInstUsesWith(SI, TrueVal);
9375
9376   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9377     return ReplaceInstUsesWith(SI, FalseVal);
9378   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9379     return ReplaceInstUsesWith(SI, TrueVal);
9380   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9381     if (isa<Constant>(TrueVal))
9382       return ReplaceInstUsesWith(SI, TrueVal);
9383     else
9384       return ReplaceInstUsesWith(SI, FalseVal);
9385   }
9386
9387   if (SI.getType() == Type::Int1Ty) {
9388     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9389       if (C->getZExtValue()) {
9390         // Change: A = select B, true, C --> A = or B, C
9391         return BinaryOperator::CreateOr(CondVal, FalseVal);
9392       } else {
9393         // Change: A = select B, false, C --> A = and !B, C
9394         Value *NotCond =
9395           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9396                                              "not."+CondVal->getName()), SI);
9397         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9398       }
9399     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9400       if (C->getZExtValue() == false) {
9401         // Change: A = select B, C, false --> A = and B, C
9402         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9403       } else {
9404         // Change: A = select B, C, true --> A = or !B, C
9405         Value *NotCond =
9406           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9407                                              "not."+CondVal->getName()), SI);
9408         return BinaryOperator::CreateOr(NotCond, TrueVal);
9409       }
9410     }
9411     
9412     // select a, b, a  -> a&b
9413     // select a, a, b  -> a|b
9414     if (CondVal == TrueVal)
9415       return BinaryOperator::CreateOr(CondVal, FalseVal);
9416     else if (CondVal == FalseVal)
9417       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9418   }
9419
9420   // Selecting between two integer constants?
9421   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9422     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9423       // select C, 1, 0 -> zext C to int
9424       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9425         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9426       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9427         // select C, 0, 1 -> zext !C to int
9428         Value *NotCond =
9429           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9430                                                "not."+CondVal->getName()), SI);
9431         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9432       }
9433
9434       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9435         // If one of the constants is zero (we know they can't both be) and we
9436         // have an icmp instruction with zero, and we have an 'and' with the
9437         // non-constant value, eliminate this whole mess.  This corresponds to
9438         // cases like this: ((X & 27) ? 27 : 0)
9439         if (TrueValC->isZero() || FalseValC->isZero())
9440           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9441               cast<Constant>(IC->getOperand(1))->isNullValue())
9442             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9443               if (ICA->getOpcode() == Instruction::And &&
9444                   isa<ConstantInt>(ICA->getOperand(1)) &&
9445                   (ICA->getOperand(1) == TrueValC ||
9446                    ICA->getOperand(1) == FalseValC) &&
9447                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9448                 // Okay, now we know that everything is set up, we just don't
9449                 // know whether we have a icmp_ne or icmp_eq and whether the 
9450                 // true or false val is the zero.
9451                 bool ShouldNotVal = !TrueValC->isZero();
9452                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9453                 Value *V = ICA;
9454                 if (ShouldNotVal)
9455                   V = InsertNewInstBefore(BinaryOperator::Create(
9456                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9457                 return ReplaceInstUsesWith(SI, V);
9458               }
9459       }
9460     }
9461
9462   // See if we are selecting two values based on a comparison of the two values.
9463   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9464     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9465       // Transform (X == Y) ? X : Y  -> Y
9466       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9467         // This is not safe in general for floating point:  
9468         // consider X== -0, Y== +0.
9469         // It becomes safe if either operand is a nonzero constant.
9470         ConstantFP *CFPt, *CFPf;
9471         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9472               !CFPt->getValueAPF().isZero()) ||
9473             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9474              !CFPf->getValueAPF().isZero()))
9475         return ReplaceInstUsesWith(SI, FalseVal);
9476       }
9477       // Transform (X != Y) ? X : Y  -> X
9478       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9479         return ReplaceInstUsesWith(SI, TrueVal);
9480       // NOTE: if we wanted to, this is where to detect MIN/MAX
9481
9482     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9483       // Transform (X == Y) ? Y : X  -> X
9484       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9485         // This is not safe in general for floating point:  
9486         // consider X== -0, Y== +0.
9487         // It becomes safe if either operand is a nonzero constant.
9488         ConstantFP *CFPt, *CFPf;
9489         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9490               !CFPt->getValueAPF().isZero()) ||
9491             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9492              !CFPf->getValueAPF().isZero()))
9493           return ReplaceInstUsesWith(SI, FalseVal);
9494       }
9495       // Transform (X != Y) ? Y : X  -> Y
9496       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9497         return ReplaceInstUsesWith(SI, TrueVal);
9498       // NOTE: if we wanted to, this is where to detect MIN/MAX
9499     }
9500     // NOTE: if we wanted to, this is where to detect ABS
9501   }
9502
9503   // See if we are selecting two values based on a comparison of the two values.
9504   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9505     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9506       return Result;
9507
9508   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9509     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9510       if (TI->hasOneUse() && FI->hasOneUse()) {
9511         Instruction *AddOp = 0, *SubOp = 0;
9512
9513         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9514         if (TI->getOpcode() == FI->getOpcode())
9515           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9516             return IV;
9517
9518         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9519         // even legal for FP.
9520         if ((TI->getOpcode() == Instruction::Sub &&
9521              FI->getOpcode() == Instruction::Add) ||
9522             (TI->getOpcode() == Instruction::FSub &&
9523              FI->getOpcode() == Instruction::FAdd)) {
9524           AddOp = FI; SubOp = TI;
9525         } else if ((FI->getOpcode() == Instruction::Sub &&
9526                     TI->getOpcode() == Instruction::Add) ||
9527                    (FI->getOpcode() == Instruction::FSub &&
9528                     TI->getOpcode() == Instruction::FAdd)) {
9529           AddOp = TI; SubOp = FI;
9530         }
9531
9532         if (AddOp) {
9533           Value *OtherAddOp = 0;
9534           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9535             OtherAddOp = AddOp->getOperand(1);
9536           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9537             OtherAddOp = AddOp->getOperand(0);
9538           }
9539
9540           if (OtherAddOp) {
9541             // So at this point we know we have (Y -> OtherAddOp):
9542             //        select C, (add X, Y), (sub X, Z)
9543             Value *NegVal;  // Compute -Z
9544             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9545               NegVal = ConstantExpr::getNeg(C);
9546             } else {
9547               NegVal = InsertNewInstBefore(
9548                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9549                                               "tmp"), SI);
9550             }
9551
9552             Value *NewTrueOp = OtherAddOp;
9553             Value *NewFalseOp = NegVal;
9554             if (AddOp != TI)
9555               std::swap(NewTrueOp, NewFalseOp);
9556             Instruction *NewSel =
9557               SelectInst::Create(CondVal, NewTrueOp,
9558                                  NewFalseOp, SI.getName() + ".p");
9559
9560             NewSel = InsertNewInstBefore(NewSel, SI);
9561             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9562           }
9563         }
9564       }
9565
9566   // See if we can fold the select into one of our operands.
9567   if (SI.getType()->isInteger()) {
9568     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9569     if (FoldI)
9570       return FoldI;
9571   }
9572
9573   if (BinaryOperator::isNot(CondVal)) {
9574     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9575     SI.setOperand(1, FalseVal);
9576     SI.setOperand(2, TrueVal);
9577     return &SI;
9578   }
9579
9580   return 0;
9581 }
9582
9583 /// EnforceKnownAlignment - If the specified pointer points to an object that
9584 /// we control, modify the object's alignment to PrefAlign. This isn't
9585 /// often possible though. If alignment is important, a more reliable approach
9586 /// is to simply align all global variables and allocation instructions to
9587 /// their preferred alignment from the beginning.
9588 ///
9589 static unsigned EnforceKnownAlignment(Value *V,
9590                                       unsigned Align, unsigned PrefAlign) {
9591
9592   User *U = dyn_cast<User>(V);
9593   if (!U) return Align;
9594
9595   switch (Operator::getOpcode(U)) {
9596   default: break;
9597   case Instruction::BitCast:
9598     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9599   case Instruction::GetElementPtr: {
9600     // If all indexes are zero, it is just the alignment of the base pointer.
9601     bool AllZeroOperands = true;
9602     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9603       if (!isa<Constant>(*i) ||
9604           !cast<Constant>(*i)->isNullValue()) {
9605         AllZeroOperands = false;
9606         break;
9607       }
9608
9609     if (AllZeroOperands) {
9610       // Treat this like a bitcast.
9611       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9612     }
9613     break;
9614   }
9615   }
9616
9617   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9618     // If there is a large requested alignment and we can, bump up the alignment
9619     // of the global.
9620     if (!GV->isDeclaration()) {
9621       if (GV->getAlignment() >= PrefAlign)
9622         Align = GV->getAlignment();
9623       else {
9624         GV->setAlignment(PrefAlign);
9625         Align = PrefAlign;
9626       }
9627     }
9628   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9629     // If there is a requested alignment and if this is an alloca, round up.  We
9630     // don't do this for malloc, because some systems can't respect the request.
9631     if (isa<AllocaInst>(AI)) {
9632       if (AI->getAlignment() >= PrefAlign)
9633         Align = AI->getAlignment();
9634       else {
9635         AI->setAlignment(PrefAlign);
9636         Align = PrefAlign;
9637       }
9638     }
9639   }
9640
9641   return Align;
9642 }
9643
9644 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9645 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9646 /// and it is more than the alignment of the ultimate object, see if we can
9647 /// increase the alignment of the ultimate object, making this check succeed.
9648 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9649                                                   unsigned PrefAlign) {
9650   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9651                       sizeof(PrefAlign) * CHAR_BIT;
9652   APInt Mask = APInt::getAllOnesValue(BitWidth);
9653   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9654   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9655   unsigned TrailZ = KnownZero.countTrailingOnes();
9656   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9657
9658   if (PrefAlign > Align)
9659     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9660   
9661     // We don't need to make any adjustment.
9662   return Align;
9663 }
9664
9665 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9666   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9667   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9668   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9669   unsigned CopyAlign = MI->getAlignment();
9670
9671   if (CopyAlign < MinAlign) {
9672     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9673                                              MinAlign, false));
9674     return MI;
9675   }
9676   
9677   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9678   // load/store.
9679   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9680   if (MemOpLength == 0) return 0;
9681   
9682   // Source and destination pointer types are always "i8*" for intrinsic.  See
9683   // if the size is something we can handle with a single primitive load/store.
9684   // A single load+store correctly handles overlapping memory in the memmove
9685   // case.
9686   unsigned Size = MemOpLength->getZExtValue();
9687   if (Size == 0) return MI;  // Delete this mem transfer.
9688   
9689   if (Size > 8 || (Size&(Size-1)))
9690     return 0;  // If not 1/2/4/8 bytes, exit.
9691   
9692   // Use an integer load+store unless we can find something better.
9693   Type *NewPtrTy =
9694                 PointerType::getUnqual(IntegerType::get(Size<<3));
9695   
9696   // Memcpy forces the use of i8* for the source and destination.  That means
9697   // that if you're using memcpy to move one double around, you'll get a cast
9698   // from double* to i8*.  We'd much rather use a double load+store rather than
9699   // an i64 load+store, here because this improves the odds that the source or
9700   // dest address will be promotable.  See if we can find a better type than the
9701   // integer datatype.
9702   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9703     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9704     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9705       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9706       // down through these levels if so.
9707       while (!SrcETy->isSingleValueType()) {
9708         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9709           if (STy->getNumElements() == 1)
9710             SrcETy = STy->getElementType(0);
9711           else
9712             break;
9713         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9714           if (ATy->getNumElements() == 1)
9715             SrcETy = ATy->getElementType();
9716           else
9717             break;
9718         } else
9719           break;
9720       }
9721       
9722       if (SrcETy->isSingleValueType())
9723         NewPtrTy = PointerType::getUnqual(SrcETy);
9724     }
9725   }
9726   
9727   
9728   // If the memcpy/memmove provides better alignment info than we can
9729   // infer, use it.
9730   SrcAlign = std::max(SrcAlign, CopyAlign);
9731   DstAlign = std::max(DstAlign, CopyAlign);
9732   
9733   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9734   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9735   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9736   InsertNewInstBefore(L, *MI);
9737   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9738
9739   // Set the size of the copy to 0, it will be deleted on the next iteration.
9740   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9741   return MI;
9742 }
9743
9744 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9745   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9746   if (MI->getAlignment() < Alignment) {
9747     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9748                                              Alignment, false));
9749     return MI;
9750   }
9751   
9752   // Extract the length and alignment and fill if they are constant.
9753   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9754   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9755   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9756     return 0;
9757   uint64_t Len = LenC->getZExtValue();
9758   Alignment = MI->getAlignment();
9759   
9760   // If the length is zero, this is a no-op
9761   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9762   
9763   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9764   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9765     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9766     
9767     Value *Dest = MI->getDest();
9768     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9769
9770     // Alignment 0 is identity for alignment 1 for memset, but not store.
9771     if (Alignment == 0) Alignment = 1;
9772     
9773     // Extract the fill value and store.
9774     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9775     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9776                                       Dest, false, Alignment), *MI);
9777     
9778     // Set the size of the copy to 0, it will be deleted on the next iteration.
9779     MI->setLength(Constant::getNullValue(LenC->getType()));
9780     return MI;
9781   }
9782
9783   return 0;
9784 }
9785
9786
9787 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9788 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9789 /// the heavy lifting.
9790 ///
9791 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9792   // If the caller function is nounwind, mark the call as nounwind, even if the
9793   // callee isn't.
9794   if (CI.getParent()->getParent()->doesNotThrow() &&
9795       !CI.doesNotThrow()) {
9796     CI.setDoesNotThrow();
9797     return &CI;
9798   }
9799   
9800   
9801   
9802   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9803   if (!II) return visitCallSite(&CI);
9804   
9805   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9806   // visitCallSite.
9807   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9808     bool Changed = false;
9809
9810     // memmove/cpy/set of zero bytes is a noop.
9811     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9812       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9813
9814       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9815         if (CI->getZExtValue() == 1) {
9816           // Replace the instruction with just byte operations.  We would
9817           // transform other cases to loads/stores, but we don't know if
9818           // alignment is sufficient.
9819         }
9820     }
9821
9822     // If we have a memmove and the source operation is a constant global,
9823     // then the source and dest pointers can't alias, so we can change this
9824     // into a call to memcpy.
9825     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9826       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9827         if (GVSrc->isConstant()) {
9828           Module *M = CI.getParent()->getParent()->getParent();
9829           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9830           const Type *Tys[1];
9831           Tys[0] = CI.getOperand(3)->getType();
9832           CI.setOperand(0, 
9833                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9834           Changed = true;
9835         }
9836
9837       // memmove(x,x,size) -> noop.
9838       if (MMI->getSource() == MMI->getDest())
9839         return EraseInstFromFunction(CI);
9840     }
9841
9842     // If we can determine a pointer alignment that is bigger than currently
9843     // set, update the alignment.
9844     if (isa<MemTransferInst>(MI)) {
9845       if (Instruction *I = SimplifyMemTransfer(MI))
9846         return I;
9847     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9848       if (Instruction *I = SimplifyMemSet(MSI))
9849         return I;
9850     }
9851           
9852     if (Changed) return II;
9853   }
9854   
9855   switch (II->getIntrinsicID()) {
9856   default: break;
9857   case Intrinsic::bswap:
9858     // bswap(bswap(x)) -> x
9859     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9860       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9861         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9862     break;
9863   case Intrinsic::ppc_altivec_lvx:
9864   case Intrinsic::ppc_altivec_lvxl:
9865   case Intrinsic::x86_sse_loadu_ps:
9866   case Intrinsic::x86_sse2_loadu_pd:
9867   case Intrinsic::x86_sse2_loadu_dq:
9868     // Turn PPC lvx     -> load if the pointer is known aligned.
9869     // Turn X86 loadups -> load if the pointer is known aligned.
9870     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9871       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9872                                    PointerType::getUnqual(II->getType()),
9873                                        CI);
9874       return new LoadInst(Ptr);
9875     }
9876     break;
9877   case Intrinsic::ppc_altivec_stvx:
9878   case Intrinsic::ppc_altivec_stvxl:
9879     // Turn stvx -> store if the pointer is known aligned.
9880     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9881       const Type *OpPtrTy = 
9882         PointerType::getUnqual(II->getOperand(1)->getType());
9883       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9884       return new StoreInst(II->getOperand(1), Ptr);
9885     }
9886     break;
9887   case Intrinsic::x86_sse_storeu_ps:
9888   case Intrinsic::x86_sse2_storeu_pd:
9889   case Intrinsic::x86_sse2_storeu_dq:
9890     // Turn X86 storeu -> store if the pointer is known aligned.
9891     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9892       const Type *OpPtrTy = 
9893         PointerType::getUnqual(II->getOperand(2)->getType());
9894       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9895       return new StoreInst(II->getOperand(2), Ptr);
9896     }
9897     break;
9898     
9899   case Intrinsic::x86_sse_cvttss2si: {
9900     // These intrinsics only demands the 0th element of its input vector.  If
9901     // we can simplify the input based on that, do so now.
9902     unsigned VWidth =
9903       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9904     APInt DemandedElts(VWidth, 1);
9905     APInt UndefElts(VWidth, 0);
9906     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9907                                               UndefElts)) {
9908       II->setOperand(1, V);
9909       return II;
9910     }
9911     break;
9912   }
9913     
9914   case Intrinsic::ppc_altivec_vperm:
9915     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9916     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9917       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9918       
9919       // Check that all of the elements are integer constants or undefs.
9920       bool AllEltsOk = true;
9921       for (unsigned i = 0; i != 16; ++i) {
9922         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9923             !isa<UndefValue>(Mask->getOperand(i))) {
9924           AllEltsOk = false;
9925           break;
9926         }
9927       }
9928       
9929       if (AllEltsOk) {
9930         // Cast the input vectors to byte vectors.
9931         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9932         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9933         Value *Result = UndefValue::get(Op0->getType());
9934         
9935         // Only extract each element once.
9936         Value *ExtractedElts[32];
9937         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9938         
9939         for (unsigned i = 0; i != 16; ++i) {
9940           if (isa<UndefValue>(Mask->getOperand(i)))
9941             continue;
9942           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9943           Idx &= 31;  // Match the hardware behavior.
9944           
9945           if (ExtractedElts[Idx] == 0) {
9946             Instruction *Elt = 
9947               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9948                   ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
9949             InsertNewInstBefore(Elt, CI);
9950             ExtractedElts[Idx] = Elt;
9951           }
9952         
9953           // Insert this value into the result vector.
9954           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9955                                ConstantInt::get(Type::Int32Ty, i, false), 
9956                                "tmp");
9957           InsertNewInstBefore(cast<Instruction>(Result), CI);
9958         }
9959         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9960       }
9961     }
9962     break;
9963
9964   case Intrinsic::stackrestore: {
9965     // If the save is right next to the restore, remove the restore.  This can
9966     // happen when variable allocas are DCE'd.
9967     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9968       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9969         BasicBlock::iterator BI = SS;
9970         if (&*++BI == II)
9971           return EraseInstFromFunction(CI);
9972       }
9973     }
9974     
9975     // Scan down this block to see if there is another stack restore in the
9976     // same block without an intervening call/alloca.
9977     BasicBlock::iterator BI = II;
9978     TerminatorInst *TI = II->getParent()->getTerminator();
9979     bool CannotRemove = false;
9980     for (++BI; &*BI != TI; ++BI) {
9981       if (isa<AllocaInst>(BI)) {
9982         CannotRemove = true;
9983         break;
9984       }
9985       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9986         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9987           // If there is a stackrestore below this one, remove this one.
9988           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9989             return EraseInstFromFunction(CI);
9990           // Otherwise, ignore the intrinsic.
9991         } else {
9992           // If we found a non-intrinsic call, we can't remove the stack
9993           // restore.
9994           CannotRemove = true;
9995           break;
9996         }
9997       }
9998     }
9999     
10000     // If the stack restore is in a return/unwind block and if there are no
10001     // allocas or calls between the restore and the return, nuke the restore.
10002     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10003       return EraseInstFromFunction(CI);
10004     break;
10005   }
10006   }
10007
10008   return visitCallSite(II);
10009 }
10010
10011 // InvokeInst simplification
10012 //
10013 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10014   return visitCallSite(&II);
10015 }
10016
10017 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10018 /// passed through the varargs area, we can eliminate the use of the cast.
10019 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10020                                          const CastInst * const CI,
10021                                          const TargetData * const TD,
10022                                          const int ix) {
10023   if (!CI->isLosslessCast())
10024     return false;
10025
10026   // The size of ByVal arguments is derived from the type, so we
10027   // can't change to a type with a different size.  If the size were
10028   // passed explicitly we could avoid this check.
10029   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10030     return true;
10031
10032   const Type* SrcTy = 
10033             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10034   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10035   if (!SrcTy->isSized() || !DstTy->isSized())
10036     return false;
10037   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10038     return false;
10039   return true;
10040 }
10041
10042 // visitCallSite - Improvements for call and invoke instructions.
10043 //
10044 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10045   bool Changed = false;
10046
10047   // If the callee is a constexpr cast of a function, attempt to move the cast
10048   // to the arguments of the call/invoke.
10049   if (transformConstExprCastCall(CS)) return 0;
10050
10051   Value *Callee = CS.getCalledValue();
10052
10053   if (Function *CalleeF = dyn_cast<Function>(Callee))
10054     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10055       Instruction *OldCall = CS.getInstruction();
10056       // If the call and callee calling conventions don't match, this call must
10057       // be unreachable, as the call is undefined.
10058       new StoreInst(ConstantInt::getTrue(*Context),
10059                 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
10060                                   OldCall);
10061       if (!OldCall->use_empty())
10062         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10063       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10064         return EraseInstFromFunction(*OldCall);
10065       return 0;
10066     }
10067
10068   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10069     // This instruction is not reachable, just remove it.  We insert a store to
10070     // undef so that we know that this code is not reachable, despite the fact
10071     // that we can't modify the CFG here.
10072     new StoreInst(ConstantInt::getTrue(*Context),
10073                UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10074                   CS.getInstruction());
10075
10076     if (!CS.getInstruction()->use_empty())
10077       CS.getInstruction()->
10078         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10079
10080     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10081       // Don't break the CFG, insert a dummy cond branch.
10082       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10083                          ConstantInt::getTrue(*Context), II);
10084     }
10085     return EraseInstFromFunction(*CS.getInstruction());
10086   }
10087
10088   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10089     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10090       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10091         return transformCallThroughTrampoline(CS);
10092
10093   const PointerType *PTy = cast<PointerType>(Callee->getType());
10094   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10095   if (FTy->isVarArg()) {
10096     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10097     // See if we can optimize any arguments passed through the varargs area of
10098     // the call.
10099     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10100            E = CS.arg_end(); I != E; ++I, ++ix) {
10101       CastInst *CI = dyn_cast<CastInst>(*I);
10102       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10103         *I = CI->getOperand(0);
10104         Changed = true;
10105       }
10106     }
10107   }
10108
10109   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10110     // Inline asm calls cannot throw - mark them 'nounwind'.
10111     CS.setDoesNotThrow();
10112     Changed = true;
10113   }
10114
10115   return Changed ? CS.getInstruction() : 0;
10116 }
10117
10118 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10119 // attempt to move the cast to the arguments of the call/invoke.
10120 //
10121 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10122   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10123   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10124   if (CE->getOpcode() != Instruction::BitCast || 
10125       !isa<Function>(CE->getOperand(0)))
10126     return false;
10127   Function *Callee = cast<Function>(CE->getOperand(0));
10128   Instruction *Caller = CS.getInstruction();
10129   const AttrListPtr &CallerPAL = CS.getAttributes();
10130
10131   // Okay, this is a cast from a function to a different type.  Unless doing so
10132   // would cause a type conversion of one of our arguments, change this call to
10133   // be a direct call with arguments casted to the appropriate types.
10134   //
10135   const FunctionType *FT = Callee->getFunctionType();
10136   const Type *OldRetTy = Caller->getType();
10137   const Type *NewRetTy = FT->getReturnType();
10138
10139   if (isa<StructType>(NewRetTy))
10140     return false; // TODO: Handle multiple return values.
10141
10142   // Check to see if we are changing the return type...
10143   if (OldRetTy != NewRetTy) {
10144     if (Callee->isDeclaration() &&
10145         // Conversion is ok if changing from one pointer type to another or from
10146         // a pointer to an integer of the same size.
10147         !((isa<PointerType>(OldRetTy) || !TD ||
10148            OldRetTy == TD->getIntPtrType()) &&
10149           (isa<PointerType>(NewRetTy) || !TD ||
10150            NewRetTy == TD->getIntPtrType())))
10151       return false;   // Cannot transform this return value.
10152
10153     if (!Caller->use_empty() &&
10154         // void -> non-void is handled specially
10155         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10156       return false;   // Cannot transform this return value.
10157
10158     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10159       Attributes RAttrs = CallerPAL.getRetAttributes();
10160       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10161         return false;   // Attribute not compatible with transformed value.
10162     }
10163
10164     // If the callsite is an invoke instruction, and the return value is used by
10165     // a PHI node in a successor, we cannot change the return type of the call
10166     // because there is no place to put the cast instruction (without breaking
10167     // the critical edge).  Bail out in this case.
10168     if (!Caller->use_empty())
10169       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10170         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10171              UI != E; ++UI)
10172           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10173             if (PN->getParent() == II->getNormalDest() ||
10174                 PN->getParent() == II->getUnwindDest())
10175               return false;
10176   }
10177
10178   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10179   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10180
10181   CallSite::arg_iterator AI = CS.arg_begin();
10182   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10183     const Type *ParamTy = FT->getParamType(i);
10184     const Type *ActTy = (*AI)->getType();
10185
10186     if (!CastInst::isCastable(ActTy, ParamTy))
10187       return false;   // Cannot transform this parameter value.
10188
10189     if (CallerPAL.getParamAttributes(i + 1) 
10190         & Attribute::typeIncompatible(ParamTy))
10191       return false;   // Attribute not compatible with transformed value.
10192
10193     // Converting from one pointer type to another or between a pointer and an
10194     // integer of the same size is safe even if we do not have a body.
10195     bool isConvertible = ActTy == ParamTy ||
10196       (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10197               (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10198     if (Callee->isDeclaration() && !isConvertible) return false;
10199   }
10200
10201   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10202       Callee->isDeclaration())
10203     return false;   // Do not delete arguments unless we have a function body.
10204
10205   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206       !CallerPAL.isEmpty())
10207     // In this case we have more arguments than the new function type, but we
10208     // won't be dropping them.  Check that these extra arguments have attributes
10209     // that are compatible with being a vararg call argument.
10210     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10212         break;
10213       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10214       if (PAttrs & Attribute::VarArgsIncompatible)
10215         return false;
10216     }
10217
10218   // Okay, we decided that this is a safe thing to do: go ahead and start
10219   // inserting cast instructions as necessary...
10220   std::vector<Value*> Args;
10221   Args.reserve(NumActualArgs);
10222   SmallVector<AttributeWithIndex, 8> attrVec;
10223   attrVec.reserve(NumCommonArgs);
10224
10225   // Get any return attributes.
10226   Attributes RAttrs = CallerPAL.getRetAttributes();
10227
10228   // If the return value is not being used, the type may not be compatible
10229   // with the existing attributes.  Wipe out any problematic attributes.
10230   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10231
10232   // Add the new return attributes.
10233   if (RAttrs)
10234     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10235
10236   AI = CS.arg_begin();
10237   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238     const Type *ParamTy = FT->getParamType(i);
10239     if ((*AI)->getType() == ParamTy) {
10240       Args.push_back(*AI);
10241     } else {
10242       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10243           false, ParamTy, false);
10244       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10245       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10246     }
10247
10248     // Add any parameter attributes.
10249     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10250       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10251   }
10252
10253   // If the function takes more arguments than the call was taking, add them
10254   // now...
10255   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10256     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10257
10258   // If we are removing arguments to the function, emit an obnoxious warning...
10259   if (FT->getNumParams() < NumActualArgs) {
10260     if (!FT->isVarArg()) {
10261       errs() << "WARNING: While resolving call to function '"
10262              << Callee->getName() << "' arguments were dropped!\n";
10263     } else {
10264       // Add all of the arguments in their promoted form to the arg list...
10265       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10266         const Type *PTy = getPromotedType((*AI)->getType());
10267         if (PTy != (*AI)->getType()) {
10268           // Must promote to pass through va_arg area!
10269           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10270                                                                 PTy, false);
10271           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10272           InsertNewInstBefore(Cast, *Caller);
10273           Args.push_back(Cast);
10274         } else {
10275           Args.push_back(*AI);
10276         }
10277
10278         // Add any parameter attributes.
10279         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10280           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10281       }
10282     }
10283   }
10284
10285   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10286     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10287
10288   if (NewRetTy == Type::VoidTy)
10289     Caller->setName("");   // Void type should not have a name.
10290
10291   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10292                                                      attrVec.end());
10293
10294   Instruction *NC;
10295   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10296     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10297                             Args.begin(), Args.end(),
10298                             Caller->getName(), Caller);
10299     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10300     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10301   } else {
10302     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10303                           Caller->getName(), Caller);
10304     CallInst *CI = cast<CallInst>(Caller);
10305     if (CI->isTailCall())
10306       cast<CallInst>(NC)->setTailCall();
10307     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10308     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10309   }
10310
10311   // Insert a cast of the return type as necessary.
10312   Value *NV = NC;
10313   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10314     if (NV->getType() != Type::VoidTy) {
10315       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10316                                                             OldRetTy, false);
10317       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10318
10319       // If this is an invoke instruction, we should insert it after the first
10320       // non-phi, instruction in the normal successor block.
10321       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10322         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10323         InsertNewInstBefore(NC, *I);
10324       } else {
10325         // Otherwise, it's a call, just insert cast right after the call instr
10326         InsertNewInstBefore(NC, *Caller);
10327       }
10328       AddUsersToWorkList(*Caller);
10329     } else {
10330       NV = UndefValue::get(Caller->getType());
10331     }
10332   }
10333
10334   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10335     Caller->replaceAllUsesWith(NV);
10336   Caller->eraseFromParent();
10337   RemoveFromWorkList(Caller);
10338   return true;
10339 }
10340
10341 // transformCallThroughTrampoline - Turn a call to a function created by the
10342 // init_trampoline intrinsic into a direct call to the underlying function.
10343 //
10344 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10345   Value *Callee = CS.getCalledValue();
10346   const PointerType *PTy = cast<PointerType>(Callee->getType());
10347   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10348   const AttrListPtr &Attrs = CS.getAttributes();
10349
10350   // If the call already has the 'nest' attribute somewhere then give up -
10351   // otherwise 'nest' would occur twice after splicing in the chain.
10352   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10353     return 0;
10354
10355   IntrinsicInst *Tramp =
10356     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10357
10358   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10359   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10360   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10361
10362   const AttrListPtr &NestAttrs = NestF->getAttributes();
10363   if (!NestAttrs.isEmpty()) {
10364     unsigned NestIdx = 1;
10365     const Type *NestTy = 0;
10366     Attributes NestAttr = Attribute::None;
10367
10368     // Look for a parameter marked with the 'nest' attribute.
10369     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10370          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10371       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10372         // Record the parameter type and any other attributes.
10373         NestTy = *I;
10374         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10375         break;
10376       }
10377
10378     if (NestTy) {
10379       Instruction *Caller = CS.getInstruction();
10380       std::vector<Value*> NewArgs;
10381       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10382
10383       SmallVector<AttributeWithIndex, 8> NewAttrs;
10384       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10385
10386       // Insert the nest argument into the call argument list, which may
10387       // mean appending it.  Likewise for attributes.
10388
10389       // Add any result attributes.
10390       if (Attributes Attr = Attrs.getRetAttributes())
10391         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10392
10393       {
10394         unsigned Idx = 1;
10395         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10396         do {
10397           if (Idx == NestIdx) {
10398             // Add the chain argument and attributes.
10399             Value *NestVal = Tramp->getOperand(3);
10400             if (NestVal->getType() != NestTy)
10401               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10402             NewArgs.push_back(NestVal);
10403             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10404           }
10405
10406           if (I == E)
10407             break;
10408
10409           // Add the original argument and attributes.
10410           NewArgs.push_back(*I);
10411           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10412             NewAttrs.push_back
10413               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10414
10415           ++Idx, ++I;
10416         } while (1);
10417       }
10418
10419       // Add any function attributes.
10420       if (Attributes Attr = Attrs.getFnAttributes())
10421         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10422
10423       // The trampoline may have been bitcast to a bogus type (FTy).
10424       // Handle this by synthesizing a new function type, equal to FTy
10425       // with the chain parameter inserted.
10426
10427       std::vector<const Type*> NewTypes;
10428       NewTypes.reserve(FTy->getNumParams()+1);
10429
10430       // Insert the chain's type into the list of parameter types, which may
10431       // mean appending it.
10432       {
10433         unsigned Idx = 1;
10434         FunctionType::param_iterator I = FTy->param_begin(),
10435           E = FTy->param_end();
10436
10437         do {
10438           if (Idx == NestIdx)
10439             // Add the chain's type.
10440             NewTypes.push_back(NestTy);
10441
10442           if (I == E)
10443             break;
10444
10445           // Add the original type.
10446           NewTypes.push_back(*I);
10447
10448           ++Idx, ++I;
10449         } while (1);
10450       }
10451
10452       // Replace the trampoline call with a direct call.  Let the generic
10453       // code sort out any function type mismatches.
10454       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10455                                                 FTy->isVarArg());
10456       Constant *NewCallee =
10457         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10458         NestF : ConstantExpr::getBitCast(NestF, 
10459                                          PointerType::getUnqual(NewFTy));
10460       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10461                                                    NewAttrs.end());
10462
10463       Instruction *NewCaller;
10464       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10465         NewCaller = InvokeInst::Create(NewCallee,
10466                                        II->getNormalDest(), II->getUnwindDest(),
10467                                        NewArgs.begin(), NewArgs.end(),
10468                                        Caller->getName(), Caller);
10469         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10470         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10471       } else {
10472         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10473                                      Caller->getName(), Caller);
10474         if (cast<CallInst>(Caller)->isTailCall())
10475           cast<CallInst>(NewCaller)->setTailCall();
10476         cast<CallInst>(NewCaller)->
10477           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10478         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10479       }
10480       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10481         Caller->replaceAllUsesWith(NewCaller);
10482       Caller->eraseFromParent();
10483       RemoveFromWorkList(Caller);
10484       return 0;
10485     }
10486   }
10487
10488   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10489   // parameter, there is no need to adjust the argument list.  Let the generic
10490   // code sort out any function type mismatches.
10491   Constant *NewCallee =
10492     NestF->getType() == PTy ? NestF : 
10493                               ConstantExpr::getBitCast(NestF, PTy);
10494   CS.setCalledFunction(NewCallee);
10495   return CS.getInstruction();
10496 }
10497
10498 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10499 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10500 /// and a single binop.
10501 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10502   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10503   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10504   unsigned Opc = FirstInst->getOpcode();
10505   Value *LHSVal = FirstInst->getOperand(0);
10506   Value *RHSVal = FirstInst->getOperand(1);
10507     
10508   const Type *LHSType = LHSVal->getType();
10509   const Type *RHSType = RHSVal->getType();
10510   
10511   // Scan to see if all operands are the same opcode, all have one use, and all
10512   // kill their operands (i.e. the operands have one use).
10513   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10514     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10515     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10516         // Verify type of the LHS matches so we don't fold cmp's of different
10517         // types or GEP's with different index types.
10518         I->getOperand(0)->getType() != LHSType ||
10519         I->getOperand(1)->getType() != RHSType)
10520       return 0;
10521
10522     // If they are CmpInst instructions, check their predicates
10523     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10524       if (cast<CmpInst>(I)->getPredicate() !=
10525           cast<CmpInst>(FirstInst)->getPredicate())
10526         return 0;
10527     
10528     // Keep track of which operand needs a phi node.
10529     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10530     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10531   }
10532   
10533   // Otherwise, this is safe to transform!
10534   
10535   Value *InLHS = FirstInst->getOperand(0);
10536   Value *InRHS = FirstInst->getOperand(1);
10537   PHINode *NewLHS = 0, *NewRHS = 0;
10538   if (LHSVal == 0) {
10539     NewLHS = PHINode::Create(LHSType,
10540                              FirstInst->getOperand(0)->getName() + ".pn");
10541     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10542     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10543     InsertNewInstBefore(NewLHS, PN);
10544     LHSVal = NewLHS;
10545   }
10546   
10547   if (RHSVal == 0) {
10548     NewRHS = PHINode::Create(RHSType,
10549                              FirstInst->getOperand(1)->getName() + ".pn");
10550     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10551     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10552     InsertNewInstBefore(NewRHS, PN);
10553     RHSVal = NewRHS;
10554   }
10555   
10556   // Add all operands to the new PHIs.
10557   if (NewLHS || NewRHS) {
10558     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10559       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10560       if (NewLHS) {
10561         Value *NewInLHS = InInst->getOperand(0);
10562         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10563       }
10564       if (NewRHS) {
10565         Value *NewInRHS = InInst->getOperand(1);
10566         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10567       }
10568     }
10569   }
10570     
10571   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10572     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10573   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10574   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10575                          LHSVal, RHSVal);
10576 }
10577
10578 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10579   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10580   
10581   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10582                                         FirstInst->op_end());
10583   // This is true if all GEP bases are allocas and if all indices into them are
10584   // constants.
10585   bool AllBasePointersAreAllocas = true;
10586   
10587   // Scan to see if all operands are the same opcode, all have one use, and all
10588   // kill their operands (i.e. the operands have one use).
10589   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10590     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10592       GEP->getNumOperands() != FirstInst->getNumOperands())
10593       return 0;
10594
10595     // Keep track of whether or not all GEPs are of alloca pointers.
10596     if (AllBasePointersAreAllocas &&
10597         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10598          !GEP->hasAllConstantIndices()))
10599       AllBasePointersAreAllocas = false;
10600     
10601     // Compare the operand lists.
10602     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10603       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10604         continue;
10605       
10606       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10607       // if one of the PHIs has a constant for the index.  The index may be
10608       // substantially cheaper to compute for the constants, so making it a
10609       // variable index could pessimize the path.  This also handles the case
10610       // for struct indices, which must always be constant.
10611       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10612           isa<ConstantInt>(GEP->getOperand(op)))
10613         return 0;
10614       
10615       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10616         return 0;
10617       FixedOperands[op] = 0;  // Needs a PHI.
10618     }
10619   }
10620   
10621   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10622   // bother doing this transformation.  At best, this will just save a bit of
10623   // offset calculation, but all the predecessors will have to materialize the
10624   // stack address into a register anyway.  We'd actually rather *clone* the
10625   // load up into the predecessors so that we have a load of a gep of an alloca,
10626   // which can usually all be folded into the load.
10627   if (AllBasePointersAreAllocas)
10628     return 0;
10629   
10630   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10631   // that is variable.
10632   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10633   
10634   bool HasAnyPHIs = false;
10635   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10636     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10637     Value *FirstOp = FirstInst->getOperand(i);
10638     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10639                                      FirstOp->getName()+".pn");
10640     InsertNewInstBefore(NewPN, PN);
10641     
10642     NewPN->reserveOperandSpace(e);
10643     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10644     OperandPhis[i] = NewPN;
10645     FixedOperands[i] = NewPN;
10646     HasAnyPHIs = true;
10647   }
10648
10649   
10650   // Add all operands to the new PHIs.
10651   if (HasAnyPHIs) {
10652     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10653       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10654       BasicBlock *InBB = PN.getIncomingBlock(i);
10655       
10656       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10657         if (PHINode *OpPhi = OperandPhis[op])
10658           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10659     }
10660   }
10661   
10662   Value *Base = FixedOperands[0];
10663   GetElementPtrInst *GEP =
10664     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10665                               FixedOperands.end());
10666   if (cast<GEPOperator>(FirstInst)->isInBounds())
10667     cast<GEPOperator>(GEP)->setIsInBounds(true);
10668   return GEP;
10669 }
10670
10671
10672 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10673 /// sink the load out of the block that defines it.  This means that it must be
10674 /// obvious the value of the load is not changed from the point of the load to
10675 /// the end of the block it is in.
10676 ///
10677 /// Finally, it is safe, but not profitable, to sink a load targetting a
10678 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10679 /// to a register.
10680 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10681   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10682   
10683   for (++BBI; BBI != E; ++BBI)
10684     if (BBI->mayWriteToMemory())
10685       return false;
10686   
10687   // Check for non-address taken alloca.  If not address-taken already, it isn't
10688   // profitable to do this xform.
10689   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10690     bool isAddressTaken = false;
10691     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10692          UI != E; ++UI) {
10693       if (isa<LoadInst>(UI)) continue;
10694       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10695         // If storing TO the alloca, then the address isn't taken.
10696         if (SI->getOperand(1) == AI) continue;
10697       }
10698       isAddressTaken = true;
10699       break;
10700     }
10701     
10702     if (!isAddressTaken && AI->isStaticAlloca())
10703       return false;
10704   }
10705   
10706   // If this load is a load from a GEP with a constant offset from an alloca,
10707   // then we don't want to sink it.  In its present form, it will be
10708   // load [constant stack offset].  Sinking it will cause us to have to
10709   // materialize the stack addresses in each predecessor in a register only to
10710   // do a shared load from register in the successor.
10711   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10712     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10713       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10714         return false;
10715   
10716   return true;
10717 }
10718
10719
10720 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10721 // operator and they all are only used by the PHI, PHI together their
10722 // inputs, and do the operation once, to the result of the PHI.
10723 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10724   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10725
10726   // Scan the instruction, looking for input operations that can be folded away.
10727   // If all input operands to the phi are the same instruction (e.g. a cast from
10728   // the same type or "+42") we can pull the operation through the PHI, reducing
10729   // code size and simplifying code.
10730   Constant *ConstantOp = 0;
10731   const Type *CastSrcTy = 0;
10732   bool isVolatile = false;
10733   if (isa<CastInst>(FirstInst)) {
10734     CastSrcTy = FirstInst->getOperand(0)->getType();
10735   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10736     // Can fold binop, compare or shift here if the RHS is a constant, 
10737     // otherwise call FoldPHIArgBinOpIntoPHI.
10738     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10739     if (ConstantOp == 0)
10740       return FoldPHIArgBinOpIntoPHI(PN);
10741   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10742     isVolatile = LI->isVolatile();
10743     // We can't sink the load if the loaded value could be modified between the
10744     // load and the PHI.
10745     if (LI->getParent() != PN.getIncomingBlock(0) ||
10746         !isSafeAndProfitableToSinkLoad(LI))
10747       return 0;
10748     
10749     // If the PHI is of volatile loads and the load block has multiple
10750     // successors, sinking it would remove a load of the volatile value from
10751     // the path through the other successor.
10752     if (isVolatile &&
10753         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10754       return 0;
10755     
10756   } else if (isa<GetElementPtrInst>(FirstInst)) {
10757     return FoldPHIArgGEPIntoPHI(PN);
10758   } else {
10759     return 0;  // Cannot fold this operation.
10760   }
10761
10762   // Check to see if all arguments are the same operation.
10763   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10764     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10765     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10766     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10767       return 0;
10768     if (CastSrcTy) {
10769       if (I->getOperand(0)->getType() != CastSrcTy)
10770         return 0;  // Cast operation must match.
10771     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10772       // We can't sink the load if the loaded value could be modified between 
10773       // the load and the PHI.
10774       if (LI->isVolatile() != isVolatile ||
10775           LI->getParent() != PN.getIncomingBlock(i) ||
10776           !isSafeAndProfitableToSinkLoad(LI))
10777         return 0;
10778       
10779       // If the PHI is of volatile loads and the load block has multiple
10780       // successors, sinking it would remove a load of the volatile value from
10781       // the path through the other successor.
10782       if (isVolatile &&
10783           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784         return 0;
10785       
10786     } else if (I->getOperand(1) != ConstantOp) {
10787       return 0;
10788     }
10789   }
10790
10791   // Okay, they are all the same operation.  Create a new PHI node of the
10792   // correct type, and PHI together all of the LHS's of the instructions.
10793   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10794                                    PN.getName()+".in");
10795   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10796
10797   Value *InVal = FirstInst->getOperand(0);
10798   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10799
10800   // Add all operands to the new PHI.
10801   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10802     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10803     if (NewInVal != InVal)
10804       InVal = 0;
10805     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10806   }
10807
10808   Value *PhiVal;
10809   if (InVal) {
10810     // The new PHI unions all of the same values together.  This is really
10811     // common, so we handle it intelligently here for compile-time speed.
10812     PhiVal = InVal;
10813     delete NewPN;
10814   } else {
10815     InsertNewInstBefore(NewPN, PN);
10816     PhiVal = NewPN;
10817   }
10818
10819   // Insert and return the new operation.
10820   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10821     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10822   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10823     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10824   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10825     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10826                            PhiVal, ConstantOp);
10827   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10828   
10829   // If this was a volatile load that we are merging, make sure to loop through
10830   // and mark all the input loads as non-volatile.  If we don't do this, we will
10831   // insert a new volatile load and the old ones will not be deletable.
10832   if (isVolatile)
10833     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10834       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10835   
10836   return new LoadInst(PhiVal, "", isVolatile);
10837 }
10838
10839 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10840 /// that is dead.
10841 static bool DeadPHICycle(PHINode *PN,
10842                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10843   if (PN->use_empty()) return true;
10844   if (!PN->hasOneUse()) return false;
10845
10846   // Remember this node, and if we find the cycle, return.
10847   if (!PotentiallyDeadPHIs.insert(PN))
10848     return true;
10849   
10850   // Don't scan crazily complex things.
10851   if (PotentiallyDeadPHIs.size() == 16)
10852     return false;
10853
10854   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10855     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10856
10857   return false;
10858 }
10859
10860 /// PHIsEqualValue - Return true if this phi node is always equal to
10861 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10862 ///   z = some value; x = phi (y, z); y = phi (x, z)
10863 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10864                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10865   // See if we already saw this PHI node.
10866   if (!ValueEqualPHIs.insert(PN))
10867     return true;
10868   
10869   // Don't scan crazily complex things.
10870   if (ValueEqualPHIs.size() == 16)
10871     return false;
10872  
10873   // Scan the operands to see if they are either phi nodes or are equal to
10874   // the value.
10875   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10876     Value *Op = PN->getIncomingValue(i);
10877     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10878       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10879         return false;
10880     } else if (Op != NonPhiInVal)
10881       return false;
10882   }
10883   
10884   return true;
10885 }
10886
10887
10888 // PHINode simplification
10889 //
10890 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10891   // If LCSSA is around, don't mess with Phi nodes
10892   if (MustPreserveLCSSA) return 0;
10893   
10894   if (Value *V = PN.hasConstantValue())
10895     return ReplaceInstUsesWith(PN, V);
10896
10897   // If all PHI operands are the same operation, pull them through the PHI,
10898   // reducing code size.
10899   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10900       isa<Instruction>(PN.getIncomingValue(1)) &&
10901       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10902       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10903       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10904       // than themselves more than once.
10905       PN.getIncomingValue(0)->hasOneUse())
10906     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10907       return Result;
10908
10909   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10910   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10911   // PHI)... break the cycle.
10912   if (PN.hasOneUse()) {
10913     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10914     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10915       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10916       PotentiallyDeadPHIs.insert(&PN);
10917       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10918         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10919     }
10920    
10921     // If this phi has a single use, and if that use just computes a value for
10922     // the next iteration of a loop, delete the phi.  This occurs with unused
10923     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10924     // common case here is good because the only other things that catch this
10925     // are induction variable analysis (sometimes) and ADCE, which is only run
10926     // late.
10927     if (PHIUser->hasOneUse() &&
10928         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10929         PHIUser->use_back() == &PN) {
10930       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10931     }
10932   }
10933
10934   // We sometimes end up with phi cycles that non-obviously end up being the
10935   // same value, for example:
10936   //   z = some value; x = phi (y, z); y = phi (x, z)
10937   // where the phi nodes don't necessarily need to be in the same block.  Do a
10938   // quick check to see if the PHI node only contains a single non-phi value, if
10939   // so, scan to see if the phi cycle is actually equal to that value.
10940   {
10941     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10942     // Scan for the first non-phi operand.
10943     while (InValNo != NumOperandVals && 
10944            isa<PHINode>(PN.getIncomingValue(InValNo)))
10945       ++InValNo;
10946
10947     if (InValNo != NumOperandVals) {
10948       Value *NonPhiInVal = PN.getOperand(InValNo);
10949       
10950       // Scan the rest of the operands to see if there are any conflicts, if so
10951       // there is no need to recursively scan other phis.
10952       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10953         Value *OpVal = PN.getIncomingValue(InValNo);
10954         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10955           break;
10956       }
10957       
10958       // If we scanned over all operands, then we have one unique value plus
10959       // phi values.  Scan PHI nodes to see if they all merge in each other or
10960       // the value.
10961       if (InValNo == NumOperandVals) {
10962         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10963         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10964           return ReplaceInstUsesWith(PN, NonPhiInVal);
10965       }
10966     }
10967   }
10968   return 0;
10969 }
10970
10971 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10972                                    Instruction *InsertPoint,
10973                                    InstCombiner *IC) {
10974   unsigned PtrSize = DTy->getScalarSizeInBits();
10975   unsigned VTySize = V->getType()->getScalarSizeInBits();
10976   // We must cast correctly to the pointer type. Ensure that we
10977   // sign extend the integer value if it is smaller as this is
10978   // used for address computation.
10979   Instruction::CastOps opcode = 
10980      (VTySize < PtrSize ? Instruction::SExt :
10981       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10982   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10983 }
10984
10985
10986 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10987   Value *PtrOp = GEP.getOperand(0);
10988   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10989   // If so, eliminate the noop.
10990   if (GEP.getNumOperands() == 1)
10991     return ReplaceInstUsesWith(GEP, PtrOp);
10992
10993   if (isa<UndefValue>(GEP.getOperand(0)))
10994     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10995
10996   bool HasZeroPointerIndex = false;
10997   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10998     HasZeroPointerIndex = C->isNullValue();
10999
11000   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11001     return ReplaceInstUsesWith(GEP, PtrOp);
11002
11003   // Eliminate unneeded casts for indices.
11004   bool MadeChange = false;
11005   
11006   gep_type_iterator GTI = gep_type_begin(GEP);
11007   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11008        i != e; ++i, ++GTI) {
11009     if (TD && isa<SequentialType>(*GTI)) {
11010       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11011         if (CI->getOpcode() == Instruction::ZExt ||
11012             CI->getOpcode() == Instruction::SExt) {
11013           const Type *SrcTy = CI->getOperand(0)->getType();
11014           // We can eliminate a cast from i32 to i64 iff the target 
11015           // is a 32-bit pointer target.
11016           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11017             MadeChange = true;
11018             *i = CI->getOperand(0);
11019           }
11020         }
11021       }
11022       // If we are using a wider index than needed for this platform, shrink it
11023       // to what we need.  If narrower, sign-extend it to what we need.
11024       // If the incoming value needs a cast instruction,
11025       // insert it.  This explicit cast can make subsequent optimizations more
11026       // obvious.
11027       Value *Op = *i;
11028       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11029         if (Constant *C = dyn_cast<Constant>(Op)) {
11030           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
11031           MadeChange = true;
11032         } else {
11033           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11034                                 GEP);
11035           *i = Op;
11036           MadeChange = true;
11037         }
11038       } else if (TD->getTypeSizeInBits(Op->getType()) 
11039                   < TD->getPointerSizeInBits()) {
11040         if (Constant *C = dyn_cast<Constant>(Op)) {
11041           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
11042           MadeChange = true;
11043         } else {
11044           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11045                                 GEP);
11046           *i = Op;
11047           MadeChange = true;
11048         }
11049       }
11050     }
11051   }
11052   if (MadeChange) return &GEP;
11053
11054   // Combine Indices - If the source pointer to this getelementptr instruction
11055   // is a getelementptr instruction, combine the indices of the two
11056   // getelementptr instructions into a single instruction.
11057   //
11058   SmallVector<Value*, 8> SrcGEPOperands;
11059   bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11060   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11061     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11062     if (!Src->isInBounds())
11063       BothInBounds = false;
11064   }
11065
11066   if (!SrcGEPOperands.empty()) {
11067     // Note that if our source is a gep chain itself that we wait for that
11068     // chain to be resolved before we perform this transformation.  This
11069     // avoids us creating a TON of code in some cases.
11070     //
11071     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11072         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11073       return 0;   // Wait until our source is folded to completion.
11074
11075     SmallVector<Value*, 8> Indices;
11076
11077     // Find out whether the last index in the source GEP is a sequential idx.
11078     bool EndsWithSequential = false;
11079     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11080            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11081       EndsWithSequential = !isa<StructType>(*I);
11082
11083     // Can we combine the two pointer arithmetics offsets?
11084     if (EndsWithSequential) {
11085       // Replace: gep (gep %P, long B), long A, ...
11086       // With:    T = long A+B; gep %P, T, ...
11087       //
11088       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11089       if (SO1 == Constant::getNullValue(SO1->getType())) {
11090         Sum = GO1;
11091       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11092         Sum = SO1;
11093       } else {
11094         // If they aren't the same type, convert both to an integer of the
11095         // target's pointer size.
11096         if (SO1->getType() != GO1->getType()) {
11097           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11098             SO1 =
11099                 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11100           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11101             GO1 =
11102                 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11103           } else if (TD) {
11104             unsigned PS = TD->getPointerSizeInBits();
11105             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11106               // Convert GO1 to SO1's type.
11107               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11108
11109             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11110               // Convert SO1 to GO1's type.
11111               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11112             } else {
11113               const Type *PT = TD->getIntPtrType();
11114               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11115               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11116             }
11117           }
11118         }
11119         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11120           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), 
11121                                             cast<Constant>(GO1));
11122         else {
11123           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11124           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11125         }
11126       }
11127
11128       // Recycle the GEP we already have if possible.
11129       if (SrcGEPOperands.size() == 2) {
11130         GEP.setOperand(0, SrcGEPOperands[0]);
11131         GEP.setOperand(1, Sum);
11132         return &GEP;
11133       } else {
11134         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11135                        SrcGEPOperands.end()-1);
11136         Indices.push_back(Sum);
11137         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11138       }
11139     } else if (isa<Constant>(*GEP.idx_begin()) &&
11140                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11141                SrcGEPOperands.size() != 1) {
11142       // Otherwise we can do the fold if the first index of the GEP is a zero
11143       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11144                      SrcGEPOperands.end());
11145       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11146     }
11147
11148     if (!Indices.empty()) {
11149       GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11150                                                             Indices.begin(),
11151                                                             Indices.end(),
11152                                                             GEP.getName());
11153       if (BothInBounds)
11154         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11155       return NewGEP;
11156     }
11157
11158   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11159     // GEP of global variable.  If all of the indices for this GEP are
11160     // constants, we can promote this to a constexpr instead of an instruction.
11161
11162     // Scan for nonconstants...
11163     SmallVector<Constant*, 8> Indices;
11164     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11165     for (; I != E && isa<Constant>(*I); ++I)
11166       Indices.push_back(cast<Constant>(*I));
11167
11168     if (I == E) {  // If they are all constants...
11169       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11170                                                     &Indices[0],Indices.size());
11171
11172       // Replace all uses of the GEP with the new constexpr...
11173       return ReplaceInstUsesWith(GEP, CE);
11174     }
11175   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11176     if (!isa<PointerType>(X->getType())) {
11177       // Not interesting.  Source pointer must be a cast from pointer.
11178     } else if (HasZeroPointerIndex) {
11179       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11180       // into     : GEP [10 x i8]* X, i32 0, ...
11181       //
11182       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11183       //           into     : GEP i8* X, ...
11184       // 
11185       // This occurs when the program declares an array extern like "int X[];"
11186       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11187       const PointerType *XTy = cast<PointerType>(X->getType());
11188       if (const ArrayType *CATy =
11189           dyn_cast<ArrayType>(CPTy->getElementType())) {
11190         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11191         if (CATy->getElementType() == XTy->getElementType()) {
11192           // -> GEP i8* X, ...
11193           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11194           GetElementPtrInst *NewGEP =
11195             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11196                                       GEP.getName());
11197           if (cast<GEPOperator>(&GEP)->isInBounds())
11198             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11199           return NewGEP;
11200         } else if (const ArrayType *XATy =
11201                  dyn_cast<ArrayType>(XTy->getElementType())) {
11202           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11203           if (CATy->getElementType() == XATy->getElementType()) {
11204             // -> GEP [10 x i8]* X, i32 0, ...
11205             // At this point, we know that the cast source type is a pointer
11206             // to an array of the same type as the destination pointer
11207             // array.  Because the array type is never stepped over (there
11208             // is a leading zero) we can fold the cast into this GEP.
11209             GEP.setOperand(0, X);
11210             return &GEP;
11211           }
11212         }
11213       }
11214     } else if (GEP.getNumOperands() == 2) {
11215       // Transform things like:
11216       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11217       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11218       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11219       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11220       if (TD && isa<ArrayType>(SrcElTy) &&
11221           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11222           TD->getTypeAllocSize(ResElTy)) {
11223         Value *Idx[2];
11224         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11225         Idx[1] = GEP.getOperand(1);
11226         GetElementPtrInst *NewGEP =
11227           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11228         if (cast<GEPOperator>(&GEP)->isInBounds())
11229           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11230         Value *V = InsertNewInstBefore(NewGEP, GEP);
11231         // V and GEP are both pointer types --> BitCast
11232         return new BitCastInst(V, GEP.getType());
11233       }
11234       
11235       // Transform things like:
11236       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11237       //   (where tmp = 8*tmp2) into:
11238       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11239       
11240       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11241         uint64_t ArrayEltSize =
11242             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11243         
11244         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11245         // allow either a mul, shift, or constant here.
11246         Value *NewIdx = 0;
11247         ConstantInt *Scale = 0;
11248         if (ArrayEltSize == 1) {
11249           NewIdx = GEP.getOperand(1);
11250           Scale = 
11251                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11252         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11253           NewIdx = ConstantInt::get(CI->getType(), 1);
11254           Scale = CI;
11255         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11256           if (Inst->getOpcode() == Instruction::Shl &&
11257               isa<ConstantInt>(Inst->getOperand(1))) {
11258             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11259             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11260             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11261                                      1ULL << ShAmtVal);
11262             NewIdx = Inst->getOperand(0);
11263           } else if (Inst->getOpcode() == Instruction::Mul &&
11264                      isa<ConstantInt>(Inst->getOperand(1))) {
11265             Scale = cast<ConstantInt>(Inst->getOperand(1));
11266             NewIdx = Inst->getOperand(0);
11267           }
11268         }
11269         
11270         // If the index will be to exactly the right offset with the scale taken
11271         // out, perform the transformation. Note, we don't know whether Scale is
11272         // signed or not. We'll use unsigned version of division/modulo
11273         // operation after making sure Scale doesn't have the sign bit set.
11274         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11275             Scale->getZExtValue() % ArrayEltSize == 0) {
11276           Scale = ConstantInt::get(Scale->getType(),
11277                                    Scale->getZExtValue() / ArrayEltSize);
11278           if (Scale->getZExtValue() != 1) {
11279             Constant *C =
11280                    ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11281                                                        false /*ZExt*/);
11282             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11283             NewIdx = InsertNewInstBefore(Sc, GEP);
11284           }
11285
11286           // Insert the new GEP instruction.
11287           Value *Idx[2];
11288           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11289           Idx[1] = NewIdx;
11290           Instruction *NewGEP =
11291             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11292           if (cast<GEPOperator>(&GEP)->isInBounds())
11293             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11294           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11295           // The NewGEP must be pointer typed, so must the old one -> BitCast
11296           return new BitCastInst(NewGEP, GEP.getType());
11297         }
11298       }
11299     }
11300   }
11301   
11302   /// See if we can simplify:
11303   ///   X = bitcast A to B*
11304   ///   Y = gep X, <...constant indices...>
11305   /// into a gep of the original struct.  This is important for SROA and alias
11306   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11307   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11308     if (TD &&
11309         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11310       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11311       // a constant back from EmitGEPOffset.
11312       ConstantInt *OffsetV =
11313                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11314       int64_t Offset = OffsetV->getSExtValue();
11315       
11316       // If this GEP instruction doesn't move the pointer, just replace the GEP
11317       // with a bitcast of the real input to the dest type.
11318       if (Offset == 0) {
11319         // If the bitcast is of an allocation, and the allocation will be
11320         // converted to match the type of the cast, don't touch this.
11321         if (isa<AllocationInst>(BCI->getOperand(0))) {
11322           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11323           if (Instruction *I = visitBitCast(*BCI)) {
11324             if (I != BCI) {
11325               I->takeName(BCI);
11326               BCI->getParent()->getInstList().insert(BCI, I);
11327               ReplaceInstUsesWith(*BCI, I);
11328             }
11329             return &GEP;
11330           }
11331         }
11332         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11333       }
11334       
11335       // Otherwise, if the offset is non-zero, we need to find out if there is a
11336       // field at Offset in 'A's type.  If so, we can pull the cast through the
11337       // GEP.
11338       SmallVector<Value*, 8> NewIndices;
11339       const Type *InTy =
11340         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11341       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11342         Instruction *NGEP =
11343            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11344                                      NewIndices.end());
11345         if (NGEP->getType() == GEP.getType()) return NGEP;
11346         if (cast<GEPOperator>(&GEP)->isInBounds())
11347           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11348         InsertNewInstBefore(NGEP, GEP);
11349         NGEP->takeName(&GEP);
11350         return new BitCastInst(NGEP, GEP.getType());
11351       }
11352     }
11353   }    
11354     
11355   return 0;
11356 }
11357
11358 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11359   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11360   if (AI.isArrayAllocation()) {  // Check C != 1
11361     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11362       const Type *NewTy = 
11363         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11364       AllocationInst *New = 0;
11365
11366       // Create and insert the replacement instruction...
11367       if (isa<MallocInst>(AI))
11368         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11369       else {
11370         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11371         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11372       }
11373
11374       InsertNewInstBefore(New, AI);
11375
11376       // Scan to the end of the allocation instructions, to skip over a block of
11377       // allocas if possible...also skip interleaved debug info
11378       //
11379       BasicBlock::iterator It = New;
11380       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11381
11382       // Now that I is pointing to the first non-allocation-inst in the block,
11383       // insert our getelementptr instruction...
11384       //
11385       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11386       Value *Idx[2];
11387       Idx[0] = NullIdx;
11388       Idx[1] = NullIdx;
11389       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11390                                            New->getName()+".sub", It);
11391       cast<GEPOperator>(V)->setIsInBounds(true);
11392
11393       // Now make everything use the getelementptr instead of the original
11394       // allocation.
11395       return ReplaceInstUsesWith(AI, V);
11396     } else if (isa<UndefValue>(AI.getArraySize())) {
11397       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11398     }
11399   }
11400
11401   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11402     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11403     // Note that we only do this for alloca's, because malloc should allocate
11404     // and return a unique pointer, even for a zero byte allocation.
11405     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11406       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11407
11408     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11409     if (AI.getAlignment() == 0)
11410       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11411   }
11412
11413   return 0;
11414 }
11415
11416 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11417   Value *Op = FI.getOperand(0);
11418
11419   // free undef -> unreachable.
11420   if (isa<UndefValue>(Op)) {
11421     // Insert a new store to null because we cannot modify the CFG here.
11422     new StoreInst(ConstantInt::getTrue(*Context),
11423            UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11424     return EraseInstFromFunction(FI);
11425   }
11426   
11427   // If we have 'free null' delete the instruction.  This can happen in stl code
11428   // when lots of inlining happens.
11429   if (isa<ConstantPointerNull>(Op))
11430     return EraseInstFromFunction(FI);
11431   
11432   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11433   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11434     FI.setOperand(0, CI->getOperand(0));
11435     return &FI;
11436   }
11437   
11438   // Change free (gep X, 0,0,0,0) into free(X)
11439   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11440     if (GEPI->hasAllZeroIndices()) {
11441       AddToWorkList(GEPI);
11442       FI.setOperand(0, GEPI->getOperand(0));
11443       return &FI;
11444     }
11445   }
11446   
11447   // Change free(malloc) into nothing, if the malloc has a single use.
11448   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11449     if (MI->hasOneUse()) {
11450       EraseInstFromFunction(FI);
11451       return EraseInstFromFunction(*MI);
11452     }
11453
11454   return 0;
11455 }
11456
11457
11458 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11459 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11460                                         const TargetData *TD) {
11461   User *CI = cast<User>(LI.getOperand(0));
11462   Value *CastOp = CI->getOperand(0);
11463   LLVMContext *Context = IC.getContext();
11464
11465   if (TD) {
11466     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11467       // Instead of loading constant c string, use corresponding integer value
11468       // directly if string length is small enough.
11469       std::string Str;
11470       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11471         unsigned len = Str.length();
11472         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11473         unsigned numBits = Ty->getPrimitiveSizeInBits();
11474         // Replace LI with immediate integer store.
11475         if ((numBits >> 3) == len + 1) {
11476           APInt StrVal(numBits, 0);
11477           APInt SingleChar(numBits, 0);
11478           if (TD->isLittleEndian()) {
11479             for (signed i = len-1; i >= 0; i--) {
11480               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11481               StrVal = (StrVal << 8) | SingleChar;
11482             }
11483           } else {
11484             for (unsigned i = 0; i < len; i++) {
11485               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11486               StrVal = (StrVal << 8) | SingleChar;
11487             }
11488             // Append NULL at the end.
11489             SingleChar = 0;
11490             StrVal = (StrVal << 8) | SingleChar;
11491           }
11492           Value *NL = ConstantInt::get(*Context, StrVal);
11493           return IC.ReplaceInstUsesWith(LI, NL);
11494         }
11495       }
11496     }
11497   }
11498
11499   const PointerType *DestTy = cast<PointerType>(CI->getType());
11500   const Type *DestPTy = DestTy->getElementType();
11501   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11502
11503     // If the address spaces don't match, don't eliminate the cast.
11504     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11505       return 0;
11506
11507     const Type *SrcPTy = SrcTy->getElementType();
11508
11509     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11510          isa<VectorType>(DestPTy)) {
11511       // If the source is an array, the code below will not succeed.  Check to
11512       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11513       // constants.
11514       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11515         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11516           if (ASrcTy->getNumElements() != 0) {
11517             Value *Idxs[2];
11518             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11519             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11520             SrcTy = cast<PointerType>(CastOp->getType());
11521             SrcPTy = SrcTy->getElementType();
11522           }
11523
11524       if (IC.getTargetData() &&
11525           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11526             isa<VectorType>(SrcPTy)) &&
11527           // Do not allow turning this into a load of an integer, which is then
11528           // casted to a pointer, this pessimizes pointer analysis a lot.
11529           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11530           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11531                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11532
11533         // Okay, we are casting from one integer or pointer type to another of
11534         // the same size.  Instead of casting the pointer before the load, cast
11535         // the result of the loaded value.
11536         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11537                                                              CI->getName(),
11538                                                          LI.isVolatile()),LI);
11539         // Now cast the result of the load.
11540         return new BitCastInst(NewLoad, LI.getType());
11541       }
11542     }
11543   }
11544   return 0;
11545 }
11546
11547 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11548   Value *Op = LI.getOperand(0);
11549
11550   // Attempt to improve the alignment.
11551   if (TD) {
11552     unsigned KnownAlign =
11553       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11554     if (KnownAlign >
11555         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11556                                   LI.getAlignment()))
11557       LI.setAlignment(KnownAlign);
11558   }
11559
11560   // load (cast X) --> cast (load X) iff safe
11561   if (isa<CastInst>(Op))
11562     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11563       return Res;
11564
11565   // None of the following transforms are legal for volatile loads.
11566   if (LI.isVolatile()) return 0;
11567   
11568   // Do really simple store-to-load forwarding and load CSE, to catch cases
11569   // where there are several consequtive memory accesses to the same location,
11570   // separated by a few arithmetic operations.
11571   BasicBlock::iterator BBI = &LI;
11572   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11573     return ReplaceInstUsesWith(LI, AvailableVal);
11574
11575   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11576     const Value *GEPI0 = GEPI->getOperand(0);
11577     // TODO: Consider a target hook for valid address spaces for this xform.
11578     if (isa<ConstantPointerNull>(GEPI0) &&
11579         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11580       // Insert a new store to null instruction before the load to indicate
11581       // that this code is not reachable.  We do this instead of inserting
11582       // an unreachable instruction directly because we cannot modify the
11583       // CFG.
11584       new StoreInst(UndefValue::get(LI.getType()),
11585                     Constant::getNullValue(Op->getType()), &LI);
11586       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11587     }
11588   } 
11589
11590   if (Constant *C = dyn_cast<Constant>(Op)) {
11591     // load null/undef -> undef
11592     // TODO: Consider a target hook for valid address spaces for this xform.
11593     if (isa<UndefValue>(C) || (C->isNullValue() && 
11594         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11595       // Insert a new store to null instruction before the load to indicate that
11596       // this code is not reachable.  We do this instead of inserting an
11597       // unreachable instruction directly because we cannot modify the CFG.
11598       new StoreInst(UndefValue::get(LI.getType()),
11599                     Constant::getNullValue(Op->getType()), &LI);
11600       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11601     }
11602
11603     // Instcombine load (constant global) into the value loaded.
11604     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11605       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11606         return ReplaceInstUsesWith(LI, GV->getInitializer());
11607
11608     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11609     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11610       if (CE->getOpcode() == Instruction::GetElementPtr) {
11611         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11612           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11613             if (Constant *V = 
11614                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11615                                                       *Context))
11616               return ReplaceInstUsesWith(LI, V);
11617         if (CE->getOperand(0)->isNullValue()) {
11618           // Insert a new store to null instruction before the load to indicate
11619           // that this code is not reachable.  We do this instead of inserting
11620           // an unreachable instruction directly because we cannot modify the
11621           // CFG.
11622           new StoreInst(UndefValue::get(LI.getType()),
11623                         Constant::getNullValue(Op->getType()), &LI);
11624           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11625         }
11626
11627       } else if (CE->isCast()) {
11628         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11629           return Res;
11630       }
11631     }
11632   }
11633     
11634   // If this load comes from anywhere in a constant global, and if the global
11635   // is all undef or zero, we know what it loads.
11636   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11637     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11638       if (GV->getInitializer()->isNullValue())
11639         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11640       else if (isa<UndefValue>(GV->getInitializer()))
11641         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11642     }
11643   }
11644
11645   if (Op->hasOneUse()) {
11646     // Change select and PHI nodes to select values instead of addresses: this
11647     // helps alias analysis out a lot, allows many others simplifications, and
11648     // exposes redundancy in the code.
11649     //
11650     // Note that we cannot do the transformation unless we know that the
11651     // introduced loads cannot trap!  Something like this is valid as long as
11652     // the condition is always false: load (select bool %C, int* null, int* %G),
11653     // but it would not be valid if we transformed it to load from null
11654     // unconditionally.
11655     //
11656     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11657       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11658       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11659           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11660         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11661                                      SI->getOperand(1)->getName()+".val"), LI);
11662         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11663                                      SI->getOperand(2)->getName()+".val"), LI);
11664         return SelectInst::Create(SI->getCondition(), V1, V2);
11665       }
11666
11667       // load (select (cond, null, P)) -> load P
11668       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11669         if (C->isNullValue()) {
11670           LI.setOperand(0, SI->getOperand(2));
11671           return &LI;
11672         }
11673
11674       // load (select (cond, P, null)) -> load P
11675       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11676         if (C->isNullValue()) {
11677           LI.setOperand(0, SI->getOperand(1));
11678           return &LI;
11679         }
11680     }
11681   }
11682   return 0;
11683 }
11684
11685 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11686 /// when possible.  This makes it generally easy to do alias analysis and/or
11687 /// SROA/mem2reg of the memory object.
11688 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11689   User *CI = cast<User>(SI.getOperand(1));
11690   Value *CastOp = CI->getOperand(0);
11691
11692   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11693   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11694   if (SrcTy == 0) return 0;
11695   
11696   const Type *SrcPTy = SrcTy->getElementType();
11697
11698   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11699     return 0;
11700   
11701   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11702   /// to its first element.  This allows us to handle things like:
11703   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11704   /// on 32-bit hosts.
11705   SmallVector<Value*, 4> NewGEPIndices;
11706   
11707   // If the source is an array, the code below will not succeed.  Check to
11708   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11709   // constants.
11710   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11711     // Index through pointer.
11712     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11713     NewGEPIndices.push_back(Zero);
11714     
11715     while (1) {
11716       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11717         if (!STy->getNumElements()) /* Struct can be empty {} */
11718           break;
11719         NewGEPIndices.push_back(Zero);
11720         SrcPTy = STy->getElementType(0);
11721       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11722         NewGEPIndices.push_back(Zero);
11723         SrcPTy = ATy->getElementType();
11724       } else {
11725         break;
11726       }
11727     }
11728     
11729     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11730   }
11731
11732   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11733     return 0;
11734   
11735   // If the pointers point into different address spaces or if they point to
11736   // values with different sizes, we can't do the transformation.
11737   if (!IC.getTargetData() ||
11738       SrcTy->getAddressSpace() != 
11739         cast<PointerType>(CI->getType())->getAddressSpace() ||
11740       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11741       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11742     return 0;
11743
11744   // Okay, we are casting from one integer or pointer type to another of
11745   // the same size.  Instead of casting the pointer before 
11746   // the store, cast the value to be stored.
11747   Value *NewCast;
11748   Value *SIOp0 = SI.getOperand(0);
11749   Instruction::CastOps opcode = Instruction::BitCast;
11750   const Type* CastSrcTy = SIOp0->getType();
11751   const Type* CastDstTy = SrcPTy;
11752   if (isa<PointerType>(CastDstTy)) {
11753     if (CastSrcTy->isInteger())
11754       opcode = Instruction::IntToPtr;
11755   } else if (isa<IntegerType>(CastDstTy)) {
11756     if (isa<PointerType>(SIOp0->getType()))
11757       opcode = Instruction::PtrToInt;
11758   }
11759   
11760   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11761   // emit a GEP to index into its first field.
11762   if (!NewGEPIndices.empty()) {
11763     if (Constant *C = dyn_cast<Constant>(CastOp))
11764       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11765                                               NewGEPIndices.size());
11766     else
11767       CastOp = IC.InsertNewInstBefore(
11768               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11769                                         NewGEPIndices.end()), SI);
11770     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11771   }
11772   
11773   if (Constant *C = dyn_cast<Constant>(SIOp0))
11774     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11775   else
11776     NewCast = IC.InsertNewInstBefore(
11777       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11778       SI);
11779   return new StoreInst(NewCast, CastOp);
11780 }
11781
11782 /// equivalentAddressValues - Test if A and B will obviously have the same
11783 /// value. This includes recognizing that %t0 and %t1 will have the same
11784 /// value in code like this:
11785 ///   %t0 = getelementptr \@a, 0, 3
11786 ///   store i32 0, i32* %t0
11787 ///   %t1 = getelementptr \@a, 0, 3
11788 ///   %t2 = load i32* %t1
11789 ///
11790 static bool equivalentAddressValues(Value *A, Value *B) {
11791   // Test if the values are trivially equivalent.
11792   if (A == B) return true;
11793   
11794   // Test if the values come form identical arithmetic instructions.
11795   if (isa<BinaryOperator>(A) ||
11796       isa<CastInst>(A) ||
11797       isa<PHINode>(A) ||
11798       isa<GetElementPtrInst>(A))
11799     if (Instruction *BI = dyn_cast<Instruction>(B))
11800       if (cast<Instruction>(A)->isIdenticalTo(BI))
11801         return true;
11802   
11803   // Otherwise they may not be equivalent.
11804   return false;
11805 }
11806
11807 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11808 // return the llvm.dbg.declare.
11809 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810   if (!V->hasNUses(2))
11811     return 0;
11812   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813        UI != E; ++UI) {
11814     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815       return DI;
11816     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818         return DI;
11819       }
11820   }
11821   return 0;
11822 }
11823
11824 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825   Value *Val = SI.getOperand(0);
11826   Value *Ptr = SI.getOperand(1);
11827
11828   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11829     EraseInstFromFunction(SI);
11830     ++NumCombined;
11831     return 0;
11832   }
11833   
11834   // If the RHS is an alloca with a single use, zapify the store, making the
11835   // alloca dead.
11836   // If the RHS is an alloca with a two uses, the other one being a 
11837   // llvm.dbg.declare, zapify the store and the declare, making the
11838   // alloca dead.  We must do this to prevent declare's from affecting
11839   // codegen.
11840   if (!SI.isVolatile()) {
11841     if (Ptr->hasOneUse()) {
11842       if (isa<AllocaInst>(Ptr)) {
11843         EraseInstFromFunction(SI);
11844         ++NumCombined;
11845         return 0;
11846       }
11847       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848         if (isa<AllocaInst>(GEP->getOperand(0))) {
11849           if (GEP->getOperand(0)->hasOneUse()) {
11850             EraseInstFromFunction(SI);
11851             ++NumCombined;
11852             return 0;
11853           }
11854           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855             EraseInstFromFunction(*DI);
11856             EraseInstFromFunction(SI);
11857             ++NumCombined;
11858             return 0;
11859           }
11860         }
11861       }
11862     }
11863     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864       EraseInstFromFunction(*DI);
11865       EraseInstFromFunction(SI);
11866       ++NumCombined;
11867       return 0;
11868     }
11869   }
11870
11871   // Attempt to improve the alignment.
11872   if (TD) {
11873     unsigned KnownAlign =
11874       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11875     if (KnownAlign >
11876         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11877                                   SI.getAlignment()))
11878       SI.setAlignment(KnownAlign);
11879   }
11880
11881   // Do really simple DSE, to catch cases where there are several consecutive
11882   // stores to the same location, separated by a few arithmetic operations. This
11883   // situation often occurs with bitfield accesses.
11884   BasicBlock::iterator BBI = &SI;
11885   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11886        --ScanInsts) {
11887     --BBI;
11888     // Don't count debug info directives, lest they affect codegen,
11889     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11890     // It is necessary for correctness to skip those that feed into a
11891     // llvm.dbg.declare, as these are not present when debugging is off.
11892     if (isa<DbgInfoIntrinsic>(BBI) ||
11893         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11894       ScanInsts++;
11895       continue;
11896     }    
11897     
11898     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11899       // Prev store isn't volatile, and stores to the same location?
11900       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11901                                                           SI.getOperand(1))) {
11902         ++NumDeadStore;
11903         ++BBI;
11904         EraseInstFromFunction(*PrevSI);
11905         continue;
11906       }
11907       break;
11908     }
11909     
11910     // If this is a load, we have to stop.  However, if the loaded value is from
11911     // the pointer we're loading and is producing the pointer we're storing,
11912     // then *this* store is dead (X = load P; store X -> P).
11913     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11914       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11915           !SI.isVolatile()) {
11916         EraseInstFromFunction(SI);
11917         ++NumCombined;
11918         return 0;
11919       }
11920       // Otherwise, this is a load from some other location.  Stores before it
11921       // may not be dead.
11922       break;
11923     }
11924     
11925     // Don't skip over loads or things that can modify memory.
11926     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11927       break;
11928   }
11929   
11930   
11931   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11932
11933   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11934   if (isa<ConstantPointerNull>(Ptr) &&
11935       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11936     if (!isa<UndefValue>(Val)) {
11937       SI.setOperand(0, UndefValue::get(Val->getType()));
11938       if (Instruction *U = dyn_cast<Instruction>(Val))
11939         AddToWorkList(U);  // Dropped a use.
11940       ++NumCombined;
11941     }
11942     return 0;  // Do not modify these!
11943   }
11944
11945   // store undef, Ptr -> noop
11946   if (isa<UndefValue>(Val)) {
11947     EraseInstFromFunction(SI);
11948     ++NumCombined;
11949     return 0;
11950   }
11951
11952   // If the pointer destination is a cast, see if we can fold the cast into the
11953   // source instead.
11954   if (isa<CastInst>(Ptr))
11955     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11956       return Res;
11957   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11958     if (CE->isCast())
11959       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11960         return Res;
11961
11962   
11963   // If this store is the last instruction in the basic block (possibly
11964   // excepting debug info instructions and the pointer bitcasts that feed
11965   // into them), and if the block ends with an unconditional branch, try
11966   // to move it to the successor block.
11967   BBI = &SI; 
11968   do {
11969     ++BBI;
11970   } while (isa<DbgInfoIntrinsic>(BBI) ||
11971            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11972   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11973     if (BI->isUnconditional())
11974       if (SimplifyStoreAtEndOfBlock(SI))
11975         return 0;  // xform done!
11976   
11977   return 0;
11978 }
11979
11980 /// SimplifyStoreAtEndOfBlock - Turn things like:
11981 ///   if () { *P = v1; } else { *P = v2 }
11982 /// into a phi node with a store in the successor.
11983 ///
11984 /// Simplify things like:
11985 ///   *P = v1; if () { *P = v2; }
11986 /// into a phi node with a store in the successor.
11987 ///
11988 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11989   BasicBlock *StoreBB = SI.getParent();
11990   
11991   // Check to see if the successor block has exactly two incoming edges.  If
11992   // so, see if the other predecessor contains a store to the same location.
11993   // if so, insert a PHI node (if needed) and move the stores down.
11994   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11995   
11996   // Determine whether Dest has exactly two predecessors and, if so, compute
11997   // the other predecessor.
11998   pred_iterator PI = pred_begin(DestBB);
11999   BasicBlock *OtherBB = 0;
12000   if (*PI != StoreBB)
12001     OtherBB = *PI;
12002   ++PI;
12003   if (PI == pred_end(DestBB))
12004     return false;
12005   
12006   if (*PI != StoreBB) {
12007     if (OtherBB)
12008       return false;
12009     OtherBB = *PI;
12010   }
12011   if (++PI != pred_end(DestBB))
12012     return false;
12013
12014   // Bail out if all the relevant blocks aren't distinct (this can happen,
12015   // for example, if SI is in an infinite loop)
12016   if (StoreBB == DestBB || OtherBB == DestBB)
12017     return false;
12018
12019   // Verify that the other block ends in a branch and is not otherwise empty.
12020   BasicBlock::iterator BBI = OtherBB->getTerminator();
12021   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12022   if (!OtherBr || BBI == OtherBB->begin())
12023     return false;
12024   
12025   // If the other block ends in an unconditional branch, check for the 'if then
12026   // else' case.  there is an instruction before the branch.
12027   StoreInst *OtherStore = 0;
12028   if (OtherBr->isUnconditional()) {
12029     --BBI;
12030     // Skip over debugging info.
12031     while (isa<DbgInfoIntrinsic>(BBI) ||
12032            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12033       if (BBI==OtherBB->begin())
12034         return false;
12035       --BBI;
12036     }
12037     // If this isn't a store, or isn't a store to the same location, bail out.
12038     OtherStore = dyn_cast<StoreInst>(BBI);
12039     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12040       return false;
12041   } else {
12042     // Otherwise, the other block ended with a conditional branch. If one of the
12043     // destinations is StoreBB, then we have the if/then case.
12044     if (OtherBr->getSuccessor(0) != StoreBB && 
12045         OtherBr->getSuccessor(1) != StoreBB)
12046       return false;
12047     
12048     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12049     // if/then triangle.  See if there is a store to the same ptr as SI that
12050     // lives in OtherBB.
12051     for (;; --BBI) {
12052       // Check to see if we find the matching store.
12053       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12054         if (OtherStore->getOperand(1) != SI.getOperand(1))
12055           return false;
12056         break;
12057       }
12058       // If we find something that may be using or overwriting the stored
12059       // value, or if we run out of instructions, we can't do the xform.
12060       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12061           BBI == OtherBB->begin())
12062         return false;
12063     }
12064     
12065     // In order to eliminate the store in OtherBr, we have to
12066     // make sure nothing reads or overwrites the stored value in
12067     // StoreBB.
12068     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12069       // FIXME: This should really be AA driven.
12070       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12071         return false;
12072     }
12073   }
12074   
12075   // Insert a PHI node now if we need it.
12076   Value *MergedVal = OtherStore->getOperand(0);
12077   if (MergedVal != SI.getOperand(0)) {
12078     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12079     PN->reserveOperandSpace(2);
12080     PN->addIncoming(SI.getOperand(0), SI.getParent());
12081     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12082     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12083   }
12084   
12085   // Advance to a place where it is safe to insert the new store and
12086   // insert it.
12087   BBI = DestBB->getFirstNonPHI();
12088   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12089                                     OtherStore->isVolatile()), *BBI);
12090   
12091   // Nuke the old stores.
12092   EraseInstFromFunction(SI);
12093   EraseInstFromFunction(*OtherStore);
12094   ++NumCombined;
12095   return true;
12096 }
12097
12098
12099 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12100   // Change br (not X), label True, label False to: br X, label False, True
12101   Value *X = 0;
12102   BasicBlock *TrueDest;
12103   BasicBlock *FalseDest;
12104   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12105       !isa<Constant>(X)) {
12106     // Swap Destinations and condition...
12107     BI.setCondition(X);
12108     BI.setSuccessor(0, FalseDest);
12109     BI.setSuccessor(1, TrueDest);
12110     return &BI;
12111   }
12112
12113   // Cannonicalize fcmp_one -> fcmp_oeq
12114   FCmpInst::Predicate FPred; Value *Y;
12115   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12116                              TrueDest, FalseDest)))
12117     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12118          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12119       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12120       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12121       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12122       NewSCC->takeName(I);
12123       // Swap Destinations and condition...
12124       BI.setCondition(NewSCC);
12125       BI.setSuccessor(0, FalseDest);
12126       BI.setSuccessor(1, TrueDest);
12127       RemoveFromWorkList(I);
12128       I->eraseFromParent();
12129       AddToWorkList(NewSCC);
12130       return &BI;
12131     }
12132
12133   // Cannonicalize icmp_ne -> icmp_eq
12134   ICmpInst::Predicate IPred;
12135   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12136                       TrueDest, FalseDest)))
12137     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12138          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12139          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12140       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12141       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12142       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12143       NewSCC->takeName(I);
12144       // Swap Destinations and condition...
12145       BI.setCondition(NewSCC);
12146       BI.setSuccessor(0, FalseDest);
12147       BI.setSuccessor(1, TrueDest);
12148       RemoveFromWorkList(I);
12149       I->eraseFromParent();;
12150       AddToWorkList(NewSCC);
12151       return &BI;
12152     }
12153
12154   return 0;
12155 }
12156
12157 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12158   Value *Cond = SI.getCondition();
12159   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12160     if (I->getOpcode() == Instruction::Add)
12161       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12162         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12163         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12164           SI.setOperand(i,
12165                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12166                                                 AddRHS));
12167         SI.setOperand(0, I->getOperand(0));
12168         AddToWorkList(I);
12169         return &SI;
12170       }
12171   }
12172   return 0;
12173 }
12174
12175 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12176   Value *Agg = EV.getAggregateOperand();
12177
12178   if (!EV.hasIndices())
12179     return ReplaceInstUsesWith(EV, Agg);
12180
12181   if (Constant *C = dyn_cast<Constant>(Agg)) {
12182     if (isa<UndefValue>(C))
12183       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12184       
12185     if (isa<ConstantAggregateZero>(C))
12186       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12187
12188     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12189       // Extract the element indexed by the first index out of the constant
12190       Value *V = C->getOperand(*EV.idx_begin());
12191       if (EV.getNumIndices() > 1)
12192         // Extract the remaining indices out of the constant indexed by the
12193         // first index
12194         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12195       else
12196         return ReplaceInstUsesWith(EV, V);
12197     }
12198     return 0; // Can't handle other constants
12199   } 
12200   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12201     // We're extracting from an insertvalue instruction, compare the indices
12202     const unsigned *exti, *exte, *insi, *inse;
12203     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12204          exte = EV.idx_end(), inse = IV->idx_end();
12205          exti != exte && insi != inse;
12206          ++exti, ++insi) {
12207       if (*insi != *exti)
12208         // The insert and extract both reference distinctly different elements.
12209         // This means the extract is not influenced by the insert, and we can
12210         // replace the aggregate operand of the extract with the aggregate
12211         // operand of the insert. i.e., replace
12212         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12213         // %E = extractvalue { i32, { i32 } } %I, 0
12214         // with
12215         // %E = extractvalue { i32, { i32 } } %A, 0
12216         return ExtractValueInst::Create(IV->getAggregateOperand(),
12217                                         EV.idx_begin(), EV.idx_end());
12218     }
12219     if (exti == exte && insi == inse)
12220       // Both iterators are at the end: Index lists are identical. Replace
12221       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12222       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12223       // with "i32 42"
12224       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12225     if (exti == exte) {
12226       // The extract list is a prefix of the insert list. i.e. replace
12227       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12228       // %E = extractvalue { i32, { i32 } } %I, 1
12229       // with
12230       // %X = extractvalue { i32, { i32 } } %A, 1
12231       // %E = insertvalue { i32 } %X, i32 42, 0
12232       // by switching the order of the insert and extract (though the
12233       // insertvalue should be left in, since it may have other uses).
12234       Value *NewEV = InsertNewInstBefore(
12235         ExtractValueInst::Create(IV->getAggregateOperand(),
12236                                  EV.idx_begin(), EV.idx_end()),
12237         EV);
12238       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12239                                      insi, inse);
12240     }
12241     if (insi == inse)
12242       // The insert list is a prefix of the extract list
12243       // We can simply remove the common indices from the extract and make it
12244       // operate on the inserted value instead of the insertvalue result.
12245       // i.e., replace
12246       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12247       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12248       // with
12249       // %E extractvalue { i32 } { i32 42 }, 0
12250       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12251                                       exti, exte);
12252   }
12253   // Can't simplify extracts from other values. Note that nested extracts are
12254   // already simplified implicitely by the above (extract ( extract (insert) )
12255   // will be translated into extract ( insert ( extract ) ) first and then just
12256   // the value inserted, if appropriate).
12257   return 0;
12258 }
12259
12260 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12261 /// is to leave as a vector operation.
12262 static bool CheapToScalarize(Value *V, bool isConstant) {
12263   if (isa<ConstantAggregateZero>(V)) 
12264     return true;
12265   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12266     if (isConstant) return true;
12267     // If all elts are the same, we can extract.
12268     Constant *Op0 = C->getOperand(0);
12269     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12270       if (C->getOperand(i) != Op0)
12271         return false;
12272     return true;
12273   }
12274   Instruction *I = dyn_cast<Instruction>(V);
12275   if (!I) return false;
12276   
12277   // Insert element gets simplified to the inserted element or is deleted if
12278   // this is constant idx extract element and its a constant idx insertelt.
12279   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12280       isa<ConstantInt>(I->getOperand(2)))
12281     return true;
12282   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12283     return true;
12284   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12285     if (BO->hasOneUse() &&
12286         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12287          CheapToScalarize(BO->getOperand(1), isConstant)))
12288       return true;
12289   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12290     if (CI->hasOneUse() &&
12291         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12292          CheapToScalarize(CI->getOperand(1), isConstant)))
12293       return true;
12294   
12295   return false;
12296 }
12297
12298 /// Read and decode a shufflevector mask.
12299 ///
12300 /// It turns undef elements into values that are larger than the number of
12301 /// elements in the input.
12302 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12303   unsigned NElts = SVI->getType()->getNumElements();
12304   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12305     return std::vector<unsigned>(NElts, 0);
12306   if (isa<UndefValue>(SVI->getOperand(2)))
12307     return std::vector<unsigned>(NElts, 2*NElts);
12308
12309   std::vector<unsigned> Result;
12310   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12311   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12312     if (isa<UndefValue>(*i))
12313       Result.push_back(NElts*2);  // undef -> 8
12314     else
12315       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12316   return Result;
12317 }
12318
12319 /// FindScalarElement - Given a vector and an element number, see if the scalar
12320 /// value is already around as a register, for example if it were inserted then
12321 /// extracted from the vector.
12322 static Value *FindScalarElement(Value *V, unsigned EltNo,
12323                                 LLVMContext *Context) {
12324   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12325   const VectorType *PTy = cast<VectorType>(V->getType());
12326   unsigned Width = PTy->getNumElements();
12327   if (EltNo >= Width)  // Out of range access.
12328     return UndefValue::get(PTy->getElementType());
12329   
12330   if (isa<UndefValue>(V))
12331     return UndefValue::get(PTy->getElementType());
12332   else if (isa<ConstantAggregateZero>(V))
12333     return Constant::getNullValue(PTy->getElementType());
12334   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12335     return CP->getOperand(EltNo);
12336   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12337     // If this is an insert to a variable element, we don't know what it is.
12338     if (!isa<ConstantInt>(III->getOperand(2))) 
12339       return 0;
12340     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12341     
12342     // If this is an insert to the element we are looking for, return the
12343     // inserted value.
12344     if (EltNo == IIElt) 
12345       return III->getOperand(1);
12346     
12347     // Otherwise, the insertelement doesn't modify the value, recurse on its
12348     // vector input.
12349     return FindScalarElement(III->getOperand(0), EltNo, Context);
12350   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12351     unsigned LHSWidth =
12352       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12353     unsigned InEl = getShuffleMask(SVI)[EltNo];
12354     if (InEl < LHSWidth)
12355       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12356     else if (InEl < LHSWidth*2)
12357       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12358     else
12359       return UndefValue::get(PTy->getElementType());
12360   }
12361   
12362   // Otherwise, we don't know.
12363   return 0;
12364 }
12365
12366 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12367   // If vector val is undef, replace extract with scalar undef.
12368   if (isa<UndefValue>(EI.getOperand(0)))
12369     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12370
12371   // If vector val is constant 0, replace extract with scalar 0.
12372   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12373     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12374   
12375   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12376     // If vector val is constant with all elements the same, replace EI with
12377     // that element. When the elements are not identical, we cannot replace yet
12378     // (we do that below, but only when the index is constant).
12379     Constant *op0 = C->getOperand(0);
12380     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12381       if (C->getOperand(i) != op0) {
12382         op0 = 0; 
12383         break;
12384       }
12385     if (op0)
12386       return ReplaceInstUsesWith(EI, op0);
12387   }
12388   
12389   // If extracting a specified index from the vector, see if we can recursively
12390   // find a previously computed scalar that was inserted into the vector.
12391   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12392     unsigned IndexVal = IdxC->getZExtValue();
12393     unsigned VectorWidth = 
12394       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12395       
12396     // If this is extracting an invalid index, turn this into undef, to avoid
12397     // crashing the code below.
12398     if (IndexVal >= VectorWidth)
12399       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12400     
12401     // This instruction only demands the single element from the input vector.
12402     // If the input vector has a single use, simplify it based on this use
12403     // property.
12404     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12405       APInt UndefElts(VectorWidth, 0);
12406       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12407       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12408                                                 DemandedMask, UndefElts)) {
12409         EI.setOperand(0, V);
12410         return &EI;
12411       }
12412     }
12413     
12414     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12415       return ReplaceInstUsesWith(EI, Elt);
12416     
12417     // If the this extractelement is directly using a bitcast from a vector of
12418     // the same number of elements, see if we can find the source element from
12419     // it.  In this case, we will end up needing to bitcast the scalars.
12420     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12421       if (const VectorType *VT = 
12422               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12423         if (VT->getNumElements() == VectorWidth)
12424           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12425                                              IndexVal, Context))
12426             return new BitCastInst(Elt, EI.getType());
12427     }
12428   }
12429   
12430   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12431     if (I->hasOneUse()) {
12432       // Push extractelement into predecessor operation if legal and
12433       // profitable to do so
12434       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12435         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12436         if (CheapToScalarize(BO, isConstantElt)) {
12437           ExtractElementInst *newEI0 = 
12438             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12439                                    EI.getName()+".lhs");
12440           ExtractElementInst *newEI1 =
12441             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12442                                    EI.getName()+".rhs");
12443           InsertNewInstBefore(newEI0, EI);
12444           InsertNewInstBefore(newEI1, EI);
12445           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12446         }
12447       } else if (isa<LoadInst>(I)) {
12448         unsigned AS = 
12449           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12450         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12451                                   PointerType::get(EI.getType(), AS),EI);
12452         GetElementPtrInst *GEP =
12453           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12454         cast<GEPOperator>(GEP)->setIsInBounds(true);
12455         InsertNewInstBefore(GEP, EI);
12456         return new LoadInst(GEP);
12457       }
12458     }
12459     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12460       // Extracting the inserted element?
12461       if (IE->getOperand(2) == EI.getOperand(1))
12462         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12463       // If the inserted and extracted elements are constants, they must not
12464       // be the same value, extract from the pre-inserted value instead.
12465       if (isa<Constant>(IE->getOperand(2)) &&
12466           isa<Constant>(EI.getOperand(1))) {
12467         AddUsesToWorkList(EI);
12468         EI.setOperand(0, IE->getOperand(0));
12469         return &EI;
12470       }
12471     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12472       // If this is extracting an element from a shufflevector, figure out where
12473       // it came from and extract from the appropriate input element instead.
12474       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12475         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12476         Value *Src;
12477         unsigned LHSWidth =
12478           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12479
12480         if (SrcIdx < LHSWidth)
12481           Src = SVI->getOperand(0);
12482         else if (SrcIdx < LHSWidth*2) {
12483           SrcIdx -= LHSWidth;
12484           Src = SVI->getOperand(1);
12485         } else {
12486           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12487         }
12488         return ExtractElementInst::Create(Src,
12489                          ConstantInt::get(Type::Int32Ty, SrcIdx, false));
12490       }
12491     }
12492     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12493   }
12494   return 0;
12495 }
12496
12497 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12498 /// elements from either LHS or RHS, return the shuffle mask and true. 
12499 /// Otherwise, return false.
12500 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12501                                          std::vector<Constant*> &Mask,
12502                                          LLVMContext *Context) {
12503   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12504          "Invalid CollectSingleShuffleElements");
12505   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12506
12507   if (isa<UndefValue>(V)) {
12508     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12509     return true;
12510   } else if (V == LHS) {
12511     for (unsigned i = 0; i != NumElts; ++i)
12512       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12513     return true;
12514   } else if (V == RHS) {
12515     for (unsigned i = 0; i != NumElts; ++i)
12516       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12517     return true;
12518   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12519     // If this is an insert of an extract from some other vector, include it.
12520     Value *VecOp    = IEI->getOperand(0);
12521     Value *ScalarOp = IEI->getOperand(1);
12522     Value *IdxOp    = IEI->getOperand(2);
12523     
12524     if (!isa<ConstantInt>(IdxOp))
12525       return false;
12526     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12527     
12528     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12529       // Okay, we can handle this if the vector we are insertinting into is
12530       // transitively ok.
12531       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12532         // If so, update the mask to reflect the inserted undef.
12533         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12534         return true;
12535       }      
12536     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12537       if (isa<ConstantInt>(EI->getOperand(1)) &&
12538           EI->getOperand(0)->getType() == V->getType()) {
12539         unsigned ExtractedIdx =
12540           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12541         
12542         // This must be extracting from either LHS or RHS.
12543         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12544           // Okay, we can handle this if the vector we are insertinting into is
12545           // transitively ok.
12546           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12547             // If so, update the mask to reflect the inserted value.
12548             if (EI->getOperand(0) == LHS) {
12549               Mask[InsertedIdx % NumElts] = 
12550                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12551             } else {
12552               assert(EI->getOperand(0) == RHS);
12553               Mask[InsertedIdx % NumElts] = 
12554                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12555               
12556             }
12557             return true;
12558           }
12559         }
12560       }
12561     }
12562   }
12563   // TODO: Handle shufflevector here!
12564   
12565   return false;
12566 }
12567
12568 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12569 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12570 /// that computes V and the LHS value of the shuffle.
12571 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12572                                      Value *&RHS, LLVMContext *Context) {
12573   assert(isa<VectorType>(V->getType()) && 
12574          (RHS == 0 || V->getType() == RHS->getType()) &&
12575          "Invalid shuffle!");
12576   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12577
12578   if (isa<UndefValue>(V)) {
12579     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12580     return V;
12581   } else if (isa<ConstantAggregateZero>(V)) {
12582     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12583     return V;
12584   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12585     // If this is an insert of an extract from some other vector, include it.
12586     Value *VecOp    = IEI->getOperand(0);
12587     Value *ScalarOp = IEI->getOperand(1);
12588     Value *IdxOp    = IEI->getOperand(2);
12589     
12590     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592           EI->getOperand(0)->getType() == V->getType()) {
12593         unsigned ExtractedIdx =
12594           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12595         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12596         
12597         // Either the extracted from or inserted into vector must be RHSVec,
12598         // otherwise we'd end up with a shuffle of three inputs.
12599         if (EI->getOperand(0) == RHS || RHS == 0) {
12600           RHS = EI->getOperand(0);
12601           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12602           Mask[InsertedIdx % NumElts] = 
12603             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12604           return V;
12605         }
12606         
12607         if (VecOp == RHS) {
12608           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12609                                             RHS, Context);
12610           // Everything but the extracted element is replaced with the RHS.
12611           for (unsigned i = 0; i != NumElts; ++i) {
12612             if (i != InsertedIdx)
12613               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12614           }
12615           return V;
12616         }
12617         
12618         // If this insertelement is a chain that comes from exactly these two
12619         // vectors, return the vector and the effective shuffle.
12620         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12621                                          Context))
12622           return EI->getOperand(0);
12623         
12624       }
12625     }
12626   }
12627   // TODO: Handle shufflevector here!
12628   
12629   // Otherwise, can't do anything fancy.  Return an identity vector.
12630   for (unsigned i = 0; i != NumElts; ++i)
12631     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12632   return V;
12633 }
12634
12635 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12636   Value *VecOp    = IE.getOperand(0);
12637   Value *ScalarOp = IE.getOperand(1);
12638   Value *IdxOp    = IE.getOperand(2);
12639   
12640   // Inserting an undef or into an undefined place, remove this.
12641   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12642     ReplaceInstUsesWith(IE, VecOp);
12643   
12644   // If the inserted element was extracted from some other vector, and if the 
12645   // indexes are constant, try to turn this into a shufflevector operation.
12646   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12647     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12648         EI->getOperand(0)->getType() == IE.getType()) {
12649       unsigned NumVectorElts = IE.getType()->getNumElements();
12650       unsigned ExtractedIdx =
12651         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12652       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12653       
12654       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12655         return ReplaceInstUsesWith(IE, VecOp);
12656       
12657       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12658         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12659       
12660       // If we are extracting a value from a vector, then inserting it right
12661       // back into the same place, just use the input vector.
12662       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12663         return ReplaceInstUsesWith(IE, VecOp);      
12664       
12665       // We could theoretically do this for ANY input.  However, doing so could
12666       // turn chains of insertelement instructions into a chain of shufflevector
12667       // instructions, and right now we do not merge shufflevectors.  As such,
12668       // only do this in a situation where it is clear that there is benefit.
12669       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12670         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12671         // the values of VecOp, except then one read from EIOp0.
12672         // Build a new shuffle mask.
12673         std::vector<Constant*> Mask;
12674         if (isa<UndefValue>(VecOp))
12675           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12676         else {
12677           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12678           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12679                                                        NumVectorElts));
12680         } 
12681         Mask[InsertedIdx] = 
12682                            ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12683         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12684                                      ConstantVector::get(Mask));
12685       }
12686       
12687       // If this insertelement isn't used by some other insertelement, turn it
12688       // (and any insertelements it points to), into one big shuffle.
12689       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12690         std::vector<Constant*> Mask;
12691         Value *RHS = 0;
12692         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12693         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12694         // We now have a shuffle of LHS, RHS, Mask.
12695         return new ShuffleVectorInst(LHS, RHS,
12696                                      ConstantVector::get(Mask));
12697       }
12698     }
12699   }
12700
12701   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12702   APInt UndefElts(VWidth, 0);
12703   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12704   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12705     return &IE;
12706
12707   return 0;
12708 }
12709
12710
12711 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12712   Value *LHS = SVI.getOperand(0);
12713   Value *RHS = SVI.getOperand(1);
12714   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12715
12716   bool MadeChange = false;
12717
12718   // Undefined shuffle mask -> undefined value.
12719   if (isa<UndefValue>(SVI.getOperand(2)))
12720     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12721
12722   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12723
12724   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12725     return 0;
12726
12727   APInt UndefElts(VWidth, 0);
12728   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12730     LHS = SVI.getOperand(0);
12731     RHS = SVI.getOperand(1);
12732     MadeChange = true;
12733   }
12734   
12735   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12736   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12737   if (LHS == RHS || isa<UndefValue>(LHS)) {
12738     if (isa<UndefValue>(LHS) && LHS == RHS) {
12739       // shuffle(undef,undef,mask) -> undef.
12740       return ReplaceInstUsesWith(SVI, LHS);
12741     }
12742     
12743     // Remap any references to RHS to use LHS.
12744     std::vector<Constant*> Elts;
12745     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12746       if (Mask[i] >= 2*e)
12747         Elts.push_back(UndefValue::get(Type::Int32Ty));
12748       else {
12749         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12750             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12751           Mask[i] = 2*e;     // Turn into undef.
12752           Elts.push_back(UndefValue::get(Type::Int32Ty));
12753         } else {
12754           Mask[i] = Mask[i] % e;  // Force to LHS.
12755           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12756         }
12757       }
12758     }
12759     SVI.setOperand(0, SVI.getOperand(1));
12760     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12761     SVI.setOperand(2, ConstantVector::get(Elts));
12762     LHS = SVI.getOperand(0);
12763     RHS = SVI.getOperand(1);
12764     MadeChange = true;
12765   }
12766   
12767   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12768   bool isLHSID = true, isRHSID = true;
12769     
12770   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12772     // Is this an identity shuffle of the LHS value?
12773     isLHSID &= (Mask[i] == i);
12774       
12775     // Is this an identity shuffle of the RHS value?
12776     isRHSID &= (Mask[i]-e == i);
12777   }
12778
12779   // Eliminate identity shuffles.
12780   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12781   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12782   
12783   // If the LHS is a shufflevector itself, see if we can combine it with this
12784   // one without producing an unusual shuffle.  Here we are really conservative:
12785   // we are absolutely afraid of producing a shuffle mask not in the input
12786   // program, because the code gen may not be smart enough to turn a merged
12787   // shuffle into two specific shuffles: it may produce worse code.  As such,
12788   // we only merge two shuffles if the result is one of the two input shuffle
12789   // masks.  In this case, merging the shuffles just removes one instruction,
12790   // which we know is safe.  This is good for things like turning:
12791   // (splat(splat)) -> splat.
12792   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12793     if (isa<UndefValue>(RHS)) {
12794       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12795
12796       std::vector<unsigned> NewMask;
12797       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12798         if (Mask[i] >= 2*e)
12799           NewMask.push_back(2*e);
12800         else
12801           NewMask.push_back(LHSMask[Mask[i]]);
12802       
12803       // If the result mask is equal to the src shuffle or this shuffle mask, do
12804       // the replacement.
12805       if (NewMask == LHSMask || NewMask == Mask) {
12806         unsigned LHSInNElts =
12807           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12808         std::vector<Constant*> Elts;
12809         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12810           if (NewMask[i] >= LHSInNElts*2) {
12811             Elts.push_back(UndefValue::get(Type::Int32Ty));
12812           } else {
12813             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12814           }
12815         }
12816         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12817                                      LHSSVI->getOperand(1),
12818                                      ConstantVector::get(Elts));
12819       }
12820     }
12821   }
12822
12823   return MadeChange ? &SVI : 0;
12824 }
12825
12826
12827
12828
12829 /// TryToSinkInstruction - Try to move the specified instruction from its
12830 /// current block into the beginning of DestBlock, which can only happen if it's
12831 /// safe to move the instruction past all of the instructions between it and the
12832 /// end of its block.
12833 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12834   assert(I->hasOneUse() && "Invariants didn't hold!");
12835
12836   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12837   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12838     return false;
12839
12840   // Do not sink alloca instructions out of the entry block.
12841   if (isa<AllocaInst>(I) && I->getParent() ==
12842         &DestBlock->getParent()->getEntryBlock())
12843     return false;
12844
12845   // We can only sink load instructions if there is nothing between the load and
12846   // the end of block that could change the value.
12847   if (I->mayReadFromMemory()) {
12848     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12849          Scan != E; ++Scan)
12850       if (Scan->mayWriteToMemory())
12851         return false;
12852   }
12853
12854   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12855
12856   CopyPrecedingStopPoint(I, InsertPos);
12857   I->moveBefore(InsertPos);
12858   ++NumSunkInst;
12859   return true;
12860 }
12861
12862
12863 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12864 /// all reachable code to the worklist.
12865 ///
12866 /// This has a couple of tricks to make the code faster and more powerful.  In
12867 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12868 /// them to the worklist (this significantly speeds up instcombine on code where
12869 /// many instructions are dead or constant).  Additionally, if we find a branch
12870 /// whose condition is a known constant, we only visit the reachable successors.
12871 ///
12872 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12873                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12874                                        InstCombiner &IC,
12875                                        const TargetData *TD) {
12876   SmallVector<BasicBlock*, 256> Worklist;
12877   Worklist.push_back(BB);
12878
12879   while (!Worklist.empty()) {
12880     BB = Worklist.back();
12881     Worklist.pop_back();
12882     
12883     // We have now visited this block!  If we've already been here, ignore it.
12884     if (!Visited.insert(BB)) continue;
12885
12886     DbgInfoIntrinsic *DBI_Prev = NULL;
12887     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12888       Instruction *Inst = BBI++;
12889       
12890       // DCE instruction if trivially dead.
12891       if (isInstructionTriviallyDead(Inst)) {
12892         ++NumDeadInst;
12893         DOUT << "IC: DCE: " << *Inst << '\n';
12894         Inst->eraseFromParent();
12895         continue;
12896       }
12897       
12898       // ConstantProp instruction if trivially constant.
12899       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12900         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
12901         Inst->replaceAllUsesWith(C);
12902         ++NumConstProp;
12903         Inst->eraseFromParent();
12904         continue;
12905       }
12906      
12907       // If there are two consecutive llvm.dbg.stoppoint calls then
12908       // it is likely that the optimizer deleted code in between these
12909       // two intrinsics. 
12910       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12911       if (DBI_Next) {
12912         if (DBI_Prev
12913             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12914             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12915           IC.RemoveFromWorkList(DBI_Prev);
12916           DBI_Prev->eraseFromParent();
12917         }
12918         DBI_Prev = DBI_Next;
12919       } else {
12920         DBI_Prev = 0;
12921       }
12922
12923       IC.AddToWorkList(Inst);
12924     }
12925
12926     // Recursively visit successors.  If this is a branch or switch on a
12927     // constant, only visit the reachable successor.
12928     TerminatorInst *TI = BB->getTerminator();
12929     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12930       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12931         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12932         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12933         Worklist.push_back(ReachableBB);
12934         continue;
12935       }
12936     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12937       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12938         // See if this is an explicit destination.
12939         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12940           if (SI->getCaseValue(i) == Cond) {
12941             BasicBlock *ReachableBB = SI->getSuccessor(i);
12942             Worklist.push_back(ReachableBB);
12943             continue;
12944           }
12945         
12946         // Otherwise it is the default destination.
12947         Worklist.push_back(SI->getSuccessor(0));
12948         continue;
12949       }
12950     }
12951     
12952     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12953       Worklist.push_back(TI->getSuccessor(i));
12954   }
12955 }
12956
12957 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12958   bool Changed = false;
12959   TD = getAnalysisIfAvailable<TargetData>();
12960   
12961   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12962         << F.getNameStr() << "\n");
12963
12964   {
12965     // Do a depth-first traversal of the function, populate the worklist with
12966     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12967     // track of which blocks we visit.
12968     SmallPtrSet<BasicBlock*, 64> Visited;
12969     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12970
12971     // Do a quick scan over the function.  If we find any blocks that are
12972     // unreachable, remove any instructions inside of them.  This prevents
12973     // the instcombine code from having to deal with some bad special cases.
12974     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12975       if (!Visited.count(BB)) {
12976         Instruction *Term = BB->getTerminator();
12977         while (Term != BB->begin()) {   // Remove instrs bottom-up
12978           BasicBlock::iterator I = Term; --I;
12979
12980           DOUT << "IC: DCE: " << *I << '\n';
12981           // A debug intrinsic shouldn't force another iteration if we weren't
12982           // going to do one without it.
12983           if (!isa<DbgInfoIntrinsic>(I)) {
12984             ++NumDeadInst;
12985             Changed = true;
12986           }
12987           if (!I->use_empty())
12988             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12989           I->eraseFromParent();
12990         }
12991       }
12992   }
12993
12994   while (!Worklist.empty()) {
12995     Instruction *I = RemoveOneFromWorkList();
12996     if (I == 0) continue;  // skip null values.
12997
12998     // Check to see if we can DCE the instruction.
12999     if (isInstructionTriviallyDead(I)) {
13000       // Add operands to the worklist.
13001       if (I->getNumOperands() < 4)
13002         AddUsesToWorkList(*I);
13003       ++NumDeadInst;
13004
13005       DOUT << "IC: DCE: " << *I << '\n';
13006
13007       I->eraseFromParent();
13008       RemoveFromWorkList(I);
13009       Changed = true;
13010       continue;
13011     }
13012
13013     // Instruction isn't dead, see if we can constant propagate it.
13014     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13015       DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
13016
13017       // Add operands to the worklist.
13018       AddUsesToWorkList(*I);
13019       ReplaceInstUsesWith(*I, C);
13020
13021       ++NumConstProp;
13022       I->eraseFromParent();
13023       RemoveFromWorkList(I);
13024       Changed = true;
13025       continue;
13026     }
13027
13028     if (TD) {
13029       // See if we can constant fold its operands.
13030       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13031         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13032           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13033                                   F.getContext(), TD))
13034             if (NewC != CE) {
13035               i->set(NewC);
13036               Changed = true;
13037             }
13038     }
13039
13040     // See if we can trivially sink this instruction to a successor basic block.
13041     if (I->hasOneUse()) {
13042       BasicBlock *BB = I->getParent();
13043       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13044       if (UserParent != BB) {
13045         bool UserIsSuccessor = false;
13046         // See if the user is one of our successors.
13047         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13048           if (*SI == UserParent) {
13049             UserIsSuccessor = true;
13050             break;
13051           }
13052
13053         // If the user is one of our immediate successors, and if that successor
13054         // only has us as a predecessors (we'd have to split the critical edge
13055         // otherwise), we can keep going.
13056         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13057             next(pred_begin(UserParent)) == pred_end(UserParent))
13058           // Okay, the CFG is simple enough, try to sink this instruction.
13059           Changed |= TryToSinkInstruction(I, UserParent);
13060       }
13061     }
13062
13063     // Now that we have an instruction, try combining it to simplify it...
13064 #ifndef NDEBUG
13065     std::string OrigI;
13066 #endif
13067     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13068     if (Instruction *Result = visit(*I)) {
13069       ++NumCombined;
13070       // Should we replace the old instruction with a new one?
13071       if (Result != I) {
13072         DOUT << "IC: Old = " << *I << '\n'
13073              << "    New = " << *Result << '\n';
13074
13075         // Everything uses the new instruction now.
13076         I->replaceAllUsesWith(Result);
13077
13078         // Push the new instruction and any users onto the worklist.
13079         AddToWorkList(Result);
13080         AddUsersToWorkList(*Result);
13081
13082         // Move the name to the new instruction first.
13083         Result->takeName(I);
13084
13085         // Insert the new instruction into the basic block...
13086         BasicBlock *InstParent = I->getParent();
13087         BasicBlock::iterator InsertPos = I;
13088
13089         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13090           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13091             ++InsertPos;
13092
13093         InstParent->getInstList().insert(InsertPos, Result);
13094
13095         // Make sure that we reprocess all operands now that we reduced their
13096         // use counts.
13097         AddUsesToWorkList(*I);
13098
13099         // Instructions can end up on the worklist more than once.  Make sure
13100         // we do not process an instruction that has been deleted.
13101         RemoveFromWorkList(I);
13102
13103         // Erase the old instruction.
13104         InstParent->getInstList().erase(I);
13105       } else {
13106 #ifndef NDEBUG
13107         DOUT << "IC: Mod = " << OrigI << '\n'
13108              << "    New = " << *I << '\n';
13109 #endif
13110
13111         // If the instruction was modified, it's possible that it is now dead.
13112         // if so, remove it.
13113         if (isInstructionTriviallyDead(I)) {
13114           // Make sure we process all operands now that we are reducing their
13115           // use counts.
13116           AddUsesToWorkList(*I);
13117
13118           // Instructions may end up in the worklist more than once.  Erase all
13119           // occurrences of this instruction.
13120           RemoveFromWorkList(I);
13121           I->eraseFromParent();
13122         } else {
13123           AddToWorkList(I);
13124           AddUsersToWorkList(*I);
13125         }
13126       }
13127       Changed = true;
13128     }
13129   }
13130
13131   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13132     
13133   // Do an explicit clear, this shrinks the map if needed.
13134   WorklistMap.clear();
13135   return Changed;
13136 }
13137
13138
13139 bool InstCombiner::runOnFunction(Function &F) {
13140   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13141   Context = &F.getContext();
13142   
13143   bool EverMadeChange = false;
13144
13145   // Iterate while there is work to do.
13146   unsigned Iteration = 0;
13147   while (DoOneIteration(F, Iteration++))
13148     EverMadeChange = true;
13149   return EverMadeChange;
13150 }
13151
13152 FunctionPass *llvm::createInstructionCombiningPass() {
13153   return new InstCombiner();
13154 }